Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ type Options = {
onNextNode?: NextNodeCallback;
// update the DOM using document.startViewTransition (default: false)
transition?: boolean;
// callback to ignore nodes (default: undefined)
// callback to leave nodes alone, on both the old and the new tree: an
// ignored node is never updated, moved or removed, and never counts as one
// of the old children the diff has to prune (default: undefined)
shouldIgnoreNode?: (node: Node | null) => boolean;
};
```
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"files": [
{
"path": "./build/index.js",
"maxSize": "1.5 kB"
"maxSize": "1.6 kB"
}
]
},
Expand Down
35 changes: 33 additions & 2 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1680,12 +1680,14 @@ describe("Diff test", () => {
],
ignoreId: true,
});
// Ignored means untouched: the node keeps its own content ("bar", not the
// incoming "bazz!") and stays put, while its siblings diff as usual.
expect(newHTML).toBe(
normalize(`
<html>
<head></head>
<body>
<div>bar</div>
<div>bar<div id="ignore">bar</div></div>
</body>
</html>
`),
Expand All @@ -1710,7 +1712,36 @@ describe("Diff test", () => {
<html>
<head></head>
<body>
<div><b>new</b></div>
<div><span id="ignore">skip</span><b>new</b></div>
</body>
</html>
`),
);
});

it("should options.shouldIgnoreNode keep an ignored node the incoming page does not list", async () => {
// The reason the option exists: a stylesheet injected at runtime (a lazy
// editor's CSS, a dev server's <style>) lives only in the live document,
// so the incoming page is always one node shorter. Counting it made the
// tail removal take it, and re-attaching a detached stylesheet leaves it
// pending — the page paints unstyled for a frame.
const [newHTML] = await testDiff({
oldHTMLString: `
<div>
<b>old</b>
<span id="ignore">injected</span>
</div>
`,
newHTMLStringChunks: ["<html><head></head><body><div><b>new</b></div></body></html>"],
ignoreId: true,
});

expect(newHTML).toBe(
normalize(`
<html>
<head></head>
<body>
<div><b>new</b><span id="ignore">injected</span></div>
</body>
</html>
`),
Expand Down
41 changes: 32 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type Walker = {
[APPLY_TRANSITION]: (v: () => void) => void;
[VISITED]: WeakSet<Node>;
[SETTLE]: (node: Node) => Promise<void>;
[IGNORED]: (node: Node | null) => unknown;
};

type NextNodeCallback = (node: Node) => void;
Expand All @@ -28,6 +29,7 @@ const FIRST_CHILD = 1;
const NEXT_SIBLING = 2;
const VISITED = 3;
const SETTLE = 4;
const IGNORED = 5;
const SPECIAL_TAGS = new Set(["HTML", "HEAD", "BODY"]);

/**
Expand Down Expand Up @@ -111,11 +113,10 @@ function settledWalker(walker: Walker, options: Options = {}): Walker {
};

return {
root: walker.root,
...walker,
[FIRST_CHILD]: hop("firstChild"),
[NEXT_SIBLING]: hop("nextSibling"),
[APPLY_TRANSITION]: (v) => v(),
[VISITED]: walker[VISITED],
[SETTLE]: async () => {},
};
}
Expand Down Expand Up @@ -213,18 +214,30 @@ async function setChildNodes(oldParent: Node, newParent: Node, walker: Walker) {

// Extract keyed nodes from previous children and keep track of total count.
while (oldNode) {
extra++;
checkOld = oldNode;
oldKey = getKey(checkOld);
oldNode = oldNode.nextSibling;
// An ignored node is not the diff's to account for: counting it inflates
// `extra`, and the tail removal below then takes one node too many.
if (walker[IGNORED](checkOld)) continue;
extra++;
oldKey = getKey(checkOld);

if (oldKey) {
if (!keyedNodes) keyedNodes = {};
keyedNodes[oldKey] = checkOld;
}
}

oldNode = oldParent.firstChild;
// Ignored nodes are invisible to the walk as well as to the removal: matched
// against an incoming node they would be rewritten into it, which is the one
// thing the caller asked not to happen.
const nextOwn = (node: ChildNode | null) => {
while (node && walker[IGNORED](node)) node = node.nextSibling;

return node;
};

oldNode = nextOwn(oldParent.firstChild);

// Loop over new nodes and perform updates.
while (newNode) {
Expand All @@ -241,13 +254,13 @@ async function setChildNodes(oldParent: Node, newParent: Node, walker: Walker) {
oldParent.insertBefore(foundNode!, oldNode),
);
} else {
oldNode = oldNode.nextSibling;
oldNode = nextOwn(oldNode.nextSibling);
}

await updateNode(foundNode, newNode, walker);
} else if (oldNode) {
checkOld = oldNode;
oldNode = oldNode.nextSibling;
oldNode = nextOwn(oldNode.nextSibling);
if (getKey(checkOld)) {
await walker[SETTLE](newNode);
markSubtree(newNode, walker[VISITED]);
Expand Down Expand Up @@ -279,8 +292,17 @@ async function setChildNodes(oldParent: Node, newParent: Node, walker: Walker) {
oldParent.removeChild(keyedNodes![oldKey]!);
}

// If we have any remaining unkeyed nodes remove them from the end.
while (--extra >= 0) oldParent.removeChild(oldParent.lastChild!);
// If we have any remaining unkeyed nodes remove them from the end,
// stepping over the ignored ones: a runtime-injected `<style>` sitting at
// the end of `<head>` is exactly what `shouldIgnoreNode` is asked to
// protect, and detaching it makes the page paint unstyled.
while (--extra >= 0) {
let doomed = oldParent.lastChild;

while (doomed && walker[IGNORED](doomed)) doomed = doomed.previousSibling;
if (!doomed) break;
oldParent.removeChild(doomed);
}
});
}

Expand Down Expand Up @@ -418,6 +440,7 @@ async function htmlStreamWalker(
} else v();
},
[VISITED]: visited,
[IGNORED]: (node) => options.shouldIgnoreNode?.(node),
// Waits until the node stops being the parser's frontier (or the stream
// ends), so cloning it deeply cannot snapshot a half-parsed subtree.
[SETTLE]: async (node: Node) => {
Expand Down
Loading