feat: tweet embed (#488)

Co-authored-by: DIYgod <i@diygod.me>
This commit is contained in:
birdgg
2023-05-09 16:28:20 +01:00
committed by GitHub
co-authored by DIYgod
parent 32e82e69ba
commit 21cbd12e00
6 changed files with 92 additions and 1 deletions
+12
View File
@@ -0,0 +1,12 @@
import Image from "next/image"
import { Tweet as ReactTweet } from "react-tweet"
import type { TweetComponents } from "react-tweet"
const components: TweetComponents = {
AvatarImg: (props) => <Image {...props} />,
MediaImg: (props) => <Image {...props} fill unoptimized />,
}
export function Tweet({ id }: { id: string }) {
return <ReactTweet id={id} components={components} />
}
+4
View File
@@ -32,6 +32,7 @@ import { APlayer } from "~/components/ui/APlayer"
import { ZoomedImage } from "~/components/ui/Image"
import { Mention } from "~/components/ui/Mention"
import { Mermaid } from "~/components/ui/Mermaid"
import { Tweet } from "~/components/ui/Tweet"
import { rehypeAudio } from "./rehype-audio"
import {
@@ -41,6 +42,7 @@ import {
} from "./rehype-custom-wrapper"
import { rehypeImage } from "./rehype-image"
import { rehypeTable } from "./rehype-table"
import { rehypeTweet } from "./rehype-tweet"
import { rehypeWrapCode } from "./rehype-wrap-code"
import { rehypeExternalLink } from "./rehyper-external-link"
import { remarkCallout } from "./remark-callout"
@@ -165,6 +167,7 @@ export const renderPageContent = (
.use(rehypeExternalLink)
.use(rehypeWrapCode)
.use(rehypeInferDescriptionMeta)
.use(rehypeTweet)
.use(rehypeRewrite, {
selector: "p, li",
rewrite: (node: any) => {
@@ -213,6 +216,7 @@ export const renderPageContent = (
mention: Mention,
mermaid: Mermaid,
audio: APlayer,
tweet: Tweet,
style: Style,
} as any,
})
+31
View File
@@ -0,0 +1,31 @@
import { Root } from "rehype-raw"
import { Plugin } from "unified"
import { visit } from "unist-util-visit"
export const rehypeTweet: Plugin<Array<void>, Root> = () => (tree) => {
visit(tree, { tagName: "a" }, (node, i, parent) => {
if (
!parent ||
!("tagName" in parent) ||
parent.tagName !== "p" ||
parent.children.length > 1
)
return
const tweetRegex =
/^https?:\/\/(?:www\.)?twitter\.com\/\w+\/status\/(\d+)(?:\?.*)?(?:#.*)?$/
const href = node.properties?.href
if (typeof href === "string") {
const match = href.match(tweetRegex)
if (match && match[0] === href) {
const tweetId = match[1]
node.tagName = "tweet"
node.properties = {
id: tweetId,
}
}
}
})
}