Bug: [lexical] Typing at a link's edge is lost, or lands before the link, when the caret's text is in an inline element inside the link
Lexical version: 0.52.0 (the current latest), Chromium 153 on Linux. The code is unchanged on main at f0fefed.
Steps To Reproduce
- Mount a rich-text editor with
LinkNodeand a custom inlineElementNode. The element takes text at its edges, asElementNodedoes by default. - Write
ab [cd (xy)]: a link whose last child is that inline element, holdingxy. - Put the caret at the end of
xy. That's also the end of the link, and of the line. - Type
Xon the keyboard.
Link to code example: the snippet below does steps 1–3. It needs a real key press for step 4, from the keyboard or from Playwright's page.keyboard.type('X').
import {$createLinkNode, LinkNode} from '@lexical/link';
import {$createMarkNode, MarkNode} from '@lexical/mark';
import {registerRichText} from '@lexical/rich-text';
import {
$createParagraphNode,
$createTextNode,
$getRoot,
createEditor,
ElementNode,
type SerializedElementNode,
} from 'lexical';
// Any custom inline element. Like ElementNode by default, it takes text at its edges.
class InlineNode extends ElementNode {
static getType() {
return 'inline';
}
static clone(node: InlineNode) {
return new InlineNode(node.__key);
}
static importJSON(json: SerializedElementNode) {
return new InlineNode().updateFromJSON(json);
}
createDOM() {
return document.createElement('span');
}
updateDOM() {
return false;
}
isInline(): true {
return true;
}
}
const root = document.createElement('div');
root.contentEditable = 'true';
document.body.append(root);
const editor = createEditor({
nodes: [LinkNode, MarkNode, InlineNode],
onError: (error) => {
throw error;
},
});
editor.setRootElement(root);
registerRichText(editor);
root.focus();
editor.update(() => {
const xy = $createTextNode('xy');
$getRoot().append(
$createParagraphNode().append(
$createTextNode('ab '),
$createLinkNode('https://example.com/').append(
$createTextNode('cd '),
new InlineNode().append(xy), // or: $createMarkNode(['id']).append(xy)
),
),
);
xy.select(2, 2);
});The current behavior
The editor still reads ab cd xy: the X is lost. It's lost the same way in two more places:
- when text follows the link:
ab [cd (xy)] ef; - at the start of a link that starts the line:
[(xy) cd] ef, with the caret beforexy.
With a MarkNode in place of the inline element, as a comment on the link's last word makes, the X isn't lost. It lands before the link instead: ab X[cd (xy)].
For comparison, these work:
- The link's own text: typing at its edges puts the character outside the link, which is Lexical's chosen behaviour (#2543).
ab [cd]givesab [cd]X, and[cd] efgivesX[cd] ef. - Away from the link's edge: typing at the end of
xyinab [(xy) cd]writesxyXinside the element.
Why:
$shouldInsertTextAfterOrBeforeTextNodedecides whether Lexical writes a character typed at a text's edge itself, or leaves it to the browser. It asks only the text's parent:parent.canInsertTextAfter(). Here the parent is the inline element, which takes text there. So$shouldPreventDefaultAndInsertTextdoesn't cancelbeforeinput, although the caret is also at the edge of the link, which takes no text.- Chromium moves an insertion at an
<a>'s edge out of the<a>: it adds a new text node to the<p>, beside it. Lexical doesn't know that node, and$flushMutationsremoves it, so the character is gone. AMutationObservershows+#text("X")on the<p>, then-#text("X"). Thebeforeinputevent's target range is still insidexy. - A
MarkNodetakes no text at its edges, so there Lexical does take the event, andRangeSelection.insertTextredirects. It adds an empty text node after the mark, still inside the link, and calls itself again. That node is empty, so offset 0 is also its end, butconst before = offset === 0reads it as the start. The link takes no text before it, so the text goes before the link.
The expected behavior
A character typed at a link's edge is written outside the link, whatever inline element holds the caret's text. At the link's end it goes after the link, and at its start before it, as at the link's own text.
Steps 1 and 3 look only at the text's parent. The fix is to ask every inline element whose edge the text is at, and to step beside the outermost one that takes no text there. I checked this change against a copy of 0.52.0's dist/Lexical.dev.js, with real key presses in Chromium:
- every case above writes the character outside the link;
- these give the same results as before: the link's own text, inside the element away from the link's edge, mid-paragraph, an empty paragraph, and the end of a bold word.
In packages/lexical/src/LexicalUtils.ts, a helper beside $previousSiblingDoesNotAcceptText:
/**
* The outermost element that takes no text at the start (or end) of `node`:
* its parent, and each inline element above it that `node` is also at the
* start (or end) of. Null when every one takes text there.
*/
export function $getOutermostAncestorRefusingText(
node: TextNode,
isBefore: boolean,
): ElementNode | null {
let refusing: ElementNode | null = null;
let child: LexicalNode = node;
let parent = child.getParent();
while (
parent !== null &&
(isBefore ? child.getPreviousSibling() : child.getNextSibling()) === null
) {
if (
isBefore ? !parent.canInsertTextBefore() : !parent.canInsertTextAfter()
) {
refusing = parent;
}
if (!parent.isInline()) {
break;
}
child = parent;
parent = child.getParent();
}
return refusing;
}and in $shouldInsertTextAfterOrBeforeTextNode:
if (offset === 0) {
return (
!node.canInsertTextBefore() ||
- (!parent.canInsertTextBefore() && !node.isComposing()) ||
+ ((!parent.canInsertTextBefore() ||
+ $getOutermostAncestorRefusingText(node, true) !== null) &&
+ !node.isComposing()) ||
isToken ||
$previousSiblingDoesNotAcceptText(node)
);
} else if (offset === node.getTextContentSize()) {
return (
!node.canInsertTextAfter() ||
- (!parent.canInsertTextAfter() && !node.isComposing()) ||
+ ((!parent.canInsertTextAfter() ||
+ $getOutermostAncestorRefusingText(node, false) !== null) &&
+ !node.isComposing()) ||
isToken
);In packages/lexical/src/LexicalSelection.ts, RangeSelection.insertText (with the helper added to the import from ./LexicalUtils):
const anchorParent = anchorNode.getParentOrThrow();
const anchorSize = anchorNode.getTextContentSize();
+ const refusingBefore =
+ offset === 0
+ ? $getOutermostAncestorRefusingText(anchorNode, true)
+ : null;
+ const refusingAfter =
+ offset === anchorSize
+ ? $getOutermostAncestorRefusingText(anchorNode, false)
+ : null;
const needsRedirect =
$isTokenOrSegmented(anchorNode) ||
(offset === 0 &&
- (!anchorNode.canInsertTextBefore() ||
- (!anchorParent.canInsertTextBefore() && !anchorNode.__prev))) ||
+ (!anchorNode.canInsertTextBefore() || refusingBefore !== null)) ||
(offset === anchorSize &&
- (!anchorNode.canInsertTextAfter() ||
- (!anchorParent.canInsertTextAfter() && !anchorNode.__next)));
+ (!anchorNode.canInsertTextAfter() || refusingAfter !== null)); if (offset === 0 || offset === anchorSize) {
- const before = offset === 0;
+ // An empty text is at both edges: redirect the way something refuses.
+ const before =
+ offset === 0 && (refusingBefore !== null || refusingAfter === null);
const direction = before ? 'previous' : 'next';
+ const beside = (before ? refusingBefore : refusingAfter) || anchorNode;
const sibling = $getSiblingCaret(
- anchorNode,
+ beside,
direction,
).getNodeAtCaret();
let target: TextNode;
if (
$isTextNode(sibling) &&
(before
? sibling.canInsertTextAfter()
: sibling.canInsertTextBefore()) &&
!$isTokenOrSegmented(sibling)
) {
target = sibling;
} else {
target = $createTextNode().setFormat(format).setStyle(style);
- const canInsert = before
- ? anchorParent.canInsertTextBefore()
- : anchorParent.canInsertTextAfter();
- $getSiblingCaret(
- canInsert ? anchorNode : anchorParent,
- direction,
- ).insert(target);
+ $getSiblingCaret(beside, direction).insert(target);
}For the parent, the helper asks the same question as the old checks, so the redirect only changes where an inline element above the parent refuses text. One more change is deliberate: where the text itself refuses (a token) but isn't at its parent's edge, the new text goes beside the text, rather than jumping out beside the parent.
Impact of fix
It hits any editor with a custom inline ElementNode that can end up at a link's edge, such as inline math or a mention built as an element. We met it with inline math at a link's end. The typed character disappears, with no error. With stock nodes, a comment on a link's last word sends what is typed at the link's end to before the link.
Source: facebook/lexical