-
-
Notifications
You must be signed in to change notification settings - Fork 848
/
rehype-filter.js
66 lines (58 loc) · 1.8 KB
/
rehype-filter.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
import {visit} from 'unist-util-visit'
/**
* @typedef {import('unist').Node} Node
* @typedef {import('hast').Root} Root
* @typedef {import('hast').Element} Element
*
* @callback AllowElement
* @param {Element} element
* @param {number} index
* @param {Element|Root} parent
* @returns {boolean|undefined}
*
* @typedef Options
* @property {Array<string>} [allowedElements]
* @property {Array<string>} [disallowedElements=[]]
* @property {AllowElement} [allowElement]
* @property {boolean} [unwrapDisallowed=false]
*/
/**
* @type {import('unified').Plugin<[Options], Root>}
*/
export default function rehypeFilter(options) {
if (options.allowedElements && options.disallowedElements) {
throw new TypeError(
'Only one of `allowedElements` and `disallowedElements` should be defined'
)
}
if (
options.allowedElements ||
options.disallowedElements ||
options.allowElement
) {
return (tree) => {
visit(tree, 'element', (node, index, parent_) => {
const parent = /** @type {Element|Root} */ (parent_)
/** @type {boolean|undefined} */
let remove
if (options.allowedElements) {
remove = !options.allowedElements.includes(node.tagName)
} else if (options.disallowedElements) {
remove = options.disallowedElements.includes(node.tagName)
}
if (!remove && options.allowElement && typeof index === 'number') {
remove = !options.allowElement(node, index, parent)
}
if (remove && typeof index === 'number') {
if (options.unwrapDisallowed && node.children) {
parent.children.splice(index, 1, ...node.children)
} else {
parent.children.splice(index, 1)
}
return index
}
return undefined
})
}
}
}