Skip to content

[Breaking Change][lexical] Fix: Preserve the first linebreak when passing inline nodes to insertNodes and add data-lexical-managed-linebreak attribute to managed linebreaks - #8615

Merged
etrepum merged 10 commits into
meta:mainfrom
levensta:wrap-inline-nodes
Jun 13, 2026

Conversation

@levensta

@levensta levensta commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Breaking Change

Lexical's reconciler inserts managed line breaks (<br> tags) that have no representation in the document under certain conditions to help the native browser render and navigate content correctly, without them the cursor wouldn't be able to land in the correct place. These are now identifiable in the DOM as <br data-lexical-managed-linebreak="true">). You may need to change test expectations to ignore this attribute, or expect its presence. On iOS Safari the linebreak may also be preceded by an <img data-lexical-managed-linebreak="true" style="…" /> under certain conditions for similar input related reasons (this is existing behavior that predates this PR).

Description

  1. Changed normalization of inline nodes when inserting via the RangeSelection.insertNodes method. The first linebreak is always preserved
  2. The attribute data-lexical-managed-linebreak="true" has been added to managed line break. This is done to make debugging and reading tests easier, where you need to distinguish where <br> is inserted from LineBreakNode, and where a managed line break is used to display an empty line.

    For example, this is what a paragraph containing a single line break would look like in the DOM
    <p>
      <br>
      <br data-managed-linebreak="true">
    </p>

Closes #3980

Test plan

Before

For example, if when calling $insertNodes() there are inline nodes, at least one block element, and the first node is a LineBreakNode

<br>
hello world
<p></p>

Then the linebreak is removed, and the remaining inlines are wrapped in a paragraph

 root
  ├ paragraph 
  | └ text "hello world"
  └ paragraph 

After

Now the first linebreak is preserved

 root
  ├ paragraph 
  | ├  linebreak 
  | └ text "hello world"
  └ paragraph 

@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 Jun 3, 2026
@vercel

vercel Bot commented Jun 3, 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, Comment Jun 12, 2026 5:51pm
lexical-playground Ready Ready Preview, Comment Jun 12, 2026 5:51pm

Request Review

@levensta

levensta commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

There are two <br> in the failed test because one of them is a managed line break and the other is a LineBreakNode

We can either settle for a small refactoring of wrapInlineNodes or try to solve this issue #3980

@potatowagon

Copy link
Copy Markdown
Contributor

Review (automated — Navi for @potatowagon)

Status: Not ready to approve — CI still failing

What changed (latest commit 007cd16)

The code change is a clean simplification of $wrapInlineNodes:

Assessment

Logic correctness: The simplification is sound — there's no semantic reason to silently discard the first linebreak. The old behavior was a lossy workaround.

