From c5becd1b5e9391a2def6f89df99e9bc33f4b399b Mon Sep 17 00:00:00 2001 From: Chris Angelico Date: Sat, 9 Nov 2024 03:04:39 +1100 Subject: [PATCH] Avoid (some) unnecessary removal and reinsertion of DOM elements --- factory.js | 12 ++++++++++-- package.json | 2 +- whatsnew.md | 4 ++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/factory.js b/factory.js index 7b8741b..43b2e51 100644 --- a/factory.js +++ b/factory.js @@ -334,7 +334,15 @@ export function replace_content(target, template) { if (t && typeof t === "object" && !Array.isArray(t) && !t.river) pristine = false; }); if (pristine) return target; - return set_content(target, content); + //At this point, we could just "return set_content(target, content);" but this would unnecessarily + //remove and reinsert DOM elements. This next step is far from perfect but will cope with common + //cases: the first N matching DOM elements will not be removed. TODO: Also check for the _last_ N + //matching elements, which will allow any single block of deletions/insertions. + let keep = 0; + while (keep < content.length && content[keep] instanceof Node && target.children[keep] === content[keep]) ++keep; + while (target.children.length > keep) target.removeChild(target.lastChild); + append_child(target, content.slice(keep)); + return target; } //TODO: Unify lindt and choc. Maybe have choc call lindt and then render? @@ -361,7 +369,7 @@ function autobind(obj, prop) { choc = new Proxy(choc, {get: autobind}); lindt = new Proxy(lindt, {get: autobind}); -choc.__version__ = "1.8.3"; +choc.__version__ = "1.9.0"; //For modules, make the main entry-point easily available. export default choc; diff --git a/package.json b/package.json index 3761854..23a7eb5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "chocfactory", - "version": "1.8.3", + "version": "1.9.0", "description": "Simple JS front end library", "main": "factory.js", "scripts": { diff --git a/whatsnew.md b/whatsnew.md index 2f037c8..1aa1cb8 100644 --- a/whatsnew.md +++ b/whatsnew.md @@ -1,5 +1,9 @@ ## Chocolate Factory version history +### v1.9.0 +* In Lindt mode, appending new children to a DOM element will not cause existing + elements to be removed and reinserted unnecessarily. + ### v1.8.3 * Importer bugfix: `//extcall` now works on arrow functions (JS only)