Repository navigation
[*] Refactor: Use explicit active editor when reading or serializing an editor state from listeners - #9941
Conversation
…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>
|
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.
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 guardexamples/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'sVerify:. A separate[feature]entry forlexicalwould 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 existingupdateEditorSyncDEV warning. Apps that follow the updatedlisteners.mdand pass{editor}may see it. packages/lexical-y/AGENTS.mdasks a refactor to show identical updates and states over the fuzz seeds before and after. The full@lexical/yunit 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.
…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>
There was a problem hiding this comment.
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
@lexical/yjsawareness listeners now run inside the editor-active read (packages/lexical-yjs/src/SyncEditorStates.ts:370and:598). Both local syncs callsyncLexicalSelectionToYjsinsidebinding.editor.read(currEditorState, ...), and it callsawareness.setLocalState(packages/lexical-yjs/src/SyncCursors.ts:1166), which emitschange/updatesynchronously. 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/ydeliberately keeps this class of callback out of the read (D137 inpackages/lexical-y/DECISIONS.md), so for consistency consider computing the relative positions inside the read and callingsetLocalStateafter it returns, or naming awareness listeners in the changeset'sVerify:paragraph (AGENTS.md, Changesets).- Byte comparison for
@lexical/y. The PR is titled a Refactor, andpackages/lexical-y/AGENTS.mdasks a refactor to show identical updates and states over thesrc/__tests__/fuzz/seeds and a run of random sessions. Pasting that comparison would close the loop on the write-path change inpackages/lexical-y/src/internal/Binding.ts. - 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.
- 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.tsandHeadingAnnounceExtension.tswould cover the remaining read paths.
…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>
There was a problem hiding this comment.
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:
- Changeset for the new
@lexical/fileoption (.changeset/active-editor-in-state-reads.md:16). The neweditoroption ofserializedDocumentFromEditorStateis mentioned only inside the fix entry'sVerify:paragraph. A one-line[feature]entry for@lexical/filewould list it under features, using the categories in CONTRIBUTING.md and.changeset/README.md. - 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 anEditorState. Only code that re-declaresreadwould need to accept the new shape: a subclass overridingLexicalEditor.read, or an object typed asPick<LexicalEditor, 'read'>.[feature]looks right, but a sentence in the entry would settle it for readers. - Coverage for the one-line conversions.
IMEExtension.ts:109,NodeSelectionExtension.ts:44,NodeSelectionDataSelectedExtension.ts:104andHeadingAnnounceExtension.ts:89have no test of their own. They have the same shape as the tested sites, so this is polish. - Unrecognized first argument (
packages/lexical/src/LexicalEditor.ts:1969-1994). A first argument that is neither anEditorStatefrom this copy of Lexical nor a known mode silently reads the committed state. A development-only warning would make that misuse visible. - Docs (
packages/lexical-website/docs/serialization/serialization.md:61). The new caveat could also mention thatJSON.stringify(editor)now exports with the editor active.
…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>
There was a problem hiding this comment.
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.
…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>
There was a problem hiding this comment.
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
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'sVerify:paragraph documents this, but AGENTS.md ("Backwards Compatibility") asks that existing behavior keep working. You could throw only for an object that is not anEditorState(the duplicated-lexicalcase) and keep other values on the committed-state path, perhaps with a development warning. That catches the real hazard without breaking forwarding callers.- With no
editorgiven,toJSON()uses whichever editor is active, including an outer one (packages/lexical/src/LexicalEditorState.ts:367). Insideouter.read(...),nested.getEditorState().toJSON($isCompactExport())now exports the nested nodes with the outer editor active. That is the pattern the$isCompactExportJSDoc recommends for a getter that serializes a nested editor (packages/lexical/src/LexicalSerializedExport.ts:111-115). Pointing that JSDoc atnestedEditor.toJSON()oreditorState.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. - Changeset wording (
.changeset/active-editor-in-state-reads.md): theVerify:paragraph listseditor.toJSON()but not a bareeditorState.toJSON()called inside a read or update, which now keeps that read's editor too. - 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.
… 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>
There was a problem hiding this comment.
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:
- 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 typedPick<LexicalEditor, 'read'>orPick<EditorState, 'toJSON'>has to accept the new shape. If maintainers want the strict reading, a[breaking]entry withDetect:naming that shape andMigration:(accept anEditorStatefirst argument, or an options object) would cover it. Keeping[feature]is also defensible, since no call site changes type. - Say that the in-read export pattern needs this release (
packages/lexical-website/docs/serialization/serialization.md:61-68, and theeditor.read('latest', () => editor.getEditorState().toJSON())snippets indocs/concepts/editor-state.mdandpackages/lexical/README.md). On earlier releasesEditorState.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 theeditor.read(editorState, fn)JSDoc would make that clear. - Test plan output. AGENTS.md ("Commits and Pull Requests") asks the
### Aftersection 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.
| 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: |
There was a problem hiding this comment.
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.
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 witheditorState.read(fn)and no{editor}. Text content listeners were the reported case (triggerTextContentListeners). The same happened in history merging, markdown/mdast shortcuts,@lexical/yand@lexical/yjsv2 collaboration, HMR,editor.toJSON(),exportFile,useLexicalIsTextContentEmptyandTableOfContentsPlugin.editor.toJSON()exports with its editor active, andEditorState.toJSON()keeps the editor of the read or update it is called in (it used to set none).serializedDocumentFromEditorStatetakes an optionaleditor(declared in Flow too).editor.read(editorState, fn)overload: reads a given state of the editor (such as a listener'sprevEditorState) with the editor active and without flushing. Package internals, the playground and dev-examples read with it.examples/and the docs keepeditorState.read(fn, {editor}), since examples run on a published Lexical; a lint rule keeps the overload out ofexamples/and devtools. An object that is not anEditorStatefrom this copy of Lexical (a state from a duplicatedlexical) 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.editorState.toJSON({compact, editor}): exports a state with its editor active in one call, with the return type followingcompact. Withouteditorit keeps the active editor, astoJSON()does.editor.toJSON(),serializedDocumentFromEditorState,@lexical/yand the playground use it. Its overloads come before the boolean ones, soParameters<EditorState['toJSON']>is unchanged.no-restricted-syntaxselector flags new editor-lessEditorState#readcalls in library sources, the playground (including its ESM demo), devtools, the website, examples and dev-examples. It also matchesprevandheldreceivers.{editor}(or useeditor.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,afterTransactionhandlers, the undo manager's listeners such as theCAN_UNDO_COMMANDdispatch) 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 callawareness.setLocalStateafter 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 aVerify:paragraph),.changeset/editor-read-editor-state.md([feature], theeditor.read(editorState, fn)overload, with aVerify:paragraph for the new error),.changeset/editor-state-tojson-options.md([feature],editorState.toJSON({compact, editor})) and.changeset/file-serialized-document-editor.md([feature], theeditoroption ofserializedDocumentFromEditorState).Test plan
Before
The new regression tests, run against the unchanged sources:
The awareness tests, before the
@lexical/yjschange:After
The new tests cover lexical (text content listener,
editor.toJSON,EditorState.toJSONand its options form,editor.readwith 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, andregressions/UndoEventsAfterWriteReadfor undo manager events after the write's read). The standalone examples were not type-checked against their own installs.