-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (67 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const visit = require("unist-util-visit")
const isYoutubeEmbedLink = (node) => {
if (!node.url) {
return false
}
try {
const {host} = new URL(node.url)
const isYoutubeUrl = host.includes("youtube")
const isLink = node.type === "link"
const isEmbedLink =
node.children.length === 1 &&
node.children[0].value.toLowerCase().includes("embed")
return isLink && isEmbedLink && isYoutubeUrl
} catch (e) {
return false
}
}
const getEmbedCode = (url) => {
const urlObject = new URL(url)
const videoId = urlObject.searchParams.get("v") // https://www.youtube.com/watch?v=GV3MeVtOBGw
const {host} = urlObject
// Attributes
const src = host && videoId ? `https://${host}/embed/${videoId}` : url
const style = "width: 100%;aspect-ratio: 16/9;"
const allow =
"accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture"
return `<iframe src="${src}" frameborder="0" allow="${allow}" allowfullscreen style="${style}"></iframe>`
}
module.exports = async ({markdownAST, cache, reporter}, pluginOptions) => {
try {
const youtubeElements = []
visit(markdownAST, "paragraph", (paragraphNode) => {
if (paragraphNode.children.length !== 1) {
return
}
const [node] = paragraphNode.children
if (!isYoutubeEmbedLink(node)) {
return
}
youtubeElements.push(node)
})
await Promise.all(
youtubeElements.map(async (node) => {
try {
let html = await cache.get(node.url)
if (!html) {
html = getEmbedCode(node.url)
await cache.set(node.url, html)
}
node.type = `html`
node.value = html
node.children = undefined
if (pluginOptions.debug) {
reporter.success(`remark-youtube: EMBED OK ${node.url}`)
}
} catch (e) {
if (pluginOptions.debug) {
reporter.warn(`remark-youtube: EMBED NOK ${node.url}`)
}
}
})
)
} catch (e) {
reporter.warn(`remark-youtube: ${e.message}`)
}
return markdownAST
}