Skip to content

[Breaking Change][lexical] Chore: Remove redundant registerCommand/registerNodeTransform generics - #8877

Merged
etrepum merged 9 commits into
meta:mainfrom
mayrang:chore/remove-redundant-registercommand-generics
Jul 25, 2026
Merged

etrepum merged 9 commits into
meta:mainfrom
mayrang:chore/remove-redundant-registercommand-generics

Conversation

@mayrang

@mayrang mayrang commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Breaking Change

This PR makes the type for LexicalCommand stricter by carrying a brand to invariantly witness the phantom payload type. When not using inference (e.g. with an explicit generic or in some cases by annotating the handler function) it was previously possible to write unsafe code that still passed the type checker because all LexicalCommand were structurally compatible from TypeScript's perspective. Previously correct code requires no changes, even if it was using annotations or explicit generics.

To correct this code, you can either annotate the correct type, or remove the explicit annotation altogether and let TypeScript infer the correct type from the command argument.

If you were using the unsafe LexicalCommand<unknown> you should switch to the newly exported AnyLexicalCommand alias or write LexicalCommand<any> instead (backwards compatible).

Description

Every LexicalCommand<T> constant already carries its payload type, so the explicit generic on registerCommand<T>(...) is always inferred. This removes the redundant generic from 61 call sites (57 registerCommand + 4 in tests) across 20 files.

Also includes two small opportunistic cleanups in the same files:

  • Replaces one $isRootNode(x) || $isShadowRootNode(x) with $isRootOrShadowRoot(x) in lexical-rich-text
  • registerNodeTransform<T> in lexical-text (same redundancy — Klass<T> argument already infers T)

Two KEY_ENTER_COMMAND listeners in lexical-code-core and lexical-playground/ImageComponent previously used <KeyboardEvent> to narrow away the command's null payload. Removing the generic surfaced this, so explicit null checks were added (matching the pattern already used in lexical-rich-text and lexical-plain-text).

The type for dispatchCommand was also modified to allow the payload argument to be optional when it can be undefined or void. The codebase was cleaned up to remove the redundant trailing undefined arguments accordingly.

Test plan

  • pnpm test-unit — 3984 pass
  • pnpm test-e2e-chromium — 771 pass
  • tsc / flow / prettier / eslint clean

mayrang added 4 commits July 24, 2026 11:11
All command constants are already typed as LexicalCommand<T>, so the generic on registerCommand is always inferred. This removes the explicit generic from 57 call sites across 18 files.

Also replaces one $isRootNode(x) || $isShadowRootNode(x) with the combined $isRootOrShadowRoot(x) guard in lexical-rich-text, and adds null-safety for KEY_ENTER_COMMAND listeners that previously narrowed away the null via the explicit generic.
@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 Jul 24, 2026
@vercel

vercel Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Jul 25, 2026 7:29pm
lexical-playground Ready Ready Preview Jul 25, 2026 7:29pm

Request Review

@levensta

Copy link
Copy Markdown
Contributor

I also noticed that the editor is excessively passing undefined to the payload argument when the command doesn't require a payload.
Is it possible to improve the typing of dispatchCommand so that it doesn't require explicitly passing undefined if the command type doesn't require a payload?

- editor.dispatchCommand(UNDO_COMMAND, undefined);
+ editor.dispatchCommand(UNDO_COMMAND);

@etrepum

etrepum commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

I also noticed that the editor is excessively passing undefined to the payload argument when the command doesn't require a payload. Is it possible to improve the typing of dispatchCommand so that it doesn't require explicitly passing undefined if the command type doesn't require a payload?

- editor.dispatchCommand(UNDO_COMMAND, undefined);
+ editor.dispatchCommand(UNDO_COMMAND);

It's possible just a more complicated conditional type, there are no constraints on T so undefined isn't an inhabitant of all possible generics.

export interface LexicalCommand<T> {}
export type CommandPayloadType<TCommand> =
  TCommand extends LexicalCommand<infer TPayload> ? TPayload : never;

export function createCommand<T>(name: string): LexicalCommand<T> { return {}; }

export type DispatchArgs<TCommand extends LexicalCommand<undefined>> = TCommand extends LexicalCommand<infer TPayload> ? 
  ((TPayload extends undefined ? [TCommand] : never) | [TCommand, TPayload]) :
  never;

export function dispatchCommandEx<TCommand extends LexicalCommand<unknown>>(
  ...args: DispatchArgs<TCommand>
): boolean {
  return false;
}

