Skip to content

[lexical] Feature: Only serialize ElementNode textFormat and textStyle when necessary - #7971

Merged
etrepum merged 3 commits into
meta:mainfrom
etrepum:elementnode-textFormat-serialization
Nov 3, 2025
Merged

etrepum merged 3 commits into
meta:mainfrom
etrepum:elementnode-textFormat-serialization

Conversation

@etrepum

@etrepum etrepum commented Nov 3, 2025 •

Copy link
Copy Markdown
Collaborator

Breaking Change

Previously the derived properties textFormat and textStyle would always be serialized to JSON if not set to the default values. These should only be useful when the ElementNode does not currently have any TextNode children, to preserve formatting choices, and will be recomputed when reconciled. Now they are only reconciled when they are determined to be useful (in an ElementNode with no direct TextNode children that is not a root or shadow root).

Description

Avoid serializing derived textFormat and textStyle whenever their values would be useless (in a root or shadow root that should not have TextNode children) or recomputed on first reconcile (when the ElementNode has a TextNode child).

Also fixes a bug where in some cases the ElementNode's format and style could be coming from two different TextNodes. It should really only come from the first TextNode.

Closes #7968

Future Considerations

We should eventually start changing the JSON in backwards incompatible ways, notably to remove default and useless values (e.g. the version attribute). They make the data less compact and provide no value other than to be compatible with very old versions of lexical.

Test plan

New unit tests and all existing tests should pass (nothing exercised these edge cases)

@vercel

vercel Bot commented Nov 3, 2025 •

Copy link
Copy Markdown

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

Project Deployment Preview Comments Updated (UTC)
lexical Ready Ready Preview Comment Nov 3, 2025 8:11pm
lexical-playground Ready Ready Preview Comment Nov 3, 2025 8:11pm

@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 3, 2025
@etrepum
etrepum added this pull request to the merge queue Nov 3, 2025
Merged via the queue into meta:main with commit da56dcf Nov 3, 2025
@buondevid

Copy link
Copy Markdown

Thank you for this @etrepum!

@etrepum etrepum mentioned this pull request Dec 10, 2025
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 19, 2026
…][lexical-playground][lexical-react][lexical-rich-text][lexical-selection][lexical-table][lexical-website] Feature: write exportJSON from the json schema

## Description

The `json` schema described only the parse direction, so every node still
hand-wrote `exportJSON` — the same property list a second time, by hand,
with no guarantee the two agreed.

Schema fields now carry a getter as well as a setter, and the base
`LexicalNode.exportJSON` writes every declared property by reading it through
that getter, using exporters compiled once per class exactly like the setters
are. A getter returning `undefined` omits its property, which is how an
optional or conditionally-persisted property is expressed (absent and
explicitly-`undefined` are indistinguishable once stringified). The naming
mirrors the setter side — `get<Prop>` by default, with combinators for
everything else:

- `withGetter(schema, 'getURL')` for a differently-named method
- `withField(schema, '__id')` to read the node's own field, via `getLatest()`,
  for a property no getter exposes
- `withAccessors(schema, {getter, setter})` for the common case of naming both

