1 | 'use strict';
|
---|
2 |
|
---|
3 | exports.name = 'addAttributesToSVGElement';
|
---|
4 | exports.type = 'visitor';
|
---|
5 | exports.active = false;
|
---|
6 | exports.description = 'adds attributes to an outer <svg> element';
|
---|
7 |
|
---|
8 | var ENOCLS = `Error in plugin "addAttributesToSVGElement": absent parameters.
|
---|
9 | It should have a list of "attributes" or one "attribute".
|
---|
10 | Config example:
|
---|
11 |
|
---|
12 | plugins: [
|
---|
13 | {
|
---|
14 | name: 'addAttributesToSVGElement',
|
---|
15 | params: {
|
---|
16 | attribute: "mySvg"
|
---|
17 | }
|
---|
18 | }
|
---|
19 | ]
|
---|
20 |
|
---|
21 | plugins: [
|
---|
22 | {
|
---|
23 | name: 'addAttributesToSVGElement',
|
---|
24 | params: {
|
---|
25 | attributes: ["mySvg", "size-big"]
|
---|
26 | }
|
---|
27 | }
|
---|
28 | ]
|
---|
29 |
|
---|
30 | plugins: [
|
---|
31 | {
|
---|
32 | name: 'addAttributesToSVGElement',
|
---|
33 | params: {
|
---|
34 | attributes: [
|
---|
35 | {
|
---|
36 | focusable: false
|
---|
37 | },
|
---|
38 | {
|
---|
39 | 'data-image': icon
|
---|
40 | }
|
---|
41 | ]
|
---|
42 | }
|
---|
43 | }
|
---|
44 | ]
|
---|
45 | `;
|
---|
46 |
|
---|
47 | /**
|
---|
48 | * Add attributes to an outer <svg> element. Example config:
|
---|
49 | *
|
---|
50 | * @author April Arcus
|
---|
51 | *
|
---|
52 | * @type {import('../lib/types').Plugin<{
|
---|
53 | * attribute?: string | Record<string, null | string>,
|
---|
54 | * attributes?: Array<string | Record<string, null | string>>
|
---|
55 | * }>}
|
---|
56 | */
|
---|
57 | exports.fn = (root, params) => {
|
---|
58 | if (!Array.isArray(params.attributes) && !params.attribute) {
|
---|
59 | console.error(ENOCLS);
|
---|
60 | return null;
|
---|
61 | }
|
---|
62 | const attributes = params.attributes || [params.attribute];
|
---|
63 | return {
|
---|
64 | element: {
|
---|
65 | enter: (node, parentNode) => {
|
---|
66 | if (node.name === 'svg' && parentNode.type === 'root') {
|
---|
67 | for (const attribute of attributes) {
|
---|
68 | if (typeof attribute === 'string') {
|
---|
69 | if (node.attributes[attribute] == null) {
|
---|
70 | // @ts-ignore disallow explicit nullable attribute value
|
---|
71 | node.attributes[attribute] = undefined;
|
---|
72 | }
|
---|
73 | }
|
---|
74 | if (typeof attribute === 'object') {
|
---|
75 | for (const key of Object.keys(attribute)) {
|
---|
76 | if (node.attributes[key] == null) {
|
---|
77 | // @ts-ignore disallow explicit nullable attribute value
|
---|
78 | node.attributes[key] = attribute[key];
|
---|
79 | }
|
---|
80 | }
|
---|
81 | }
|
---|
82 | }
|
---|
83 | }
|
---|
84 | },
|
---|
85 | },
|
---|
86 | };
|
---|
87 | };
|
---|