cleanupAttrs.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. exports.name = 'cleanupAttrs';
  3. exports.type = 'visitor';
  4. exports.active = true;
  5. exports.description =
  6. 'cleanups attributes from newlines, trailing and repeating spaces';
  7. const regNewlinesNeedSpace = /(\S)\r?\n(\S)/g;
  8. const regNewlines = /\r?\n/g;
  9. const regSpaces = /\s{2,}/g;
  10. /**
  11. * Cleanup attributes values from newlines, trailing and repeating spaces.
  12. *
  13. * @author Kir Belevich
  14. *
  15. * @type {import('../lib/types').Plugin<{
  16. * newlines?: boolean,
  17. * trim?: boolean,
  18. * spaces?: boolean
  19. * }>}
  20. */
  21. exports.fn = (root, params) => {
  22. const { newlines = true, trim = true, spaces = true } = params;
  23. return {
  24. element: {
  25. enter: (node) => {
  26. for (const name of Object.keys(node.attributes)) {
  27. if (newlines) {
  28. // new line which requires a space instead of themselve
  29. node.attributes[name] = node.attributes[name].replace(
  30. regNewlinesNeedSpace,
  31. (match, p1, p2) => p1 + ' ' + p2
  32. );
  33. // simple new line
  34. node.attributes[name] = node.attributes[name].replace(
  35. regNewlines,
  36. ''
  37. );
  38. }
  39. if (trim) {
  40. node.attributes[name] = node.attributes[name].trim();
  41. }
  42. if (spaces) {
  43. node.attributes[name] = node.attributes[name].replace(
  44. regSpaces,
  45. ' '
  46. );
  47. }
  48. }
  49. },
  50. },
  51. };
  52. };