Feature: [lexical] Let an ElementDOMSlot remove, replace and order the children it inserts
Lexical version: 0.52.0 (the current latest), Chromium 153 on Linux. The code is unchanged on main at f0fefed.
Description
An ElementNode can override getDOMSlot to decide where its children's DOM goes. The reconciler inserts every child through the slot's insertChild (LexicalReconciler.ts#L819-L821), so a slot can put each child in a wrapper of its own. It can't keep that shape, though. The reconciler removes a child, replaces one, and finds where the next one goes through the child's own DOM, as if it were a direct child of slot.element:
- Removal:
$destroyNoderemoves a child onlyif (dom.parentNode === parentDOM), withparentDOM.removeChild(dom)(L311-L316). - Replacement: when
updateDOMreturns true,$reconcileNodecallsparentDOM.replaceChild(replacementDOM, dom)(L1777). An element's only child is replaced withdom.replaceChildwhenlastDOM.parentNode === dom. Otherwise the new child is inserted and the old DOM is left where it is (L1601-L1608, then$destroyNode(prevFirstChildKey, null)at L1623). - Order: the keyed walk in
$reconcileNodeChildrentakes the next insertion point fromgetNextSibling(childDOM), the child's ownnextSibling(L2000-L2047). The suffix fast path takes it from the next child's keyed DOM instead (L1215-L1228).
DOMSlot has had removeChild and replaceChild since #8519, next to insertChild (LexicalDOMSlot.ts#L160-L190), but the reconciler never calls them. Outside it, the one caller of replaceChild is ElementNode.reconcileObservedMutation (LexicalElementNode.ts#L1086-L1108). DOMSlot and ElementDOMSlot are also exported as types only (index.ts#L140-L141), so a subclass has to take the constructor off an instance.
Slots that move all the children into one inner element, as TableNode's does, aren't affected: every child is still a direct child of slot.element.
Example
A slot that puts each child in a <span data-wrapper> of its own, and implements removeChild, replaceChild and getFirstChild for that shape:
import {$createTextNode, $getNodeByKey, $getRoot, createEditor, ElementNode} from 'lexical';
// ElementDOMSlot is exported as a type only, so the constructor is taken off an instance.
function wrapEachChild(slot) {
const ElementDOMSlot = slot.constructor;
const outer = (dom) =>
dom?.parentElement?.hasAttribute('data-wrapper') ? dom.parentElement : dom;
class WrapEachChild extends ElementDOMSlot {
withBefore(before) {
return new WrapEachChild(this.element, before, this.after);
}
withAfter(after) {
return new WrapEachChild(this.element, this.before, after);
}
withElement(element) {
return element === this.element
? this
: new WrapEachChild(element, this.before, this.after);
}
insertChild(dom) {
const wrapper = document.createElement('span');
wrapper.setAttribute('data-wrapper', '');
wrapper.append(dom);
this.element.insertBefore(wrapper, outer(this.before));
return this;
}
removeChild(dom) {
outer(dom).remove();
return this;
}
replaceChild(dom, prevDom) {
prevDom.replaceWith(dom);
return this;
}
getFirstChild() {
return this.element.firstElementChild?.firstChild ?? null;
}
}
return new WrapEachChild(slot.element, slot.before, slot.after);
}
class BoxNode extends ElementNode {
static getType() {
return 'box';
}
static clone(node) {
return new BoxNode(node.__key);
}
createDOM() {
return document.createElement('div');
}
updateDOM() {
return false;
}
getDOMSlot(element) {
return wrapEachChild(super.getDOMSlot(element));
}
}
const root = document.createElement('div');
root.contentEditable = 'true';
document.body.append(root);
const editor = createEditor({nodes: [BoxNode], onError: (error) => console.error(error)});
editor.setRootElement(root);
const update = (fn) => editor.update(fn, {discrete: true});
const show = (step) => {
const dom = [...root.firstElementChild.children].map((w) => w.textContent).join(' ');
const model = editor.getEditorState().read(() =>
$getRoot().getFirstChildOrThrow().getChildren().map((n) => n.getTextContent()).join(' '),
);
console.log(`${step}: DOM ${dom} / model ${model}`);
};
const key = {};
update(() => {
const a = $createTextNode('a');
const b = $createTextNode('b').toggleFormat('bold');
const c = $createTextNode('c').toggleFormat('italic');
[key.a, key.b, key.c] = [a.getKey(), b.getKey(), c.getKey()];
$getRoot().append(new BoxNode().append(a, b, c));
});
show('mounted');
update(() => $getNodeByKey(key.a).insertAfter($createTextNode('d').toggleFormat('underline')));
show('inserted d after a');
update(() => $getNodeByKey(key.b).remove());
show('removed b');
update(() => $getNodeByKey(key.c).toggleFormat('code'));What it prints:
| step | DOM (each wrapper's text) | model |
|---|---|---|
| mounted | a b c |
a b c |
inserted d after a |
a b c d |
a d b c |
removed b |
a b c d |
a d c |
made c code, so its tag changes |
NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node. |
Replacing an element's only child leaves the old child's wrapper in place too. A slot that only logs its calls, without wrapping, shows the same split: the reconciler asks it to insert each child, and never to remove or replace one, though it does both.
Use case
We're building an editor with inline math on Lexical, rendered as MathML. A MathML container such as <mrow> lays out only MathML children, so an HTML child, such as a decorator's DOM, gets no box unless it sits in an <mtext> of its own. The rule belongs to the parent: any child of a MathML container that isn't MathML needs the wrapper. A slot is the natural place for it. The same shape comes up with SVG (<foreignObject> around HTML children), and with any element that wants chrome around each child.
What it would take, roughly
- Remove and replace children through the parent's slot (
slot.removeChild,slot.replaceChild). Let the slot say whether it still holds a child's DOM, where$destroyNodechecksdom.parentNode === parentDOMtoday for a node moved in the same update. - Take the next insertion point from the next child's keyed DOM, as the suffix fast path does, or from the slot, rather than from
childDOM.nextSibling.getFirstChild()is already the slot's. - Export
DOMSlotandElementDOMSlotas values, so a node can subclass them.
A DOM selection point inside a wrapper, beside the child, would need mapping too: ElementDOMSlot.resolveChildIndex reads points in slot.element itself.
Alternatives considered
- Each child wraps its own DOM, with a slot pointing inside, the leaf pattern from #8519. The child then has to know its parent's kind in
createDOM, returntruefromupdateDOMwhenever it moves between an HTML parent and a MathML one, and leave the wrapper out ofexportDOM. That's what we do today, once per node class. - The same from a
DOMRenderExtension$createDOMoverride: one rule instead of one per class, with the same costs.
Impact
It helps editors whose elements lay out children in a namespace or a structure that needs a container around each child: MathML and SVG content, and elements with chrome around each child. It also makes the slot's removeChild and replaceChild mean what they say. Today the reconciler bypasses a slot that overrides them. A slot that places children anywhere but directly in slot.element leaves stale DOM on removal, and throws on replacement.
Source: facebook/lexical