Repository navigation
[lexical] Bug Fix: recover from an empty editor state instead of throwing - #9183
Conversation
…wing ## Description `editor.setEditorState()` currently throws an invariant (minified error meta#38, "setEditorState: the editor state is empty") whenever it is handed an `EditorState` whose root has no children. The check is right that such a state is not the canonical empty document — it reconciles to a contenteditable with no block element in it at all, so there is nowhere to place a caret, and everything downstream that assumes `root.getFirstChild()` exists has to special-case it — but throwing is a harsh response to a shape that routinely arrives from *outside* the editor: content that was persisted while the editor was empty round-trips to `{"root":{"children":[]}}` and comes back through `parseEditorState()` on rehydrate. In production that turns recoverable bad input into a crash of the host application. This change keeps the condition loud where it is actionable and recoverable where it is not: - It is reported through the editor's warn-level hook (`onWarn`), whose default throws in development — so the dev-time behaviour of `setEditorState` is unchanged — and only `console.warn`s in production. Embedders can pass their own `onWarn` to route it to telemetry, or to restore the old throw-everywhere behaviour. - The state is then recovered to the canonical empty document (a root with a single empty paragraph) inside the update that applies it, so the editor that comes out the other side is a normal empty editor. This is the pattern the update-recursion guard in `LexicalUpdates` already uses, and `onWarn` is documented as being for conditions the editor has already recovered from — hence the recovery rather than a bare warning. The warning is raised with a direct `editor._onWarn(...)` call rather than an `invariant`, because `transform-error-messages` rewrites invariant call sites into `formatProdErrorMessage(...)` and the warning would never reach the hook in a built artifact. Error code 38 is left in `scripts/error-codes/codes.json` untouched. No API changes; `setEditorState` keeps its signature and its development-time behaviour. ## Test plan Two tests added to `packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx`: an empty parsed state is recovered to one empty paragraph, is reported once to `onWarn`, renders a block in the DOM and accepts text; and the default `onWarn` still throws in development. ### Before ``` $ npx vitest run --project unit \ packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx -t 'empty editor state' ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ FAIL |unit| packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx > LexicalEditor tests > setEditorState recovers an empty editor state and reports it to onWarn Error: setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty. ❯ invariant packages/lexical-internal/src/invariant.ts:28:9 ❯ LexicalEditor.setEditorState packages/lexical/src/LexicalEditor.ts:1737:7 ❯ packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx:3030:12 Test Files 1 failed (1) Tests 1 failed | 1 passed | 92 skipped (94) ``` ### After ``` $ npx vitest run --project unit \ packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx -t 'empty editor state' ✓ |unit| packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx (94 tests | 92 skipped) 156ms Test Files 1 passed (1) Tests 2 passed | 92 skipped (94) $ pnpm run test-unit Test Files 257 passed (257) Tests 5134 passed | 1 skipped (5135) $ pnpm run tsc # clean $ pnpm run flow # No errors! $ pnpm run prettier # no differences $ pnpm run lint # clean ``` E2E and browser-mode tests were not run in this environment (no browser runner available); the change is covered by the unit tests above.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Some archaeology on where this invariant came from, since "why was it a throw in the first place?" is the obvious question to ask of this PR. OriginIt arrived in #669 ("Add further invariants", Sep 2021), back when it read The twin invariant was already removed#669 added the check in two places:
The second one was removed in #1316 ("Make root selectable", Feb 2022), by the same author. That is likely the original rationale, and it has expired: before root was selectable, an empty root meant there was nowhere for a selection to live. Once root became selectable that hazard went away, and the update-path check went with it. The The result today is an asymmetry — Lexical produces a state it then refuses to accept: editor.update(() => { $getRoot().clear(); }, {discrete: true});
// does not throw
editor.getEditorState().isEmpty(); // true
JSON.stringify(editor.getEditorState());
// {"root":{"children":[],"direction":null,"format":"","indent":0,"type":"root","version":1}}
// ^ exactly the payload setEditorState rejectsSo This has surfaced repeatedly
What that means for this changeThe condition is worth reporting — a childless root is not the canonical empty document, and code downstream that assumes Risks I can see, for reviewers to weigh:
Happy to gate the recovery behind an opt-in, or to warn without recovering, if either fits the project's intent better. I went with recover-by-default because a childless root reconciles to a contenteditable with no block element in it at all, so a bare warning leaves the editor in a state with nowhere to place a caret. |
| /** | ||
| * Imperatively set the EditorState. Triggers reconciliation like an update. | ||
| * | ||
| * An empty EditorState (a root with no children) is not the canonical empty |
There was a problem hiding this comment.
I don’t think this edge case should be in the documentation of the function
There was a problem hiding this comment.
Done in d5824a4 — the docblock is back to what it was, and the reasoning now lives as an implementation comment next to the code it explains.
| // bundle, dropping the editor reference, so the warning would never | ||
| // reach `_onWarn` in a built artifact. | ||
| this._onWarn( | ||
| new Error( |
There was a problem hiding this comment.
This long string doesn’t get reduced in the codes map. It’s probably not even worth a warning, especially in prod
There was a problem hiding this comment.
also the whole rationale for using a bare message is moot if the warning is moved to the same location where the workaround occurs (inside if (isEmptyEditorState) { … })
There was a problem hiding this comment.
Fixed in d5824a4 by switching to devInvariant and keeping the message byte-identical to the invariant this PR replaces, so it maps to the code that already exists (38) and codes.json needs no change.
Verified against a real production build — 1 → 0 occurrences of the string:
$ pnpm run build-prod
$ grep -c "editor state is empty" packages/lexical/dist/Lexical.prod.js
0
$ grep -oE "[A-Za-z_$]+\(38\)" packages/lexical/dist/Lexical.prod.js
e(38)
$ grep -oE "Minified Lexical warning #" packages/lexical/dist/Lexical.prod.js
Minified Lexical warning #
On whether it is worth a warning at all: I kept one because the condition is silent otherwise and the recovery changes the document the caller asked for. Now that it costs a code rather than a string, it is cheap — but I am happy to drop it entirely and just recover if you would rather this stayed quiet.
There was a problem hiding this comment.
Agreed, and moved in d5824a4 — the report now sits in the same if (isEmptyEditorState) block as the recovery, inside the update, so the whole _onWarn detour is gone:
if (isEmptyEditorState) {
devInvariant(
false,
"setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty.",
);
$getRoot().append($createParagraphNode());
}One consequence worth flagging, since it is a behaviour change rather than a refactor: devInvariant now throws from inside the update rather than ahead of it, so outside production the empty state reaches the caller through editor._onError instead of being thrown out of setEditorState, and the update is rolled back — the content already in the editor survives. That is covered by the development-arm test. In production it warns once and the recovery applies.
## Description Review feedback on meta#9183 (@etrepum): the edge case did not belong in `setEditorState`'s API documentation, the warning shipped a long string that the error-code map could not reduce, and once the warning sits next to the workaround the rationale for bypassing the invariant helpers disappears. This commit takes all three: - The docblock goes back to what it was; the reasoning stays as an implementation comment next to the code it explains. - The `_onWarn(new Error(...))` call is replaced by `devInvariant`, which the `transform-error-messages` Babel plugin rewrites to `formatProdWarningMessage(code)` in a production build. The message is byte-identical to the invariant this PR replaces, so it maps to the error code that already exists (38) and `scripts/error-codes/codes.json` needs no change. - The report now sits inside the same `if (isEmptyEditorState)` block as the recovery, instead of ahead of the update. Behaviour is unchanged in spirit and simpler in practice: outside production `devInvariant` throws, so the empty state is reported through the editor's normal error handling and the update is rolled back, leaving whatever content was already there; in production it warns once and the root is recovered with an empty paragraph. The dedicated `onWarn` routing this PR previously relied on is no longer needed. ## Test plan `LexicalEditorEmptyState.test.ts` covers the production arm by stubbing `devInvariant` (which would otherwise throw and roll the recovery back before it can be observed); the development arm is covered in `LexicalEditor.test.tsx` against the real helper. ### Before The warning shipped its own string, so a production build carried the full message rather than an error code: ``` $ pnpm run build-prod $ grep -c "editor state is empty" packages/lexical/dist/Lexical.prod.js 1 ``` ### After ``` $ pnpm run build-prod $ grep -c "editor state is empty" packages/lexical/dist/Lexical.prod.js 0 $ grep -oE "[A-Za-z_$]+\(38\)" packages/lexical/dist/Lexical.prod.js e(38) $ grep -oE "Minified Lexical warning #" packages/lexical/dist/Lexical.prod.js Minified Lexical warning # ``` ``` $ npx vitest run --project unit \ packages/lexical/src/__tests__/unit/LexicalEditorEmptyState.test.ts ✓ |unit| packages/lexical/src/__tests__/unit/LexicalEditorEmptyState.test.ts (2 tests) 153ms Test Files 1 passed (1) Tests 2 passed (2) $ pnpm run test-unit Test Files 348 passed (349) Tests 8533 passed | 1 skipped (8537) $ pnpm run tsc # clean $ pnpm run lint # clean $ pnpm run prettier # no differences ``` The one unrun file in `test-unit` is `LexicalCharacterLimitPlugin.test.tsx`, whose worker dies with SIGSEGV on this machine; it does the same on an unmodified checkout of `main`, so it is environmental rather than caused by this change. CI runs the full suite. E2E and browser-mode tests were not run locally (no browser runner available); CI covers both.
Description
editor.setEditorState()throws an invariant (minified error #38, "setEditorState: the editor state is empty") whenever it is handed anEditorStatewhose root has no children. The check is right that such a state is not the canonical empty document — it reconciles to a contenteditable with no block element in it at all, so there is nowhere to place a caret, and everything downstream that assumesroot.getFirstChild()exists has to special-case it — but throwing is a harsh response to a shape that routinely arrives from outside the editor: content that was persisted while the editor was empty round-trips to{"root":{"children":[]}}and comes back throughparseEditorState()on rehydrate. In production that turns recoverable bad input into a crash of the host application.Lexical already produces this state itself —
$getRoot().clear()inside an update is legal, and serializing the result gives exactly the payloadsetEditorStaterejects — so the asymmetry is the bug.This change keeps the condition loud where it is actionable and recoverable where it is not. The empty state is reported with
devInvariant, which throws outside production (so the development behaviour ofsetEditorStateis unchanged in spirit — it is now surfaced through the editor's normal error handling rather than thrown at the caller) and onlyconsole.warns in a production build. The report sits in the same block as the recovery, which appends an empty paragraph to the root so the editor that comes out is a normal empty editor rather than a childless one.The message is byte-identical to the invariant it replaces, so
transform-error-messagesmaps it to the error code that already exists (38) andscripts/error-codes/codes.jsonneeds no change — a production build carriesformatProdWarningMessage(38), not the string.No API changes.
The history of the invariant, the prior reports of this crash, and the risks of recovering rather than throwing are in this comment.
Test plan
LexicalEditorEmptyState.test.tscovers the production arm by stubbingdevInvariant(which would otherwise throw and roll the recovery back before it can be observed): an empty parsed state recovers to exactly one empty paragraph, renders a block in the DOM and accepts text, and a non-empty state is left untouched.LexicalEditor.test.tsxcovers the development arm against the real helper: the empty state is reported throughonErrorand the content already in the editor survives.Before
Both new tests against an unmodified
main:After
The message is reduced to the existing error code in a production build
(
1→0occurrences of the string, against this PR's previous revision):The one unrun file in
test-unitisLexicalCharacterLimitPlugin.test.tsx, whose worker dies with SIGSEGV on the machine used here; it does the same on an unmodified checkout ofmain, so it is environmental rather than caused by this change. E2E and browser-mode tests were not run locally (no browser runner available); CI covers both.