moveGroupAttrsToElems.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const { pathElems, referencesProps } = require('./_collections.js');
  3. exports.name = 'moveGroupAttrsToElems';
  4. exports.type = 'perItem';
  5. exports.active = true;
  6. exports.description = 'moves some group attributes to the content elements';
  7. const pathElemsWithGroupsAndText = [...pathElems, 'g', 'text'];
  8. /**
  9. * Move group attrs to the content elements.
  10. *
  11. * @example
  12. * <g transform="scale(2)">
  13. * <path transform="rotate(45)" d="M0,0 L10,20"/>
  14. * <path transform="translate(10, 20)" d="M0,10 L20,30"/>
  15. * </g>
  16. * ⬇
  17. * <g>
  18. * <path transform="scale(2) rotate(45)" d="M0,0 L10,20"/>
  19. * <path transform="scale(2) translate(10, 20)" d="M0,10 L20,30"/>
  20. * </g>
  21. *
  22. * @param {Object} item current iteration item
  23. * @return {Boolean} if false, item will be filtered out
  24. *
  25. * @author Kir Belevich
  26. */
  27. exports.fn = function (item) {
  28. // move group transform attr to content's pathElems
  29. if (
  30. item.type === 'element' &&
  31. item.name === 'g' &&
  32. item.children.length !== 0 &&
  33. item.attributes.transform != null &&
  34. Object.entries(item.attributes).some(
  35. ([name, value]) =>
  36. referencesProps.includes(name) && value.includes('url(')
  37. ) === false &&
  38. item.children.every(
  39. (inner) =>
  40. pathElemsWithGroupsAndText.includes(inner.name) &&
  41. inner.attributes.id == null
  42. )
  43. ) {
  44. for (const inner of item.children) {
  45. const value = item.attributes.transform;
  46. if (inner.attributes.transform != null) {
  47. inner.attributes.transform = value + ' ' + inner.attributes.transform;
  48. } else {
  49. inner.attributes.transform = value;
  50. }
  51. }
  52. delete item.attributes.transform;
  53. }
  54. };