-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
removeUselessDefs.js
62 lines (58 loc) · 1.64 KB
/
removeUselessDefs.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
import { detachNodeFromParent } from '../lib/xast.js';
import { elemsGroups } from './_collections.js';
/**
* @typedef {import('../lib/types.js').XastElement} XastElement
*/
export const name = 'removeUselessDefs';
export const description = 'removes elements in <defs> without id';
/**
* Removes content of defs and properties that aren't rendered directly without ids.
*
* @author Lev Solntsev
*
* @type {import('./plugins-types.js').Plugin<'removeUselessDefs'>}
*/
export const fn = () => {
return {
element: {
enter: (node, parentNode) => {
if (
node.name === 'defs' ||
(elemsGroups.nonRendering.has(node.name) &&
node.attributes.id == null)
) {
/**
* @type {XastElement[]}
*/
const usefulNodes = [];
collectUsefulNodes(node, usefulNodes);
if (usefulNodes.length === 0) {
detachNodeFromParent(node, parentNode);
}
// TODO remove legacy parentNode in v4
for (const usefulNode of usefulNodes) {
Object.defineProperty(usefulNode, 'parentNode', {
writable: true,
value: node,
});
}
node.children = usefulNodes;
}
},
},
};
};
/**
* @type {(node: XastElement, usefulNodes: XastElement[]) => void}
*/
const collectUsefulNodes = (node, usefulNodes) => {
for (const child of node.children) {
if (child.type === 'element') {
if (child.attributes.id != null || child.name === 'style') {
usefulNodes.push(child);
} else {
collectUsefulNodes(child, usefulNodes);
}
}
}
};