Feature: [lexical] Let an inline ElementNode opt out of having a range's end moved into it when the selection is read back
Lexical version: 0.52.0 (the current latest), Chromium 153 on Linux. The code is unchanged on main at f0fefed.
Description
When Lexical reads the DOM selection back, it moves a range's end that sits at a text node's edge into the inline element beside it ($resolveSelectionPointOnBoundary, through $normalizeSelectionPointsForBoundaries). A range from the end of ab into a link, ab |[c|d], gets an anchor at the link's own element point, link@0.
That suits Lexical's own editing. An editor that keeps its own selection, though, can't keep this from happening to it:
- It runs before anything else can. The read-back is in
$internalCreateRangeSelection, which$beginUpdatecalls at the start of each update (LexicalUpdates.ts#L1276-L1284).- It re-reads the DOM for updates started by
selectionchange,beforeinput,compositionstart,compositionend, a drop, a triple-click, and for any update started outside an event (useDOMSelection, LexicalSelection.ts#L3501-L3512). - All of this happens before the update function and before any command listener runs.
- It re-reads the DOM for updates started by
- Then it's written back. The reconciler writes the moved point into the DOM whenever the update has dirty nodes. So an update the editor didn't start moves its range in the DOM too: a timer's, a collaborator's, or one of Lexical's own deferred updates.
- No hook can undo it.
TextNode.selectionTransformruns after the read-back, but only for text points (applySelectionTransforms). An end that has already become an element point never reaches it.
This sets such a range in an update, then runs an unrelated update from a timer, and logs Lexical's selection and the DOM's:
import {$createLinkNode, LinkNode} from '@lexical/link';
import {registerRichText} from '@lexical/rich-text';
import {
$createParagraphNode,
$createRangeSelection,
$createTextNode,
$getRoot,
$getSelection,
$isRangeSelection,
$setSelection,
createEditor,
} from 'lexical';
const root = document.createElement('div');
root.contentEditable = 'true';
document.body.append(root);
const editor = createEditor({
nodes: [LinkNode],
onError: (error) => {
throw error;
},
});
editor.setRootElement(root);
registerRichText(editor);
root.focus();
const show = (step) => {
const lexical = editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) {
return String(selection);
}
const point = (p) => `${p.getNode().getType()}@${p.offset} (${p.type})`;
return `${point(selection.anchor)} .. ${point(selection.focus)}`;
});
const dom = document.getSelection();
console.log(
`${step}: Lexical ${lexical}; DOM ${dom.anchorNode.nodeName}@${dom.anchorOffset} .. ${dom.focusNode.nodeName}@${dom.focusOffset}`,
);
};
let after;
editor.update(
() => {
const before = $createTextNode('ab ');
const inLink = $createTextNode('cd');
after = $createTextNode(' ef');
$getRoot().append(
$createParagraphNode().append(
before,
$createLinkNode('https://example.com/').append(inLink),
after,
),
);
// A range from the end of "ab " into the link: "ab |" .. "c|d".
const selection = $createRangeSelection();
selection.anchor.set(before.getKey(), 3, 'text');
selection.focus.set(inLink.getKey(), 1, 'text');
$setSelection(selection);
},
{discrete: true},
);
show('set in an update');
setTimeout(() => {
show('after the selectionchange read-back');
// An update started outside any event, as a timer's or a collaborator's is.
editor.update(() => after.setTextContent(' eg'), {discrete: true});
show('after an unrelated update');
}, 100);It prints:
| Step | Lexical's selection | DOM selection |
|---|---|---|
| set in an update | text@3 .. text@1 |
#text@3 .. #text@1 |
after the selectionchange read-back |
link@0 (element) .. text@1 |
#text@3 .. #text@1 |
| after an unrelated update | link@0 (element) .. text@1 |
A@0 .. #text@1 |
A range from inside the link to the start of ef behaves the same way: its focus becomes link@1, and then the DOM's A@1. A range that ends inside ab is left alone.
Use case
We're building an editor with inline math on Lexical. Formulas are inline elements. The editor draws its own caret and keeps its own selection record, mirrored into the DOM selection so input methods and screen readers follow it, as CodeMirror 6 does.
A range from prose into a formula starts at the end of the prose's text. After any update the editor didn't start, Lexical's selection and the DOM's start at the formula's element point instead. It's the same visible position but a different point, so anything that compares the DOM selection with the editor's record sees a change nobody made.
The same applies to:
- mentions or references built as inline elements;
- collaborative editing, where a remote update re-normalizes the local user's range and moves their DOM selection.
Proposal
An opt-out on ElementNode, consulted by that branch, and true by default so nothing changes unless a node overrides it. The name is open.
--- a/packages/lexical/src/nodes/LexicalElementNode.ts
+++ b/packages/lexical/src/nodes/LexicalElementNode.ts
@@ canInsertTextAfter(): boolean {
return true;
}
+ /**
+ * Whether a selection point at the edge of a text node beside this inline
+ * element may be moved into it when the selection is read from the DOM.
+ * Return false to leave such points in the text, where the DOM has them.
+ */
+ canNormalizeSelectionInto(): boolean {
+ return true;
+ }
--- a/packages/lexical/src/LexicalSelection.ts
+++ b/packages/lexical/src/LexicalSelection.ts
@@ function $resolveSelectionPointOnBoundary(
if (
before !== isBackward &&
$isElementNode(sibling) &&
sibling.isInline() &&
+ sibling.canNormalizeSelectionInto() &&
(!before || !isCollapsed)
) {- Size: with the Flow declaration (
canNormalizeSelectionInto(): boolean;inLexical.js.flow) and a unit test, it's about ten lines of source. - Checked on a copy of 0.52.0's build patched the same way. There,
main's single condition is still two branches, and the patch adds the call to both.- With
LinkNodeanswering false, both ranges above keep their text points through the read-back and through the unrelated update. - The range inside
abis unchanged either way. - In our editor's own probes (146 typing and composition cases, with its formula element answering false), nothing else changed.
- With
Alternatives considered
- Restoring the selection after the fact. This works in the editor's own updates, and on
selectionchange. It can't work for updates others start, because no hook between the read-back and the commit sees element points. - An editor-level flag that turns the normalization off. It's coarser: links in the same editor would change behaviour too.
- Calling selection transforms for element points as well (in
applySelectionTransforms). It's more general, but every implementer would have to restore points by hand. - Normalizing only on a user's
selectionchange, and not when an update re-reads the DOM selection for other reasons.
Impact
It helps editors that keep their own selection, or draw their own caret, over inline elements: math, and mentions or references built as elements. It also helps collaborative editors, where others' updates re-normalize the local user's range. The default is unchanged, so no one else sees a difference.
Source: facebook/lexical