Skip to content

Commit

Permalink
Improve mergePaths performance on large files
Browse files Browse the repository at this point in the history
  • Loading branch information
jussiKC committed Apr 25, 2023
1 parent 73f7002 commit 866352a
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 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,16 @@ 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 +44,9 @@ exports.fn = (root, params) => {
prevChild.children.length !== 0 ||
prevChild.attributes.d == null
) {
if(prevPathJS) {
saveCurrent();
}
prevChild = child;
continue;
}
Expand All @@ -47,6 +58,9 @@ exports.fn = (root, params) => {
child.children.length !== 0 ||
child.attributes.d == null
) {
if(prevPathJS) {
saveCurrent();
}
prevChild = child;
continue;
}
Expand All @@ -58,10 +72,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 +91,30 @@ 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 866352a

Please sign in to comment.