1 | 'use strict';
|
---|
2 |
|
---|
3 | exports.type = 'visitor';
|
---|
4 | exports.name = 'removeUnusedNS';
|
---|
5 | exports.active = true;
|
---|
6 | exports.description = 'removes unused namespaces declaration';
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * Remove unused namespaces declaration from svg element
|
---|
10 | * which are not used in elements or attributes
|
---|
11 | *
|
---|
12 | * @author Kir Belevich
|
---|
13 | *
|
---|
14 | * @type {import('../lib/types').Plugin<void>}
|
---|
15 | */
|
---|
16 | exports.fn = () => {
|
---|
17 | /**
|
---|
18 | * @type {Set<string>}
|
---|
19 | */
|
---|
20 | const unusedNamespaces = new Set();
|
---|
21 | return {
|
---|
22 | element: {
|
---|
23 | enter: (node, parentNode) => {
|
---|
24 | // collect all namespaces from svg element
|
---|
25 | // (such as xmlns:xlink="http://www.w3.org/1999/xlink")
|
---|
26 | if (node.name === 'svg' && parentNode.type === 'root') {
|
---|
27 | for (const name of Object.keys(node.attributes)) {
|
---|
28 | if (name.startsWith('xmlns:')) {
|
---|
29 | const local = name.slice('xmlns:'.length);
|
---|
30 | unusedNamespaces.add(local);
|
---|
31 | }
|
---|
32 | }
|
---|
33 | }
|
---|
34 | if (unusedNamespaces.size !== 0) {
|
---|
35 | // preserve namespace used in nested elements names
|
---|
36 | if (node.name.includes(':')) {
|
---|
37 | const [ns] = node.name.split(':');
|
---|
38 | if (unusedNamespaces.has(ns)) {
|
---|
39 | unusedNamespaces.delete(ns);
|
---|
40 | }
|
---|
41 | }
|
---|
42 | // preserve namespace used in nested elements attributes
|
---|
43 | for (const name of Object.keys(node.attributes)) {
|
---|
44 | if (name.includes(':')) {
|
---|
45 | const [ns] = name.split(':');
|
---|
46 | unusedNamespaces.delete(ns);
|
---|
47 | }
|
---|
48 | }
|
---|
49 | }
|
---|
50 | },
|
---|
51 | exit: (node, parentNode) => {
|
---|
52 | // remove unused namespace attributes from svg element
|
---|
53 | if (node.name === 'svg' && parentNode.type === 'root') {
|
---|
54 | for (const name of unusedNamespaces) {
|
---|
55 | delete node.attributes[`xmlns:${name}`];
|
---|
56 | }
|
---|
57 | }
|
---|
58 | },
|
---|
59 | },
|
---|
60 | };
|
---|
61 | };
|
---|