Every node in the repo drops its `exportJSON` as a result, except the three
whose output a schema cannot describe: `ElementNode` (which prepends the
structural `children` array), `ParagraphNode` (backwards-compatible
textFormat/textStyle, meta#7971), and the nodes' conditional cases, which are now
`undefined`-returning getters instead (`ElementNode`'s textFormat/textStyle,
`TableNode`'s frozen counts and rowStriping, `TableCellNode`'s verticalAlign,
`ExcalidrawNode`'s 'inherit' dimensions). Precise return types are preserved
by declaration merging, matching how `updateFromJSON` is typed.

Serialized output is unchanged except for property order, which now follows
the schema (a subclass's own properties, then its ancestors', then
`type`/`version`) rather than each hand-written method's spread position. One
test compares a serialized string and was updated; `CodeNode`'s
`theme: undefined` is now simply absent.

## Test plan

### Before

Every node repeated its schema by hand, e.g. TextNode:

```ts
exportJSON(): SerializedTextNode {
  return {
    detail: this.getDetail(),
    format: this.getFormat(),
    mode: this.getMode(),
    style: this.getStyle(),
    text: this.getTextContent(),
    ...super.exportJSON(),
  };
}
```

### After

The method is gone; the schema's getters write those five properties.

```
$ npm run test-unit
 Test Files  263 passed (263)
      Tests  5239 passed | 1 skipped (5240)

$ npm run ci-check; echo "exit: $?"
exit: 0
```

Playground E2E and browser suites were not exercised in this environment.

Co-Authored-By: Claude Fable 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 21, 2026
…exical-website] Refactor: drop jsonOverride and write the compact form directly

## Description

`jsonOverride` had no clear use case yet, and nearly all the remaining
complexity in the serialization path existed to serve it: the `$next()` chain,
the enhance-vs-replace marker, `AppliedSerialization.recurseChildren`, the
omission path through both export walks, the compaction type-gate, the
clipboard's scratch-array splice, and the node-matcher. Every data-loss defect
found in review so far has been in that machinery; none has been in compaction.
So it is removed, and both walks return to reading a node's JSON and recursing.

With overrides gone, compaction no longer has to be a pass over a finished
object, so it moves into the write path. `exportJSON(compact)` and
`exportJSONInto(json, compact)` take the form as an argument, and
`$writeJSONGetters` applies it while writing: a derived property is skipped
without even calling its getter, a value equal to the schema default is simply
not written, and `version` is not written at all. That deletes
`$compactSerializedNode`, the `CompactField` table and its per-class WeakMap —
one fewer cache keyed by node class — and leaves nothing for a later pass to
inspect, which is what lets a node generate its own `exportJSON` and never
consult the schema at runtime.

`ParagraphNode` back-fills `textFormat`/`textStyle` after calling `super` for
backwards compatibility (meta#7971); it now does that only for the legacy form,
since a compact reader restores exactly those values from the schema.

Also from review of the same code:

- The `$` prefix marks a function that needs an editor context. The methods
  added by this branch — `$getSerializedCaption`, `$getSerializedTextFormat`,
  `$exportJSONInto` and the rest — are node methods, where that context is
  implied, and no other node method is spelled that way. They lose the prefix.
- Seven schemas spelled out a `setter:` that was exactly the conventional
  `set<Prop>`, so only the getter carried information. They use `withGetter`.
  `TableCellNode.headerState` keeps `withAccessors`, since `setHeaderStyles`
  really is not the default name.
- `exportJSONInto` is `@internal` and every caller passes `compact`, so the
  parameter is required rather than defaulted. The public `exportJSON` keeps
  its default, since existing callers pass nothing.

Line counts: `LexicalSerializationContext.ts` 390 → 177,
`LexicalSerializedExport.ts` 114 → 85, `JSONExtension.ts` 290 → 97.

## Test plan

### Before

```
$ npx vitest run
 Test Files  287 passed (287)
      Tests  5561 passed | 2 skipped (5563)
```

### After

The 34 override-specific cases across four files are removed with the feature;
the compaction cases they sat beside all still pass, including the slot-host
and nested-editor ones.

```
$ npx vitest run
 Test Files  287 passed (287)
      Tests  5535 passed | 2 skipped (5537)

$ npx tsc --noEmit -p tsconfig.json && npx flow check && npx eslint packages && npx prettier --check packages
No errors!
All matched files use Prettier code style!
```
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 21, 2026
…-list][lexical-rich-text] Bug Fix: stop the schema from discarding values it should keep

## Description

Review found several places where the schema silently dropped a value.

**Round trips that lost data**

- `indent` was declared `numberValue(0, {integer: true, max: 128, min: 0})`,
  but `numberValue` falls back to its *default* rather than clamping, so any
  document with `indent > 128` reopened flush-left — worse than the unbounded
  parse the cap was defending against, and applied to every element type. The
  cap is gone from the shared schema (a plain element stores the value
  verbatim, so there is nothing to defend); the walk that actually motivated
  it, `ListItemNode.setIndent`, bounds its own target instead, which is where
  the per-level work happens.
- `ParagraphNode` back-fills `textFormat`/`textStyle` from its first text child
  for meta#7971. The compact form skipped that on the grounds that the parser would
  restore the same values — false whenever the first child is formatted, so the
  two forms described different documents. It runs for both forms now, and
  drops only the values that really are the default.
- `quoteShadowRootState` went back to `parse: Boolean`. `booleanValue()` reads
  a stored `1` or `"true"` as `false`, and a quote that stops being a shadow
  root has its children restructured by `$normalizeShadowRootChildren` — the
  narrowing changed document structure, not just a flag.

**Equality and defaults**

- `optional` and `nullable` did not carry their inner schema's `isEqual`, so
  one wrapper was enough to turn content comparison back into identity and stop
  a reference-typed property from ever compacting.
- `arrayValue`/`objectValue`'s `isEqual` assumed both operands were parsed
  values, but the export path hands it whatever a getter returned. A getter
  returning `null` threw a `TypeError` mid-export. Both are total now.
- `makeSchema` froze the `defaultValue` even when the caller passed one in,
  so `enumValue([shared], shared)` silently froze an object the caller still
  owned. Only a default the factory derived is frozen.
- `unionValue(members, fallback)` returned `undefined` from `schema(undefined)`
  when a member accepted `undefined`, contradicting its own `defaultValue` —
  which is what compaction and `omitDefault` compare against.
- `StateConfig` picked up a schema's `parse` and `meta` but not its `isEqual`
  or `defaultValue`, so `createState('ids', {parse: arrayValue(stringValue())})`
  — the pattern the new docs recommend — fell back to `Object.is`: an empty
  array was written into every node and every equal `$setState` dirtied it.
  It adopts both now, so the shared default is also the frozen one.

**Types and guards**

- The declaration-merged `exportJSON(): SerializedX` on 16 node classes hid the
  base's `compact` parameter, so the documented `super.exportJSON(compact)`
  recipe did not compile and a downstream subclass could not participate in the
  compact form at all.
- The `withField` setter had neither the existence check its getter mirror has
  nor a `__proto__` guard, where an assignment would reparent the node.
- A key declared as both a schema field and a flat NodeState resolves opposite
  ways on export and import; DEV rejects the collision rather than picking.
- The `withField` getter's DEV check ran on every read; it now runs only when
  the value is missing, which is the case it exists to catch.

Also: Flow gains the `compact` parameter and `meta.defaultAsNull`; the
pure-annotation rule drops two factories this branch deleted and is sorted
again; `$isCompactExport` is removed (nothing called it — `exportJSON` receives
the flag); and the `version`, `updateFromJSON` and `@lexical/fast-check` docs
say what the code does.

## Test plan

### Before

```
$ npx vitest run packages/lexical/src/__tests__/unit/LexicalSchema.test.ts
 × a caller-supplied default is not frozen
 × equality is total: an unvalidated getter result cannot throw
 × optional and nullable keep the inner content comparison
 × a union parses undefined to the fallback it declared
 × a state built from a schema adopts its equality and default
      Tests  5 failed | 51 passed (56)
```

The compact-form regression is pinned separately by `a formatted first text
child survives compaction (meta#7971)`, and the `exportJSON(compact)` typing by
compiling the documented override recipe against a ported node.

### After

```
$ npx vitest run
 Test Files  286 passed (286)
      Tests  5540 passed | 2 skipped (5542)

$ npx tsc --noEmit -p tsconfig.json && npx flow check && npx eslint packages && npx prettier --check packages
No errors!
All matched files use Prettier code style!
```
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 22, 2026
…ir schema

## Description

`exportJSON` is a table-driven walk: per node it looks up a compiled table,
loops it, calls an accessor indirectly per property, and writes each value with
a keyed store whose key changes every iteration. Every one of those decisions —
which accessor to read, what the node's type string is, which properties the
legacy form writes — is fixed once the schema is written, so this decides them
at build time and emits an object literal instead. That is what the hand-written
`exportJSON` methods the schema replaced used to be, recovered without hand
writing them.

`scripts/generate-node-json.mjs` (`pnpm run generate-node-json`) reads each
class's composed schema and writes `LexicalGeneratedJSON.ts`, which is checked
in. Reading a schema needs no editor and constructs no node, so this is an
ordinary build step rather than anything that has to run in the app.

Three things make it safe to have on by default:

- **It is verified against the walk.** `LexicalGeneratedJSON.test.ts` exports
  every generated class both ways and requires the same values *and* the same
  key order, so the two forms are byte-identical.
- **It regenerates in CI.** The same test re-runs the generator and fails if the
  checked-in file differs, so a schema change nobody regenerated for cannot ship
  an exporter describing the previous schema.
- **It only claims what the schema describes.** A class that overrides
  `exportJSON` gets no generated exporter — ParagraphNode back-fills
  `textFormat`/`textStyle` from its first text child for meta#7971, which its schema
  does not describe, and the generator skips it and says so. Compaction is left
  to the walk too, since which properties it drops depends on each node's values
  rather than on the schema alone.

The lookup is keyed by node type rather than by class. That is what keeps the
generated module free of runtime imports — a value import of the node classes
would be a cycle, since they import `LexicalNode`, which reads this — and it
makes the lookup exact: a subclass registers under its own type, so it never
reaches its parent's exporter.

The generator runs in two phases, replacing its own output with a valid
do-nothing module before importing `lexical`. Without that, one run that
produced broken output could never be run again to fix it.

## Test plan

`npx vitest run --project unit packages/lexical/src/__tests__/unit/LexicalGeneratedJSON.test.ts`

### Before

```
 Test Files  1 failed (1)
      Tests  no tests
```

(The test is new; before this change there is no generated module for it to
import, so the suite fails to load.)

### After

```
 Test Files  1 passed (1)
      Tests  5 passed (5)
```

Unit projects, `npx vitest run --project unit --project scripts-unit`:

```
 Test Files  266 passed (266)
      Tests  5279 passed | 1 skipped (5280)
```

Browser tests, `npx vitest run --project browser` (Chromium):

```
 Test Files  18 passed (18)
      Tests  131 passed | 1 skipped (132)
```

`npx tsc --noEmit -p .`, `npx flow check` (`No errors!`), `npx eslint` and
`npx prettier --list-different .` are clean. Firefox and WebKit browser runs and
the Playwright E2E suite were not exercised.

Note on speed: the generated literal is not yet faster than the walk. Isolating
the cost shows it is not the object shape but `getLatest()`, which each
conventional `get<Prop>` accessor calls — five per TextNode. Hoisting one
`getLatest()` and reading the fields off it is 3.48x faster and semantically
identical, but the generator cannot know that `getDetail()` is
`getLatest().__detail` unless the schema says so. That is a schema change, kept
out of this commit.
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 22, 2026
…graphNode's exporter

## Description

The generated exporters landed correct but no faster, and isolating the cost
showed why: it was never the object shape, it was `getLatest()`. Each
conventional `get<Prop>` accessor is exactly `getLatest().__field`, so exporting
one TextNode did five node-map lookups to read five fields off a node the
caller already had.

Nothing needs resolving there. An export walk reaches a node through the
EditorState's node map, so it is the current version by construction — which is
what the schema's direct-field path already documents and relies on. So the
schema now says which properties simply *are* their field, and both the walk and
the generated exporter read them directly. Four of TextNode's five qualify.

The fifth, `mode`, is stored as a bitmask and serialized as a name, so it needed
an accessor purely for that mapping. A field accessor can now carry the lookup
table that relates the two:

```ts
mode: withGetter(enumValue(['normal', 'token', 'segmented']), {
  decode: TEXT_TYPE_TO_MODE,
  field: '__mode',
}),
```

The table is plain data, so the generator inlines it as a literal and the
generated exporter stays free of runtime imports. TextNode now exports with no
`getLatest()` at all.

ParagraphNode is generated too. It used to override `exportJSON` to write the
`textFormat`/`textStyle` its older readers expect (meta#7971), computed from its
first text child — output no schema can describe, which is why the generator
skipped it. That behavior is unchanged, but it now lives in `afterExportJSON`, a
declared seam that runs on both paths: the walk calls it from `exportJSONInto`,
and the generated exporter calls it after building the literal. The call is
emitted only for a class that declares one, so TextNode pays nothing for it.

Overriding `exportJSON` still works and still opts a class out of generation.
`afterExportJSON` is the way to keep both.

## Test plan

`npx vitest bench --project bench --run packages/lexical/src/__bench__/serialization.bench.ts`

### Before

```
   · 12001 nodes                     115.17   7.8915  11.2656   8.6830   9.6405  11.2656  ±2.91%       58
   · schema-driven walk             211.53   4.3697   7.2415   4.7275   4.7868   7.1590  ±1.82%      106
```

### After

```
   · 12001 nodes                     156.48   5.0106   9.4674   6.3904   7.0527   9.4674  ±3.60%       79
   · schema-driven walk             249.55   3.5835   7.0441   4.0072   4.1739   6.7655  ±2.41%      125
   · generated where available      425.62   1.8554  18.0878   2.3495   2.3181   5.0449  ±6.63%      213

    1.71x faster than schema-driven walk
```

A full `editorState.toJSON()` of a 12,001-node document goes from 8.68 ms to
6.39 ms — a 26% improvement, and more than the 21% the table-driven walk cost
against the hand-written methods it replaced. The walk itself also got faster,
since the direct-field reads help both paths.

Unit projects, `npx vitest run --project unit --project scripts-unit`:

```
 Test Files  266 passed (266)
      Tests  5279 passed | 1 skipped (5280)
```

Browser tests, `npx vitest run --project browser` (Chromium):

```
 Test Files  18 passed (18)
      Tests  131 passed | 1 skipped (132)
```

`LexicalGeneratedJSON.test.ts` continues to require that every generated
exporter and the schema-driven walk produce the same values in the same key
order, and now also that the meta#7971 values survive generation. `npx tsc --noEmit
-p .`, `npx flow check` (`No errors!`), `npx eslint` and `npx prettier
--list-different .` are clean. Firefox and WebKit browser runs and the
Playwright E2E suite were not exercised.
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 22, 2026
…ady composes

## Description

The previous commit added an `afterExportJSON` hook so ParagraphNode could keep
writing the `textFormat`/`textStyle` its older readers expect (meta#7971) while
still having a generated exporter. It was not needed, and it is removed:
ParagraphNode goes back to the plain `exportJSON` override it always had.

The dispatch to a generated exporter lives in the base `exportJSON`, which is
exactly what `super.exportJSON(compact)` reaches. So an override that calls
`super` receives the generated literal and post-processes it, with no seam
required — and an override that does not call `super` never reaches the
generated function, so registering one for such a class is merely unused.
Either way, overriding `exportJSON` is safe and the generator no longer skips
it.

What actually disqualifies a class is overriding `exportJSONInto`: the generated
path does not go through it, so whatever it adds would be silently dropped. That
check stays, and now says why.

The reason for the wrong conclusion is worth recording, because the reasoning
looked sound: the equivalence test compared `exportJSON()` against
`exportJSONInto()`. For ParagraphNode those were never equal — the meta#7971
back-fill lives in `exportJSON`, so the `exportJSONInto` path never had it, on
`main` as much as here. Reading that difference as "this class cannot be
generated" produced a hook whose only real effect was to make the two paths
agree, which nothing observes: `exportJSONInto` has no callers outside
`exportJSON` itself.

The test now checks what matters instead — that the meta#7971 values are present and
that the generated literal underneath them is intact — including the key order,
which puts the two back-filled keys after `type`/`version` because the override
appends them to a finished object. That is unchanged from before the literal was
generated, since the override itself is unchanged.

## Test plan

`npx vitest run --project unit packages/lexical/src/__tests__/unit/LexicalGeneratedJSON.test.ts`

### Before

```
     × an exportJSON override composes with its generated exporter 17ms

AssertionError: expected [ 'children', 'direction', …(6) ] to deeply equal [ 'children', 'direction', …(6) ]
-   "textFormat",
-   "textStyle",
    "type",
    "version",
+   "textFormat",
+   "textStyle",
```

(The failure is the assertion I wrote being wrong about key order, not the
composition: the override appends after `type`/`version`, as it always has.)

### After

```
 Test Files  1 passed (1)
      Tests  5 passed (5)
```

Unit projects, `npx vitest run --project unit --project scripts-unit`:

```
 Test Files  266 passed (266)
      Tests  5279 passed | 1 skipped (5280)
```

Browser tests, `npx vitest run --project browser` (Chromium):

```
 Test Files  18 passed (18)
      Tests  131 passed | 1 skipped (132)
```

The generated exporters are unaffected — ParagraphNode still gets one, and a
full `editorState.toJSON()` of a 12,001-node document measures the same as
before this commit. `npx tsc --noEmit -p .`, `npx flow check` (`No errors!`),
`npx eslint` and `npx prettier --list-different .` are clean. Firefox and WebKit
browser runs and the Playwright E2E suite were not exercised.
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 22, 2026
…of being matched to it

## Description

The generated `exportJSON`/`updateFromJSON` implementations were keyed by node
type, and a type does not identify a class: a subclass that declares no
`$config` of its own inherits its ancestor's, type included, while being free to
override an accessor the generated code compiled away. Guarding that took a
`shape` string — how a class reaches each of its serialized properties —
derived once by the codegen from the schema and once by the runtime from the
compiled tables, and compared. Two derivations of the same string that had to
agree, with nothing to make them: if they ever stopped, every node would quietly
fall back to the walk and nothing would fail. `getGeneratedJSONUsage` existed
only so a test could notice, which is public API that only tests use.

Handing the code to the class through `$config` removes the question. The
association is then the same one the schema already has — the class whose
`$config` named it — so matching code to class is an identity comparison against
the most basal class in the chain that names the same functions, exactly as
`declaredBy` resolves a schema field. Inheriting the declaration is the case to
reject, and it is now the only case there is.

Gone with it: the `shape` string and both of its derivations, the type-keyed
map and `getGeneratedJSON`, `getGeneratedJSONUsage` and its test, and the `name`
fields added to the two compiled accessor tables solely to build the string.
The generated module drops its lookup for one exported constant per class.

Not changed: the dispatch stays inside the schema-driven walks rather than
installing a method on each prototype at registration. ParagraphNode's
`exportJSON` override reaches its generated literal through
`super.exportJSON(compact)` — that is how the meta#7971 back-fill composes, and it
is documented for third-party nodes. An installed method would resolve `super`
to ElementNode's, so a paragraph would get an element's literal; guarding that
by class identity would be correct but would take paragraphs off the generated
path entirely.

## Test plan

### Before

```
$ grep -c "shape" packages/lexical/src/LexicalGeneratedJSON.ts
6
$ grep -n "getGeneratedJSONUsage" packages/lexical/src/index.ts
395:  getGeneratedJSONUsage,
```

### After

```
$ grep -c "shape" packages/lexical/src/LexicalGeneratedJSON.ts
0
$ grep -n "getGeneratedJSONUsage" packages/lexical/src/index.ts
$
```

A subclass that inherits its ancestor's type *and* its generated code, and
overrides an accessor that code compiled away, still gets the walk — which is
the case the shape string existed to catch:

```
BareLoud (inherits type 'text' and the generated code, overrides an accessor)
  exportJSON().style: "color: red;set;loud"
  walk .style:        "color: red;set;loud"
```

and a plain TextNode still uses its own generated code, round trip included:

```
TextNode (its own generated code)
  exportJSON(): {"detail":0,"format":1,"mode":"segmented","style":"s","text":"","type":"text","version":1}
  round trip:   {"detail":0,"format":1,"mode":"segmented","style":"s","text":"","type":"text","version":1}
```

```
$ pnpm run ci-check
No errors!
$ echo $?
0
```

```
$ npx vitest run

 Test Files  293 passed (293)
      Tests  5624 passed | 2 skipped (5626)
   Duration  380.03s
```

That run covers the browser project as well as the jsdom one; the E2E matrix
(Chromium/Firefox/WebKit) was not exercised, since it needs the playground dev
server.

Co-Authored-By: Claude Opus 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 22, 2026
…tion

## Description

The base `exportJSON` had to find the right generated code for whatever node it
was handed, which is a node-class-record lookup per node. The literal it then
calls is small enough that finding it cost more than running it: measured over
10,000 TextNodes, the lookup and the branches around it were about two thirds of
the export path.

Which code is right is settled once, when the class is registered, so it is
settled there now — the generated exporter goes on the class's prototype and
exporting one of its nodes is a call.

Two classes of node must not get it, and both fall out of one guard plus one
condition.

A class that writes its own `exportJSON` keeps it. That method is the class's
answer, and it composes with the generated literal by calling
`super.exportJSON(compact)`, which reaches the base and its lookup — that is how
ParagraphNode's meta#7971 back-fill works, so nothing may displace it. Since
ElementNode declares no `exportJSON` and has no generated code of its own, a
paragraph's `super` still lands on the base implementation and still finds the
paragraph's literal.

A subclass that declares no `$config` inherits its ancestor's — the node type
and the generated code with it — while being free to override an accessor that
code compiled away. It inherits the installed method too, so that method checks
`this.constructor` and defers to the base for anything but the exact class it
was installed on. That is the same guard `generatedFor` applies and the same
shape as the synthesized `getType` beside it.

## Test plan

### Before

Per-node export over the document's 10,000 TextNodes, and the whole-document
walk, min of 40 after warmup, three paired runs:

```
per-node exportJSON   51.0 / 55.4 / 54.2 ns/node
editorState.toJSON()  8.697 / 9.392 / 9.160 ms
```

### After

```
per-node exportJSON   16.2 / 16.3 / 16.8 ns/node
editorState.toJSON()  8.185 / 8.330 / 8.424 ms
```

3.3x on the per-node export. The whole-document figure moves ~8%, because
walking the tree is most of what it does.

The two classes that must not get it still do not, and a subclass that inherits
the declaration still agrees with the walk:

```
BareLoud exportJSON().style: "color: red;set;loud"
BareLoud walk .style:        "color: red;set;loud"

paragraph exportJSON(): {"children":[],"direction":null,"format":"","indent":0,"type":"paragraph","version":1,"textFormat":1,"textStyle":""}
```

```
$ pnpm run ci-check
No errors!
$ echo $?
0
```

```
$ npx vitest run

 Test Files  293 passed (293)
      Tests  5627 passed | 2 skipped (5629)
   Duration  370.67s
```

Three of those are new: that the declaring class gets the method, that a class
with its own `exportJSON` keeps it, and that a subclass inheriting the
declaration is left on the base implementation and agrees with the walk.

That run covers the browser project as well as the jsdom one; the E2E matrix
(Chromium/Firefox/WebKit) was not exercised, since it needs the playground dev
server.

Co-Authored-By: Claude Opus 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 25, 2026
…lowed in the value position

## Description

The generated legacy exporter carried a guarded fast path — return a literal
only when every getter returned a value — with an incremental fallback for when
one did not, and the walk omitted a property whose getter returned `undefined`.
Both existed to keep `undefined` out of the value position.

Nothing required that. `JSON.stringify` omits an undefined-valued property, so
the serialized bytes are identical either way — and present-with-undefined is
the shape the hand-written exporters always had: on main, ListItemNode writes
`checked: this.getChecked()` on every non-checklist item, TableNode writes
`colWidths: undefined` by explicit ternary, CodeNode writes `theme:
this.getTheme()` unconditionally. The walk's omission was the deviation from
main's object shape, not the preservation of it.

So the legacy walk now writes every schema property unconditionally, and the
generated legacy exporter is a single unconditional literal — the exact shape
of the hand-written method it replaces, with no guard chain, no fallback, and
one object shape per class:

    function exportTextNode(node: TextNode): {[key: string]: unknown} {
      return {
        detail: node.__detail,
        format: node.__format,
        mode: TEXT_MODE_DECODE[node.__mode],
        style: node.__style,
        text: node.__text,
        type: 'text',
        version: 1,
      };
    }

The compact form still omits, deliberately: its output is for storage, and an
object-level consumer — a structured clone into IndexedDB — counts keys the
way stringify counts bytes.

One observable consequence: ParagraphNode's meta#7971 back-fill now assigns into
`textFormat`/`textStyle` keys that already exist in the literal, so they sit at
their schema position instead of trailing after `version`. Values are
identical; the key order becomes the canonical schema order. Golden strings
that pinned the old order are updated, and one `toStrictEqual` in
lexical-code now spells out the present-with-undefined keys.

## Test plan

### Before

The unconditional-literal form measured against the guarded one (production,
min of 50, 10,000 text nodes / 2,000 mixed paragraphs):

```
text A: guarded + fallback (today)               0.119 ms
text D: one unconditional literal                0.170 ms
para A: guarded + fallback (today)               0.050 ms
para D: one unconditional literal                0.038 ms
para stringify from A (mixed shapes)             0.495 ms
para stringify from D (one shape)                0.545 ms
bytes identical: true
```

A wash on speed; what it buys is one code path, one object shape per class,
and shape parity with main's own exporters.

### After

```
$ npx vitest run --project unit .../LexicalGeneratedJSON.test.ts .../LexicalSerialization.test.ts .../LexicalCodeNode.test.ts

 Test Files  3 passed (3)
      Tests  76 passed | 1 skipped (77)
```

The full-suite and benchmark runs are in the follow-up commit alongside the
schema field sweep, which regenerates the same file.

Co-Authored-By: Claude Fable 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 27, 2026
…thGetter` names, the cited issue, and a recipe that does not run

## Description

`withGetter` was replaced by `withAccessors` in `799f61114`, but three
references to it survived — two JSDoc blocks that reach the published API docs
and, worse, the runtime `invariant` text a developer sees when a schema names a
getter their class does not have, which told them to reach for a function that
no longer exists.

`ElementNode`'s `textFormat`/`textStyle` comment — the one place the whole
`when` mechanism is explained — cited meta#7971 for the rule that they are
persisted only for an element with no `TextNode` child. That rule is meta#7968;
meta#7971 is the unrelated `ParagraphNode` back-fill, which the method a few lines
down cites correctly. A maintainer following the wrong number lands on the
back-fill and concludes the gate is about something else.

`{@link SchemaField.method}` does not resolve: `SchemaField` became a union of
the two direction-specific types, and a union alias has no members to link to.
It points at `SchemaFieldBase.method`, which is where `method` is declared.

Finally, the `@lexical/fast-check` README's `afterCloneFrom` recipe could not
run as written: it appends the node straight to the root (a leaf cannot be a
root child) and passes the generated props through unmodified (an empty
`TextNode` is removed by normalization between the two updates, leaving nothing
to clone). Both fixes were in the in-repo test it mirrors and had been dropped
from the published version. It now matches that test, and names `TextNode`
throughout instead of switching to it halfway through the prose.

## Test plan

The README snippet, extracted verbatim into a test file and run.

### Before

```
$ npx vitest run …/readme-before.test.ts
   × a clone carries every property MyNode declares 33ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
Error: Property failed after 1 tests
Caused by: Error: rootNode.splice: Only element or decorator nodes can be inserted to the root node
```

### After

```
$ npx vitest run …/readme-after.test.ts
 Test Files  1 passed (1)
      Tests  1 passed (1)
```

And no `withGetter` is left in the sources:

```
$ grep -rn withGetter packages/ scripts/ --include=*.ts --include=*.tsx \
    --include=*.mjs --include=*.md --include=*.flow | grep -v node_modules
(no matches; the remaining hits are under lexical-website/static/llms, which is
gitignored build output)
```

Co-Authored-By: Claude Opus 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 27, 2026
…thGetter` names, the cited issue, and a recipe that does not run

## Description

`withGetter` was replaced by `withAccessors` in `799f61114`, but three
references to it survived — two JSDoc blocks that reach the published API docs
and, worse, the runtime `invariant` text a developer sees when a schema names a
getter their class does not have, which told them to reach for a function that
no longer exists.

`ElementNode`'s `textFormat`/`textStyle` comment — the one place the whole
`when` mechanism is explained — cited meta#7971 for the rule that they are
persisted only for an element with no `TextNode` child. That rule is meta#7968;
meta#7971 is the unrelated `ParagraphNode` back-fill, which the method a few lines
down cites correctly. A maintainer following the wrong number lands on the
back-fill and concludes the gate is about something else.

`{@link SchemaField.method}` does not resolve: `SchemaField` became a union of
the two direction-specific types, and a union alias has no members to link to.
It points at `SchemaFieldBase.method`, which is where `method` is declared.

Finally, the `@lexical/fast-check` README's `afterCloneFrom` recipe could not
run as written: it appends the node straight to the root (a leaf cannot be a
root child) and passes the generated props through unmodified (an empty
`TextNode` is removed by normalization between the two updates, leaving nothing
to clone). Both fixes were in the in-repo test it mirrors and had been dropped
from the published version. It now matches that test, and names `TextNode`
throughout instead of switching to it halfway through the prose.

## Test plan

The README snippet, extracted verbatim into a test file and run.

### Before

```
$ npx vitest run …/readme-before.test.ts
   × a clone carries every property MyNode declares 33ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
Error: Property failed after 1 tests
Caused by: Error: rootNode.splice: Only element or decorator nodes can be inserted to the root node
```

### After

```
$ npx vitest run …/readme-after.test.ts
 Test Files  1 passed (1)
      Tests  1 passed (1)
```

And no `withGetter` is left in the sources:

```
$ grep -rn withGetter packages/ scripts/ --include=*.ts --include=*.tsx \
    --include=*.mjs --include=*.md --include=*.flow | grep -v node_modules
(no matches; the remaining hits are under lexical-website/static/llms, which is
gitignored build output)
```

Co-Authored-By: Claude Opus 5 <[email protected]>

This branch was successfully deployed

2 active deployments
Preview – lexical-playground — 2fbab6a0 Deployed Nov 3, 2025 by vercel[bot]
Preview – lexical — 2fbab6a0 Deployed Nov 3, 2025 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.

Editor State from Headless Lexical and React Lexical slightly differs

3 participants