feat: more embed support (#560)

This commit is contained in:
Birdgg
2023-05-19 15:35:04 +01:00
committed by GitHub
parent f903699842
commit add4afcabc
13 changed files with 326 additions and 36 deletions
+5
View File
@@ -0,0 +1,5 @@
import { GithubRepo as ReactGithubRepo } from "@birdgg/react-github"
export default function GithubRepo({ repo }: { repo: string }) {
return <ReactGithubRepo repo={repo} />
}
@@ -0,0 +1,23 @@
import type { Transformer } from "../rehype-embed"
import { generateIframeHTML, isHostIncludes } from "./utils"
export const CodeSandboxTransformer: Transformer = {
name: "CodeSandbox",
shouldTransform(url) {
const { host, pathname } = url
return isHostIncludes("codesandbox.io", host) && pathname.includes("/s/")
},
getHTML(url) {
return generateIframeHTML({
name: "codesandbox",
src: url.toString().replace("/s/", "/embed/"),
height: "500px",
width: "100%",
allow:
"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking",
sandbox:
"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts",
})
},
}
+21
View File
@@ -0,0 +1,21 @@
import { match } from "path-to-regexp"
import type { Transformer } from "../rehype-embed"
import { isHostIncludes } from "./utils"
export const GithubRepoTransformer: Transformer = {
name: "GithubRepo",
shouldTransform(url) {
const { host } = url
return isHostIncludes("github.com", host)
},
getHTML(url) {
const matched = match<{ user: string; repo: string }>("/:user/:repo")(
url.pathname,
)
if (!matched) return
const repo = `${matched.params.user}/${matched.params.repo}`
return `<github-repo repo="${repo}"/>`
},
}
@@ -0,0 +1,57 @@
import type { Transformer } from "../rehype-embed"
import { generateIframeHTML, includesSomeOfArray } from "./utils"
const parseLink = (url: string) => {
const rules = [
["music.163.com.*playlist", "0"],
["music.163.com.*album", "1"],
["music.163.com.*song", "2"],
]
for (let rule of rules) {
let patt = new RegExp(rule[0])
let res = patt.exec(url)
if (res !== null) {
return {
type: rule[1],
}
}
}
return {}
}
const getIFrame = (url: URL) => {
const { pathname, searchParams } = url
const isSong = pathname.includes("/song")
const id = searchParams.get("id")
const { type } = parseLink(url.toString())
const height = isSong ? 66 : 250
return {
src: `https://music.163.com/outchain/player?type=${type}&id=${id}&auto=0&height=${height}`,
height: isSong ? 86 : 250,
}
}
export const NetEaseMusicTransformer: Transformer = {
name: "NetEaseMusic",
shouldTransform(url) {
const { host, pathname } = url
return (
host === "music.163.com" &&
includesSomeOfArray(pathname, ["/song", "/playlist", "/album"])
)
},
getHTML(url) {
const iframe = getIFrame(url)
return generateIframeHTML({
name: "netease",
src: iframe.src,
height: iframe.height + "px",
width: "330px",
allow:
"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",
})
},
}
+19
View File
@@ -0,0 +1,19 @@
import { match } from "path-to-regexp"
import type { Transformer } from "../rehype-embed"
import { isHostIncludes } from "./utils"
export const TweetTransformer: Transformer = {
name: "Tweet",
shouldTransform(url) {
const { host, pathname } = url
return isHostIncludes("twitter.com", host) && pathname.includes("/status/")
},
getHTML(url) {
const { pathname } = url
const matched = match<{ id: string }>("/:user/status/:id")(pathname)
if (!matched) return
return `<tweet id=${matched.params.id}/>`
},
}
@@ -0,0 +1,62 @@
import type { Transformer } from "../rehype-embed"
import { generateIframeHTML, isHostIncludes } from "./utils"
const getTimeValueInSeconds = (timeValue: string) => {
if (Number(timeValue).toString() === timeValue) {
return timeValue
}
const {
2: hours = "0",
4: minutes = "0",
6: seconds = "0",
} = timeValue.match(/((\d*)h)?((\d*)m)?((\d*)s)?/)!
return String((Number(hours) * 60 + Number(minutes)) * 60 + Number(seconds))
}
const getYouTubeIFrameSrc = (url: URL) => {
const id =
url.host === "youtu.be" ? url.pathname.slice(1) : url.searchParams.get("v")
const embedUrl = new URL(`https://www.youtube-nocookie.com/embed/${id}?rel=0`)
url.searchParams.forEach((value, name) => {
if (name === "v") {
return
}
if (name === "t") {
embedUrl.searchParams.append("start", getTimeValueInSeconds(value))
} else {
embedUrl.searchParams.append(name, value)
}
})
return embedUrl.toString()
}
export const YoutubeTransformer: Transformer = {
name: "Youtube",
shouldTransform(url) {
const { host, pathname, searchParams } = url
return (
host === "youtu.be" ||
(isHostIncludes("youtube.com", host) &&
pathname.includes("/watch") &&
Boolean(searchParams.get("v")))
)
},
getHTML(url) {
return generateIframeHTML({
name: "youtube",
src: getYouTubeIFrameSrc(url),
width: "100%",
height: "410px",
allow:
"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",
allowFullScreen: true,
})
},
}
+14
View File
@@ -0,0 +1,14 @@
import type { Transformer } from "../rehype-embed"
import { CodeSandboxTransformer } from "./CodeSandBox"
import { GithubRepoTransformer } from "./Github"
import { NetEaseMusicTransformer } from "./NetEaseMusic"
import { TweetTransformer } from "./Tweet"
import { YoutubeTransformer } from "./Youtube"
export const transformers: Transformer[] = [
CodeSandboxTransformer,
TweetTransformer,
GithubRepoTransformer,
YoutubeTransformer,
NetEaseMusicTransformer,
]
+34
View File
@@ -0,0 +1,34 @@
import { IframeHTMLAttributes } from "react"
interface IframeProps extends IframeHTMLAttributes<HTMLIFrameElement> {
name: string
}
export const isHostIncludes = (domain: string, host: string) => {
return [domain, `www.${domain}`].includes(host)
}
export const includesSomeOfArray = (string: string, array: string[]) =>
array.some((item) => string.includes(item))
export const generateIframeHTML = ({
name,
src,
height,
width,
style,
...attributes
}: IframeProps) => {
const iframeStyle =
'style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"'
const iframeAttributes = Object.entries(attributes)
.map(([key, value]) => {
if (key === "allowFullScreen") return key.toLowerCase()
return `${key.toLowerCase()}="${value}"`
})
.join(" ")
return `<div class="xlog-post-content-${name}" style="position: relative; width: ${width}; height: ${height}; margin: 1rem auto;">
<iframe src="${src}" border="0" ${iframeStyle} ${iframeAttributes}></iframe>
</div>`
}
+8 -2
View File
@@ -31,15 +31,16 @@ import { unified } from "unified"
import { ZoomedImage } from "~/components/ui/Image"
import { transformers } from "./embed-transformers"
import { rehypeAudio } from "./rehype-audio"
import {
allowedCustomWrappers,
defaultRules,
rehypeCustomWrapper,
} from "./rehype-custom-wrapper"
import { rehypeEmbed } from "./rehype-embed"
import { rehypeImage } from "./rehype-image"
import { rehypeTable } from "./rehype-table"
import { rehypeTweet } from "./rehype-tweet"
import { rehypeVideo } from "./rehype-video"
import { rehypeWrapCode } from "./rehype-wrap-code"
import { rehypeExternalLink } from "./rehyper-external-link"
@@ -53,7 +54,9 @@ const Style = dynamic(() => import("~/components/common/Style"))
const Mention = dynamic(() => import("~/components/ui/Mention"))
const Mermaid = dynamic(() => import("~/components/ui/Mermaid"))
const Tweet = dynamic(() => import("~/components/ui/Tweet"))
const GithubRepo = dynamic(() => import("~/components/ui/GithubRepo"))
const APlayer = dynamic(() => import("~/components/ui/APlayer"))
const DPlayer = dynamic(() => import("~/components/ui/DPlayer"), {
ssr: false,
})
@@ -176,7 +179,9 @@ export const renderPageContent = (
.use(rehypeExternalLink)
.use(rehypeWrapCode)
.use(rehypeInferDescriptionMeta)
.use(rehypeTweet)
.use(rehypeEmbed, {
transformers,
})
.use(rehypeRewrite, {
selector: "p, li",
rewrite: (node: any) => {
@@ -227,6 +232,7 @@ export const renderPageContent = (
audio: APlayer,
video: DPlayer,
tweet: Tweet,
"github-repo": GithubRepo,
style: Style,
} as any,
})
+41
View File
@@ -0,0 +1,41 @@
import { fromHtml } from "hast-util-from-html"
import { Root } from "rehype-raw"
import { Plugin } from "unified"
import { visit } from "unist-util-visit"
export interface Transformer {
name: string
shouldTransform: (url: URL) => boolean
getHTML: (url: URL) => string | undefined
}
export const rehypeEmbed: Plugin<
Array<{ transformers: Transformer[] }>,
Root
> =
({ transformers }) =>
(tree) => {
visit(tree, { tagName: "a" }, (node, i, parent) => {
if (
!parent ||
!("tagName" in parent) ||
parent.tagName !== "p" ||
parent.children.length > 1
)
return
const href = node.properties?.href
if (typeof href === "string") {
const url = new URL(href)
for (const transformer of transformers) {
if (transformer.shouldTransform(url)) {
const html = transformer.getHTML(url)?.trim()
if (!html) return
const hast = fromHtml(html, { fragment: true }).children[0]
Object.assign(parent, hast)
}
}
}
})
}
-31
View File
@@ -1,31 +0,0 @@
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]
parent.tagName = "tweet"
parent.properties = {
id: tweetId,
}
}
}
})
}