1 | 'use strict';
|
---|
2 |
|
---|
3 | const { detachNodeFromParent } = require('../lib/xast.js');
|
---|
4 | const { editorNamespaces } = require('./_collections.js');
|
---|
5 |
|
---|
6 | exports.type = 'visitor';
|
---|
7 | exports.name = 'removeEditorsNSData';
|
---|
8 | exports.active = true;
|
---|
9 | exports.description = 'removes editors namespaces, elements and attributes';
|
---|
10 |
|
---|
11 | /**
|
---|
12 | * Remove editors namespaces, elements and attributes.
|
---|
13 | *
|
---|
14 | * @example
|
---|
15 | * <svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd">
|
---|
16 | * <sodipodi:namedview/>
|
---|
17 | * <path sodipodi:nodetypes="cccc"/>
|
---|
18 | *
|
---|
19 | * @author Kir Belevich
|
---|
20 | *
|
---|
21 | * @type {import('../lib/types').Plugin<{
|
---|
22 | * additionalNamespaces?: Array<string>
|
---|
23 | * }>}
|
---|
24 | */
|
---|
25 | exports.fn = (_root, params) => {
|
---|
26 | let namespaces = editorNamespaces;
|
---|
27 | if (Array.isArray(params.additionalNamespaces)) {
|
---|
28 | namespaces = [...editorNamespaces, ...params.additionalNamespaces];
|
---|
29 | }
|
---|
30 | /**
|
---|
31 | * @type {Array<string>}
|
---|
32 | */
|
---|
33 | const prefixes = [];
|
---|
34 | return {
|
---|
35 | element: {
|
---|
36 | enter: (node, parentNode) => {
|
---|
37 | // collect namespace aliases from svg element
|
---|
38 | if (node.name === 'svg') {
|
---|
39 | for (const [name, value] of Object.entries(node.attributes)) {
|
---|
40 | if (name.startsWith('xmlns:') && namespaces.includes(value)) {
|
---|
41 | prefixes.push(name.slice('xmlns:'.length));
|
---|
42 | // <svg xmlns:sodipodi="">
|
---|
43 | delete node.attributes[name];
|
---|
44 | }
|
---|
45 | }
|
---|
46 | }
|
---|
47 | // remove editor attributes, for example
|
---|
48 | // <* sodipodi:*="">
|
---|
49 | for (const name of Object.keys(node.attributes)) {
|
---|
50 | if (name.includes(':')) {
|
---|
51 | const [prefix] = name.split(':');
|
---|
52 | if (prefixes.includes(prefix)) {
|
---|
53 | delete node.attributes[name];
|
---|
54 | }
|
---|
55 | }
|
---|
56 | }
|
---|
57 | // remove editor elements, for example
|
---|
58 | // <sodipodi:*>
|
---|
59 | if (node.name.includes(':')) {
|
---|
60 | const [prefix] = node.name.split(':');
|
---|
61 | if (prefixes.includes(prefix)) {
|
---|
62 | detachNodeFromParent(node, parentNode);
|
---|
63 | }
|
---|
64 | }
|
---|
65 | },
|
---|
66 | },
|
---|
67 | };
|
---|
68 | };
|
---|