addAttributesToSVGElement.js 2.0 KB

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