Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .changeset/no-nested-editor-updates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@lexical/eslint-plugin': patch
'@lexical/list': patch
'@lexical/react': patch
'@lexical/y': patch
---

[feature] Warn about accidental nested editor updates in the default ESLint presets

The new `@lexical/no-nested-editor-updates` rule identifies same-editor
nested updates and explains how to preserve update options, move updates
out of read callbacks, and clarify `$function` context ownership. Async
functions are left alone because their editor context may end at an `await`.
Both rules preserve the existing ESLint 8 source-code access fallback, and
the new rule resolves receiver bindings through the scope manager when
`SourceCode#getScope` is unavailable (before ESLint 8.37). `$function`
diagnostics condition wrapper removal and option migration on targeting
the active editor. Transform diagnostics link to the preconditions needed
for inline mutations to converge.

Checklist space-key handlers and collaboration initial-state callbacks use
their surrounding update context. Intentional nested updates and
cross-editor verification receive targeted lint exemptions.

Verify: Review new lint warnings in command and transform callbacks, check
transform preconditions and `$function` editor ownership when removing an
update wrapper, confirm updates after `await` are left alone, and verify
checklist toggling and collaboration initialization and undo behavior.
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,9 @@ export const MarkdownPersistenceExtension = defineExtension({
if (hasStorage) {
window.localStorage.removeItem(storageKey);
}
editor.update(() => {
// Document replacement, like the repro-link path above.
editor.dispatchCommand(CLEAR_EDITOR_COMMAND);
$convertFromMarkdownString(defaultMarkdown);
});
// Document replacement, like the repro-link path above.
editor.dispatchCommand(CLEAR_EDITOR_COMMAND);
$convertFromMarkdownString(defaultMarkdown);
return true;
},
COMMAND_PRIORITY_EDITOR,
Expand Down
5 changes: 5 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,11 @@ export default [
files: ['**/*.ts', '**/*.tsx', '**/*.mts'],
})),
lexicalPlugin.configs['flat/all'],
{
rules: {
'@lexical/no-nested-editor-updates': ERROR,
Comment thread
rootnode-bot[bot] marked this conversation as resolved.
Resolved

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, for the rebase: #9862 on main added a $retokenizeOldTokens helper that opens its own editor.update(…, {discrete: true}), in packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts (line 816) and packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts (line 840). With this ERROR, lint on the head merged into current main reports both, and nothing else. Renaming the helper to retokenizeOldTokens (three call sites per file), as this PR does for pasteHtml and runOutdentScenario, keeps it green.

},
},
{
files: ['**/*.ts', '**/*.tsx', '**/*.mts'],
languageOptions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export const MarkdownPersistenceExtension = defineExtension({
if (hasStorage) {
window.localStorage.removeItem(storageKey);
}
editor.update(() => $fromString(defaultMarkdown));
$fromString(defaultMarkdown);
return true;
},
COMMAND_PRIORITY_EDITOR,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function dataTransferWithPlainText(text: string): DataTransfer {
return dt as unknown as DataTransfer;
}

function $pasteHtml(editor: LexicalEditorWithDispose, html: string) {
function pasteHtml(editor: LexicalEditorWithDispose, html: string) {
editor.update(
() => {
const selection = $getSelection();
Expand All @@ -72,7 +72,7 @@ describe('ClipboardImportExtension', () => {
using editor = buildEditorFromExtensions(
defineExtension({$initialEditorState, name: 'host'}),
);
$pasteHtml(editor, '<p>hello</p>');
pasteHtml(editor, '<p>hello</p>');
editor.read(() => {
const lastChild = $getRoot().getLastChild();
assert($isParagraphNode(lastChild), 'expected paragraph');
Expand Down Expand Up @@ -104,7 +104,7 @@ describe('ClipboardImportExtension', () => {
name: 'host',
}),
);
$pasteHtml(editor, '<p>ignored</p>');
pasteHtml(editor, '<p>ignored</p>');
editor.read(() => {
const lastChild = $getRoot().getLastChild();
assert($isParagraphNode(lastChild), 'expected paragraph');
Expand Down Expand Up @@ -133,7 +133,7 @@ describe('ClipboardImportExtension', () => {
name: 'host',
}),
);
$pasteHtml(editor, '<p>hello</p>');
pasteHtml(editor, '<p>hello</p>');
editor.read(() => {
const lastChild = $getRoot().getLastChild();
assert($isParagraphNode(lastChild), 'expected paragraph');
Expand Down Expand Up @@ -348,7 +348,7 @@ describe('ClipboardImportExtension', () => {
name: 'host',
}),
);
$pasteHtml(editor, '<p>via <strong>new</strong> pipeline</p>');
pasteHtml(editor, '<p>via <strong>new</strong> pipeline</p>');
editor.read(() => {
const lastChild = $getRoot().getLastChild();
assert($isParagraphNode(lastChild), 'expected paragraph');
Expand Down Expand Up @@ -379,7 +379,7 @@ describe('$insertDataTransferForRichText selection argument (#6278)', () => {
);
}

function $insertOverFirstParagraph(
function insertOverFirstParagraph(
editor: LexicalEditorWithDispose,
dataTransfer: DataTransfer,
) {
Expand All @@ -405,29 +405,29 @@ describe('$insertDataTransferForRichText selection argument (#6278)', () => {

test('text/plain is inserted at the supplied selection', () => {
using editor = makeEditor();
$insertOverFirstParagraph(editor, dataTransferWithPlainText('replacement'));
insertOverFirstParagraph(editor, dataTransferWithPlainText('replacement'));
expect(paragraphTexts(editor)).toEqual(['replacement', 'second']);
});

test('multi-line text/plain is inserted at the supplied selection', () => {
using editor = makeEditor();
$insertOverFirstParagraph(editor, dataTransferWithPlainText('one\ntwo'));
insertOverFirstParagraph(editor, dataTransferWithPlainText('one\ntwo'));
expect(paragraphTexts(editor)).toEqual(['one', 'two', 'second']);
});

test('text/uri-list is inserted at the supplied selection', () => {
using editor = makeEditor();
const dt = new DataTransfer();
dt.setData('text/uri-list', 'https://lexical.dev');
$insertOverFirstParagraph(editor, dt as unknown as DataTransfer);
insertOverFirstParagraph(editor, dt as unknown as DataTransfer);
expect(paragraphTexts(editor)).toEqual(['https://lexical.dev', 'second']);
});

test('text/html is inserted at the supplied selection', () => {
// Control: the text/html handler already honored the argument before
// this fix, so this passes with or without it.
using editor = makeEditor();
$insertOverFirstParagraph(
insertOverFirstParagraph(
editor,
dataTransferWithHtml('<p>replacement</p>'),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {assert} from 'vitest';
* call its own `registerCodeHighlighting(editor, ..., tabSize)` and any
* async language/theme loading the highlighter requires.
*/
export function $runOutdentScenario(
export function runOutdentScenario(
editor: LexicalEditor,
rawText: string,
cursorOffset: number,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ import {
import {describe, expect, test} from 'vitest';

import {
$runOutdentScenario,
OUTDENT_SCENARIOS,
runOutdentScenario,
} from '../../../../lexical-code-core/src/__tests__/outdentTestUtils';

describe('LexicalCodeNode tests', () => {
Expand Down Expand Up @@ -262,7 +262,7 @@ describe('LexicalCodeNode tests', () => {
],
name: 'prism-outdent',
});
const {text, cursor} = $runOutdentScenario(
const {text, cursor} = runOutdentScenario(
editor,
rawText,
cursorOffset,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ import {
import {assert, describe, expect, test} from 'vitest';

import {
$runOutdentScenario,
OUTDENT_SCENARIOS,
runOutdentScenario,
} from '../../../../lexical-code-core/src/__tests__/outdentTestUtils';
import {isCodeThemeLoaded} from '../../FacadeShiki';

Expand Down Expand Up @@ -309,7 +309,7 @@ describe('LexicalCodeNode tests', () => {
],
name: 'shiki-outdent',
});
const {text, cursor} = $runOutdentScenario(
const {text, cursor} = runOutdentScenario(
editor,
rawText,
cursorOffset,
Expand Down
95 changes: 94 additions & 1 deletion packages/lexical-eslint-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ export default [

`lexical.configs['flat/recommended']` and `lexical.configs['flat/all']` are
aliases of `recommended` and `all` from when those names were the legacy
configs.
configs. The default presets enable `@lexical/rules-of-lexical` and
`@lexical/no-nested-editor-updates` as warnings.
`@lexical/no-document-in-dom-methods` remains opt-in because it is specific
to Lexical DOM method implementations.

### Custom Configuration

Expand All @@ -46,6 +49,96 @@ export default [
];
```

### Preventing nested editor updates

`@lexical/no-nested-editor-updates` reports same-editor `update()` calls
directly inside `update`, `registerCommand`, or `registerNodeTransform`
callbacks. The receivers must match by expression and identifier binding;
updates to a different editor, such as `childEditor.update(...)`, are valid.
The default presets enable the rule as a warning; set it to `error` or `off`
in your flat configuration's `rules` object to change that severity.

When removing an update wrapper from a node transform, check the transform's
[preconditions](https://lexical.dev/docs/concepts/transforms#preconditions)
so its mutations converge. Inline mutations participate in the current
transform cycle and can trigger the transform again.

Command listeners already provide an update context. Remove a nested
`editor.update()` wrapper and perform the mutation directly:

```js
editor.registerCommand(
REMOVE_NODE_COMMAND,
() => {
$getSelection().removeText();
return true;
},
COMMAND_PRIORITY_EDITOR,
);
```

Inside `editor.read(callback)` or `editor.read(mode, callback)`, the context
is read-only. Move the intact update after the read instead of removing its
wrapper:

```js
const shouldRemove = editor.read('latest', () => {
return $getSelection()?.isCollapsed() === false;
});

if (shouldRemove) {
editor.update(() => {
$getSelection()?.removeText();
});
}
```

An update directly inside a $function receives separate guidance: remove the
wrapper if the function uses the active editor context, or remove the `$`
prefix if the function intentionally owns the update.

For a statically analyzable options object, preserve `tag` with `$addUpdateTag`
(once per value for an array), `discrete` with `$flushSyncAfterUpdate`, and
`onUpdate` with `$onUpdate` before removing the wrapper. Preserve conditional
option values: call `$flushSyncAfterUpdate()` only when `discrete` is true.
`skipTransforms` has no in-place equivalent, so objects containing it, opaque
identifiers, spreads, computed properties, and unknown properties are left
alone. Updates inside `read()` retain all options when moved after the read.

By default, editor expressions must end in `editor`, ignoring case. This
recognizes `editor`, `childEditor`, `props.editor`, `$getEditor()`, and
`this.editor`. The last expression matches across arrow callbacks, where
`this` is lexical, but not ordinary function callbacks. Inside $functions,
`editor`, `$getEditor()`, and receivers matching configured `isEditor`
patterns are assumed to be the active editor.

Use `isEditor` to add names or patterns, and `isDollarFunction` to extend
the default `/^\$[a-z_]/` function-name matcher:

```js
const rules = {
'@lexical/no-nested-editor-updates': [
'error',
{
isDollarFunction: '^INTERNAL_\\$',
isEditor: ['^lexicalInstance$', '^getMyEditor$'],
},
],
};
```

Repeated zero-argument accessors matching the default naming convention or
configured `isEditor` patterns, such as `getNestedEditor()`, match as the
same editor expression. The analysis does not follow callbacks passed by
reference, aliases between differently named editor variables, or another
nested callback such as `setTimeout(() => editor.update(...))`. There is no
autofix.

Async callbacks and async $functions are also left alone because code after
an `await` no longer has the surrounding editor context. A synchronous
editor callback nested inside an async function is still checked.


### Advanced configuration

Most of the heuristics in `@lexical/rules-of-lexical` can be extended with
Expand Down
7 changes: 5 additions & 2 deletions packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
// @ts-check

import {noDocumentInDomMethods} from './rules/no-document-in-dom-methods.js';
import {noNestedEditorUpdates} from './rules/no-nested-editor-updates.js';
import {rulesOfLexical} from './rules/rules-of-lexical.js';
import {yCollabStatus} from './rules/y-collab-status.js';
import {SOURCE_VERSION} from './version.js';

/**
* @typedef {import('eslint').Rule.RuleModule} RuleModule
* @typedef {{plugins: {'@lexical': Plugin}; rules: {'@lexical/rules-of-lexical': 'warn' | 'error' | 'off'; '@lexical/y-collab-status': 'warn' | 'error' | 'off'}}} FlatConfig
* @typedef {{plugins: {'@lexical': Plugin}; rules: {'@lexical/no-nested-editor-updates': 'warn' | 'error' | 'off'; '@lexical/rules-of-lexical': 'warn' | 'error' | 'off'; '@lexical/y-collab-status': 'warn' | 'error' | 'off'}}} FlatConfig
* @typedef {{meta: {name: string; version: string}; rules: Rules; configs: Configs}} Plugin
* @typedef {{'no-document-in-dom-methods': RuleModule; 'rules-of-lexical': RuleModule; 'y-collab-status': RuleModule}} Rules
* @typedef {{'no-document-in-dom-methods': RuleModule; 'no-nested-editor-updates': RuleModule; 'rules-of-lexical': RuleModule; 'y-collab-status': RuleModule}} Rules
* @typedef {{all: FlatConfig; recommended: FlatConfig; 'flat/all': FlatConfig; 'flat/recommended': FlatConfig}} Configs
*/

Expand Down Expand Up @@ -67,6 +68,7 @@ function createConfigs(pluginMeta, pluginRules) {
'@lexical': plugin,
},
rules: {
'@lexical/no-nested-editor-updates': 'warn',
'@lexical/rules-of-lexical': 'warn',
// Fires only on configExtension(YCollabExtension, {doc, ...}).
'@lexical/y-collab-status': 'error',
Expand All @@ -91,6 +93,7 @@ export const meta = createMeta();
/** @type {Rules} */
export const rules = {
'no-document-in-dom-methods': noDocumentInDomMethods,
'no-nested-editor-updates': noNestedEditorUpdates,
'rules-of-lexical': rulesOfLexical,
'y-collab-status': yCollabStatus,
};
Expand Down
Loading
Loading