Skip to content

Commit

Permalink
Improve mergePaths plugin performance on large files
Browse files Browse the repository at this point in the history
  • Loading branch information
Jussi Timonen committed Sep 27, 2023
1 parent ad3e604 commit d9b4580
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions plugins/mergePaths.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

const { detachNodeFromParent } = require('../lib/xast.js');
const { collectStylesheet, computeStyle } = require('../lib/style.js');
const { path2js, js2path, intersects } = require('./_path.js');

Expand All @@ -26,7 +25,15 @@ exports.fn = (root, params) => {
element: {
enter: (node) => {
let prevChild = null;
let prevPathJS = null;

const saveCurrent = () => {
js2path(prevChild, prevPathJS, {
floatPrecision,
noSpaceAfterFlags,
});
prevPathJS = null;
};
for (const child of node.children) {
// skip if previous element is not path or contains animation elements
if (
Expand All @@ -36,6 +43,9 @@ exports.fn = (root, params) => {
prevChild.children.length !== 0 ||
prevChild.attributes.d == null
) {
if (prevPathJS) {
saveCurrent();
}
prevChild = child;
continue;
}
Expand All @@ -47,6 +57,9 @@ exports.fn = (root, params) => {
child.children.length !== 0 ||
child.attributes.d == null
) {
if (prevPathJS) {
saveCurrent();
}
prevChild = child;
continue;
}
Expand All @@ -58,10 +71,12 @@ exports.fn = (root, params) => {
computedStyle['marker-mid'] ||
computedStyle['marker-end']
) {
if (prevPathJS) {
saveCurrent();
}
prevChild = child;
continue;
}

const prevChildAttrs = Object.keys(prevChild.attributes);
const childAttrs = Object.keys(child.attributes);
let attributesAreEqual = prevChildAttrs.length === childAttrs.length;
Expand All @@ -75,23 +90,32 @@ exports.fn = (root, params) => {
}
}
}
const prevPathJS = path2js(prevChild);
const hasPrevPath = !!prevPathJS;
if (!hasPrevPath) prevPathJS = path2js(prevChild);
const curPathJS = path2js(child);

if (
attributesAreEqual &&
(force || !intersects(prevPathJS, curPathJS))
) {
js2path(prevChild, prevPathJS.concat(curPathJS), {
floatPrecision,
noSpaceAfterFlags,
});
detachNodeFromParent(child, node);
prevPathJS.push(...curPathJS);
child._deleteAfterwards = 1;

continue;
}

if (hasPrevPath) {
saveCurrent();
}
prevPathJS = null;
prevChild = child;
}
if (prevPathJS) {
saveCurrent();
}
node.children = node.children.filter(
(child) => !child._deleteAfterwards
);
},
},
};
Expand Down

0 comments on commit d9b4580

Please sign in to comment.