Skip to content

Fix ParentNode insertBefore linked-list corruption#610

Open
TrevorSundberg wants to merge 1 commit intoShopify:mainfrom
TrevorSundberg:fix-parentnode-insertbefore-links
Open

Fix ParentNode insertBefore linked-list corruption#610
TrevorSundberg wants to merge 1 commit intoShopify:mainfrom
TrevorSundberg:fix-parentnode-insertbefore-links

Conversation

@TrevorSundberg
Copy link
Copy Markdown

@TrevorSundberg TrevorSundberg commented Apr 29, 2026

Summary

This fixes ParentNode.insertInto() in @remote-dom/polyfill so inserting a child before a non-head reference node correctly links the previous sibling to the inserted child.

The current implementation updates the inserted child and the reference node, but it does not update the previous sibling's NEXT pointer when before[PREV] is not null. That leaves the sibling list internally inconsistent: the inserted node has PREV/NEXT links, and the reference node points back to it, but traversal from the parent's first child skips the inserted node.

Affected source:
https://github.com/Shopify/remote-dom/blob/main/packages/polyfill/source/ParentNode.ts#L120-L127

Before:

child[NEXT] = before;
child[PREV] = before[PREV];
if (before[PREV] === null) this[CHILD] = child;
before[PREV] = child;

After:

child[NEXT] = before;
child[PREV] = before[PREV];
if (before[PREV] === null) this[CHILD] = child;
else before[PREV][NEXT] = child; // Link the previous sibling to the inserted child.
before[PREV] = child;

Tests passed: corepack pnpm type-check, corepack pnpm lint, and corepack pnpm exec vitest run.

Root Cause

For non-head insertions, before[PREV] is the previous sibling. That sibling must have its NEXT pointer changed to the inserted child. Without that update, the list can become inconsistent after DOM moves such as keyed reorders.

This diverges from the normal DOM insertion invariant:

previousSibling -> insertedChild -> before

Instead, the current state can become:

previousSibling -> before
insertedChild -> before
before.prev -> insertedChild

@TrevorSundberg
Copy link
Copy Markdown
Author

I have signed the CLA!

@TrevorSundberg TrevorSundberg marked this pull request as ready for review April 29, 2026 01:24
@TrevorSundberg TrevorSundberg force-pushed the fix-parentnode-insertbefore-links branch from 4256476 to 13ae5c3 Compare April 29, 2026 01:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant