removeEmptyText.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const { detachNodeFromParent } = require('../lib/xast.js');
  3. exports.name = 'removeEmptyText';
  4. exports.type = 'visitor';
  5. exports.active = true;
  6. exports.description = 'removes empty <text> elements';
  7. /**
  8. * Remove empty Text elements.
  9. *
  10. * @see https://www.w3.org/TR/SVG11/text.html
  11. *
  12. * @example
  13. * Remove empty text element:
  14. * <text/>
  15. *
  16. * Remove empty tspan element:
  17. * <tspan/>
  18. *
  19. * Remove tref with empty xlink:href attribute:
  20. * <tref xlink:href=""/>
  21. *
  22. * @author Kir Belevich
  23. *
  24. * @type {import('../lib/types').Plugin<{
  25. * text?: boolean,
  26. * tspan?: boolean,
  27. * tref?: boolean
  28. * }>}
  29. */
  30. exports.fn = (root, params) => {
  31. const { text = true, tspan = true, tref = true } = params;
  32. return {
  33. element: {
  34. enter: (node, parentNode) => {
  35. // Remove empty text element
  36. if (text && node.name === 'text' && node.children.length === 0) {
  37. detachNodeFromParent(node, parentNode);
  38. }
  39. // Remove empty tspan element
  40. if (tspan && node.name === 'tspan' && node.children.length === 0) {
  41. detachNodeFromParent(node, parentNode);
  42. }
  43. // Remove tref with empty xlink:href attribute
  44. if (
  45. tref &&
  46. node.name === 'tref' &&
  47. node.attributes['xlink:href'] == null
  48. ) {
  49. detachNodeFromParent(node, parentNode);
  50. }
  51. },
  52. },
  53. };
  54. };