1 | 'use strict';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * @typedef {import('../lib/types').XastElement} XastElement
|
---|
5 | */
|
---|
6 |
|
---|
7 | const { detachNodeFromParent } = require('../lib/xast.js');
|
---|
8 | const { elemsGroups } = require('./_collections.js');
|
---|
9 |
|
---|
10 | exports.type = 'visitor';
|
---|
11 | exports.name = 'removeUselessDefs';
|
---|
12 | exports.active = true;
|
---|
13 | exports.description = 'removes elements in <defs> without id';
|
---|
14 |
|
---|
15 | /**
|
---|
16 | * Removes content of defs and properties that aren't rendered directly without ids.
|
---|
17 | *
|
---|
18 | * @author Lev Solntsev
|
---|
19 | *
|
---|
20 | * @type {import('../lib/types').Plugin<void>}
|
---|
21 | */
|
---|
22 | exports.fn = () => {
|
---|
23 | return {
|
---|
24 | element: {
|
---|
25 | enter: (node, parentNode) => {
|
---|
26 | if (node.name === 'defs') {
|
---|
27 | /**
|
---|
28 | * @type {Array<XastElement>}
|
---|
29 | */
|
---|
30 | const usefulNodes = [];
|
---|
31 | collectUsefulNodes(node, usefulNodes);
|
---|
32 | if (usefulNodes.length === 0) {
|
---|
33 | detachNodeFromParent(node, parentNode);
|
---|
34 | }
|
---|
35 | // TODO remove in SVGO 3
|
---|
36 | for (const usefulNode of usefulNodes) {
|
---|
37 | // @ts-ignore parentNode is legacy
|
---|
38 | usefulNode.parentNode = node;
|
---|
39 | }
|
---|
40 | node.children = usefulNodes;
|
---|
41 | } else if (
|
---|
42 | elemsGroups.nonRendering.includes(node.name) &&
|
---|
43 | node.attributes.id == null
|
---|
44 | ) {
|
---|
45 | detachNodeFromParent(node, parentNode);
|
---|
46 | }
|
---|
47 | },
|
---|
48 | },
|
---|
49 | };
|
---|
50 | };
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * @type {(node: XastElement, usefulNodes: Array<XastElement>) => void}
|
---|
54 | */
|
---|
55 | const collectUsefulNodes = (node, usefulNodes) => {
|
---|
56 | for (const child of node.children) {
|
---|
57 | if (child.type === 'element') {
|
---|
58 | if (child.attributes.id != null || child.name === 'style') {
|
---|
59 | usefulNodes.push(child);
|
---|
60 | } else {
|
---|
61 | collectUsefulNodes(child, usefulNodes);
|
---|
62 | }
|
---|
63 | }
|
---|
64 | }
|
---|
65 | };
|
---|