Repository navigation
[lexical-table] Bug Fix: don't throw on stale table node keys in $handleTableSelectionChangeCommand - #8674
Merged
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…dleTableSelectionChangeCommand The SELECTION_CHANGE_COMMAND handler dereferenced table node keys with $getNodeByKeyOrThrow in two places where the key can be stale, throwing invariant #63 ("Expected node with key %s to exist but it's not in the nodeMap"): - The shouldCheckSelectionForTable key recorded on ArrowDown (the Firefox workaround for scrollable tables) when the table is removed before the next selection change. - The tableObservers registry sweep, when a TableNode's destroyed mutation was missed (e.g. an update performed while the editor's root element was detached skips reconciliation), leaving a permanently poisoned registry that threw on every subsequent selection change. The shouldCheckSelectionForTable lookup now uses $getNodeByKey and skips missing nodes, and the registry maintenance is centralized in the TableObservers class so it self-heals instead of erroring for the rest of the session: - TableObservers.removeObserver(tableKey) is the canonical teardown (removeListeners + registry delete) used by the mutation listener (destroyed and DOM-recreated branches) - TableObservers.removeAllObservers() handles plugin unregistration - TableObservers.$getTableNodesAndObservers() returns a snapshot of the registry for the current editor state, pruning entries whose table no longer exists so a missed destroyed mutation can't poison the registry TableObservers is not exported from the package index, so the new methods are internal and the public API is unchanged. The regression tests drive both scenarios through the public API with an editor built from TableExtension. Fixes meta#8670 https://claude.ai/code/session_01V5ShLDk437pCFXFjQtRewR
etrepum
force-pushed
the
claude/sleepy-allen-23qxk1
branch
from
June 11, 2026 04:40
2a3cbd1 to
4041fab
Compare
etrepum
marked this pull request as ready for review
June 11, 2026 05:17
etrepum
requested review from
acywatson,
fantactuka,
ivailop7,
potatowagon and
zurfyx
as code owners
June 11, 2026 05:17
potatowagon
reviewed
Jun 11, 2026
potatowagon
left a comment
Contributor
There was a problem hiding this comment.
Reviewed by Navi (Tater Thoughts Bobblehead) on behalf of @potatowagon.
LGTM ✅ — This is a well-structured defensive fix for a real edge case (stale table node keys in the observer registry).
What I checked:
- Logic correctness:
$handleTableSelectionChangeCommandnow uses$getNodeByKey(nullable) instead of$getTableNodeByKeyOrThrowfor theshouldCheckSelectionForTablepath. This correctly handles the case where a table is removed before its pending selection-change fires — instead of throwing, it gracefully skips the stale reference. The$isTableNodeguard before proceeding is the right pattern. - Self-healing registry (
$getTableNodesAndObservers): Iterates all entries and prunes stale ones (where the node no longer exists) before returning. This prevents "poisoned registry" issues when a table is removed while the root element is detached (missing thedestroyedmutation). UsesArray.from()before iteration to safely mutate during the loop — correct. - Encapsulation improvements:
removeObserver,removeAllObservers, and$getTableNodesAndObserversare properly marked@internaland centralize cleanup logic that was previously inlined in multiple places. No new public API surface. - Edge cases: The two new unit tests cover both scenarios — (1) ArrowDown records a table key, table is removed, selection change fires without throwing; (2) table removed while root detached, subsequent selection changes self-heal the registry and new tables still register correctly.
- Test coverage: 112-line test file with proper setup/teardown, uses
buildEditorFromExtensions+TableExtension(modern API),discreteupdates for synchronous assertions. - www backwards compatibility: No exports are removed or renamed. The new methods are
@internalonTableObserversclass. The$getTableNodeByKeyOrThrowimport removal inLexicalTableSelectionHelpers.tsis local — that function is still exported from@lexical/tablefor external consumers. No breaking change. - CI: All checks green — browser tests (mac/linux/windows × chromium/firefox/webkit), unit tests (Node 22.x/24.x), e2e (plain/rich/collab/collab-v2), integration, integrity, CLA, Vercel.
Assessment: Clean defensive fix. The pattern of swapping OrThrow for nullable-with-guard is well-established in Lexical for handling stale references. The self-healing $getTableNodesAndObservers is a nice addition that prevents accumulation of leaked observers. Ready to approve.
zurfyx
approved these changes
Jun 11, 2026
Merged
taylorpapke
pushed a commit
to life-itself/ForumMagnum
that referenced
this pull request
Sep 14, 2026
<details> <summary>Prompts Used</summary> In Lexical, deleting a table that's the last thing in the document, by placing the cursor after it and pressing backspace, crashes with: `Uncaught Error: Expected node with key 193 to exist but it's not in the nodeMap.` (the key number varies), after which the editor JS breaks. > Fixed. The crash is a known upstream bug in `@lexical/table` 0.44 ([meta/lexical#8670](meta/lexical#8670)); I reproduced it in a unit test and added an app-level workaround, since the real fix only ships in lexical 0.46. > > **Root cause:** With scrollable tables active (our `tableHorizontalScroll: true`), pressing ArrowDown while the selection is outside a table makes `@lexical/table` record that table's node key in `shouldCheckSelectionForTable` — part of a Firefox caret-placement workaround. The key is consumed by the *next* `SELECTION_CHANGE_COMMAND`, via `$getNodeByKeyOrThrow`. Normally the ArrowDown moves the caret and the resulting selection change consumes the key immediately. But when the cursor is after a trailing table (in the sentinel paragraph our `BlockCursorNavigationPlugin` maintains there), ArrowDown can't move the caret, so no selection change happens and the key stays pending. Backspace then deletes the table, and the selection change triggered by the deletion dereferences the dead key — the "Expected node with key N to exist" throw, with the key varying because it's the deleted table's key. The throw escapes mid-selection-change handling, which is why the editor stays broken afterward. > > **What I did:** > > - `packages/lesswrong/unitTests/tableBackspaceDelete.tests.tsx` — a jsdom test mounting the real plugins (vendored `TablePlugin` with horizontal scroll, `BlockCursorNavigationPlugin`, and a variant with the Yjs `CollaborationPlugin` on a fake in-memory provider). The ArrowDown→backspace→selection-change sequence reproduced the exact error before the fix; all four scenarios pass now, and the tests also verify the table actually gets deleted and that later edits still work. > - `packages/lesswrong/components/editor/lexicalPlugins/tables/TableDeleteCrashWorkaroundPlugin.tsx` (mounted in `Editor.tsx` next to `TablesPlugin`) — before backspace/delete/undo/redo, if an ArrowDown happened with no selection change since (the only state where the stale key can be pending), it dispatches a synthetic `SELECTION_CHANGE_COMMAND` so the pending key is consumed while the table still exists, which is a harmless no-op. It never fires during normal editing. > - `notes/lexical-upgrade-for-table-stale-key-bug.md` — the proper fix is upgrading lexical to ≥0.46 (upstream PR [ForumMagnum#8674](meta/lexical#8674), which also fixes a second "poisoned observer registry" variant that can't be worked around from app code); the note says to delete the workaround plugin then and keep the regression test. > > `yarn tsc` is clean apart from pre-existing errors in your locally-modified `Layout.tsx` (`WrapperComponentThatIsNew` undefined), which predate this session. One caveat: I verified the fix via the unit-test harness, not in a live browser — worth a quick manual check that backspace-deleting a trailing table now works in the real editor. <hr> A post with a section heading wrapped in both <strong> and <b> winds up with two copies of that heading in the ToC. Fix, and, if the bug wasn't always there, determine when it was introduced. > Fixed, with a regression test, and the bug is dated. > > **Cause.** In `packages/lesswrong/lib/tableOfContents.ts`, `extractTableOfContents` queries for `h1,h2,h3,h4,strong,b` and gets back both the outer `<strong>` and the inner `<b>`. The whole-paragraph check accepted each of them independently, because each is the sole content of its parent and its text equals the paragraph's text. So both got an anchor and a ToC entry. > > **Fix.** The extraction loop now records each element it accepts as a heading and skips any later candidate that is nested inside one of them. Since `querySelectorAll` returns ancestors before descendants, the outer element is the one kept, so the anchor lands on the `<strong>`. This also covers `<b><strong>`, `<strong><strong>`, and similar nestings. > > **Test.** Added a case to `packages/lesswrong/unitTests/tableOfContents.tests.ts` covering both nesting orders. It fails on the old code and passes with the fix. The full file passes and `yarn tsc` is clean. > > **When it was introduced.** The bug was not always there. The original 2018 code required a `<strong>` or `<b>` to have a `<p>` as its direct parent, which excluded the inner tag. Commit 9c62824 ("Improve tagIsWholeParagraph heuristics", 2022-07-03, merged to master in PR ForumMagnum#5159 on 2022-07-06) replaced that with a check that the tag's siblings are all the same tag type and that the enclosing paragraph's text matches, which the inner tag also satisfies. The 2024 DOM rewrite (PR merged 2024-04-03) ported the same logic faithfully, so the double entry has existed since July 2022. > > Nothing is committed. The two modified files are ready for review. </details>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
The
SELECTION_CHANGE_COMMANDhandler dereferenced table node keys with$getNodeByKeyOrThrowin two places where the key can be stale, throwing invariant#63("Expected node with key %s to exist but it's not in the nodeMap"):shouldCheckSelectionForTablekey recorded on ArrowDown (the Firefox workaround for scrollable tables) when the table is removed before the next selection change.tableObserversregistry sweep, when aTableNode's destroyed mutation was missed (e.g. an update performed while the editor's root element was detached skips reconciliation), leaving a permanently poisoned registry that threw on every subsequent selection change.The
shouldCheckSelectionForTablelookup now uses$getNodeByKeyand skips missing nodes, and the registry maintenance is centralized in theTableObserversclass so it self-heals instead of erroring for the rest of the session:TableObservers.removeObserver(tableKey)is the canonical teardown (removeListeners + registry delete) used by the mutation listener (destroyed and DOM-recreated branches)TableObservers.removeAllObservers()handles plugin unregistrationTableObservers.$getTableNodesAndObservers()returns a snapshot of the registry for the current editor state, pruning entries whose table no longer exists so a missed destroyed mutation can't poison the registryTableObserversis not exported from the package, so the public API is unchanged.Closes #8670
Test plan
New unit tests