Feature: Support wrapped DOM structures in createDOM()
Description
Currently, Lexical's createDOM() method only supports returning a single, flat DOM element. This can be quite limiting, especially when working with HTML elements that have strict styling constraints.
Use case:
An example is wanting to add an icon or visual indicator to line breaks. Lexical natively uses <br> elements for this. However, <br> elements have strict DOM restrictions: they cannot accept standard styling, or utilize ::before/::after pseudo-elements.
To achieve this visual effect, we would need to wrap the <br> in a container (e.g., a <span>) that can handle the styling/icons. Because createDOM() expects a single node to represent the Lexical node, I believe this currently isn't possible natively without breaking reconciliation. (Note: I know that wrapping <br> elements comes with its own contenteditable caret-placement challenges, but the overall styling limitation applies to other elements as well).
Impact
This would allow developers to create more complex editors and UI while staying close to web standards and natively integrating with other Lexical features. It would also prevent the need for hacky workarounds (such as injecting empty <img> tags solely for styling purposes).
Other notes
I am not quite sure what the best API surface area would be to implement this safely (e.g., whether createDOM should support returning nested elements, or if a middleware/hook approach for DOM manipulation would be better).
I am happy to work on this issue, however, since this touches on core API decisions and DOM reconciliation and also has some ongoing work, I wanted to open this discussion first.
Possibly related work:
- https://github.com/facebook/lexical/pull/7885
- Experimental
$getDOMSlotAPI
Selection gets more complicated when this constraint is relaxed, there are issues both with lexical’s mapping of the selection and how the native browser manages it (arrow keys, cursor, etc.) in a contentEditable. Styling line breaks this way seems like a lot of work with considerable downsides. It may be easier to maintain that kind of thing by placing markers on top of the DOM for BRs that are in the viewport.
I wouldn’t recommend any changes to this unless you have a very concrete proposal and some other use cases to demonstrate the utility. A first step might be coming up with more use cases and documentation to make getDOMSlot a public API, then adding support for nodes other than ElementNode could be considered.
Related #7259
Hi @etrepum — I've been digging into the convergence between this issue, #5930, and #7259 (your linked references) and want to share the plan before opening a PR.
Plan
The two-step framing you stated here ("make getDOMSlot a public API, then add support for nodes other than ElementNode") extends naturally to the DecoratorElementNode pattern in #5930 — the slot abstraction is the unifying primitive across both:
-
Promote
getDOMSlotto public. Reframe the JSDoc onElementDOMSlotandElementNode.getDOMSlotaround the override pattern; drop the experimental hedge; add a node-authoring guide section. -
Surface the slot hook on
LexicalNodebase. Default returns the keyed DOM as-is; subclasses override when theircreateDOMreturns a wrapper.LineBreakNode's<br>-in-<span>from this issue is the first worked example. -
Add a
DecoratorElementNodebase class. Combines decorator-style render (outer DOM via React component) with element-style children (lexical-managed inside). The React component exposes a ref viagetDOMSlotoverride; the reconciler inserts children at that ref's element. Card-style container as the worked example. -
Selection / caret plumbing around wrappers. Detail below.
One PR rather than splitting — the foundational API surface and the worked examples need to land coherently to be useful, and the same selection plumbing serves both wrap shapes. The exportDOM middleware in #7259 is a natural follow-up on the serialization side, separate concern.
Risks and how I plan to handle them
-
Arrow-key traversal stopping inside a wrapper. Intercept in
KEY_ARROW_*_COMMANDhandlers when the caret would land inside a wrapper that should be atomic, and jump it to the next valid lexical position. Covershift/ctrl/optioncombinations. Verify in Chrome, Safari, Firefox. -
Caret painting offset from the inner element baseline. Pure browser rendering, not directly controllable. Mitigation is documentation: recommend wrapper CSS patterns (
inline-flex, zero padding/margin on the wrapper element) in the node-authoring guide so the visual matches the unwrapped baseline. Accept slight visual variance when wrapper styling deviates from those recommendations. -
DOM-range resolution crossing a wrapper boundary. Normalize in
applyDOMRangeand$internalResolveSelectionPoint: if a DOM endpoint lands inside a wrapper (between the wrapper element and itsgetDOMSlot().element), snap it to the canonical lexical position. Headless tests for several DOM-range shapes against bothLineBreakNodewrap andDecoratorElementNode. -
IME composition mistargeting the wrapper. Same shape as #5026 / #8507 — the IME picks the wrapper as composition target. The general fix is the
$handleCompositionStartheuristic extension we already considered, but on the current macOS Chrome 148 / iOS 26.5 we couldn't reliably reproduce the original symptom, so I'm not landing that piece in this PR. Documenting the known shape and pointing at #8507 from the new node-authoring guide so future users hitting it have a thread to land on. -
DecoratorElementNodeshape. Going with a new base class rather than a mixin over existingDecoratorNode+ElementNode. Matches lexical's "separate node type per concern" pattern and keeps the type ergonomics for subclasses straightforward (one base to extend). -
Test coverage limits. Headless reliably covers selection-range resolution and reconciler interaction. Arrow-key traversal and caret painting need manual playground verification — I'll include a checklist in the PR body so review can spot-check.
Close
Going to start the PR work along these lines. If there's a risk I'm missing that you've already hit, or if the direction itself is off in a way I haven't noticed, would appreciate a flag before I commit the implementation.
I think it makes sense to extend DOMSlot to also work for all nodes or at least TextNode so I would prefer not making it a public API until we have some concrete plan around that.
I think having this sort of thing extend ElementNode rather than being a new base class would probably make more sense. I don’t really see a justification for making it separate and it would add a lot of busywork to handle this extra node type everywhere that does traversals.
Replanning around both:
- Slot hook on
LexicalNodebase, default returns the keyed DOM. ElementNode's existing override stays. - TextNode and LineBreakNode each get their own override — real non-Element coverage before we commit to public.
- LineBreakNode wrap from this issue is the first concrete user of the TextNode-side override.
- Selection, caret painting, and DOM-range normalization around the wrappers — same four risks I listed before, now they apply across all node types.
- DecoratorElementNode becomes a docs pattern, not a base class. ElementNode subclass + custom createDOM + custom getDOMSlot. Card-shaped container as the example.
Promotion in the same PR. With three node-type shapes exercised in-tree, flipping the JSDoc and dropping @experimental is a one-line addition. Can split if you'd rather stage it, default is one PR.
Two things to check before I start:
- TextNode generalization — slot returns the actual text-bearing element (inner span for wrapped TextNode, inner
<br>for wrapped LineBreakNode), default is the keyed DOM. Is that the shape? - ElementNode-subclass route loses React rendering on the outer. If #5930 needed React-rendered outer + lexical-managed children, I should plan for it. If
createDOM-built outer is enough for the use cases you had in mind, going with that.
Sitting on the implementation PR until I have answers.
I think the most common request for a TextNode would be to insert contentEditable=false DOM nodes before or after the Text node (inside the span), and have all of the selection/navigation code work correctly. Not sure we need to worry about wrapping necessarily. This would be to perform the sort of tricks you’d normally use a pseudo-element for (rendering icons or other sorts of UI) without creating inline ElementNodes just for display reasons.
One use case could be a “visible markdown” mode where TextNodes are displayed with the characters required to generate that formatting, another might be displaying some autocomplete text. Basically the idea would be to add “decorators” that are siblings of the Text.
The DecoratorElementNode idea is a sort of separate concern that would essentially boil down to being able to create something like react portals where parts of the node tree are rendered separately (possibly even async). I think that might be worth deferring to another time and combined with some thinking about how it could be relevant to eliminating most use cases for nested editors or virtualization (not rendering things that aren’t on the screen or are collapsed for example)
Peeked at what render decoupling would actually touch — selection, mutations, the whole DOM-mount invariant — and yeah, that's a lot 😅 Parking that one for a future arc.
For the TextNode side, I think the cleanest shape is: slot returns the text-bearing element, default is the keyed DOM, and the subclass mounts whatever contentEditable=false siblings it wants in createDOM. Same mental model as ElementNode's slot — slot.element is the content boundary, everything else around it is the subclass's call.
Considered a before/after pair and a more general multi-position version, but for visible markdown / autocomplete preview / inline icons the only thing selection actually needs is "where is the text", so the boundary version is enough without locking us into a wider API. Let me know if you were picturing something else.
Plan, roughly in build order:
- Slot on
LexicalNodebase, default returns the keyed DOM ElementNode.getDOMSlotmoves to an override (no-op refactor)LineBreakNodewrap (<br>inside<span>) — first ElementNode-side override- TextNode subclass with sibling decorations — first non-ElementNode example
- Selection / caret / DOM-range plumbing for the wrap boundary and the sibling-decoration boundary — including IME composition landing on the text-bearing element through the slot, and
contentEditable=falsesiblings staying out of composition range - JSDoc flip + drop
@experimentalin the same PR
Step 5 is where the risk sits; the others are mostly isolated. Going to start in on this along these lines — flag anything that's off.
- I don't understand how LineBreakNode is an "ElementNode-side override"?
- We should also test and support the use case where DOMRenderExtension is managing the $getDOMSlot and sibling decorators. I think it's more common that we will want to add this kind of functionality with extensions rather than adding specific subclasses.
- Sounds good, yes this is indeed the hard and risky part
- I don't think we drop experimental at this point especially after adding a bunch of new stuff to it. Should stay experimental until we're confident that the plumbing all works correctly and the API is where we want it to be, e.g. let's say after being released and used for 6 months without really considering changes to it.
The tests for the ElementDOMSlot are also very light so that should be improved upon as part of this process. There were some bugs in there that took a while to surface because we were only testing the specific conditions that the scrollable table wrapper was using.
For the DOMRenderExtension type use case, consider something like rewriting the DraggableBlockPlugin to embed the drag handle in the DOM of the ElementNode, or for the code highlighting extensions to embed the line number in the gutter by decorating the first TextNode (or LineBreak?) of each line.
Point 3 — mixed up the override pattern with ElementNode in my head (long night). LineBreakNode is a leaf.
Point 4 — got it, extension-driven over subclass-driven for the common case. Adding an extension worked example to the plan. Leaning DraggableBlock rewrite over line numbers — smaller scope, sharper before/after, doesn't touch shiki/prism. Let me know if you'd prefer code-side coverage.
Point 6 — agreed, staying experimental. JSDoc flip drops from this PR.
Test bolstering — taking on as part of the work.
Revised scope:
- Slot on
LexicalNodebase, default returns the keyed DOM ElementNode.getDOMSlotmoves to an override (no-op refactor)EditorDOMRenderConfig.$getDOMSlotintegration polish for the extension pathLineBreakNodewrap (<br>inside<span>) — leaf-node worked example- TextNode subclass with sibling decorations — non-ElementNode worked example
- Extension-driven worked example (DraggableBlock rewrite)
- Selection / caret / DOM-range plumbing — wrap + sibling-decoration + extension-managed, including IME composition landing through the slot and
contentEditable=falsesiblings staying out of composition range ElementDOMSlottest expansion
Stays @experimental. Starting in on this — flag the extension example pick or anything else that needs adjustment.
The DraggableBlock and code line number examples are just the first things that came to mind of tricky or half-baked playground functionality that could be cleaner if refactored to use DOMSlot. The important parts are that one of them is based on ElementNode and the other is based on leaf nodes. I think we would want some extension-driven use case demonstrated for leaf nodes - maybe just making linebreaks visible would be good enough for that.
AutocompleteNode is another use case where it is very awkward to actually include a node in the document (causes a lot of history and collab bugs), would be another possible candidate although still fairly complex
Apologies for the back-and-forth — locking in:
DraggableBlock rewrite (extension, ElementNode) + visible linebreaks (extension, leaf) + AutocompleteNode rewrite (extension, TextNode, drop if scope inflates). Both subclass examples from my last plan come out — visible linebreaks covers wrap via extension, and AutocompleteNode (if it lands) covers sibling decoration the same way. Generalization covers TextNode either way.
Build order: slot generalize on LexicalNode base → ElementNode.getDOMSlot becomes an override → DOMRenderExtension integration → the three examples → selection/caret/DOM-range plumbing covering wrap + sibling-decoration boundaries + IME landing through the slot → ElementDOMSlot test expansion.
Stays @experimental. Going in.
Easier to do the back and forth before writing all of the code :) I can also be reached on the discord, usually at a lower latency
Thanks — already in the Discord, will catch you there next time.