Skip to content

[lexical] Bug Fix: recover from an empty editor state instead of throwing - #9183

Merged
etrepum merged 2 commits into
meta:mainfrom
potatowagon:sw/error-38-recover
Sep 22, 2026
Merged

etrepum merged 2 commits into
meta:mainfrom
potatowagon:sw/error-38-recover

Conversation

@potatowagon

@potatowagon potatowagon commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

editor.setEditorState() throws an invariant (minified error #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.

Lexical already produces this state itself — $getRoot().clear() inside an update is legal, and serializing the result gives exactly the payload setEditorState rejects — 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 of setEditorState is unchanged in spirit — it is now surfaced through the editor's normal error handling rather than thrown at the caller) and only console.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-messages maps it to the error code that already exists (38) and scripts/error-codes/codes.json needs no change — a production build carries formatProdWarningMessage(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.ts covers the production arm by stubbing devInvariant (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.tsx covers the development arm against the real helper: the empty state is reported through onError and the content already in the editor survives.

Before

Both new tests against an unmodified main:

$ npx vitest run --project unit \
    packages/lexical/src/__tests__/unit/LexicalEditorEmptyState.test.ts

 FAIL  |unit| .../LexicalEditorEmptyState.test.ts > setEditorState with an empty editor state (production arm) > recovers to an empty paragraph rather than leaving the root childless
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:1746:7

 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)

$ npx vitest run --project unit \
    packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx -t 'empty editor state'

 FAIL  |unit| .../LexicalEditor.test.tsx > LexicalEditor tests > setEditorState reports an empty editor state outside production
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:1746:7

 Test Files  1 failed (1)
      Tests  1 failed | 93 skipped (94)

After

$ npx vitest run --project unit \
    packages/lexical/src/__tests__/unit/LexicalEditorEmptyState.test.ts \
    packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx
 Test Files  2 passed (2)
      Tests  96 passed (96)

$ pnpm run test-unit
 Test Files  348 passed (349)
      Tests  8533 passed | 1 skipped (8537)

$ pnpm run tsc        # clean
$ pnpm run flow       # No errors!
$ pnpm run prettier   # no differences
$ pnpm run lint       # clean

The message is reduced to the existing error code in a production build
(1 → 0 occurrences of the string, against this PR's previous revision):

$ 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)

The one unrun file in test-unit is LexicalCharacterLimitPlugin.test.tsx, whose worker dies with SIGSEGV on the machine used here; it does the same on an unmodified checkout of main, 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.

…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.
@vercel

vercel Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lexical Ready Ready Preview Sep 22, 2026 8:06am UTC
lexical-playground Ready Ready Preview Sep 22, 2026 8:06am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Sep 21, 2026
@potatowagon potatowagon changed the title [lexical] Bug Fix: recover from an empty editor state instead of thro… [lexical] Bug Fix: recover from an empty editor state instead of throwing Sep 21, 2026
@potatowagon

Copy link
Copy Markdown
Contributor Author

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.

Origin

It arrived in #669 ("Add further invariants", Sep 2021), back when it read setViewModel: the view model is empty. The PR body in full is "Adds further invariants around empty view models." — no linked issue, no review discussion. It looks like a batch of defensive assertions rather than a considered API contract.

The twin invariant was already removed

#669 added the check in two places:

  • setViewModel — "the view model is empty"
  • the update path — "updateEditor: the pending view model is empty. Ensure the root not never becomes empty from an update."

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 setEditorState door was simply never revisited.

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 rejects

So root.clear() is legal, persisting the result is legal, and only rehydrating it throws — in production, as minified error #38, inside the host application.

This has surfaced repeatedly

What that means for this change

The condition is worth reporting — a childless root is not the canonical empty document, and code downstream that assumes root.getFirstChild() exists has to special-case it. But the response is what this PR changes: report through onWarn (throws in dev, console.warns in prod, overridable) and recover to a root with one empty paragraph, instead of throwing in production.

Risks I can see, for reviewers to weigh:

  1. Collaboration. Bug: editorState null serializes to empty editor state and can no longer be loaded #5079's "intentional" ruling was about editorState: null meaning the Yjs document owns the content. If an app passes an explicitly empty serialized state while using collab, the recovery inserts a paragraph the Yjs doc does not have, which could propagate. Narrow — the documented collab bootstrap passes null and never reaches setEditorState — but it is the case where the throw was arguably protective.
  2. Masking a broken persistence path. The throw is a tripwire; in production this now only warns. Embedders who want the old behaviour can pass an onWarn that re-throws, and anyone relying on the signal should route onWarn to telemetry rather than leaving it at console.warn.
  3. Round-trip identity. setEditorState(s) followed by getEditorState() no longer returns s for this one degenerate input — relevant to @lexical/history, where an undo onto a recorded empty state now lands on an empty paragraph rather than throwing.

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.

Comment thread packages/lexical/src/LexicalEditor.ts Outdated
/**
* Imperatively set the EditorState. Triggers reconciliation like an update.
*
* An empty EditorState (a root with no children) is not the canonical empty

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t think this edge case should be in the documentation of the function

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/lexical/src/LexicalEditor.ts Outdated
// bundle, dropping the editor reference, so the warning would never
// reach `_onWarn` in a built artifact.
this._onWarn(
new Error(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This long string doesn’t get reduced in the codes map. It’s probably not even worth a warning, especially in prod

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) { … })

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@etrepum
etrepum added this pull request to the merge queue Sep 22, 2026
Merged via the queue into meta:main with commit bc4dcc8 Sep 22, 2026
58 checks passed
@etrepum etrepum mentioned this pull request Sep 28, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — d5824a47 Deployed Sep 22, 2026 by vercel[bot]
Preview – lexical-playground — d5824a47 Deployed Sep 22, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants