Skip to content

Bug: [lexical-rich-text] Enter after a line break or an inline decorator in a heading turns the text before it into a paragraph #9293

Closed

Description

@rinarakaki

Lexical version: 0.52.0 (the current latest), Chromium 153 on Linux. It reproduces on playground.lexical.dev (0.52.0+dev.esm), and the code is unchanged on main at f0fefed.

Steps To Reproduce

  1. In the playground, type # first to make a Heading 1. Press Shift+Enter, and type second.
  2. Move the caret to the start of second: press Home, or ArrowLeft six times.
  3. Press Enter.

It also happens right after an inline decorator. Type # a , insert an inline equation (Insert → Equation, with Inline checked), and type b. Press ArrowLeft twice, so the caret is just after the equation, and press Enter.

Link to code example: the playground steps above. This snippet reproduces it on stock 0.52.0, headless in Node:

import {$createHeadingNode, HeadingNode} from '@lexical/rich-text';
import {$createLineBreakNode, $createTextNode, $getRoot, createEditor} from 'lexical';

const editor = createEditor({nodes: [HeadingNode], onError: (e) => { throw e; }});
editor.update(
  () => {
    const second = $createTextNode('second');
    $getRoot().append(
      $createHeadingNode('h1').append($createTextNode('first'), $createLineBreakNode(), second),
    );
    // Put the caret at the start of `second`, then do what Enter does.
    second.select(0, 0).insertParagraph();
  },
  {discrete: true},
);
editor.read(() => {
  const blocks = $getRoot().getChildren();
  console.log(blocks.map((n) => `${n.getType()} ${JSON.stringify(n.getTextContent())}`).join(' / '));
});
// Logs: paragraph "first\n" / heading "second"
// Expected: heading "first\n" / heading "second"

The current behavior

first becomes a paragraph, with the line break at its end, and second stays a heading. After the equation, a and the equation become a paragraph, and b stays a heading.

Enter in the middle of second keeps both halves as headings, as it does anywhere else in the middle of a heading. Enter at the heading's real start inserts an empty paragraph above it, as intended.

RangeSelection.insertParagraph splits the text at the caret and calls HeadingNode.insertNewAfter(selection). It then moves the children from the caret on into the block insertNewAfter returns (LexicalSelection.ts#L1423-L1444). insertNewAfter reads an anchor offset of 0 as the start of the heading, whatever node the anchor is on (index.ts#L466 and #L484-L488):

const anchorOffet = selection ? selection.anchor.offset : 0;
// ...
if (anchorOffet === 0 && !this.isEmpty() && selection) {
  const paragraph = $createParagraphNode();
  paragraph.select();
  this.replace(paragraph, true);
}

A caret right after a line break or an inline decorator is at offset 0 of the next text node. So the heading is replaced by a paragraph that keeps all its children, and only the children from the caret on move into the new heading.

After a text node, a caret reads back at the end of that text instead (LexicalSelection.ts#L3106-L3109). In Chromium, a caret after a link does too. So a bold run or a link before the caret doesn't trigger it from the keyboard. When code puts the caret at offset 0 of the text after one, with select(0, 0) or selectStart(), Enter demotes the heading the same way.

The end test just above has the mirror gap (#L467-L472). It compares the anchor with the last descendant's key, but no caret can be on a line break or a decorator. So in a heading that ends with one, Enter at the end adds another heading instead of a paragraph. In the playground, type # first, press Shift+Enter, then Enter. Or end a heading with an inline equation, press End, then Enter. When the heading ends with text, Enter adds a paragraph.

The expected behavior

Enter after a line break or an inline decorator splits the heading into two headings, as in the middle of a heading: first and the line break stay a heading, and second becomes a second heading. Enter at the end of a heading that ends with a line break or a decorator adds a paragraph, as it does at the end of text.

@lexical/utils already has $isAtStartOfNode and $isAtEndOfNode. They check that nothing comes before or after the point inside the element (lexical-utils/src/index.ts#L1318-L1330, built on $isAtEdgeOfElement in range-selection.ts#L74-L105), and @lexical/rich-text already depends on @lexical/utils:

--- a/packages/lexical-rich-text/src/index.ts
+++ b/packages/lexical-rich-text/src/index.ts
@@ -24,6 +24,8 @@
 import {
   $getNearestBlockElementAncestorOrThrow,
   $handleIndentAndOutdent,
+  $isAtEndOfNode,
+  $isAtStartOfNode,
   eventFiles,
   objectKlassEquals,
 } from '@lexical/utils';
@@ -463,13 +465,10 @@
     selection?: RangeSelection,
     restoreSelection = true,
   ): ParagraphNode | HeadingNode {
-    const anchorOffet = selection ? selection.anchor.offset : 0;
     const lastDesc = this.getLastDescendant();
     const isAtEnd =
-      !lastDesc ||
-      (selection &&
-        selection.anchor.key === lastDesc.getKey() &&
-        anchorOffet === lastDesc.getTextContentSize());
+      !lastDesc || (selection && $isAtEndOfNode(selection.anchor, this));
+    const isAtStart = selection && $isAtStartOfNode(selection.anchor, this);
     const newElement =
       isAtEnd || !selection
         ? $createParagraphNode()
@@ -481,7 +480,7 @@
     const direction = this.getDirection();
     newElement.setDirection(direction);
     this.insertAfter(newElement, restoreSelection);
-    if (anchorOffet === 0 && !this.isEmpty() && selection) {
+    if (isAtStart && !this.isEmpty()) {
       const paragraph = $createParagraphNode();
       paragraph.select();
       this.replace(paragraph, true);

I checked it on stock 0.52.0 by replacing HeadingNode.prototype.insertNewAfter with the patched method, in Chromium with real keys and headless in Node:

Caret when Enter is pressed 0.52.0 Patched
Start of line 2, after Shift+Enter p[first <br>] / h1[second] h1[first <br>] / h1[second]
Just after an inline decorator p[a ◆] / h1[ b] h1[a ◆] / h1[ b]
Start of the text after a link or a bold run, set by code p[…] / h1[ b] h1[…] / h1[ b]
End, after a trailing line break or decorator h1[…] / h1[] h1[…] / p[]
The heading's real start, including before a leading decorator or link p[] / h1[…] unchanged
Middle of a word h1 / h1 unchanged
End of text h1 / p[] unchanged

Comparing the anchor with the first descendant's key, as isAtEnd does with the last, also fixes the reported cases. It misses an element point at offset 0 inside a leading inline element, such as (link, 0), where it gives an empty heading above instead of an empty paragraph.

LexicalHeadingNode.test.ts covers insertNewAfter() on an empty heading, in the middle and at the end. The e2e Headings specs cover Enter at the end and in the middle. Nothing covers Enter at the start, so the fix should add those cases.

Impact of fix

Anyone who writes two-line headings with Shift+Enter, or puts inline equations, images or mentions in headings, can hit it. One Enter turns part of a heading into body text, which changes the document's outline and is easy to miss. We met it in an editor with inline math built on Lexical, where headings often hold formulas.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions