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