Bug: [lexical-plain-text] An arrow key on a node-selected decorator sends what is typed next to the top of the document
This is #4214, reported again because it reproduces with Lexical's own packages alone, and because the cause and a fix are below. Either issue can be closed as a duplicate of the other.
Lexical version: 0.52.0 (the current latest), Chromium 153 on Linux. The code is unchanged on main at f0fefed.
On whether decorators are expected to work in plain text (#4214): Lexical's own HorizontalRuleExtension works with PlainTextExtension, and a click node-selects the rule. From then on, every arrow key leaves Lexical's selection and the browser's caret in different places, and what is typed next goes to the top of the document.
Steps To Reproduce
- Run the code below.
- Click in
first. - Click the rule. It gets a node selection and the
selectedclass. - Press ArrowDown, then type
q.
Link to code example: stock packages, no React.
import {
$createHorizontalRuleNode,
buildEditorFromExtensions,
HorizontalRuleExtension,
} from '@lexical/extension';
import {PlainTextExtension} from '@lexical/plain-text';
import {
$createParagraphNode,
$createTextNode,
$getRoot,
$getSelection,
$isNodeSelection,
defineExtension,
} from 'lexical';
const root = document.createElement('div');
root.contentEditable = 'true';
document.body.append(root);
const editor = buildEditorFromExtensions(
defineExtension({
dependencies: [PlainTextExtension, HorizontalRuleExtension],
name: 'repro',
}),
);
editor.setRootElement(root);
editor.update(() => {
$getRoot()
.clear()
.append(
$createParagraphNode().append($createTextNode('first')),
$createParagraphNode().append($createTextNode('before')),
$createHorizontalRuleNode(),
$createParagraphNode().append($createTextNode('after')),
);
});
editor.registerUpdateListener(({editorState}) =>
console.log(
'node selection:',
editorState.read(() => $isNodeSelection($getSelection())),
'browser caret:',
document.getSelection()?.anchorNode,
),
);The current behavior
q is written at the start of before, above the rule. The rule stays selected, on screen and in the model: the log still says node selection: true after the q. The browser's caret moves as if it started at the top of the document:
- ArrowUp and ArrowLeft put
qat the start offirst; - ArrowDown puts it at the start of
before; - ArrowRight puts it after the
foffirst.
With Shift, each arrow also starts from the top of the document. A node-selected inline decorator in the middle of a line gives the same results. If the rule is the first thing clicked in the editor, the browser keeps a caret beside it and ArrowDown moves from there, but Lexical still keeps the node selection while q is typed.
With RichTextExtension in place of PlainTextExtension, each arrow moves the caret to the rule's side, and q is typed there: ArrowUp and ArrowLeft go to the end of before, and ArrowDown and ArrowRight to the start of after.
Why:
- Plain text's ArrowLeft and ArrowRight listeners return
falsefor anything but aRangeSelection, and it has no ArrowUp or ArrowDown listener (index.ts#L251-L294). So the browser's default action runs. - For a
NodeSelection,$updateDOMSelectionremoves the browser's range (LexicalSelection.ts#L3905-L3921). With no range to move, Chromium starts from the top of the document. - The
selectionchangethat follows is not read back. For a selection that isn't a range,$internalCreateSelectionclones the last one instead of reading the DOM (LexicalSelection.ts#L3447-L3464). So Lexical keeps the node selection while the browser's caret is elsewhere, and the next typed text goes in at the browser's caret.
Rich text avoids all of this by answering the four arrows for a NodeSelection itself (index.ts#L1510-L1728).
The expected behavior
An arrow key on a node-selected decorator moves the caret to the decorator's side, as it does in rich text, and what is typed next goes there.
One way is to share rich text's answer, as suggested in #4214:
- Move rich text's
$exitNodeSelectionTowardand$convertContiguousNodeSelection(index.ts#L1130-L1191) to@lexical/selectionunchanged. They use onlylexical's caret API and$isParentRTL, and plain text already depends on both packages. - Import them in rich text, and give plain text's arrow listeners the same node-selection branch:
--- a/packages/lexical-plain-text/src/index.ts
+++ b/packages/lexical-plain-text/src/index.ts
@@ -18,6 +18,9 @@
NormalizeTripleClickSelectionExtension,
} from '@lexical/extension';
import {
+ $convertContiguousNodeSelection,
+ $exitNodeSelectionToward,
+ $isParentRTL,
$moveCharacter,
$shouldOverrideDefaultCharacterSelection,
} from '@lexical/selection';
@@ -25,9 +28,11 @@
import {
$getSelection,
$getSlotFrame,
+ $isNodeSelection,
$isRangeSelection,
$selectAll,
CAN_USE_BEFORE_INPUT,
+ type CaretDirection,
COMMAND_PRIORITY_EDITOR,
type CommandPayloadType,
CONTROLLED_TEXT_INSERTION_COMMAND,
@@ -45,19 +50,44 @@
IS_APPLE_WEBKIT,
IS_IOS,
IS_SAFARI,
+ KEY_ARROW_DOWN_COMMAND,
KEY_ARROW_LEFT_COMMAND,
KEY_ARROW_RIGHT_COMMAND,
+ KEY_ARROW_UP_COMMAND,
KEY_BACKSPACE_COMMAND,
KEY_DELETE_COMMAND,
KEY_ENTER_COMMAND,
type LexicalEditor,
mergeRegister,
+ type NodeSelection,
PASTE_COMMAND,
PASTE_TAG,
REMOVE_TEXT_COMMAND,
SELECT_ALL_COMMAND,
} from 'lexical';
+/**
+ * Answers an arrow key for a NodeSelection as rich text does. With Shift, a
+ * contiguous NodeSelection becomes the range it covers, for the key to extend
+ * (false); otherwise the caret moves to the node's side in `direction` (true).
+ */
+function $exitNodeSelection(
+ event: KeyboardEvent,
+ selection: NodeSelection,
+ direction: CaretDirection,
+): boolean {
+ const nodes = selection.getNodes();
+ if (nodes.length === 0) {
+ return false;
+ }
+ if (event.shiftKey && $convertContiguousNodeSelection(selection, direction)) {
+ return false;
+ }
+ event.preventDefault();
+ $exitNodeSelectionToward(nodes[0], direction);
+ return true;
+}
+
function onCopyForPlainText(
event: CommandPayloadType<typeof COPY_COMMAND>,
editor: LexicalEditor,
@@ -251,13 +281,23 @@
editor.registerCommand(
KEY_ARROW_LEFT_COMMAND,
payload => {
- const selection = $getSelection();
+ let selection = $getSelection();
+ const event = payload;
+
+ if ($isNodeSelection(selection)) {
+ const [node] = selection.getNodes();
+ const direction =
+ node !== undefined && $isParentRTL(node) ? 'next' : 'previous';
+ if ($exitNodeSelection(event, selection, direction)) {
+ return true;
+ }
+ selection = $getSelection();
+ }
if (!$isRangeSelection(selection)) {
return false;
}
- const event = payload;
const isHoldingShift = event.shiftKey;
if ($shouldOverrideDefaultCharacterSelection(selection, true)) {
@@ -273,13 +313,23 @@
editor.registerCommand(
KEY_ARROW_RIGHT_COMMAND,
payload => {
- const selection = $getSelection();
+ let selection = $getSelection();
+ const event = payload;
+
+ if ($isNodeSelection(selection)) {
+ const [node] = selection.getNodes();
+ const direction =
+ node !== undefined && $isParentRTL(node) ? 'previous' : 'next';
+ if ($exitNodeSelection(event, selection, direction)) {
+ return true;
+ }
+ selection = $getSelection();
+ }
if (!$isRangeSelection(selection)) {
return false;
}
- const event = payload;
const isHoldingShift = event.shiftKey;
if ($shouldOverrideDefaultCharacterSelection(selection, false)) {
@@ -292,6 +342,28 @@
},
COMMAND_PRIORITY_EDITOR,
),
+ editor.registerCommand(
+ KEY_ARROW_UP_COMMAND,
+ event => {
+ const selection = $getSelection();
+ return (
+ $isNodeSelection(selection) &&
+ $exitNodeSelection(event, selection, 'previous')
+ );
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ editor.registerCommand(
+ KEY_ARROW_DOWN_COMMAND,
+ event => {
+ const selection = $getSelection();
+ return (
+ $isNodeSelection(selection) &&
+ $exitNodeSelection(event, selection, 'next')
+ );
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
editor.registerCommand(
KEY_BACKSPACE_COMMAND,
event => {I checked these listeners in Chromium, using copies of the two helpers, against stock rich text. The cases were a block and an inline decorator, each of the four arrows, and each with Shift. All 16 cases gave the same selection, the same browser caret, and the same text after typing q.
Impact of fix
It affects every plain-text editor with a decorator that can be node-selected, Lexical's own horizontal rule included: after any arrow key, typing goes to the top of the document while the decorator still shows as selected. #4214 has been open since 2023, with a workaround of forking the plain-text package.
Source: facebook/lexical