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 authored and SethFalco committed Dec 25, 2023
1 parent a287a2a commit 3d0d8f0
Showing 1 changed file with 44 additions and 8 deletions.
52 changes: 44 additions & 8 deletions plugins/mergePaths.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
'use strict';

/**
* @typedef {import("../lib/types").PathDataItem} PathDataItem
* @typedef {import('../lib/types').XastChild} XastChild
* @typedef {import('../lib/types').XastElement} XastElement
*/

const { collectStylesheet, computeStyle } = require('../lib/style.js');
Expand Down Expand Up @@ -35,6 +37,19 @@ exports.fn = (root, params) => {
/** @type {XastChild[]} */
const elementsToRemove = [];
let prevChild = node.children[0];
let prevPathJS = null;

/**
* @param {XastElement} child
* @param {PathDataItem[]} pathData
*/
const savePath = (child, pathData) => {
js2path(child, pathData, {
floatPrecision,
noSpaceAfterFlags,
});
prevPathJS = null;
};

for (let i = 1; i < node.children.length; i++) {
const child = node.children[i];
Expand All @@ -45,6 +60,9 @@ exports.fn = (root, params) => {
prevChild.children.length !== 0 ||
prevChild.attributes.d == null
) {
if (prevPathJS && prevChild.type === 'element') {
savePath(prevChild, prevPathJS);
}
prevChild = child;
continue;
}
Expand All @@ -55,6 +73,9 @@ exports.fn = (root, params) => {
child.children.length !== 0 ||
child.attributes.d == null
) {
if (prevPathJS) {
savePath(prevChild, prevPathJS);
}
prevChild = child;
continue;
}
Expand All @@ -65,12 +86,17 @@ exports.fn = (root, params) => {
computedStyle['marker-mid'] ||
computedStyle['marker-end']
) {
if (prevPathJS) {
savePath(prevChild, prevPathJS);
}
prevChild = child;
continue;
}

const childAttrs = Object.keys(child.attributes);
if (childAttrs.length !== Object.keys(prevChild.attributes).length) {
if (prevPathJS) {
savePath(prevChild, prevPathJS);
}
prevChild = child;
continue;
}
Expand All @@ -84,25 +110,35 @@ exports.fn = (root, params) => {
});

if (areAttrsEqual) {
if (prevPathJS) {
savePath(prevChild, prevPathJS);
}
prevChild = child;
continue;
}

const prevPathJS = path2js(prevChild);
const hasPrevPath = !!prevPathJS;
const curPathJS = path2js(child);
if (!hasPrevPath) {
prevPathJS = path2js(prevChild);
}

if (force || !intersects(prevPathJS, curPathJS)) {
if (prevPathJS && (force || !intersects(prevPathJS, curPathJS))) {
prevPathJS.push(...curPathJS);
js2path(prevChild, prevPathJS, {
floatPrecision,
noSpaceAfterFlags,
});

elementsToRemove.push(child);
continue;
}

if (hasPrevPath && prevPathJS) {
savePath(prevChild, prevPathJS);
}

prevChild = child;
prevPathJS = null;
}

if (prevPathJS && prevChild.type === 'element') {
savePath(prevChild, prevPathJS);
}

node.children = node.children.filter(
Expand Down

0 comments on commit 3d0d8f0

Please sign in to comment.