Repository navigation
[lexical] Bug Fix: A node removed while the reconciler builds its parent's DOM anew leaves the DOM map and reports destroyed - #9773
Conversation
…ent's DOM anew leaves the DOM map and reports destroyed
## Description
When an element's `updateDOM` returns true, the reconciler builds the element, and every child under it, anew with `$createNode` instead of comparing them with their previous children. The same happens in `$reconcileChildren`'s single-child path when a parent's only child is replaced by a node moved out of that child's subtree (`$createNode(key, null)` skips the reuse of a moved node's DOM). In both cases the node's previous children and slot values were never visited, so one removed in the same update kept its entry in `editor._keyToDOMMap` (a detached element, kept for as long as the editor lives, one more on every such update) and its mutation listeners never received `destroyed`. `$destroyNode` on the rebuilt node itself returns early, because the node stays in the next state.
Examples: `ListNode.setListType('number')` and removing one of its items in one update; a collaborator's change that outdents a nested list item while removing text from it (a DOM-rendered `@lexical/y` peer reads such updates in one commit).
Now, when `$createNode` builds a new DOM for a key that was in the previous state, it destroys that node's previous children and slot values; `$destroyNode` skips the ones still in the next state. In this cleanup `$destroyNode` leaves slot containers alone: the DOM they sat in is replaced as a whole, and a container resolved through a slot value's DOM can already be that value's new container. Elsewhere slot-container handling is unchanged.
Mutation listeners now receive `destroyed` for the removed children, slot values and their descendants in these updates, which they did not receive before. Nothing changes for keys that stay: a child rebuilt under its rebuilt parent still reports `created`, as before, and a moved node still reports `updated`.
Not changed: a slot container mounted outside its host (`mountSlotContainer`) stays connected after its slot is removed or moved while the host's DOM is rebuilt, as before (the keys are now cleaned up); slot-container identity after DOM reuse is a separate, existing issue.
## Changeset
`.changeset/reconcile-rebuilt-dom-children.md` (`lexical` patch, `[fix]`).
## Test plan
- `packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMChildren.test.ts` (new, 7 tests): a child, a grandchild and a decorator removed under an element whose `updateDOM` returns true; a child moved out of it stays; a node moved into its old ancestor's only-child place with a child removed; no growth over 50 repeats; cleanup without mutation listeners. Each checks the DOM map, `getElementByKey`, exactly one `destroyed` per removed key, none for kept keys, and the DOM against a fresh render.
- `packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMSlots.test.ts` (new, 22 tests) and `LexicalReconcilerRebuiltDOMSlotSources.test.ts` (new, 3 tests): slot values removed, replaced or moved around rebuilt hosts (element and decorator hosts), a slot moved from a removed child to its rebuilt ancestor, a removed slot host whose value moves to a later host, rebuilt subtrees at depths 1, 5 and 30, inverted rebuilt ancestors, decorators and pending decorators, shared-key `setEditorState`, transforms on several hosts, a nested editor, and a 10,000-item rebuild with a linear number of previous-map lookups.
- `packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMDecorators.test.ts` (new, 83 tests): a decorator whose own `updateDOM` returns true with its slot removed or replaced, transforms registered again on existing hosts, and 80 seeded pairs of forests with shared keys (removed ancestors with surviving descendants, ancestor inversions, moves in both render orders, several rebuilds) checked for the DOM map, mutations and a fresh render.
### Before
```
$ ./node_modules/.bin/vitest --run --project unit packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOM*.test.ts
AssertionError: expected <span data-lexical-text="true"></span> to be null
AssertionError: expected undefined to be 'destroyed'
Tests 103 failed | 12 passed (115)
```
### After
```
$ ./node_modules/.bin/vitest --run --project unit packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOM*.test.ts
Test Files 4 passed (4)
Tests 115 passed (115)
```
All unit tests (every package, jsdom; `@lexical/y` also with `LEXICAL_Y_GC=1`) and `scripts-unit` pass with no change from main. Playwright e2e for tables, copy and paste, lists, selection, headings, markdown, mutations and collab-y on Chromium and Firefox give the same results as main. A randomized differential of update sequences (nested lists, tables, links, decorators; nodes moved between parents, rebuilt, removed; local updates, shared-key `setEditorState` and parsed JSON), with the DOM compared to a fresh render, the DOM map checked and a mutation-listener check after every update: 200,000 sessions, main keeps stale DOM-map entries in 941 and the fix in none, with no session failing only with the fix. WebKit was not run.
## Review
Independent review with gpt-6.1-sol over four rounds (the last clean); its tests are included.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
AI review status for this pull request.
|
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/y
@lexical/yjs
commit: |
There was a problem hiding this comment.
This looks good. The new cleanup in $createNode only touches keys that are no longer in the next state: $destroyNode still returns early for anything that moved, so moved nodes keep their DOM and kept children still report created. Removed children now leave the DOM map and report destroyed.
With shipped nodes, the leak reproduces on main and is gone with this change:
One editor.update |
main |
This PR |
|---|---|---|
ListNode bullet to number, one item removed |
2 stale DOM-map entries, no destroyed |
No stale entries, destroyed delivered |
HeadingNode h1 to h2, one text child removed |
1 stale entry, no destroyed |
No stale entries, destroyed delivered |
The new tests fail on main (103 of 115) and pass here, and the changeset follows .changeset/README.md.
Optional, non-blocking: every new test drives the bug through the test-only TestUpdateDOMTrueHostNode and TestDecoratorNode. The changeset's Verify: paragraph describes the ListNode.setListType('number') plus remove-an-item case. Adding that case as a unit test under packages/lexical-list/src/__tests__/unit/, the unit-test location in AGENTS.md's Testing Strategy, would pin the real-node reproducer alongside the fixture-based coverage.
… changes leaves the DOM map
## Description
Adds a unit test with shipped nodes for the reconciler fix in this pull request: changing a list's type (`ListNode.setListType`) makes the reconciler build the list's DOM anew, and an item removed in the same update must leave the editor's DOM map and report `destroyed`. Test-only; no source change.
## Test plan
### Before
```
$ ./node_modules/.bin/vitest --run --project unit packages/lexical-list/src/__tests__/unit/ListTypeChangeRemovedItem.test.ts
AssertionError: expected [ '4', '5' ] to deeply equal []
Tests 1 failed (1)
```
### After
```
$ ./node_modules/.bin/vitest --run --project unit packages/lexical-list/src/__tests__/unit/ListTypeChangeRemovedItem.test.ts
Tests 1 passed (1)
```
|
The optional item from the review is taken in c20d603 (test only, no source change): |
There was a problem hiding this comment.
This looks good. The cleanup in $createNode only touches keys that are no longer in the next state: $destroyNode still returns early for anything that stayed or moved, so moved nodes keep their DOM and children kept under a rebuilt parent still report created. Removed children and slot values now leave the DOM map and report destroyed; the new tests reproduce the leak on main, including the ListNode case in @lexical/list, and pass here.
Two optional, non-blocking suggestions:
- Changeset wording (
.changeset/reconcile-rebuilt-dom-children.md:7). "Children and slot values that stay keep their DOM" reads as if kept children keep their DOM elements, but a child kept under a rebuilt parent gets a new element and reportscreated, asLexicalReconcilerRebuiltDOMSlots.test.tsasserts. Only moved nodes and slot values keep their DOM..changeset/README.mdcopies these paragraphs into the changelog verbatim, so something like: "Children and slot values that stay are not destroyed: a child rebuilt with its parent still reportscreated, as before, and a moved node or slot value keeps its DOM." - Follow-up for a removed slot's container (
packages/lexical/src/LexicalReconciler.ts:879-881, and the slot loop in$destroyNodeat:370-372). The description already notes that a container mounted outside its host withmountSlotContainerstays connected. The identity hazard in the code comment only applies to a slot value that is still in the next state; for a value that left the state, its DOM's parent is still its old container, so that container could be resolved before$destroyNodeand removed when!activeNextNodeMap.has(slotKey). That would take it off the page instead of leaving the removed value's text visible. Fine to leave for a separate PR.
|
|
||
| [fix] A node removed in the same update in which the reconciler builds its parent's DOM anew no longer stays in the editor's DOM map, and its mutation listeners now receive `destroyed` | ||
|
|
||
| When an element's `updateDOM` returns true, the reconciler builds the element and every child under it anew instead of comparing them with their previous children; the same happens to a node moved into a parent's only-child position out of the subtree of the child it replaces. A child (or a slot value) removed from such a node in that update kept its entry in the editor's DOM map (holding a detached DOM element for as long as the editor lived, one more on every such update) and its mutation listeners never received `destroyed`. The reconciler now destroys the previous children and slot values of a node it builds anew that left the editor state. Children and slot values that stay keep their DOM, including a slot value moved to another host in the same update; slot containers are handled as before. |
There was a problem hiding this comment.
Nit (optional): "Children and slot values that stay keep their DOM" reads as if kept children keep their DOM elements, but a child kept under a rebuilt parent gets a new element and reports created (the new LexicalReconcilerRebuiltDOMSlots.test.ts asserts this). Only moved nodes and slot values keep their DOM. Since .changeset/README.md copies these paragraphs into the changelog verbatim, maybe: "Children and slot values that stay are not destroyed: a child rebuilt with its parent still reports created, as before, and a moved node or slot value keeps its DOM."
There was a problem hiding this comment.
Done in 21dbe56 (changeset only): removed children are destroyed; a child kept under a rebuilt parent gets a new element and reports created, as before; a node or slot value moved elsewhere keeps its DOM.
| for (const prevSlotKey of $readSlots(prevNode).values()) { | ||
| $destroyNode(prevSlotKey, null, true); | ||
| } |
There was a problem hiding this comment.
Optional follow-up: the identity hazard in the comment above only applies to a slot value that is still in the next state. For a value that left the state, its DOM's parent is still its old container, so it could be resolved before $destroyNode and removed when !activeNextNodeMap.has(prevSlotKey) (and likewise in $destroyNode's slot loop when keepSlotContainers is set). That would take a container mounted outside the host with mountSlotContainer off the page instead of leaving it visible with the removed value's text. Fine to leave for a separate PR, as the description says.
There was a problem hiding this comment.
Agreed that a removed value's container could be resolved and removed before $destroyNode; left for a separate change, as this one keeps slot-container handling as it was.
## Description Rewords one sentence of `.changeset/reconcile-rebuilt-dom-children.md`, which is copied into the changelog: removed children are destroyed; a child kept under a rebuilt parent gets a new element and reports `created`, as before; a node or slot value moved elsewhere keeps its DOM. Changeset only; no source or test change.
There was a problem hiding this comment.
This looks good. The cleanup in $createNode only acts on keys that are no longer in the next state: $destroyNode still returns early for anything that stayed or moved, so removed children and slot values now leave the DOM map and report destroyed, while children kept under a rebuilt parent still report created, as before. The new tests reproduce the leak on main, including the shipped ListNode case, and pass here.
One optional, non-blocking suggestion:
- Changeset wording (
.changeset/reconcile-rebuilt-dom-children.md:7). "a node or slot value moved elsewhere ... keeps its DOM" has one exception that the same paragraph describes: the node that takes a parent's only-child position out of the replaced child's subtree is built anew, gets a new element and reportscreated(onmaintoo)..changeset/README.mdcopies these paragraphs into the changelog verbatim, so a qualifier such as "(except a node that takes a parent's only-child position, which is built anew and reportscreated, as before)" would make it exact. The description's "a moved node still reportsupdated" has the same exception.
Leaving the cleanup of an externally mounted slot container to a separate change, as you suggested, sounds right.
|
|
||
| [fix] A node removed in the same update in which the reconciler builds its parent's DOM anew no longer stays in the editor's DOM map, and its mutation listeners now receive `destroyed` | ||
|
|
||
| When an element's `updateDOM` returns true, the reconciler builds the element and every child under it anew instead of comparing them with their previous children; the same happens to a node moved into a parent's only-child position out of the subtree of the child it replaces. A child (or a slot value) removed from such a node in that update kept its entry in the editor's DOM map (holding a detached DOM element for as long as the editor lived, one more on every such update) and its mutation listeners never received `destroyed`. The reconciler now destroys the previous children and slot values of a node it builds anew that left the editor state. Removed children are destroyed; nodes that stay are not: a child kept under a rebuilt parent gets a new element and reports `created`, as before, and a node or slot value moved elsewhere (including a slot value moved to another host in the same update) keeps its DOM. Slot containers are handled as before. |
There was a problem hiding this comment.
Optional nit: "a node or slot value moved elsewhere ... keeps its DOM" has one exception this paragraph already describes: the node that takes a parent's only-child position out of the replaced child's subtree is built anew, gets a new element and reports created (on main too). Since .changeset/README.md copies this paragraph into the changelog verbatim, a qualifier such as "(except a node that takes a parent's only-child position, which is built anew and reports created, as before)" would make it exact.
There was a problem hiding this comment.
Done in 4de955b (changeset only), and the description says the same: the node that takes a parent's only-child position is built anew and reports created, as before.
… excludes ## Description Adds the exception to the changeset's sentence on moved nodes: a node that takes a parent's only-child position is built anew and reports `created`, as before. Changeset only; no source or test change.
There was a problem hiding this comment.
This change looks good to me. Destroying the previous children and slot values of a node that $createNode builds anew, while $destroyNode keeps returning early for every key still in the next state, fixes the stale DOM-map entries and the missing destroyed mutations without moving any DOM. The new tests, including the @lexical/list one with shipped nodes, fail on main and pass here, and they check the DOM map, one destroyed per removed key and the DOM against a fresh render.
One optional, non-blocking suggestion:
- Changeset wording (
.changeset/reconcile-rebuilt-dom-children.md, line 7; also the comment atpackages/lexical/src/LexicalReconciler.ts:866): the second case is described as a node moved into a parent's only-child position "out of the subtree of the child it replaces" (in the comment, "from its old ancestor").$reconcileChildren's single-child branch builds the new only child anew wherever it came from, so a node moved in from a sibling parent, with one of its children removed, had the same leak onmainand is fixed by this change too. CONTRIBUTING.md asks the changeset to be written for people who use Lexical, since it becomes the changelog entry; dropping that qualifier would make the paragraph exact.
Leaving a slot container mounted outside its host in place when the host's DOM is rebuilt is the follow-up you already called out in the description, so I have not repeated it as a request here.
|
|
||
| [fix] A node removed in the same update in which the reconciler builds its parent's DOM anew no longer stays in the editor's DOM map, and its mutation listeners now receive `destroyed` | ||
|
|
||
| When an element's `updateDOM` returns true, the reconciler builds the element and every child under it anew instead of comparing them with their previous children; the same happens to a node moved into a parent's only-child position out of the subtree of the child it replaces. A child (or a slot value) removed from such a node in that update kept its entry in the editor's DOM map (holding a detached DOM element for as long as the editor lived, one more on every such update) and its mutation listeners never received `destroyed`. The reconciler now destroys the previous children and slot values of a node it builds anew that left the editor state. Removed children are destroyed; nodes that stay are not: a child kept under a rebuilt parent gets a new element and reports `created`, as before, and a node or slot value moved elsewhere (including a slot value moved to another host in the same update) keeps its DOM, except a node that takes a parent's only-child position, which is built anew and reports `created`, as before. Slot containers are handled as before. |
There was a problem hiding this comment.
Optional nit: "out of the subtree of the child it replaces" is narrower than the fix. $reconcileChildren's single-child branch builds the new only child anew wherever it came from, so a node moved in from a sibling parent with one of its children removed had the same leak on main and is cleaned here too. Dropping that qualifier would make this changelog paragraph exact (the comment at packages/lexical/src/LexicalReconciler.ts:866, "from its old ancestor", has the same narrowing).
There was a problem hiding this comment.
Right: the single-child branch builds the new only child anew wherever it came from, so a node moved in from a sibling parent with a child removed is fixed too. The changeset names the shape the tests and the leak report started from; it understates the scope but says nothing wrong, so it stays as it is to keep the verified head.
There was a problem hiding this comment.
Fair enough — that was an optional nit, not a correctness issue. The wording as it stands describes a real case the fix covers and doesn't claim it's the only one, so leaving it unchanged to keep the verified head makes sense. The broader scope is now recorded here in the thread for changelog readers.
Description
When an element's
updateDOMreturns true, the reconciler builds the element, and every child under it, anew with$createNodeinstead of comparing them with their previous children. The same happens in$reconcileChildren's single-child path when a parent's only child is replaced by a node moved out of that child's subtree ($createNode(key, null)skips the reuse of a moved node's DOM). In both cases the node's previous children and slot values were never visited, so one removed in the same update kept its entry ineditor._keyToDOMMap(a detached element, kept for as long as the editor lives, one more on every such update) and its mutation listeners never receiveddestroyed.$destroyNodeon the rebuilt node itself returns early, because the node stays in the next state.Examples:
ListNode.setListType('number')and removing one of its items in one update; a collaborator's change that outdents a nested list item while removing text from it (a DOM-rendered@lexical/ypeer reads such updates in one commit).Now, when
$createNodebuilds a new DOM for a key that was in the previous state, it destroys that node's previous children and slot values;$destroyNodeskips the ones still in the next state. In this cleanup$destroyNodeleaves slot containers alone: the DOM they sat in is replaced as a whole, and a container resolved through a slot value's DOM can already be that value's new container. Elsewhere slot-container handling is unchanged.Mutation listeners now receive
destroyedfor the removed children, slot values and their descendants in these updates, which they did not receive before. Nothing changes for keys that stay: a child rebuilt under its rebuilt parent still reportscreated, as before, and a moved node still reportsupdated, except a node that takes a parent's only-child position, which is built anew and reportscreated, as before.Not changed: a slot container mounted outside its host (
mountSlotContainer) stays connected after its slot is removed or moved while the host's DOM is rebuilt, as before (the keys are now cleaned up); slot-container identity after DOM reuse is a separate, existing issue.Changeset
.changeset/reconcile-rebuilt-dom-children.md(lexicalpatch,[fix]).Test plan
packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMChildren.test.ts(new, 7 tests): a child, a grandchild and a decorator removed under an element whoseupdateDOMreturns true; a child moved out of it stays; a node moved into its old ancestor's only-child place with a child removed; no growth over 50 repeats; cleanup without mutation listeners. Each checks the DOM map,getElementByKey, exactly onedestroyedper removed key, none for kept keys, and the DOM against a fresh render.packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMSlots.test.ts(new, 22 tests) andLexicalReconcilerRebuiltDOMSlotSources.test.ts(new, 3 tests): slot values removed, replaced or moved around rebuilt hosts (element and decorator hosts), a slot moved from a removed child to its rebuilt ancestor, a removed slot host whose value moves to a later host, rebuilt subtrees at depths 1, 5 and 30, inverted rebuilt ancestors, decorators and pending decorators, shared-keysetEditorState, transforms on several hosts, a nested editor, and a 10,000-item rebuild with a linear number of previous-map lookups.packages/lexical/src/__tests__/unit/LexicalReconcilerRebuiltDOMDecorators.test.ts(new, 83 tests): a decorator whose ownupdateDOMreturns true with its slot removed or replaced, transforms registered again on existing hosts, and 80 seeded pairs of forests with shared keys (removed ancestors with surviving descendants, ancestor inversions, moves in both render orders, several rebuilds) checked for the DOM map, mutations and a fresh render.packages/lexical-list/src/__tests__/unit/ListTypeChangeRemovedItem.test.ts(new, 1 test, shipped nodes): a list changed from bullet to number with an item removed in the same update; the removed item and its text leave the DOM map, the item reportsdestroyed, the list shows only the kept item. On main it fails withexpected [ '4', '5' ] to deeply equal []; here it passes.Before
After
All unit tests (every package, jsdom;
@lexical/yalso withLEXICAL_Y_GC=1) andscripts-unitpass with no change from main. Playwright e2e for tables, copy and paste, lists, selection, headings, markdown, mutations and collab-y on Chromium and Firefox give the same results as main. A randomized differential of update sequences (nested lists, tables, links, decorators; nodes moved between parents, rebuilt, removed; local updates, shared-keysetEditorStateand parsed JSON), with the DOM compared to a fresh render, the DOM map checked and a mutation-listener check after every update: 200,000 sessions, main keeps stale DOM-map entries in 941 and the fix in none, with no session failing only with the fix. WebKit was not run.Review
Independent review with gpt-6.1-sol over four rounds (the last clean); its tests are included.