const OPTIONAL_COMMAND = createCommand<undefined | Event>('OPTIONAL_COMMAND');
const UNKNOWN_COMMAND = createCommand<unknown>('UNKNOWN_COMMAND');
const STRING_COMMAND = createCommand<string>('STRING_COMMAND');

dispatchCommandEx(OPTIONAL_COMMAND, new CustomEvent('type'));
dispatchCommandEx(OPTIONAL_COMMAND, undefined);
dispatchCommandEx(OPTIONAL_COMMAND);
dispatchCommandEx(UNKNOWN_COMMAND, 'anything but required');
// @ts-expect-error
dispatchCommandEx(UNKNOWN_COMMAND);
dispatchCommandEx(STRING_COMMAND, 'string');
// @ts-expect-error
dispatchCommandEx(STRING_COMMAND);

@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Jul 24, 2026
…d calls

Clean up the 7 standalone dispatchCommand(editor, CMD, undefined) calls in
LexicalEvents.ts and the JSDoc example in HorizontalRuleExtension.ts that
were missed in the previous pass.
@mayrang

mayrang commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the suggestion @levensta, and @etrepum thanks for picking this up and landing the CommandPayloadArgs approach directly.

Pushed one more commit on top cleaning up the 7 dispatchCommand(editor, CMD, undefined) calls left in LexicalEvents.ts and the JSDoc example in HorizontalRuleExtension.ts.

@etrepum etrepum changed the title [lexical] Chore: Remove redundant registerCommand/registerNodeTransform generics [Breaking Change][lexical] Chore: Remove redundant registerCommand/registerNodeTransform generics Jul 25, 2026
@etrepum
etrepum added this pull request to the merge queue Jul 25, 2026
Merged via the queue into meta:main with commit 82cdae1 Jul 25, 2026
40 checks passed
@etrepum etrepum mentioned this pull request Jul 29, 2026
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 6, 2026
Conflicts resolved:
- formatList.ts: compose upstream's named-slot guard (meta#8905) with this
  branch's $copySemanticNestingMark — the mark copy now happens inside the
  slot-host check, alongside the children move it annotates.