Concern: Unit tests are still failing (core-tests/unit on Node 22.x and 24.x). As the author notes, the failure is because LexicalSelectionHelpers.test.ts:2681 expects one <br> but gets two — one managed linebreak and one explicit LineBreakNode. This reflects a deeper issue (tracked in #3980) about duplicate line breaks.

Breaking change risk: This IS a breaking change — code that relied on the first linebreak being stripped will now see an extra linebreak. The author has correctly labeled it as such.

Recommendation: The code direction is correct but CI must be green before merging. Either:

  1. Fix the failing test expectation if the new behavior is intentionally different, or
  2. Address the underlying Bug: Line Breaks <br/> breaks markup #3980 managed-linebreak/LineBreakNode duplication

Will re-review once CI is green.

@potatowagon potatowagon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review — Preserve First Linebreak in insertNodes

Assessment: Has concerns ⚠️

What I verified:

  1. Logic correctness: The change to $wrapInlineNodes simplifies the wrapping logic — it now unconditionally appends LineBreakNodes into currentBlock rather than skipping them (the old code created a parent block but then continued, effectively dropping the LineBreak from the block's children). The refactored code is cleaner: it uses $isInlineElementOrDecoratorNode and always appends to currentBlock.

  2. Breaking change assessment: This is marked as a breaking change. The behavior change is: previously, a leading LineBreakNode before inline content would result in an empty paragraph; now it's preserved inside the wrapping paragraph. This is arguably more correct behavior (issue #4295), but it may affect existing consumers who rely on the current insertNodes behavior.

  3. Test coverage: Tests that were previously commented out (referencing issue #4295) are now enabled. A new regression test ($wrapInlineNodes regression) explicitly verifies LineBreakNode is preserved in the wrapping paragraph.

Concerns:

CI is failing: Unit tests on Node 22.x and 24.x are red. This needs to be addressed before merge. The e2e tests pass, but the core unit tests do not — which likely means the test expectations or the logic has a mismatch that needs investigation.

The fix should be verified once CI is green. The conceptual change is sound, but cannot recommend landing with failing tests.

— via Navi on behalf of potatowagon

@levensta

levensta commented Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

I just corrected the test, in general it already reflects the correct behavior: 1 <br> is the required managed linebreak, and the second <br> is a visible line break in the form of a LineBreakNode node

@etrepum

etrepum commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

Maybe we should set something on the DOM on the managed line breaks like data-lexical-linebreak="true" like we do with the webkit hack IMG

@levensta

levensta commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

I've thought about this, but it doesn't seem to serve much purpose. Maybe just as additional information that this is a special <br> and as a sort of self-documenting explanation in the tests. Or perhaps to maintain consistency with the WebKit branch

Or perhaps we should instead set the data-lexical-linebreak attribute for the LineBreakNode. Just as we already have the data-lexical-text and data-lexical-decorator attributes.

@etrepum

etrepum commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

data-lexical-managed-linebreak might be a better name for the attribute. I don't think setting data-lexical-linebreak on all LineBreakNode is worthwhile. The value here is mostly to help people with debugging and to be an easy target to unambiguously normalize them away (e.g. on import or on a serialization style html export)

@levensta

Copy link
Copy Markdown
Contributor Author

Done, now all managed linebreaks have the attribute

…raph in $wrapInlineNodes

insertNodes now preserves a leading LineBreakNode only when more inline
content follows in the same run. A run consisting of just a
LineBreakNode collapses to an empty paragraph as before, since the
block boundary already provides the visual newline. This is the same
policy as $paragraphPackageRun in @lexical/html and keeps the
trailing-<br> shape produced by clipboard sources (Google Docs,
Gmail, ...) rendering as a single empty line.

This also fixes a case where insertNodes([linebreak, block]) with the
caret at the end of a non-empty paragraph deleted the linebreak
entirely: the preserved linebreak was merged into the target block as
a trailing linebreak and then removed by the post-insert linebreak
cleanup, losing the empty line that the previous behavior produced.

Adds unit coverage for the merge-path cases and paste-layer coverage
for block-level <br> handling.

https://claude.ai/code/session_01PZ2rtiz21XyS3bSEKP7seA
claude added 2 commits June 12, 2026 15:25
These e2e tests assert that pasting (HTML and Lexical clipboard formats)
directly before/after a link inserts the content outside the link, at
the start, middle, and end of a paragraph. They were skipped pending
issue meta#4295 and now pass: inserting an inline node at a link boundary
places it correctly relative to the link.

Verified passing in rich-text mode (chromium) against both the vite dev
server and the production-style preview build used by CI.
…eal LineBreakNode expectations

The data-lexical-managed-linebreak attribute only marks reconciler-managed
terminating <br>s (empty blocks / a block ending in a linebreak). In
plain-text mode, pressing Enter inserts a real LineBreakNode that renders
as a plain <br>; once more content follows it, it is no longer the block's
terminating linebreak and carries no attribute.

Several plain-text e2e expectations had the attribute over-applied to these
mid-content real LineBreakNode <br>s, so the suite failed in plain-text mode
(24 failures) with the actual DOM emitting a plain <br>. Align the
expectations with the correct output by dropping the attribute from those
brs only; legitimate terminating/empty-block managed brs keep it.

Verified: full plain-text and rich-text e2e suites green (chromium, prod-style
preview build).
…lab initial-state assertion

The collab-only empty-state check in exposeLexicalEditor() still expected
a plain <br />, but the reconciler's managed linebreak now carries
data-lexical-managed-linebreak="true". Since this assertion runs inside
initialize(), every collab e2e test failed during setup before reaching
its body.

Verified: full rich-text-with-collab chromium suite green (587 passed,
0 failed) plus a rich-text-with-collab-v2 subset, against the prod-style
preview build and y-websocket server.
@etrepum etrepum changed the title [Breaking Change][lexical] Fix: Preserve the first linebreak when passing inline nodes to insertNodes [Breaking Change][lexical] Fix: Preserve the first linebreak when passing inline nodes to insertNodes and add data-lexical-managed-linebreak attribute to managed linebreaks Jun 13, 2026
@etrepum
etrepum added this pull request to the merge queue Jun 13, 2026
Merged via the queue into meta:main with commit 9f3c1db Jun 13, 2026
44 checks passed
etrepum pushed a commit to etrepum/lexical that referenced this pull request Jun 13, 2026
… CodeBlock layout test (meta#8603)

The main sync (meta#8615) added a data-lexical-managed-linebreak attribute to
managed linebreaks and updated most assertHTML expectations, but the
"exit from the code block inside the layout" test's empty code block and
empty paragraphs still expected bare <br />. Attribute them to match the
rendered HTML.

https://claude.ai/code/session_0125UE7Cv1mUaM82UH8N1nJX
mayrang added a commit to mayrang/lexical that referenced this pull request Jun 14, 2026
…shadow toggle

Four issues surfaced when running the ShadowDOM playwright spec on the
shadow-mounted playground:

- ShadowDOM.spec.mjs: \`<p><br /></p>\` template was missing the new
  \`data-lexical-managed-linebreak="true"\` attribute (added by meta#8615);
  the typeahead popup uses className \`typeahead-popover mentions-menu\`
  rather than a data-test-id; the table-cell test drove the toolbar
  Insert dropdown step-by-step (utils.insertTable's combined click
  triggers the dropdown's outside-click close in the shadow path) and
  picks the only non-header \`<td>\` after the headers default.
- utils/index.mjs: \`copyToClipboardPageOrFrame\` and
  \`pasteWithClipboardDataFromPageOrFrame\` used
  \`document.querySelector\` which doesn't pierce shadow roots; descend
  through any open shadow trees so the editor is found inside the
  shadow-mounted playground too. The paste helper also referenced
  \`editorSelector\` without passing it through the evaluate args
  (latent bug hidden by the active-element fast path).
- DropDown.tsx: the outside-click handler compared
  \`button.contains(event.target)\`; inside a shadow root the bubbled
  click target is retargeted to the shadow host so the comparison
  failed and the dropdown closed immediately on its own opening click.
  Use \`getComposedEventTarget\` for the un-retargeted target.

ShadowDOM e2e now passes 8 / 8 on Chromium; CopyAndPaste (53),
Headings / HorizontalRule / Tables (105) all still pass.
mayrang added a commit to mayrang/lexical that referenced this pull request Jun 17, 2026
…shadow toggle

Four issues surfaced when running the ShadowDOM playwright spec on the
shadow-mounted playground:

- ShadowDOM.spec.mjs: \`<p><br /></p>\` template was missing the new
  \`data-lexical-managed-linebreak="true"\` attribute (added by meta#8615);
  the typeahead popup uses className \`typeahead-popover mentions-menu\`
  rather than a data-test-id; the table-cell test drove the toolbar
  Insert dropdown step-by-step (utils.insertTable's combined click
  triggers the dropdown's outside-click close in the shadow path) and
  picks the only non-header \`<td>\` after the headers default.
- utils/index.mjs: \`copyToClipboardPageOrFrame\` and
  \`pasteWithClipboardDataFromPageOrFrame\` used
  \`document.querySelector\` which doesn't pierce shadow roots; descend
  through any open shadow trees so the editor is found inside the
  shadow-mounted playground too. The paste helper also referenced
  \`editorSelector\` without passing it through the evaluate args
  (latent bug hidden by the active-element fast path).
- DropDown.tsx: the outside-click handler compared
  \`button.contains(event.target)\`; inside a shadow root the bubbled
  click target is retargeted to the shadow host so the comparison
  failed and the dropdown closed immediately on its own opening click.
  Use \`getComposedEventTarget\` for the un-retargeted target.

ShadowDOM e2e now passes 8 / 8 on Chromium; CopyAndPaste (53),
Headings / HorizontalRule / Tables (105) all still pass.
@etrepum etrepum mentioned this pull request Jun 25, 2026
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

This branch was successfully deployed

2 active deployments
Preview – lexical — 55abad49 Deployed Jun 12, 2026 by vercel[bot]
Preview – lexical-playground — 55abad49 Deployed Jun 12, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Line Breaks <br/> breaks markup

4 participants