cleanupEnableBackground.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. const { visit } = require('../lib/xast.js');
  3. exports.type = 'visitor';
  4. exports.name = 'cleanupEnableBackground';
  5. exports.active = true;
  6. exports.description =
  7. 'remove or cleanup enable-background attribute when possible';
  8. /**
  9. * Remove or cleanup enable-background attr which coincides with a width/height box.
  10. *
  11. * @see https://www.w3.org/TR/SVG11/filters.html#EnableBackgroundProperty
  12. *
  13. * @example
  14. * <svg width="100" height="50" enable-background="new 0 0 100 50">
  15. * ⬇
  16. * <svg width="100" height="50">
  17. *
  18. * @author Kir Belevich
  19. *
  20. * @type {import('../lib/types').Plugin<void>}
  21. */
  22. exports.fn = (root) => {
  23. const regEnableBackground =
  24. /^new\s0\s0\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)$/;
  25. let hasFilter = false;
  26. visit(root, {
  27. element: {
  28. enter: (node) => {
  29. if (node.name === 'filter') {
  30. hasFilter = true;
  31. }
  32. },
  33. },
  34. });
  35. return {
  36. element: {
  37. enter: (node) => {
  38. if (node.attributes['enable-background'] == null) {
  39. return;
  40. }
  41. if (hasFilter) {
  42. if (
  43. (node.name === 'svg' ||
  44. node.name === 'mask' ||
  45. node.name === 'pattern') &&
  46. node.attributes.width != null &&
  47. node.attributes.height != null
  48. ) {
  49. const match =
  50. node.attributes['enable-background'].match(regEnableBackground);
  51. if (
  52. match != null &&
  53. node.attributes.width === match[1] &&
  54. node.attributes.height === match[3]
  55. ) {
  56. if (node.name === 'svg') {
  57. delete node.attributes['enable-background'];
  58. } else {
  59. node.attributes['enable-background'] = 'new';
  60. }
  61. }
  62. }
  63. } else {
  64. //we don't need 'enable-background' if we have no filters
  65. delete node.attributes['enable-background'];
  66. }
  67. },
  68. },
  69. };
  70. };