- registerList.ts: accept upstream's removal of the decorator-adjacent
  backspace handler (meta#8871); the semantic parking that handler carried
  lives in ListItemNode.collapseAtStart, which the core deleteCharacter
  path invokes, and registerListBackspaceDecorator.test.ts still passes.
  Drop the now-unused $parkNestedListsInWrapper import here.

Also align this branch's ARROW_RIGHT registration with upstream's
registerCommand generics removal (meta#8877 follow-up, meta#8871 series).

Verified: tsc clean; 872 list/markdown/mdast unit tests, 51 browser tests,
and 4267 core/react/html/selection/rich-text tests pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
AlessioGr added a commit to payloadcms/payload that referenced this pull request Sep 10, 2026
Upgrades `lexical` and every installed `@lexical/*` package from
`0.48.0` to `0.50.0` for Payload 4.x (`main`). Updates the dependency
pins, lockfile, `lexicalTargetVersion`, and v4 migration guide.

## Breaking changes

**No application changes or data migration are needed when using
Payload's built-in rich text features.**

If you maintain custom rich text features, check that they still compile
and that custom content loads, copies, and pastes correctly. Lexical
tightened some TypeScript types and changed how custom nodes are loaded
and copied. Tests that inspect the editor's HTML may also need updated
selectors or snapshots because Lexical adds some internal markup.

**Do not install `lexical` or `@lexical/*` yourself for use with
Payload.** Remove any direct dependencies you added for the editor and
use Payload's re-exports from `@payloadcms/richtext-lexical/lexical` and
`@payloadcms/richtext-lexical/lexical/*`. Payload supplies the matching
versions; mixing versions can break the editor. This is the existing
[custom feature
requirement](https://payloadcms.com/docs/rich-text/custom-features).

## Breaking changes and Payload migrations

Reviewed
[0.49.0](https://github.com/facebook/lexical/releases/tag/v0.49.0) and
[0.50.0](https://github.com/facebook/lexical/releases/tag/v0.50.0).
Listed below are breaking API/type changes and behavior changes
explicitly identified as breaking in the release notes. Deprecations and
routine bug fixes are omitted. **Yes** means we had to change Payload
code; **No** means no Payload migration was required.

| Release | Breaking change | Required migration in Payload | Changes
made |
| ------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ----------------------------- |
---------------------------------------------------------------------------------------------------------------------------------
|
| 0.49 | [Built-in nodes adopt
`$config()`](meta/lexical#8640). Direct
static `importJSON`, `importDOM`, `clone`, and `transform`
implementations change; `__type` becomes readonly and automatic node
construction needs zero-argument defaults. Custom static implementations
remain supported. | No | - |
| 0.49 | [`LexicalCommand<T>` checks its payload type more
strictly](meta/lexical#8877).
`LexicalCommand<unknown>` is no longer a safe catch-all. | Yes | Focus
and blur commands were incorrectly registered with `MouseEvent`. Removed
the explicit types so Lexical infers `FocusEvent`. |
| 0.50 | [Named-slot values cannot be replaced with
`LexicalNode.replace()`](meta/lexical#8938).
Block converters also [skip slot
values](meta/lexical#8905). | No | - |
| 0.50 | [Lexical JSON clipboard copying checks
`excludeFromCopy('clone')`, not
`'html'`](meta/lexical#8995). | No | - |

Also updated the copied table action menu for merged-cell bounds, header
toggles, and merge/unmerge selection, and fixed the upload alignment
test’s image selector. The nested toolbar wheel test now hovers each
toolbar before scrolling; its assertions are unchanged. Both affected
e2e tests pass locally in Chromium on TanStack. Formatting and diff
checks pass.

## Previous Lexical upgrades

- [#17554](#17554) — 0.45.0 →
0.48.0
- [#17064](#17064) — 0.41.0 →
0.45.0
- [#15760](#15760) — 0.35.0 →
0.41.0
AlessioGr added a commit to payloadcms/payload that referenced this pull request Sep 11, 2026
Upgrades `lexical` and every installed `@lexical/*` package from
`0.41.0` to `0.50.0` for Payload 3.x. Updates the dependency pins,
lockfile, and `lexicalTargetVersion`.

Also exposes the 15 React entry points added on main in
[#17554](#17554) through
`@payloadcms/richtext-lexical/lexical/react/*`, so custom features can
use these APIs through Payload.

## Breaking changes

**No application changes or data migration are needed when using
Payload's built-in rich text features.**

If you maintain custom rich text features, check that they still compile
and that custom content loads, copies, and pastes correctly. Lexical
removed some older APIs, tightened TypeScript types, and changed how
custom nodes are loaded and copied. Tests that inspect the editor's HTML
may also need updated selectors or snapshots because Lexical adds some
internal markup.

**Do not install `lexical` or `@lexical/*` yourself for use with
Payload.** Remove any direct dependencies you added for the editor and
use Payload's re-exports from `@payloadcms/richtext-lexical/lexical` and
`@payloadcms/richtext-lexical/lexical/*`. Payload supplies the matching
versions; mixing versions can break the editor. This is the existing
[custom feature
requirement](https://payloadcms.com/docs/rich-text/custom-features).

The 3.x Markdown implementation and converter defaults are preserved.
This does not backport the v4 Markdown API changes.

## Breaking changes and Payload migrations

Reviewed
[0.42.0](https://github.com/facebook/lexical/releases/tag/v0.42.0),
[0.43.0](https://github.com/facebook/lexical/releases/tag/v0.43.0),
[0.44.0](https://github.com/facebook/lexical/releases/tag/v0.44.0),
[0.45.0](https://github.com/facebook/lexical/releases/tag/v0.45.0),
[0.46.0](https://github.com/facebook/lexical/releases/tag/v0.46.0),
[0.47.0](https://github.com/facebook/lexical/releases/tag/v0.47.0),
[0.48.0](https://github.com/facebook/lexical/releases/tag/v0.48.0),
[0.49.0](https://github.com/facebook/lexical/releases/tag/v0.49.0),
[0.50.0](https://github.com/facebook/lexical/releases/tag/v0.50.0).
Listed below are breaking API/type changes and behavior changes
explicitly identified as breaking in the release notes. Deprecations and
routine bug fixes are omitted. **Yes** means we had to change Payload
code; **No** means no Payload migration was required.

| Release | Breaking change | Required migration in Payload | Changes
made |
| ------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ----------------------------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| 0.42 | [Experimental `hasFitNestedTables` moves out of the table
package into the
playground](meta/lexical#8210). | No | - |
| 0.42 | [The deprecated context-menu plugin is
removed](meta/lexical#8199). | Yes | Removed
the invalid `LexicalContextMenuPlugin` proxy and package export. Custom
consumers must use
`@payloadcms/richtext-lexical/lexical/react/LexicalNodeContextMenuPlugin`
and adapt to its node-context-menu API. |
| 0.43 | [Nested editors delegate asynchronously to their
parent](meta/lexical#8308), restoring the
behavior from before 0.42.0. | No | - |
| 0.45 | [`$getReconciledDirection` now inherits direction through
shadow-root nodes](meta/lexical#8479). | No
| - |
| 0.45 | [Backspace at the start of a non-empty block preserves the
current block type and
formatting](meta/lexical#8493). | No | - |
| 0.45 | [Moving nodes between parents adjusts selection
offsets](meta/lexical#8501). | No | - |
| 0.45 | [Markdown shortcuts can trigger when IME composition
commits](meta/lexical#8503). | No | - |
| 0.45 | [Rich/plain text automatically removes empty inline
elements](meta/lexical#8497). | No | - |
| 0.45 | [Triple-click selection normalization moves from core into
rich/plain text
registration](meta/lexical#8520). Editors
bypassing that registration must add
`NormalizeTripleClickSelectionExtension`. | No | - |
| 0.45 | [`DOMSlot` and the DOM rendering override APIs are
generalized](meta/lexical#8519); playground
`AutocompleteNode` is replaced by `VisibleLineBreakExtension`. | No | -
|
| 0.46 | [`static importJSON` widens its parameter to
`SerializedLexicalNode & Record<string,
unknown>`](#17554). Overrides
using serialized interfaces can fail TypeScript checks. | No | - |
| 0.46 | [Node lookups and traversal no longer infer unchecked subclass
types](meta/lexical#8661). Explicit
unchecked traversal generics are deprecated. | Yes | Removed the upload
drawer’s assumption that a node lookup returns `UploadNode`. Added
`$isUploadNode` before reading or updating upload data. |
| 0.46 | [DOM lookups of the editor root return `RootNode` instead of
`null`](meta/lexical#8588).
Selection-capture handling is also generalized beyond decorators. | No |
- |
| 0.46 | [`insertNodes` preserves leading line breaks, and managed line
breaks receive a DOM
marker](meta/lexical#8615). | No | - |
| 0.46 | [Experimental DOM-import rules register through node
extensions](meta/lexical#8662); the separate
per-package import extensions become deprecated aliases. | No | - |
| 0.46 | [Experimental named slots change the Yjs sync
signature](meta/lexical#8603):
`syncLexicalUpdateToYjsV2__EXPERIMENTAL` gains a `dirtyLeaves`
parameter. | No | - |
| 0.46 | [Copying an element through `NodeSelection` includes its
children](meta/lexical#8603), instead of
copying an empty shell. | No | - |
| 0.46 | [Previously deprecated exports are
removed](meta/lexical#8704): `toggleLink`,
`insertList`, `removeList`, and ContentEditable’s `Props` alias.
Replacements are `$toggleLink`, `$insertList`, `$removeList`, and
`ContentEditableProps`. | No | - |
| 0.47 | [React 17 support is
removed](meta/lexical#8782); React 18 or
later is required. | No | - |
| 0.47 | [Segmented text temporarily switches to normal mode during IME
composition while keeping its
DOM](meta/lexical#8784). Subclasses must
tolerate that temporary mode. | No | - |
| 0.49 | [Built-in nodes adopt
`$config()`](meta/lexical#8640). Direct
static `importJSON`, `importDOM`, `clone`, and `transform`
implementations change; `__type` becomes readonly and automatic node
construction needs zero-argument defaults. Custom static implementations
remain supported. | No | - |
| 0.49 | [`LexicalCommand<T>` checks its payload type more
strictly](meta/lexical#8877).
`LexicalCommand<unknown>` is no longer a safe catch-all. | Yes | Focus
and blur commands were incorrectly registered with `MouseEvent`. Removed
the explicit types so Lexical infers `FocusEvent`. |
| 0.50 | [Named-slot values cannot be replaced with
`LexicalNode.replace()`](meta/lexical#8938).
Block converters also [skip slot
values](meta/lexical#8905). | No | - |
| 0.50 | [Lexical JSON clipboard copying checks
`excludeFromCopy('clone')`, not
`'html'`](meta/lexical#8995). | No | - |

Also updated the copied table action menu for merged-cell bounds, header
toggles, and merge/unmerge selection, and fixed the upload alignment
test’s image selector. Formatting and diff checks pass for the upload
selector fix.

Verified all 15 new entry points through source and published export
maps with runtime imports and TypeScript checks. ESLint and formatting
checks pass.

## Previous Lexical upgrades

- [#15760](#15760) — 0.35.0 →
0.41.0
- [#13715](#13715) — 0.34.0 →
0.35.0
- [#13622](#13622) — 0.28.0 →
0.34.0
zurfyx added a commit that referenced this pull request Nov 2, 2026
…s in CHANGELOG.md by the call shapes they break, and add the missing v0.48 list Backspace behavior change

## Description

Three backfilled CHANGELOG.md entries did not tell people upgrading who is affected or what to change:

- v0.46.0, #8661: the breaking entry said traversal methods "return the base node type" and only named annotated assignments. It did not say that the methods (and `$getNodeByKey` / `$getNodeByKeyOrThrow`) gained a non-generic first overload, so a call without a type argument that used to infer `T` from where its result went (a function argument, a return value, an annotated variable or array) now returns `LexicalNode` and stops compiling. Detect now names those call shapes and the TypeScript error, Migration shows the function-argument case, and the matching deprecation entry now has its own Detect and says the overloads were removed from TypeScript in v0.53.0 (#9479), while the Flow declarations keep them after #9529, instead of "Removal: not scheduled".
- v0.49.0, #8877: the entry said `LexicalCommand<T>` is invariant, but Detect only named `LexicalCommand<unknown>` and explicit generics. A `registerCommand` listener whose parameter annotation is narrower or wider than the payload (for example `(event: KeyboardEvent) => ...` for `KEY_ENTER_COMMAND`, whose payload is `KeyboardEvent | null`), or a helper typed `LexicalCommand<KeyboardEvent>` called with that command, also stops compiling. Detect lists these shapes and the error, and Migration shows inferred listeners and a generic helper.
- v0.48.0, #8829: not listed at all. `registerList` handles Backspace at `COMMAND_PRIORITY_BEFORE_EDITOR`, before rich text: at the start of a top-level item it turns the item into a paragraph and splits the list, where it used to join it to the item above. It is now a behavior change with a Verify line. `ListItemNode.collapseAtStart` also widened its return type from `true` to `boolean`; the entry says why that is not filed as breaking.

To keep this from recurring, `.changeset/README.md` gets a "Type signature changes" section: a type change that can make existing call sites stop compiling is `[breaking]` even when it only deprecates something, and its Detect names the call shapes, including callers that rely on an inferred type argument. AGENTS.md and CONTRIBUTING.md, which already summarize the changeset format, get one paragraph each. `pnpm run check-changesets` now warns (without failing) when a `[deprecation]` or `[chore]` entry mentions a type parameter, overload, generic, return or payload type, or signature and has no `Detect:` paragraph. The pattern also covers "type params", "branded", "invariant", "narrowed return/payload" and "now returns". Neither the pending changesets nor the curated `[deprecation]` and Other entries in CHANGELOG.md trigger it.

Out of scope: `packages/lexical-list/flow/LexicalList.js.flow` still declares `collapseAtStart(selection: RangeSelection): true`. Changing it is a published Flow type change that needs its own changeset.

## Changeset

None needed: documentation and changeset tooling only.

## Test plan

The new CHANGELOG.md wording was checked against the declarations at the v0.45.0, v0.46.0, v0.48.0 and v0.49.0 tags, and the TypeScript errors and the Migration snippets were compiled against the current sources. The list Backspace change was checked with a scratch unit test (not committed) that presses Backspace at the start of the second of three items, with and without `ListExtension`: `["list:first","paragraph:second","list:third"]` with it, and `["list:firstsecond|third"]` with rich text alone, which is what v0.47 did.

### Before

With the test changes applied but not the CHANGELOG.md and `entry.mjs` changes:

```
$ pnpm vitest run scripts/__tests__/unit/changesets.test.ts scripts/__tests__/unit/changelog.test.ts
     × warns when a deprecation or chore changes types without Detect 4ms
     × parses the repository CHANGELOG.md 15ms
 FAIL  |scripts-unit| scripts/__tests__/unit/changelog.test.ts > parseChangelog > parses the repository CHANGELOG.md
AssertionError: expected { behavior: 43, breaking: 35, …(1) } to deeply equal { behavior: 44, breaking: 35, …(1) }
 FAIL  |scripts-unit| scripts/__tests__/unit/changesets.test.ts > changeset entry format > warns when a deprecation or chore changes types without Detect
AssertionError: expected { errors: [], warnings: [] } to deeply equal { errors: [], warnings: [ …(1) ] }
 Test Files  2 failed (2)
      Tests  2 failed | 63 passed (65)
```

### After

```
$ pnpm vitest run scripts/__tests__/unit/changesets.test.ts scripts/__tests__/unit/changelog.test.ts
 Test Files  2 passed (2)
      Tests  65 passed (65)

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

Prettier and ESLint pass on the changed files.

This branch was successfully deployed

2 active deployments
Preview – lexical — 7a68aab0 Deployed Jul 25, 2026 by vercel[bot]
Preview – lexical-playground — 7a68aab0 Deployed Jul 25, 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.

3 participants