-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
69 lines (56 loc) · 1.59 KB
/
script.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
import { unified } from "unified";
import assert from "node:assert";
import rehypeParse from "rehype-parse";
import rehypeStringify from "rehype-stringify";
import { visitParents } from "unist-util-visit-parents";
/** @type {import("@astrojs/markdown-remark").RemarkPlugin} */
const plugin = () => root => {
console.dir({ root }, { depth: null });
visitParents(
root,
node => node.type === "element" && node.tagName === "img",
node => {
assert(node.type === "element");
assert(node.tagName === "img");
node.properties ??= {};
node.properties.loading = "lazy";
},
);
visitParents(
root,
node => node.type === "element" && node.tagName === "iframe",
(node, parents) => {
console.log({ node, parents });
assert(node.type === "element");
assert(node.tagName === "iframe");
const parent = parents.at(-1);
assert(parent);
if (parent.properties.class?.split(/\s+/g).includes("embed-container")) {
return;
}
const index = parent.children.indexOf(node);
assert(index !== -1);
/** @type {import("hast").Element} */
const wrapperNode = {
tagName: "div",
type: "element",
properties: {
class: "embed-container",
},
children: [node],
};
console.log({ node, parent, index, wrapperNode });
const oldChildren = parent.children;
parent.children.splice(index, 1, wrapperNode);
console.log({ oldChildren, children: parent.children });
},
);
return root;
};
const compiler = unified().use(rehypeParse).use(plugin).use(rehypeStringify);
console.log(
compiler.processSync(`
<img src="a">
<iframe src="a"></iframe>
`),
);