-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
37 lines (31 loc) · 959 Bytes
/
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
const visit = require("unist-util-visit")
const h = require("hastscript")
function rehypeFigure(option) {
const className = (option && option.className) || "rehype-figure"
function buildFigure({ properties }) {
const figure = h("figure", { class: className }, [
h("img", { ...properties }),
properties.alt && properties.alt.trim().length > 0
? h("figcaption", properties.alt)
: "",
])
return figure
}
return function (tree) {
visit(tree, { tagName: "p" }, (node, index) => {
const images = node.children
.filter((n) => n.tagName === "img")
.map((img) => buildFigure(img))
if (images.length === 0) return
tree.children[index] =
images.length === 1
? images[0]
: (tree.children[index] = h(
"div",
{ class: `${className}-container` },
images
))
})
}
}
module.exports = rehypeFigure