mergePaths.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'merges multiple paths in one if possible';
  5. exports.params = {
  6. collapseRepeated: true,
  7. force: false,
  8. leadingZero: true,
  9. negativeExtraSpace: true,
  10. noSpaceAfterFlags: true
  11. };
  12. var path2js = require('./_path.js').path2js,
  13. js2path = require('./_path.js').js2path,
  14. intersects = require('./_path.js').intersects;
  15. /**
  16. * Merge multiple Paths into one.
  17. *
  18. * @param {Object} item current iteration item
  19. * @return {Boolean} if false, item will be filtered out
  20. *
  21. * @author Kir Belevich, Lev Solntsev
  22. */
  23. exports.fn = function(item, params) {
  24. if (!item.isElem() || item.isEmpty()) return;
  25. var prevContentItem = null,
  26. prevContentItemKeys = null;
  27. item.content = item.content.filter(function(contentItem) {
  28. if (prevContentItem &&
  29. prevContentItem.isElem('path') &&
  30. prevContentItem.isEmpty() &&
  31. prevContentItem.hasAttr('d') &&
  32. contentItem.isElem('path') &&
  33. contentItem.isEmpty() &&
  34. contentItem.hasAttr('d')
  35. ) {
  36. if (!prevContentItemKeys) {
  37. prevContentItemKeys = Object.keys(prevContentItem.attrs);
  38. }
  39. var contentItemAttrs = Object.keys(contentItem.attrs),
  40. equalData = prevContentItemKeys.length == contentItemAttrs.length &&
  41. contentItemAttrs.every(function(key) {
  42. return key == 'd' ||
  43. prevContentItem.hasAttr(key) &&
  44. prevContentItem.attr(key).value == contentItem.attr(key).value;
  45. }),
  46. prevPathJS = path2js(prevContentItem),
  47. curPathJS = path2js(contentItem);
  48. if (equalData && (params.force || !intersects(prevPathJS, curPathJS))) {
  49. js2path(prevContentItem, prevPathJS.concat(curPathJS), params);
  50. return false;
  51. }
  52. }
  53. prevContentItem = contentItem;
  54. prevContentItemKeys = null;
  55. return true;
  56. });
  57. };