Skip to content

[*] Refactor: Use explicit active editor when reading or serializing an editor state from listeners - #9941

Merged
etrepum merged 11 commits into
meta:mainfrom
etrepum:claude/project-thread-w89waf
Nov 19, 2026
Merged

etrepum merged 11 commits into
meta:mainfrom
etrepum:claude/project-thread-w89waf

Conversation

@etrepum

@etrepum etrepum commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A node method that calls $getEditor() (directly, or through $getPeerDependency/$getExtensionDependency) threw "Unable to find an active editor" wherever Lexical read an editor state with editorState.read(fn) and no {editor}. Text content listeners were the reported case (triggerTextContentListeners). The same happened in history merging, markdown/mdast shortcuts, @lexical/y and @lexical/yjs v2 collaboration, HMR, editor.toJSON(), exportFile, useLexicalIsTextContentEmpty and TableOfContentsPlugin.

  • Every such read now passes the editor.
  • editor.toJSON() exports with its editor active, and EditorState.toJSON() keeps the editor of the read or update it is called in (it used to set none).
  • serializedDocumentFromEditorState takes an optional editor (declared in Flow too).
  • New editor.read(editorState, fn) overload: reads a given state of the editor (such as a listener's prevEditorState) with the editor active and without flushing. Package internals, the playground and dev-examples read with it. examples/ and the docs keep editorState.read(fn, {editor}), since examples run on a published Lexical; a lint rule keeps the overload out of examples/ and devtools. An object that is not an EditorState from this copy of Lexical (a state from a duplicated lexical) now throws instead of silently reading the committed state; any other value that is not a mode keeps reading the committed state, with a development warning.
  • New editorState.toJSON({compact, editor}): exports a state with its editor active in one call, with the return type following compact. Without editor it keeps the active editor, as toJSON() does. editor.toJSON(), serializedDocumentFromEditorState, @lexical/y and the playground use it. Its overloads come before the boolean ones, so Parameters<EditorState['toJSON']> is unchanged.
  • A no-restricted-syntax selector flags new editor-less EditorState#read calls in library sources, the playground (including its ESM demo), devtools, the website, examples and dev-examples. It also matches prev and held receivers.
  • Docs and examples pass {editor} (or use editor.read('latest', ...) / editor.toJSON()).
  • @lexical/y: a local write opens its Yjs transactions in an editor-less read of the state and runs only the write itself with the editor active (YBinding#transact, D137). Yjs callbacks at the end of the transaction (observers, afterTransaction handlers, the undo manager's listeners such as the CAN_UNDO_COMMAND dispatch) therefore run outside that read, as before, and do not trigger the development warning about an update started in a read-only context.
  • @lexical/yjs (v1 and v2): local syncs compute the awareness state inside the read and call awareness.setLocalState after the read returns, so awareness listeners that dispatch commands run outside it too.

Closes #9934

Changeset

.changeset/active-editor-in-state-reads.md ([fix], with a Verify: paragraph), .changeset/editor-read-editor-state.md ([feature], the editor.read(editorState, fn) overload, with a Verify: paragraph for the new error), .changeset/editor-state-tojson-options.md ([feature], editorState.toJSON({compact, editor})) and .changeset/file-serialized-document-editor.md ([feature], the editor option of serializedDocumentFromEditorState).

Test plan

Before

The new regression tests, run against the unchanged sources:

Error: Unable to find an active editor. This method can only be used synchronously during the callback of editor.update(), editor.read(), or editor.getEditorState().read(..., {editor}).

The awareness tests, before the @lexical/yjs change:

AssertionError: expected "warn" to not be called at all, but actually been called 1 times

After

The new tests cover lexical (text content listener, editor.toJSON, EditorState.toJSON and its options form, editor.read with a state, a foreign state and an unknown mode), lexical-history (merge decisions), lexical-markdown, lexical-mdast, lexical-react (useLexicalIsTextContentEmpty, TableOfContentsPlugin), lexical-extension (HMR), lexical-file, lexical-yjs (v2 node methods; v1 and v2 awareness listeners run after the read) and lexical-y (regressions/NodeMethodsReadEditor, and regressions/UndoEventsAfterWriteRead for undo manager events after the write's read). The standalone examples were not type-checked against their own installs.

…arkdown][lexical-mdast][lexical-react][lexical-rich-text][lexical-y][lexical-yjs][lexical-eslint-plugin][lexical-playground][lexical-website] Bug Fix: Keep the editor active when reading or serializing an editor state from listeners

## Description

A node method that calls `$getEditor()` (directly, or through `$getPeerDependency`/`$getExtensionDependency`) threw "Unable to find an active editor" whenever Lexical read an editor state with `editorState.read(fn)` and no `{editor}`. The text content listeners hit it first (`triggerTextContentListeners`), and so did history merging, markdown/mdast shortcuts, `@lexical/y` and `@lexical/yjs` v2 collaboration, HMR, `editor.toJSON()`, `exportFile`, `useLexicalIsTextContentEmpty` and `TableOfContentsPlugin`.

Every such read now passes the editor. `editor.toJSON()` exports with its editor active, and `EditorState.toJSON()` uses the editor of a read of that same state. `serializedDocumentFromEditorState` takes an `editor` option. A new `editor.read(editorState, fn)` overload reads a given state of the editor (such as a listener's `prevEditorState`) with the editor active and without flushing. Package internals, the playground and dev-examples read with it; `examples/` and the docs keep `editorState.read(fn, {editor})`, since examples run on a published Lexical (a lint rule keeps the overload out of `examples/` and devtools). A `no-restricted-syntax` selector flags new editor-less `EditorState#read` calls in library sources, the playground, devtools, the website and the examples. Docs and examples now show `{editor}`.

Closes meta#9934

## Test plan

### Before

`./node_modules/.bin/vitest run --project unit <new tests>` with the source changes reverted:

```
Error: Unable to find an active editor. This method can only be used synchronously during the callback of editor.update(), editor.read(), or editor.getEditorState().read(..., {editor}).
```

### After

`./node_modules/.bin/vitest run --project unit <the 11 new or changed test files>`:

```
 Test Files  11 passed (11)
      Tests  101 passed (101)
```

`tsc -p .`, `tsc -p ./tsconfig.test.json`, ESLint and Prettier print nothing; `flow check` prints `No errors!`. Standalone examples could not be type-checked here (their dependencies are not installed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 18, 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 Nov 18, 2026 6:42pm UTC
lexical-playground Ready Ready Preview Nov 18, 2026 6:42pm 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 Nov 18, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Nov 18, 2026
@rootnode-bot

rootnode-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

AI review status for this pull request.

Review status Updated
🟢 Reviewed (for maintainers only) Nov 18, 2026, 7:06 PM UTC

@pkg-pr-new

pkg-pr-new Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/lexical@9941

@lexical/a11y

npm i https://pkg.pr.new/@lexical/a11y@9941

@lexical/clipboard

npm i https://pkg.pr.new/@lexical/clipboard@9941

@lexical/code

npm i https://pkg.pr.new/@lexical/code@9941

@lexical/code-core

npm i https://pkg.pr.new/@lexical/code-core@9941

@lexical/code-prism

npm i https://pkg.pr.new/@lexical/code-prism@9941

@lexical/code-shiki

npm i https://pkg.pr.new/@lexical/code-shiki@9941

@lexical/compiler

npm i https://pkg.pr.new/@lexical/compiler@9941

@lexical/devtools-core

npm i https://pkg.pr.new/@lexical/devtools-core@9941

@lexical/dragon

npm i https://pkg.pr.new/@lexical/dragon@9941

@lexical/eslint-plugin

npm i https://pkg.pr.new/@lexical/eslint-plugin@9941

@lexical/extension

npm i https://pkg.pr.new/@lexical/extension@9941

@lexical/fast-check

npm i https://pkg.pr.new/@lexical/fast-check@9941

@lexical/file

npm i https://pkg.pr.new/@lexical/file@9941

@lexical/hashtag

npm i https://pkg.pr.new/@lexical/hashtag@9941

@lexical/headless

npm i https://pkg.pr.new/@lexical/headless@9941

@lexical/history

npm i https://pkg.pr.new/@lexical/history@9941

@lexical/html

npm i https://pkg.pr.new/@lexical/html@9941

@lexical/internal

npm i https://pkg.pr.new/@lexical/internal@9941

@lexical/link

npm i https://pkg.pr.new/@lexical/link@9941

@lexical/list

npm i https://pkg.pr.new/@lexical/list@9941

@lexical/mark

npm i https://pkg.pr.new/@lexical/mark@9941

@lexical/markdown

npm i https://pkg.pr.new/@lexical/markdown@9941

@lexical/mdast

npm i https://pkg.pr.new/@lexical/mdast@9941

@lexical/offset

npm i https://pkg.pr.new/@lexical/offset@9941

@lexical/overflow

npm i https://pkg.pr.new/@lexical/overflow@9941

@lexical/plain-text

npm i https://pkg.pr.new/@lexical/plain-text@9941

@lexical/react

npm i https://pkg.pr.new/@lexical/react@9941

@lexical/rich-text

npm i https://pkg.pr.new/@lexical/rich-text@9941

@lexical/selection

npm i https://pkg.pr.new/@lexical/selection@9941

@lexical/table

npm i https://pkg.pr.new/@lexical/table@9941

@lexical/tailwind

npm i https://pkg.pr.new/@lexical/tailwind@9941

@lexical/text

npm i https://pkg.pr.new/@lexical/text@9941

@lexical/utils

npm i https://pkg.pr.new/@lexical/utils@9941

@lexical/y

npm i https://pkg.pr.new/@lexical/y@9941

@lexical/yjs

npm i https://pkg.pr.new/@lexical/yjs@9941

commit: bdb0b49

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the thorough fix for #9934. Every listener read Lexical makes now has its editor, and all 15 new tests fail on main with the issue's error and pass here. One regression in @lexical/y needs fixing before this can merge. The other points are optional.

Needs a fix: @lexical/y dispatches CAN_UNDO_COMMAND from inside a read

packages/lexical-y/src/internal/Binding.ts:6873 (and :5926 on the held path) now runs $writeCommit inside this._editor.read(editorState, …). The Yjs transaction in $runWriter (Binding.ts:7777) adds an undo step, and the binding's undo manager emits stack-item-added while that read is still on the stack. YExtension.ts:277-281 (and Collab.ts:141-145) then call editor.dispatchCommand(CAN_UNDO_COMMAND, …). Because this editor is now active in a read-only context, updateEditorSync (packages/lexical/src/LexicalUpdates.ts:1595) logs its DEV warning:

updateEditorSync: an editor update (e.g. a command listener that mutates the editor) ran while a read-only context was on the stack. …

The command still applies, but the warning fires on every new undo step and blames the app for dispatching from editor.read(). It is also every console problem reported in the 24 failing specs of e2e-tests / collab-y-linux (24.x, chromium) on this head; the collab Y harness requires a clean console. A minimal unit repro, YCollabExtension plus a CAN_UNDO_COMMAND listener and two local edits, logs no warning on main and one here.

Suggestion: hold the undo manager's stack events until the this._editor.read(…) at :5926 and :6873 returns. BindingUndoManager.emit already holds stack-item-popped this way (Binding.ts:325-337). Fixing it in the binding also keeps an app's own stack-item-added listener quiet, which patching only YExtension's listener would not. Then re-run pnpm run test-e2e-collab-y-chromium, since some failing specs involve read-only clients. Per packages/lexical-y/AGENTS.md ("Every bug fix lands with a regression test in src/__tests__/unit/regressions/"), add a test that spies console.warn around a local edit. NodeMethodsReadEditor.test.ts doesn't watch the console, which is why the unit suite stays green.

Optional, non-blocking

  • packages/lexical/src/LexicalEditor.ts:1953-1960: on a Lexical runtime from before this change, editor.read(editorState, fn) doesn't throw. It quietly reads the current state, because the old implementation treats any mode other than 'pending' like 'latest'. You already guard examples/ and devtools with lint. One sentence in the overload's TSDoc would warn library authors whose peer range includes older releases.
  • .changeset/active-editor-in-state-reads.md: the new overload appears only as "New: …" inside the [fix] entry's Verify:. A separate [feature] entry for lexical would list it under features (.changeset/README.md, CONTRIBUTING.md).
  • The same Verify: paragraph could note one more effect: a command dispatched inside one of these reads now gets the existing updateEditorSync DEV warning. Apps that follow the updated listeners.md and pass {editor} may see it.
  • packages/lexical-y/AGENTS.md asks a refactor to show identical updates and states over the fuzz seeds before and after. The full @lexical/y unit suite passes here, but the binding's reads now answer $isBlockContainer() with structure enforcement on, so a byte-identity run would confirm nothing it writes changed.

Automated review (maintainer link)

…its editor read during a write

## Description

With the editor now active in the binding's read of a local commit, the Yjs transactions it opens there ended inside that read-only context. The undo manager's `stack-item-added` and `stack-cleared` listeners, the document's observers and an app's `afterTransaction` handlers ran with the editor active, so YExtension's `CAN_UNDO_COMMAND`/`CAN_REDO_COMMAND` dispatch (or an app's) logged the `updateEditorSync` read-only-context warning on every local edit.

The binding now opens each transaction of its write (`YBinding#transact`) in a read of the same state without the editor, and runs the transaction's body with the editor active. Yjs callbacks around it run as they did before, and the bytes written are unchanged. A transaction joined to one under way keeps that transaction's context. Recorded as D137 in `DECISIONS.md`.

Also from the review:
- `editor.read(editorState, fn)` is declared before the mode overload, so `Parameters<LexicalEditor['read']>` is unchanged, and its TSDoc says what older releases do with it.
- The overload has its own `[feature]` changeset, and the fix's Verify paragraph notes the read-only warning for commands dispatched in these reads.
- The byte-trace harness exports states with the editor active.

## Test plan

### Before

`pnpm vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/UndoEventsAfterWriteRead.test.ts` on 11dcfdd:

```
 FAIL  |unit| ...UndoEventsAfterWriteRead.test.ts > a local edit announces its undo step without the active editor
 FAIL  |unit| ...UndoEventsAfterWriteRead.test.ts > an edit that clears the redo stack announces it without the active editor
 FAIL  |unit| ...UndoEventsAfterWriteRead.test.ts > an app's afterTransaction handler can dispatch a command during a local write
AssertionError: expected "warn" to not be called at all, but actually been called 4 times
      Tests  3 failed (3)
```

### After

```
      Tests  3 passed (3)
```

The @lexical/y byte traces (`LEXICAL_Y_BYTE_TRACE`, with and without `LEXICAL_Y_GC=1 FUZZ_GC=1`) match upstream main 08fbb42 in 487 of 488 test files. The other file, `LoadAcrossGap.test.ts`, also differs between two runs of main itself. The collab-y e2e suite (`pnpm run test-e2e-collab-y-chromium`) was not run here; it is left to CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This looks good: the fix is applied consistently across the packages, every public change is additive (the new editor.read(editorState, fn) overload and the optional editor option of serializedDocumentFromEditorState), and the new tests fail without the source changes and pass with them (15 of the 205 tests in the 13 new or changed test files fail on main). The suggestions below are optional and non-blocking.

Optional suggestions

  1. @lexical/yjs awareness listeners now run inside the editor-active read (packages/lexical-yjs/src/SyncEditorStates.ts:370 and :598). Both local syncs call syncLexicalSelectionToYjs inside binding.editor.read(currEditorState, ...), and it calls awareness.setLocalState (packages/lexical-yjs/src/SyncCursors.ts:1166), which emits change/update synchronously. An app awareness listener that dispatches a command now logs the development warning about an update started while a read-only context was on the stack, where it did not before (the command still applies). @lexical/y deliberately keeps this class of callback out of the read (D137 in packages/lexical-y/DECISIONS.md), so for consistency consider computing the relative positions inside the read and calling setLocalState after it returns, or naming awareness listeners in the changeset's Verify: paragraph (AGENTS.md, Changesets).
  2. Byte comparison for @lexical/y. The PR is titled a Refactor, and packages/lexical-y/AGENTS.md asks a refactor to show identical updates and states over the src/__tests__/fuzz/ seeds and a run of random sessions. Pasting that comparison would close the loop on the write-path change in packages/lexical-y/src/internal/Binding.ts.
  3. Test plan. The After section reports 11 files and 101 tests, while the PR adds or changes 13 unit test files (205 tests in them), and Before pastes one error line for all of them. AGENTS.md ('Commits and Pull Requests') asks for the real output of the command that was run.
  4. If you think it is worth it, a test with an editor-dependent node for the one-line swaps in IMEExtension.ts, NodeSelectionExtension.ts, NodeSelectionDataSelectedExtension.ts and HeadingAnnounceExtension.ts would cover the remaining read paths.

Automated review (maintainer link)

…tor read

## Description

`syncLexicalUpdateToYjs` and `syncLexicalUpdateToYjsV2__EXPERIMENTAL` call `awareness.setLocalState` from inside `binding.editor.read(currEditorState, ...)`. Since that read now has the editor active, an app awareness listener that dispatches a command (which `setLocalState` calls synchronously) gets the development warning about an update started in a read-only context.

The local syncs now compute the awareness state inside the read with a new internal `selectionAwarenessUpdate` and call `setLocalState` after the read returns. `syncLexicalSelectionToYjs` keeps its signature and behavior. The changeset's Verify paragraph mentions it.

## Test plan

### Before

```
$ npx vitest run --project unit packages/lexical-yjs/src/__tests__/unit/SyncActiveEditor.test.ts
 FAIL  |unit| packages/lexical-yjs/src/__tests__/unit/SyncActiveEditor.test.ts > awareness listeners run after the read > v1
 FAIL  |unit| packages/lexical-yjs/src/__tests__/unit/SyncActiveEditor.test.ts > awareness listeners run after the read > v2
AssertionError: expected "warn" to not be called at all, but actually been called 1 times
      Tests  2 failed | 1 passed (3)
```

### After

```
$ npx vitest run --project unit packages/lexical-yjs
 Test Files  17 passed (17)
      Tests  502 passed | 4 expected fail (506)
```

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks, this looks good. Keeping the editor active in every listener-side read, and in editor.toJSON(), fixes #9934 cleanly. The new editor.read(editorState, fn) overload is additive, and each new test fails without the source change and passes with it. Both points from the earlier review are addressed: @lexical/y now runs Yjs's transaction and undo-manager callbacks outside the editor-active write read, and @lexical/yjs applies the awareness update after its read.

Optional, non-blocking suggestions:

  1. Changeset for the new @lexical/file option (.changeset/active-editor-in-state-reads.md:16). The new editor option of serializedDocumentFromEditorState is mentioned only inside the fix entry's Verify: paragraph. A one-line [feature] entry for @lexical/file would list it under features, using the categories in CONTRIBUTING.md and .changeset/README.md.
  2. The overload and the [breaking] rule. CONTRIBUTING.md lists "a new overload" among type changes that can be breaking. No call site changes resolution here, because the new first parameter is an EditorState. Only code that re-declares read would need to accept the new shape: a subclass overriding LexicalEditor.read, or an object typed as Pick<LexicalEditor, 'read'>. [feature] looks right, but a sentence in the entry would settle it for readers.
  3. Coverage for the one-line conversions. IMEExtension.ts:109, NodeSelectionExtension.ts:44, NodeSelectionDataSelectedExtension.ts:104 and HeadingAnnounceExtension.ts:89 have no test of their own. They have the same shape as the tested sites, so this is polish.
  4. Unrecognized first argument (packages/lexical/src/LexicalEditor.ts:1969-1994). A first argument that is neither an EditorState from this copy of Lexical nor a known mode silently reads the committed state. A development-only warning would make that misuse visible.
  5. Docs (packages/lexical-website/docs/serialization/serialization.md:61). The new caveat could also mention that JSON.stringify(editor) now exports with the editor active.

Automated review (maintainer link)

…romEditorState's editor option

## Description

The new `editor` option of `serializedDocumentFromEditorState` was mentioned only in the fix changeset's `Verify:` paragraph. A `[feature]` changeset for `@lexical/file` now lists it under features.

## Test plan

### After

```
$ pnpm run check-changesets
Changeset check passed: 186 pending changeset(s) valid.
```

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ecognized first argument

## Description

A first argument to `editor.read()` that is neither an `EditorState` from this copy of Lexical nor a read mode (for example a state from a duplicated copy of `lexical`) silently read the editor's committed state. In development it now logs a warning once, and the read behaves as before.

The `editor.read(editorState, fn)` changeset also says why the overload is a `[feature]`: no existing call changes resolution, and only code that re-declares `read` (a subclass overriding it, or an object typed as `Pick<LexicalEditor, 'read'>`) has to accept the new shape. Its `Verify:` paragraph covers the warning.

## Test plan

### Before

```
AssertionError: expected "warn" to be called 1 times, but got 0 times
```

### After

The new test in `LexicalCustomTextContent.test.ts` checks the warning, that it is not logged for a mode or a state of the editor, and that the read still returns the committed state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t argument

## Description

A first argument to `editor.read()` that is neither an `EditorState` from this copy of Lexical nor a read mode (for example a state from a duplicated copy of `lexical`) read the editor's committed state, which for a state is the wrong data. The previous commit warned in development; it now throws with an `invariant` in every build, naming the argument (a string mode, or its type).

## Test plan

### After

The test in `LexicalCustomTextContent.test.ts` now expects the error for a foreign state and for a misspelled mode, and checks that a valid mode or a state of the editor still reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This looks good: the listener reads that used to run with no active editor (text content listeners, history merging, the markdown and mdast shortcuts, HMR, editor.toJSON(), exportFile, useLexicalIsTextContentEmpty, TableOfContentsPlugin and both Yjs bindings) now pass the editor, the new regression tests cover each path, and keeping @lexical/y's Yjs callbacks and @lexical/yjs's awareness update outside the editor-active read avoids new development warnings. The suggestions below are optional and non-blocking.

1. Optional: narrow the new editor.read() invariant (packages/lexical/src/LexicalEditor.ts:1973-1977)
Before this change, any first argument other than 'force-commit' or 'pending' fell through to a read of the committed state. With the invariant, an untyped caller that forwards an optional mode (editor.read(options.mode, fn) with options.mode undefined) now throws in production. The types already reject that call and the changeset's Verify: paragraph mentions it, but AGENTS.md ("Backwards Compatibility") asks that existing public APIs not change behavior in ways that could break callers. The hazard the throw targets is an object that is not an EditorState of this copy of lexical, where the old fallback returned the wrong state. Throwing only when the argument is an object, and keeping undefined and other non-object values on the committed-state path (perhaps with a development warning), would catch that case without breaking forwarding callers. If the throw stays as is, consider describing it in a [breaking] entry.

2. Optional: changeset category for the overload (.changeset/editor-read-editor-state.md:7)
The entry's second paragraph says code that re-declares read has to accept the new shape. For example, an object typed Pick<LexicalEditor, 'read'> with the old (...args: [() => T] | [EditorReadMode, () => T]) signature now fails with TS2322. CONTRIBUTING.md (the changeset rules, which name "a new overload") and .changeset/README.md ("Type signature changes") class a change that makes existing code stop type checking as [breaking], with Detect: (that shape and the error) and Migration: (accept an EditorState as the first argument). Existing call sites still compile unchanged, so maintainers may prefer to keep it as a feature.

3. Nit: Test plan output. AGENTS.md ("Commits and Pull Requests") asks the ### After subsection to paste the command and its passing output, not only to list the tests.

Automated review (maintainer link)

Comment thread packages/lexical/src/LexicalEditor.ts Resolved
Comment thread .changeset/editor-read-editor-state.md Resolved
…ditorState.toJSON({compact, editor})

## Description

Exporting a state with its editor active took a read around the call, `editorState.read(() => editorState.toJSON(true), {editor})` or `editor.read(editorState, () => editorState.toJSON(true))`. `editorState.toJSON({compact, editor})` now does it in one call, and its return type follows `compact` as the boolean overloads do. Without `editor` (or with `null`), it uses the editor of an enclosing read of the state, as `toJSON()` does.

The new overloads come before the boolean ones, so `Parameters<EditorState['toJSON']>` still resolves to the boolean signature. `editor.toJSON()`, `serializedDocumentFromEditorState`, `@lexical/y`'s draft exports and the playground ESM demo use the new form. `examples/` and the docs keep `editorState.read(fn, {editor})`, since they run on a published Lexical.

## Test plan

### After

A new test in `LexicalSerializationContext.test.ts` checks the legacy and compact forms and their types with an explicit editor, and the fallback to the enclosing read's editor without one. `pnpm run flow`:

```
Found 0 errors
```

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Description

`LexicalEditor` is exported only as a type, so no subclass can override `read`. The `editor.read(editorState, fn)` changeset now names only `Pick<LexicalEditor, 'read'>` as code that has to accept the new overload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Description

`editor.read` recognized an `EditorState` argument with a direct `instanceof`. It now uses `$isEditorState`, the existing guard, and imports `EditorState` only as a type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e.toJSON

## Description

Without an editor given, `EditorState.toJSON` kept the active editor only when the read or update it was called in was of that same state, and otherwise exported with no editor. An editor has several states (a listener's `prevEditorState`, a pending state), so `editor.read(() => prevEditorState.toJSON())` lost the editor. `toJSON` now keeps whatever editor is active and only replaces it when one is given.

## Test plan

### After

`LexicalSerializationContext.test.ts` also exports a state other than the one read inside `editor.read()`, and expects the editor-reading node to see the editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks, this looks good. Every listener-side read now keeps its editor, and the new reproducers fail without the change and pass with it. The @lexical/y and @lexical/yjs changes keep Yjs observers, undo-manager events and awareness listeners where they ran before. The suggestions below are optional and non-blocking.

Optional suggestions

  1. editor.read() now throws for any first argument that is not a mode (packages/lexical/src/LexicalEditor.ts:1974-1978). Before, editor.read(undefined, fn) read the committed state, so an untyped caller that forwards an optional mode now breaks in production. The changeset's Verify: paragraph documents this, but AGENTS.md ("Backwards Compatibility") asks that existing behavior keep working. You could throw only for an object that is not an EditorState (the duplicated-lexical case) and keep other values on the committed-state path, perhaps with a development warning. That catches the real hazard without breaking forwarding callers.
  2. With no editor given, toJSON() uses whichever editor is active, including an outer one (packages/lexical/src/LexicalEditorState.ts:367). Inside outer.read(...), nested.getEditorState().toJSON($isCompactExport()) now exports the nested nodes with the outer editor active. That is the pattern the $isCompactExport JSDoc recommends for a getter that serializes a nested editor (packages/lexical/src/LexicalSerializedExport.ts:111-115). Pointing that JSDoc at nestedEditor.toJSON() or editorState.toJSON({compact: $isCompactExport(), editor: nestedEditor}) would stop a nested node from reading its parent's configuration. The PR description's "an enclosing read of that same state" also no longer matches the code.
  3. Changeset wording (.changeset/active-editor-in-state-reads.md): the Verify: paragraph lists editor.toJSON() but not a bare editorState.toJSON() called inside a read or update, which now keeps that read's editor too.
  4. Test plan: the After section describes the coverage, while AGENTS.md ("Commits and Pull Requests") asks for the pasted output of the command that was run.

Whether the new read and toJSON overloads count as [feature] or [breaking] under .changeset/README.md ("Type signature changes") is a maintainer call. No existing call site stops compiling, and both entries name the Pick<…> shape that has to accept the new overloads.

Automated review (maintainer link)

… document nested exports

## Description

`editor.read()` threw for any first argument that was not a read mode, so an untyped caller forwarding an optional mode (`editor.read(undefined, fn)`) broke where it used to read the committed state. It now throws only for an object that is not an `EditorState` from this copy of Lexical (a duplicated `lexical`); any other value reads the committed state as before and logs a development warning once.

The `$isCompactExport` docs now tell a getter that serializes a nested editor's state to pass both the form and the nested editor, `editorState.toJSON({compact: $isCompactExport(), editor: nestedEditor})`, since a bare `toJSON` keeps the outer editor. The fix changeset's `Verify:` paragraph also lists `editorState.toJSON()` inside a read or update.

## Test plan

### After

`LexicalCustomTextContent.test.ts` expects the error for a foreign state, and for `undefined` the committed text and one warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This looks good to me. Keeping the editor active in the reads and exports Lexical makes from listeners fixes #9934 on every path the issue lists, and the new tests fail on main with the reported error and pass here. A few optional, non-blocking suggestions:

  1. Changeset category for the two new overloads (.changeset/editor-read-editor-state.md, .changeset/editor-state-tojson-options.md). CONTRIBUTING.md ("Changesets") and .changeset/README.md ("Type signature changes") file a new overload that can make existing code stop type checking as [breaking]. Both entries already say that an object typed Pick<LexicalEditor, 'read'> or Pick<EditorState, 'toJSON'> has to accept the new shape. If maintainers want the strict reading, a [breaking] entry with Detect: naming that shape and Migration: (accept an EditorState first argument, or an options object) would cover it. Keeping [feature] is also defensible, since no call site changes type.
  2. Say that the in-read export pattern needs this release (packages/lexical-website/docs/serialization/serialization.md:61-68, and the editor.read('latest', () => editor.getEditorState().toJSON()) snippets in docs/concepts/editor-state.md and packages/lexical/README.md). On earlier releases EditorState.toJSON() clears the active editor even inside a read, so someone on a published version who follows the page still gets the error. A short note like the one in the editor.read(editorState, fn) JSDoc would make that clear.
  3. Test plan output. AGENTS.md ("Commits and Pull Requests") asks the ### After section to paste the command and its passing output rather than describe what the tests cover.

The $isCompactExport JSDoc now steers nested exports to editorState.toJSON({compact: $isCompactExport(), editor: nestedEditor}), and editor.read(undefined, fn) keeps reading the committed state, which settles the earlier review comments on those points.

Automated review (maintainer link)

Comment on lines +61 to +63
Called on its own like this, the export runs with no active editor, so a node
whose `exportJSON()` calls `$getEditor()` (for example, to read an extension's
config) throws. Export inside a read of the state with the editor instead:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional, non-blocking: this pattern keeps the editor only from the release that ships this change. Before it, EditorState.toJSON() exports with no active editor even inside editorState.read(…, {editor}), so a reader on a published version still gets "Unable to find an active editor". A short note that it needs this release, like the one in the editor.read(editorState, fn) JSDoc, would set expectations; the same applies to the editor.read('latest', () => editor.getEditorState().toJSON()) snippets in editor-state.md and packages/lexical/README.md.

@etrepum
etrepum marked this pull request as ready for review November 19, 2026 01:52
@etrepum
etrepum added this pull request to the merge queue Nov 19, 2026
Merged via the queue into meta:main with commit 575e431 Nov 19, 2026
53 checks passed
@potatowagon potatowagon mentioned this pull request Dec 2, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — bdb0b49e Deployed Nov 18, 2026 by vercel[bot]
Preview – lexical-playground — bdb0b49e Deployed Nov 18, 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. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: "Unable to find an active editor" error when calling $getEditor() within getTextContent()

2 participants