Skip to main content

lexical_ui/
node.rs

1//! `LexicalNode.ts`: the node trait every node implements, and [`NodeRef`],
2//! the handle through which code outside a node reads and changes one.
3
4use crate::caret::{
5    CommonAncestorResult, get_common_ancestor, get_common_ancestor_result_branch_order,
6};
7use crate::caret_tree::{
8    detach_node_with_selection, error_on_insert_text_node_on_root, insert_node_between,
9    insert_sibling, select_adjacent_node,
10};
11use crate::editor_state::NodeMap;
12use crate::error::invariant;
13use crate::lexical_selection::{
14    PointType, SelectionRef, Which, get_selection, maybe_move_children_selection_to_parent,
15    move_selection_point_to_end, move_selection_point_to_sibling, set_selection,
16};
17use crate::lexical_utils::{get_node_by_key_impl, get_writable, mutate, with_writable};
18use crate::node_state::{NodeStateRef, RequiredNodeStateConfig};
19use crate::nodes::element::{self, ElementData, is_root_or_shadow_root};
20use crate::nodes::root::RootNode;
21use crate::nodes::text::TextData;
22use crate::updates::{error_on_read_only, get_active_editor_state};
23use crate::{LexicalError, json::Object, utf16};
24use std::any::Any;
25use std::cmp::Ordering;
26use std::fmt;
27use std::rc::Rc;
28
29/// A node's key in its editor state's node map. Keys are strings, as in JS,
30/// from a per-thread counter (`generateRandomKey`).
31pub type NodeKey = String;
32
33/// The fields every node has: its key, its links to its parent and
34/// siblings (`__key`, `__parent`, `__prev`, `__next`) and its NodeState
35/// (`__state`), which a clone shares until one of them writes it; and, used
36/// by elements and decorators only, the slot fields JS's `ElementNode` and
37/// `DecoratorNode` add (`__slotHost`, `__slots`). A clone keeps them, as
38/// their `afterCloneFrom` does for the same key; `$copyNode` drops them.
39#[derive(Clone, Debug, Default)]
40pub struct NodeBase {
41    pub(crate) key: NodeKey,
42    pub(crate) parent: Option<NodeKey>,
43    pub(crate) prev: Option<NodeKey>,
44    pub(crate) next: Option<NodeKey>,
45    pub(crate) state: Option<NodeStateRef>,
46    /// `__slotHost` (an element or a decorator): the host whose named slot
47    /// holds this node, which then has no parent.
48    pub(crate) slot_host: Option<NodeKey>,
49    /// `__slots` (an element or a decorator): its named slots, shared by its
50    /// versions until one writes them.
51    pub(crate) slots: Option<Rc<crate::slot::SlotMap>>,
52    /// The id of the editor state this version was made writable (or
53    /// created) in: with the key, which version of the node this is.
54    pub(crate) written_in: u64,
55    /// What the node structure normalization recorded of this version's
56    /// rule inputs (JS's `ruleInputs` `WeakMap`, keyed by the node object):
57    /// a new version starts without.
58    pub(crate) structure_rule_inputs: StructureRuleInputs,
59}
60
61/// [`NodeBase::structure_rule_inputs`]: kept by this version only, so a
62/// clone (the next version) starts without one.
63#[derive(Debug, Default)]
64pub(crate) struct StructureRuleInputs(std::cell::Cell<Option<u8>>);
65
66impl Clone for StructureRuleInputs {
67    fn clone(&self) -> Self {
68        Self::default()
69    }
70}
71
72impl StructureRuleInputs {
73    pub(crate) fn get(&self) -> Option<u8> {
74        self.0.get()
75    }
76    pub(crate) fn set(&self, value: Option<u8>) {
77        self.0.set(value);
78    }
79}
80
81/// What every node implements. JS's class hierarchy (`LexicalNode`,
82/// `ElementNode`, `TextNode`, ...) becomes this trait plus the data each base
83/// class adds ([`ElementData`], [`TextData`]); a node that extends
84/// `ElementNode` returns its `ElementData` from [`element`](Self::element).
85///
86/// A node is a value: an editor state holds each one behind an `Rc`, and a
87/// change clones it first unless nothing else shares it (`getWritable`), so
88/// `Clone` is the JS `clone` plus `afterCloneFrom`.
89///
90/// Methods that JS subclasses override call `super`; here the base class's
91/// behavior is a free function in that class's module (such as
92/// `nodes::element::get_text_content`) that an override can call.
93///
94/// A node that extends `DecoratorNode` (`nodes/LexicalDecoratorNode.ts`)
95/// returns true from [`is_decorator`](Self::is_decorator) and may override
96/// the decorator's hooks: [`decorate`](Self::decorate),
97/// [`is_isolated`](Self::is_isolated) and
98/// [`is_keyboard_selectable`](Self::is_keyboard_selectable). A decorator is
99/// inline unless it overrides [`is_inline`](Self::is_inline).
100pub trait LexicalNode: NodeClone + fmt::Debug + 'static {
101    /// `getType()`: the type the node serializes as.
102    fn get_type(&self) -> &'static str;
103
104    fn base(&self) -> &NodeBase;
105    fn base_mut(&mut self) -> &mut NodeBase;
106
107    /// The `ElementNode` fields, for a node that extends it.
108    fn element(&self) -> Option<&ElementData> {
109        None
110    }
111    fn element_mut(&mut self) -> Option<&mut ElementData> {
112        None
113    }
114
115    /// The `TextNode` fields, for a node that extends it.
116    fn text(&self) -> Option<&TextData> {
117        None
118    }
119    fn text_mut(&mut self) -> Option<&mut TextData> {
120        None
121    }
122
123    /// The `DecoratorBlockNode` fields (`@lexical/react`), for a node that
124    /// extends it: such a node is a decorator that is not inline and can't
125    /// be indented, unless it overrides those hooks.
126    #[cfg(feature = "decorator-block")]
127    fn decorator_block(&self) -> Option<&crate::decorator_block::DecoratorBlockData> {
128        None
129    }
130    #[cfg(feature = "decorator-block")]
131    fn decorator_block_mut(&mut self) -> Option<&mut crate::decorator_block::DecoratorBlockData> {
132        None
133    }
134
135    /// `isInline()`: false for an element, true for text and a decorator
136    /// (false for a `DecoratorBlockNode`). A class whose config chain
137    /// declares `inline` ([`static_node_config_chain`](Self::static_node_config_chain))
138    /// returns the nearest declaration, as the `isInline()` JS synthesizes
139    /// for a class that declares it does.
140    fn is_inline(&self) -> bool {
141        if self.text().is_some() {
142            return true;
143        }
144        if let Some(inline) = crate::structure::declared_inline(self.as_node()) {
145            return inline;
146        }
147        self.is_decorator() && !is_decorator_block(self)
148    }
149
150    /// Whether the node extends `DecoratorNode` (`$isDecoratorNode`): a leaf
151    /// whose content an app renders ([`decorate`](Self::decorate)), which
152    /// the editor moves, selects and deletes as one unit. False by default,
153    /// but for a `DecoratorBlockNode`.
154    fn is_decorator(&self) -> bool {
155        is_decorator_block(self)
156    }
157
158    /// `DecoratorNode.decorate(editor, config)`: the value an app's renderer
159    /// shows for the decorator, or `None` (the default). Once the editor has
160    /// a root element, the reconciler calls it for each decorator it
161    /// creates or reconciles and collects the values in
162    /// [`Editor::get_decorators`](crate::Editor::get_decorators), which the
163    /// decorator listeners hear of when they change. A value is the app's
164    /// own, type-erased (JS's `T`, Swift's `Any`), and compared by identity:
165    /// returning the same `Rc` again changes nothing.
166    fn decorate(&self, editor: &crate::Editor) -> Option<Rc<dyn Any>> {
167        let _ = editor;
168        None
169    }
170
171    /// `DecoratorNode.isIsolated()`: whether the decorator is isolated from
172    /// caret interaction (not traversed, extended over, selected as a node
173    /// or deleted by an adjacent caret operation). False by default.
174    fn is_isolated(&self) -> bool {
175        false
176    }
177
178    /// `DecoratorNode.isKeyboardSelectable()`: whether moving the caret onto
179    /// the decorator selects it as a node. True by default.
180    fn is_keyboard_selectable(&self) -> bool {
181        true
182    }
183
184    /// `$isInlineFormattable(node)`: whether the node carries a text format
185    /// that formatting the selection changes (`InlineFormattableNode`): text,
186    /// and a node with the `__isInlineFormattable` brand.
187    fn is_inline_formattable(&self) -> bool {
188        self.text().is_some()
189    }
190
191    /// `InlineFormattableNode.getFormat()`.
192    fn get_inline_format(&self) -> f64 {
193        self.text().map_or(0.0, |t| t.format)
194    }
195
196    /// `InlineFormattableNode.setFormat(format)` on `this`: a text node's
197    /// [`set_format`](Self::set_format).
198    fn set_inline_format(&self, this: &NodeRef, format: f64) -> Result<(), LexicalError> {
199        self.set_format(this, format);
200        Ok(())
201    }
202
203    /// `ElementNode.isShadowRoot()`.
204    fn is_shadow_root(&self) -> bool {
205        false
206    }
207
208    /// `ElementNode.canBeEmpty()`: whether the element stays when its last
209    /// child is removed.
210    fn can_be_empty(&self) -> bool {
211        true
212    }
213
214    /// `ElementNode.canIndent()`: whether indenting the selection changes
215    /// this block's indent (`DecoratorBlockNode.canIndent()` is false).
216    fn can_indent(&self) -> bool {
217        !is_decorator_block(self)
218    }
219
220    /// `ElementNode.canMergeWhenEmpty()`: whether the element, when empty,
221    /// takes the children of the first block `insertNodes` inserts.
222    fn can_merge_when_empty(&self) -> bool {
223        false
224    }
225
226    /// `isParentRequired()`: whether the node needs a parent of a certain
227    /// kind ([`create_parent_element_node`](Self::create_parent_element_node)).
228    fn is_parent_required(&self) -> bool {
229        false
230    }
231
232    /// `createParentElementNode()`: a new parent for the node, a paragraph
233    /// by default.
234    fn create_parent_element_node(&self) -> NodeRef {
235        crate::nodes::paragraph::create_paragraph_node()
236    }
237
238    /// `ElementNode.insertNewAfter(selection, restoreSelection)` on the
239    /// element `this` (this node's handle): inserts the block that splitting
240    /// the element creates after it, and returns it. `None` (the default)
241    /// means the element can't be split.
242    fn insert_new_after(
243        &self,
244        this: &NodeRef,
245        selection: &SelectionRef,
246        restore_selection: bool,
247    ) -> Result<Option<NodeRef>, LexicalError> {
248        let _ = (this, selection, restore_selection);
249        Ok(None)
250    }
251
252    /// `ElementNode.collapseAtStart(selection)` on the element `this`: what
253    /// a backward deletion at the element's start does instead of merging
254    /// it. `true` means the element handled it. `ElementNode` returns false.
255    fn collapse_at_start(
256        &self,
257        this: &NodeRef,
258        selection: &SelectionRef,
259    ) -> Result<bool, LexicalError> {
260        let _ = (this, selection);
261        Ok(false)
262    }
263
264    /// `ElementNode.append(...nodesToAppend)` on the element `this`: inserts
265    /// `nodes` after its last child, through [`splice`](Self::splice).
266    fn append(&self, this: &NodeRef, nodes: &[NodeRef]) -> Result<(), LexicalError> {
267        this.splice(this.get_children_size(), 0, nodes)
268    }
269
270    /// `ElementNode.splice(start, deleteCount, nodesToInsert)` on the
271    /// element `this`; the default is `ElementNode`'s
272    /// ([`element::splice`]).
273    fn splice(
274        &self,
275        this: &NodeRef,
276        start: usize,
277        delete_count: usize,
278        nodes_to_insert: &[NodeRef],
279    ) -> Result<(), LexicalError> {
280        element::splice(this, start, delete_count, nodes_to_insert)
281    }
282
283    /// `replace(replaceWith, includeChildren)` on `this`; the default is
284    /// `LexicalNode`'s (`node::replace`).
285    fn replace(
286        &self,
287        this: &NodeRef,
288        replace_with: &NodeRef,
289        include_children: bool,
290    ) -> Result<NodeRef, LexicalError> {
291        replace(this, replace_with, include_children)
292    }
293
294    /// `insertAfter(nodeToInsert, restoreSelection)` on `this`; the default
295    /// is `LexicalNode`'s (`node::insert_after`).
296    fn insert_after(
297        &self,
298        this: &NodeRef,
299        node_to_insert: &NodeRef,
300        restore_selection: bool,
301    ) -> Result<NodeRef, LexicalError> {
302        insert_after(this, node_to_insert, restore_selection)
303    }
304
305    /// `remove(preserveEmptyParent)` on `this`; the default is
306    /// `LexicalNode`'s (`node::remove`).
307    fn remove(&self, this: &NodeRef, preserve_empty_parent: bool) -> Result<(), LexicalError> {
308        remove(this, preserve_empty_parent)
309    }
310
311    /// `ElementNode.getIndent()` on the element `this`: its `__indent`.
312    fn get_indent(&self, this: &NodeRef) -> Result<f64, LexicalError> {
313        let _ = this;
314        Ok(self.element().map_or(0.0, |e| e.indent))
315    }
316
317    /// `ElementNode.setIndent(indentLevel)` on the element `this`: sets its
318    /// `__indent`.
319    fn set_indent(&self, this: &NodeRef, indent: f64) -> Result<(), LexicalError> {
320        with_writable(this.get_key(), |n| {
321            n.element_mut().expect("an element").indent = indent
322        });
323        Ok(())
324    }
325
326    /// The `$transform` of the node's `$config`, which the editor runs on a
327    /// dirty node before the transforms registered for its type (and before
328    /// `ElementNode`'s own, which comes later in the class chain). None by
329    /// default.
330    fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
331        let _ = this;
332        Ok(())
333    }
334
335    /// The `stateConfigs` of the node's `$config`, its class's and those it
336    /// inherits: the NodeState its type knows before any node reads it.
337    /// None by default.
338    fn state_configs(&self) -> Vec<RequiredNodeStateConfig> {
339        Vec::new()
340    }
341
342    /// `resetOnCopyNodeFrom(originalNode)` on `this`, the copy `$copyNode`
343    /// just made of `original`, beyond `LexicalNode`'s, which resets the
344    /// NodeState that asks for it (`$copyNode` does that first). Nothing by
345    /// default.
346    fn reset_on_copy_node_from(&self, this: &NodeRef, original: &NodeRef) {
347        let _ = (this, original);
348    }
349
350    /// `ElementNode.extractWithChild(child, selection, destination)` on the
351    /// element `this`: whether copying `child` (to `"clone"` or `"html"`)
352    /// takes this element with it. `ElementNode` returns false. Nothing in
353    /// the core calls it; `@lexical/html`'s copy does, and the overrides of
354    /// `ParagraphNode` and `HeadingNode` come with it.
355    fn extract_with_child(
356        &self,
357        this: &NodeRef,
358        child: &NodeRef,
359        selection: Option<&SelectionRef>,
360        destination: &str,
361    ) -> Result<bool, LexicalError> {
362        let _ = (this, child, selection, destination);
363        Ok(false)
364    }
365
366    /// The `slots` of the node's `$config()` (`getDeclaredSlots`): the
367    /// canonical order of its named slots, before the names it doesn't
368    /// declare. None by default.
369    fn declared_slots(&self) -> &'static [&'static str] {
370        &[]
371    }
372
373    /// Whether the `children` the class declares in its `$config()`
374    /// (`getDeclaredNodeStructure(klass).children`) is `'inline'` or a list
375    /// that includes `'inline'`: a block that holds text. By default, what
376    /// [`static_node_config_chain`](Self::static_node_config_chain)
377    /// declares.
378    fn declares_inline_children(&self) -> bool {
379        use crate::structure::{NodeChildEntry, NodeChildrenConfig};
380        match crate::structure::get_declared_node_structure(self.as_node()).children {
381            Some(NodeChildrenConfig::Inline) => true,
382            Some(NodeChildrenConfig::List(entries)) => entries.contains(&NodeChildEntry::Inline),
383            _ => false,
384        }
385    }
386
387    /// The node-structure keys of the class's `$config()` and of the classes
388    /// it extends (`iterStaticNodeConfigChain(klass)`), most derived first:
389    /// `inline`, `children`, `mergeAdjacent` and the values it declares
390    /// `derived` (`@experimental node-structure`). A class that extends
391    /// another returns its own link followed by that class's chain. None by
392    /// default: the class declares nothing.
393    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
394        Vec::new()
395    }
396
397    /// `INTERNAL_$afterStructureMerge(last, first)` on the element `this`
398    /// (internal, for the node structure normalization): `this` has just
399    /// merged its next sibling, and `last` (its last child before) and
400    /// `first` (the sibling's first child) meet at the seam. Returns whether
401    /// the class has the hook (`ListNode` joins nested lists there). False by
402    /// default.
403    fn internal_after_structure_merge(
404        &self,
405        this: &NodeRef,
406        last: &NodeRef,
407        first: &NodeRef,
408    ) -> Result<bool, LexicalError> {
409        let _ = (this, last, first);
410        Ok(false)
411    }
412
413    /// `INTERNAL_$afterStructureSplit(original, preceding)` on `this`, a
414    /// copy of `original` that the node structure normalization split off
415    /// it, after the content `preceding` (an ordered list continues its
416    /// numbering). Nothing by default.
417    fn internal_after_structure_split(
418        &self,
419        this: &NodeRef,
420        original: &NodeRef,
421        preceding: &[NodeRef],
422    ) -> Result<(), LexicalError> {
423        let _ = (this, original, preceding);
424        Ok(())
425    }
426
427    /// `INTERNAL_$liftsFromStructure`: the holder's hook for a child its
428    /// declared `children` allow that the node structure normalization must
429    /// still lift out, given what else it holds (a list item lifts a nested
430    /// list that is not all it holds). None by default.
431    fn internal_lifts_from_structure(&self) -> Option<crate::structure::LiftsFromStructure> {
432        None
433    }
434
435    /// `TextNode.isTextEntity()`: whether `registerLexicalTextEntity` (the
436    /// `text` feature) treats the text node as an entity. False by default.
437    fn is_text_entity(&self) -> bool {
438        false
439    }
440
441    /// `TextNode.canHaveFormat()`: whether the text node can carry formats
442    /// and styles that `@lexical/selection` applies to it. True by default.
443    fn can_have_format(&self) -> bool {
444        true
445    }
446
447    /// `ElementNode.excludeFromCopy(destination)`: whether copying (to
448    /// `"clone"` or `"html"`) leaves this element out and keeps its
449    /// children. `ElementNode` returns false. Nothing in the core calls it;
450    /// `@lexical/clipboard`'s and `@lexical/html`'s copies do.
451    fn exclude_from_copy(&self, destination: &str) -> bool {
452        let _ = destination;
453        false
454    }
455
456    /// `ElementNode.canReplaceWith(replacement)` (deprecated and internal
457    /// upstream): true by default. Nothing in the core calls it.
458    fn can_replace_with(&self, replacement: &NodeRef) -> bool {
459        let _ = replacement;
460        true
461    }
462
463    /// `ElementNode.canInsertAfter(node)` (deprecated and internal
464    /// upstream): true by default. Nothing in the core calls it.
465    fn can_insert_after(&self, node: &NodeRef) -> bool {
466        let _ = node;
467        true
468    }
469
470    /// `TextNode.selectionTransform(prevSelection, nextSelection)`: called
471    /// on the text nodes a range selection's anchor and focus are in at the
472    /// end of each update (`applySelectionTransforms`), before the
473    /// transforms run, with the committed state's selection and the
474    /// update's. Does nothing by default.
475    fn selection_transform(
476        &self,
477        this: &NodeRef,
478        prev_selection: Option<&SelectionRef>,
479        next_selection: &SelectionRef,
480    ) -> Result<(), LexicalError> {
481        let _ = (this, prev_selection, next_selection);
482        Ok(())
483    }
484
485    /// `TextNode.setFormat(format)` on the text node `this`: sets its
486    /// `__format`, after `getWritable()`.
487    fn set_format(&self, this: &NodeRef, format: f64) {
488        with_writable(this.get_key(), |n| {
489            n.text_mut().expect("a text node").format = format
490        });
491    }
492
493    /// `canInsertTextBefore()` (`TextNode` and `ElementNode`): whether text
494    /// typed at the node's start goes into it.
495    fn can_insert_text_before(&self) -> bool {
496        true
497    }
498
499    /// `canInsertTextAfter()` (`TextNode` and `ElementNode`): whether text
500    /// typed at the node's end goes into it.
501    fn can_insert_text_after(&self) -> bool {
502        true
503    }
504
505    /// `getTextContent()`.
506    fn get_text_content(&self) -> String {
507        if let Some(text) = self.text() {
508            return text.text.clone();
509        }
510        if self.element().is_some() {
511            return element::get_text_content(self.as_node());
512        }
513        // `LexicalNode.getTextContent()`: a decorator host's slots.
514        crate::slot::get_slots_text_content(self.as_node())
515    }
516
517    /// `getTextContentSize()`: the text content's length in UTF-16 code
518    /// units, which an element sums from its children
519    /// (`ElementNode.getTextContentSize`). JS gives a class that overrides
520    /// `getTextContent` but not this method `LexicalNode`'s, the length of
521    /// its text content; Rust can't tell an override, so a class that
522    /// overrides [`get_text_content`](Self::get_text_content) overrides this
523    /// too, as Swift's do.
524    fn get_text_content_size(&self) -> usize {
525        if self.element().is_some() {
526            return element::get_text_content_size(self.as_node());
527        }
528        utf16::len(&self.get_text_content())
529    }
530
531    /// `ElementNode.shouldSerializeTextStyles()`.
532    fn should_serialize_text_styles(&self) -> bool {
533        element::should_serialize_text_styles(self.as_node())
534    }
535
536    /// `createDOM(config, editor)` (the `html` feature): the element the
537    /// node renders as. `LexicalNode` throws, and `TextNode` renders its
538    /// text; every other node that renders overrides it.
539    #[cfg(feature = "html")]
540    fn create_dom(
541        &self,
542        this: &NodeRef,
543        config: &crate::EditorConfig,
544        editor: &crate::Editor,
545    ) -> Result<crate::dom::DomNode, LexicalError> {
546        let _ = (this, editor);
547        if self.text().is_some() {
548            return crate::nodes::text::create_dom(self.as_node(), config);
549        }
550        Err(LexicalError::new("createDOM: base method not extended"))
551    }
552
553    /// `exportDOM(editor)` (the `html` feature): the DOM the node exports
554    /// to HTML. `LexicalNode` exports the element `$createDOM` makes, which
555    /// `ElementNode` gives the indent and direction and `TextNode` its
556    /// formats.
557    #[cfg(feature = "html")]
558    fn export_dom(
559        &self,
560        this: &NodeRef,
561        editor: &crate::Editor,
562    ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
563        if self.element().is_some() {
564            element::export_dom(self.as_node(), this, editor)
565        } else if self.text().is_some() {
566            crate::nodes::text::export_dom(self.as_node(), this, editor)
567        } else {
568            crate::lexical_dom::export_dom_base(self.as_node(), this, editor)
569        }
570    }
571
572    /// The node types of the classes this node's class extends, nearest
573    /// first, without the base classes that have no type of their own
574    /// (`ElementNode`, `DecoratorNode`): JS's class chain, which matches
575    /// `DOMRenderExtension`'s overrides of a class to the nodes of the
576    /// classes that extend it (the `html` feature). `["text"]` for a node
577    /// with `TextNode` fields that isn't a `TextNode` itself, and none for
578    /// any other; a class that extends another typed class overrides it.
579    /// It also stands for `instanceof` in `$applyNodeReplacement` and
580    /// `createEditor`'s check of a replacement's `withKlass`.
581    fn super_types(&self) -> Vec<&'static str> {
582        if self.text().is_some() && self.get_type() != "text" {
583            vec!["text"]
584        } else {
585            Vec::new()
586        }
587    }
588
589    /// The class's static `importDOM()` (the `html` feature): the
590    /// conversions it offers by DOM node name, or `None`.
591    #[cfg(feature = "html")]
592    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
593        None
594    }
595
596    /// The `json` of the node's `$config()` and of the classes it extends
597    /// (`iterStaticNodeConfigChain`), most derived first: the serialization
598    /// schemas `composeSchema` composes, a subclass's declaration of a key
599    /// winning. By default ElementNode's for an element
600    /// ([`element::element_node_schema`]), TextNode's for a text node and
601    /// DecoratorBlockNode's for one; a class that declares its own returns
602    /// it followed by those of the class it extends. The composed schema is
603    /// compiled once per Rust type, so it must not differ between nodes.
604    fn json_schema_chain(&self) -> Vec<crate::schema::NodeSchema> {
605        if self.element().is_some() {
606            return vec![element::element_node_schema()];
607        }
608        if self.text().is_some() {
609            return vec![crate::nodes::text::text_node_schema()];
610        }
611        #[cfg(feature = "decorator-block")]
612        if self.decorator_block().is_some() {
613            return vec![crate::decorator_block::decorator_block_node_schema()];
614        }
615        Vec::new()
616    }
617
618    /// The class's generated `exportJSON` (`$config`'s `generated`,
619    /// `LexicalGeneratedJSON.ts` and the packages' counterparts, ported by
620    /// hand): the same JSON as the walk of its schema, written faster.
621    /// `None` (the default) for a class without one, which the walk
622    /// serves.
623    fn generated_export_json(&self, compact: bool) -> Option<Object> {
624        let _ = compact;
625        None
626    }
627
628    /// The class's generated `updateFromJSON` on a writable node, which
629    /// applies what the walk of its schema would; false (the default) for a
630    /// class without one.
631    fn generated_update_from_json(&mut self, json: &Object) -> bool {
632        let _ = json;
633        false
634    }
635
636    /// `exportJSON(compact)`: the node's own properties, with an empty
637    /// `children` array for an element (the export walk fills it), without
638    /// its NodeState. By default `$exportNodeJSONOnce`: the class's
639    /// [generated code](Self::generated_export_json), or the walk of its
640    /// schema ([`crate::schema::walk_export_json`]). A class that adds to
641    /// its JSON overrides it, calling [`crate::schema::export_node_json_once`]
642    /// for what JS's `super.exportJSON` returns.
643    fn export_json(&self, compact: bool) -> Object {
644        crate::schema::export_node_json_once(self.as_node(), compact)
645    }
646
647    /// `updateFromJSON(json)` on a writable node: applies every property the
648    /// node's schema declares, a missing one as its default
649    /// (`$applyJSONSetters`, the class's
650    /// [generated code](Self::generated_update_from_json) or the walk); the
651    /// caller applies the NodeState first.
652    fn update_from_json(&mut self, json: &Object) {
653        crate::schema::apply_json_setters(self.as_node_mut(), json);
654    }
655
656    /// The model half of `updateDOM(prevNode, dom, config)`: whether the
657    /// reconciler makes the node's DOM again (what JS's returns), which
658    /// reports the node's children as created. By default a text node
659    /// compares its tags (`TextNode.updateDOM`) and any other node keeps
660    /// its DOM.
661    fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
662        match (self.text(), prev_node.text()) {
663            (Some(next), Some(prev)) => crate::nodes::text::update_dom(prev, next),
664            _ => false,
665        }
666    }
667}
668
669/// Whether `node` extends `DecoratorBlockNode`.
670#[allow(unused_variables)]
671fn is_decorator_block<N: LexicalNode + ?Sized>(node: &N) -> bool {
672    #[cfg(feature = "decorator-block")]
673    return node.decorator_block().is_some();
674    #[cfg(not(feature = "decorator-block"))]
675    false
676}
677
678/// The parts of [`LexicalNode`] every implementation writes the same way,
679/// implemented for any `Clone` node.
680pub trait NodeClone {
681    fn clone_node(&self) -> Box<dyn LexicalNode>;
682    fn as_any(&self) -> &dyn Any;
683    fn as_any_mut(&mut self) -> &mut dyn Any;
684    fn as_node(&self) -> &dyn LexicalNode;
685    fn as_node_mut(&mut self) -> &mut dyn LexicalNode;
686    /// `node.constructor.name`, which messages name a node's class by: the
687    /// Rust type's name, without its path.
688    fn class_name(&self) -> &'static str;
689}
690
691impl<T: LexicalNode + Clone> NodeClone for T {
692    fn clone_node(&self) -> Box<dyn LexicalNode> {
693        Box::new(self.clone())
694    }
695    fn as_any(&self) -> &dyn Any {
696        self
697    }
698    fn as_any_mut(&mut self) -> &mut dyn Any {
699        self
700    }
701    fn as_node(&self) -> &dyn LexicalNode {
702        self
703    }
704    fn as_node_mut(&mut self) -> &mut dyn LexicalNode {
705        self
706    }
707    fn class_name(&self) -> &'static str {
708        let name = std::any::type_name::<T>();
709        let name = name.split('<').next().unwrap_or(name);
710        name.rsplit("::").next().unwrap_or(name)
711    }
712}
713
714impl dyn LexicalNode {
715    pub fn get_key(&self) -> &str {
716        &self.base().key
717    }
718
719    /// Whether the node is a `T` (JS `instanceof`).
720    pub fn is<T: LexicalNode>(&self) -> bool {
721        self.as_any().is::<T>()
722    }
723
724    pub fn downcast_ref<T: LexicalNode>(&self) -> Option<&T> {
725        self.as_any().downcast_ref()
726    }
727
728    pub fn downcast_mut<T: LexicalNode>(&mut self) -> Option<&mut T> {
729        self.as_any_mut().downcast_mut()
730    }
731}
732
733/// A node by its key, resolved in the active editor state on every call, so
734/// it always reads the latest version, as JS node methods do through
735/// `getLatest()`. Like a JS node reference, it can only be used inside
736/// [`Editor::read`](crate::Editor::read) or
737/// [`EditorState::read`](crate::EditorState::read), and panics elsewhere.
738#[derive(Clone, Debug, PartialEq, Eq, Hash)]
739pub struct NodeRef {
740    key: NodeKey,
741}
742
743/// The sibling after `key` (before it, unless `forward`) in `node_map`,
744/// read without making a handle, as an import splits nodes in long
745/// paragraphs many times and each split walks the siblings.
746fn sibling<'a>(node_map: &'a NodeMap, key: &str, forward: bool) -> Option<&'a str> {
747    let node = node_map.get(key).unwrap_or_else(|| {
748        panic!(
749            "Lexical node does not exist in active editor state. Avoid using the same node references between nested closures from editorState.read/editor.update."
750        )
751    });
752    let base = node.base();
753    if forward { &base.next } else { &base.prev }.as_deref()
754}
755
756/// The key `steps` siblings after `key` (before it, unless `forward`) in
757/// the active editor state.
758pub(crate) fn sibling_key_at(key: &str, steps: usize, forward: bool) -> Option<NodeKey> {
759    let editor_state = get_active_editor_state();
760    let node_map = editor_state.0.node_map.borrow();
761    let mut key = key;
762    for _ in 0..steps {
763        key = sibling(&node_map, key, forward)?;
764    }
765    Some(key.to_owned())
766}
767
768impl NodeRef {
769    pub(crate) fn new(key: impl Into<NodeKey>) -> Self {
770        Self { key: key.into() }
771    }
772
773    pub fn get_key(&self) -> &str {
774        &self.key
775    }
776
777    /// `getLatest()`: the node's version in the active editor state.
778    pub fn get_latest(&self) -> Rc<dyn LexicalNode> {
779        get_node_by_key_impl(&get_active_editor_state(), &self.key).unwrap_or_else(|| {
780            panic!(
781                "Lexical node does not exist in active editor state. Avoid using the same node references between nested closures from editorState.read/editor.update."
782            )
783        })
784    }
785
786    pub fn get_type(&self) -> &'static str {
787        self.get_latest().get_type()
788    }
789
790    /// `$isElementNode(node)`.
791    pub fn is_element(&self) -> bool {
792        self.get_latest().element().is_some()
793    }
794
795    /// `$isTextNode(node)`.
796    pub fn is_text(&self) -> bool {
797        self.get_latest().text().is_some()
798    }
799
800    /// `$isDecoratorNode(node)`.
801    pub fn is_decorator(&self) -> bool {
802        self.get_latest().is_decorator()
803    }
804
805    /// `DecoratorNode.isIsolated()`.
806    pub fn is_isolated(&self) -> bool {
807        self.get_latest().is_isolated()
808    }
809
810    /// `DecoratorNode.isKeyboardSelectable()`.
811    pub fn is_keyboard_selectable(&self) -> bool {
812        self.get_latest().is_keyboard_selectable()
813    }
814
815    /// `$isRootNode(node)`.
816    pub fn is_root(&self) -> bool {
817        self.get_latest().is::<RootNode>()
818    }
819
820    pub fn is_inline(&self) -> bool {
821        self.get_latest().is_inline()
822    }
823
824    pub fn get_parent(&self) -> Option<NodeRef> {
825        self.get_latest().base().parent.clone().map(NodeRef::new)
826    }
827
828    /// `getParents()`: the ancestors, nearest first.
829    pub fn get_parents(&self) -> Vec<NodeRef> {
830        let mut parents = Vec::new();
831        let mut node = self.get_parent();
832        while let Some(n) = node {
833            node = n.get_parent();
834            parents.push(n);
835        }
836        parents
837    }
838
839    pub fn get_previous_sibling(&self) -> Option<NodeRef> {
840        self.get_latest().base().prev.clone().map(NodeRef::new)
841    }
842
843    pub fn get_next_sibling(&self) -> Option<NodeRef> {
844        self.get_latest().base().next.clone().map(NodeRef::new)
845    }
846
847    pub fn get_first_child(&self) -> Option<NodeRef> {
848        let node = self.get_latest();
849        node.element()?.first.clone().map(NodeRef::new)
850    }
851
852    pub fn get_last_child(&self) -> Option<NodeRef> {
853        let node = self.get_latest();
854        node.element()?.last.clone().map(NodeRef::new)
855    }
856
857    pub fn get_children_size(&self) -> usize {
858        self.get_latest().element().map_or(0, |e| e.size)
859    }
860
861    /// `getChildren()`; empty for a node that isn't an element.
862    pub fn get_children(&self) -> Vec<NodeRef> {
863        let mut children = Vec::with_capacity(self.get_children_size());
864        let mut child = self.get_first_child();
865        while let Some(c) = child {
866            child = c.get_next_sibling();
867            children.push(c);
868        }
869        children
870    }
871
872    pub fn get_text_content(&self) -> String {
873        self.get_latest().get_text_content()
874    }
875
876    /// `exportJSON(compact)`, with the node's NodeState.
877    pub fn export_json(&self, compact: bool) -> Object {
878        crate::node_state::export_json_with_state(&*self.get_latest(), compact)
879    }
880
881    /// `updateFromJSON(json)`: the NodeState in the JSON
882    /// (`$updateStateFromJSON`), then `$applyJSONSetters` (the flat states,
883    /// then the class's properties).
884    pub fn update_from_json(&self, json: &Object) -> Result<(), LexicalError> {
885        crate::node_state::update_state_from_json(self, json)?;
886        crate::node_state::apply_flat_states(self, json)?;
887        with_writable(&self.key, |node| node.update_from_json(json));
888        Ok(())
889    }
890
891    /// `getParentOrThrow()`.
892    pub fn get_parent_or_throw(&self) -> Result<NodeRef, LexicalError> {
893        self.get_parent().ok_or_else(|| {
894            LexicalError::new(format!("Expected node {} to have a parent.", self.key))
895        })
896    }
897
898    /// `isAttached()`: whether the node's parents (and slot hosts) lead to
899    /// the root.
900    pub fn is_attached(&self) -> bool {
901        let editor_state = get_active_editor_state();
902        let node_map = editor_state.0.node_map.borrow();
903        let mut key = self.key.as_str();
904        loop {
905            if key == "root" {
906                return true;
907            }
908            // A slotted node has no parent; its slot host leads on.
909            match node_map.get(key).and_then(|n| {
910                n.base()
911                    .parent
912                    .as_deref()
913                    .or_else(|| crate::slot::slot_host_key_field(&**n).map(String::as_str))
914            }) {
915                Some(parent) => key = parent,
916                None => return false,
917            }
918        }
919    }
920
921    /// `getIndexWithinParent()`; `None` where JS returns -1.
922    pub fn get_index_within_parent(&self) -> Option<usize> {
923        let parent = self.get_parent()?;
924        let size = parent.get_children_size();
925        let editor_state = get_active_editor_state();
926        let node_map = editor_state.0.node_map.borrow();
927        // Out from the node both ways, to whichever end is nearer: the
928        // same index as counting from the first child.
929        let (mut before, mut after) = (self.key.as_str(), self.key.as_str());
930        let mut steps = 0;
931        loop {
932            match sibling(&node_map, before, false) {
933                Some(key) => before = key,
934                None => return Some(steps),
935            }
936            match sibling(&node_map, after, true) {
937                Some(key) => after = key,
938                None => return size.checked_sub(steps + 1),
939            }
940            steps += 1;
941        }
942    }
943
944    /// `getTextContentSize()`: the text content's length in UTF-16 code
945    /// units.
946    pub fn get_text_content_size(&self) -> usize {
947        self.get_latest().get_text_content_size()
948    }
949
950    /// `ElementNode.canBeEmpty()`.
951    pub fn can_be_empty(&self) -> bool {
952        self.get_latest().can_be_empty()
953    }
954
955    /// `ElementNode.canIndent()`.
956    pub fn can_indent(&self) -> bool {
957        self.get_latest().can_indent()
958    }
959
960    /// `ElementNode.canMergeWhenEmpty()`.
961    pub fn can_merge_when_empty(&self) -> bool {
962        self.get_latest().can_merge_when_empty()
963    }
964
965    /// `isParentRequired()`.
966    pub fn is_parent_required(&self) -> bool {
967        self.get_latest().is_parent_required()
968    }
969
970    /// `createParentElementNode()`.
971    pub fn create_parent_element_node(&self) -> NodeRef {
972        self.get_latest().create_parent_element_node()
973    }
974
975    /// `ElementNode.insertNewAfter(selection, restoreSelection)`.
976    pub fn insert_new_after(
977        &self,
978        selection: &SelectionRef,
979        restore_selection: bool,
980    ) -> Result<Option<NodeRef>, LexicalError> {
981        self.get_latest()
982            .insert_new_after(self, selection, restore_selection)
983    }
984
985    /// `ElementNode.collapseAtStart(selection)`.
986    pub fn collapse_at_start(&self, selection: &SelectionRef) -> Result<bool, LexicalError> {
987        self.get_latest().collapse_at_start(self, selection)
988    }
989
990    /// `ElementNode.extractWithChild(child, selection, destination)`.
991    pub fn extract_with_child(
992        &self,
993        child: &NodeRef,
994        selection: Option<&SelectionRef>,
995        destination: &str,
996    ) -> Result<bool, LexicalError> {
997        self.get_latest()
998            .extract_with_child(self, child, selection, destination)
999    }
1000
1001    /// `TextNode.isTextEntity()`.
1002    pub fn is_text_entity(&self) -> bool {
1003        self.get_latest().is_text_entity()
1004    }
1005
1006    /// `TextNode.canHaveFormat()`.
1007    pub fn can_have_format(&self) -> bool {
1008        self.get_latest().can_have_format()
1009    }
1010
1011    /// `ElementNode.excludeFromCopy(destination)`.
1012    pub fn exclude_from_copy(&self, destination: &str) -> bool {
1013        self.get_latest().exclude_from_copy(destination)
1014    }
1015
1016    /// `ElementNode.canReplaceWith(replacement)` (deprecated upstream).
1017    pub fn can_replace_with(&self, replacement: &NodeRef) -> bool {
1018        self.get_latest().can_replace_with(replacement)
1019    }
1020
1021    /// `ElementNode.canInsertAfter(node)` (deprecated upstream).
1022    pub fn can_insert_after(&self, node: &NodeRef) -> bool {
1023        self.get_latest().can_insert_after(node)
1024    }
1025
1026    /// `getTopLevelElement()`: the highest ancestor of this node (or the
1027    /// node) below the root or a shadow root, or a slot value (the top of
1028    /// its isolated scope), or `None` when there is none (the root, or a
1029    /// node that isn't attached). Fails where JS's invariant does: on a
1030    /// non-element ancestor of the node, or a text node at the top.
1031    pub fn get_top_level_element(&self) -> Result<Option<NodeRef>, LexicalError> {
1032        let mut node = Some(self.clone());
1033        while let Some(n) = node {
1034            let parent = n.get_parent();
1035            if parent
1036                .as_ref()
1037                .is_some_and(|p| crate::nodes::element::is_root_or_shadow_root(&*p.get_latest()))
1038                || crate::slot::get_slot_host_key(&n).is_some()
1039            {
1040                if !(n.is_element() || (n == *self && n.is_decorator())) {
1041                    return Err(LexicalError::new(
1042                        "Children of root nodes must be elements or decorators",
1043                    ));
1044                }
1045                return Ok(Some(n));
1046            }
1047            node = parent;
1048        }
1049        Ok(None)
1050    }
1051
1052    /// `getTopLevelElementOrThrow()`: [`get_top_level_element`](Self::get_top_level_element),
1053    /// failing where it is `None` (with `RootNode`'s own message for the
1054    /// root).
1055    pub fn get_top_level_element_or_throw(&self) -> Result<NodeRef, LexicalError> {
1056        if self.is_root() {
1057            return Err(LexicalError::new(
1058                "getTopLevelElementOrThrow: root nodes are not top level elements",
1059            ));
1060        }
1061        self.get_top_level_element()?.ok_or_else(|| {
1062            LexicalError::new(format!(
1063                "Expected node {} to have a top parent element.",
1064                self.key
1065            ))
1066        })
1067    }
1068
1069    /// `getParentKeys()`: the keys of the ancestors, nearest first.
1070    pub fn get_parent_keys(&self) -> Vec<NodeKey> {
1071        self.get_parents()
1072            .into_iter()
1073            .map(|p| p.get_key().to_owned())
1074            .collect()
1075    }
1076
1077    /// `ElementNode.getChildrenKeys()`.
1078    pub fn get_children_keys(&self) -> Vec<NodeKey> {
1079        self.get_children()
1080            .into_iter()
1081            .map(|c| c.get_key().to_owned())
1082            .collect()
1083    }
1084
1085    /// `ElementNode.isLastChild()`: whether this is its parent's last child.
1086    /// Fails without a parent.
1087    pub fn is_last_child(&self) -> Result<bool, LexicalError> {
1088        Ok(self.get_parent_or_throw()?.get_last_child().as_ref() == Some(self))
1089    }
1090
1091    /// `ElementNode.getFirstChildOrThrow()`.
1092    pub fn get_first_child_or_throw(&self) -> Result<NodeRef, LexicalError> {
1093        self.get_first_child().ok_or_else(|| {
1094            LexicalError::new(format!("Expected node {} to have a first child.", self.key))
1095        })
1096    }
1097
1098    /// `ElementNode.getLastChildOrThrow()`.
1099    pub fn get_last_child_or_throw(&self) -> Result<NodeRef, LexicalError> {
1100        self.get_last_child().ok_or_else(|| {
1101            LexicalError::new(format!("Expected node {} to have a last child.", self.key))
1102        })
1103    }
1104
1105    /// `ElementNode.hasTextFormat(type)`: whether the element's text format
1106    /// (`__textFormat`) has the format.
1107    pub fn has_text_format(&self, format_type: &str) -> bool {
1108        use crate::constants::{TEXT_TYPE_TO_FORMAT, lookup};
1109        let flag = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
1110        let format = self.get_latest().element().map_or(0.0, |e| e.text_format);
1111        crate::nodes::text::to_int32(format) & flag != 0
1112    }
1113
1114    /// `getFormatFlags(type, alignWithFormat)` of a text node (its
1115    /// `__format`) or an element (its `__textFormat`): the format with
1116    /// `type` toggled (`toggleTextFormatType`).
1117    pub fn get_format_flags(&self, format_type: &str, align_with_format: Option<i32>) -> i32 {
1118        let latest = self.get_latest();
1119        let format = match (latest.text(), latest.element()) {
1120            (Some(text), _) => text.format,
1121            (None, Some(element)) => element.text_format,
1122            (None, None) => 0.0,
1123        };
1124        crate::nodes::text::toggle_text_format_type(
1125            crate::nodes::text::to_int32(format),
1126            format_type,
1127            align_with_format,
1128        )
1129    }
1130
1131    /// `TextNode.isDirectionless()`: whether the text's detail has
1132    /// `IS_DIRECTIONLESS`.
1133    pub fn is_directionless(&self) -> bool {
1134        let detail = self.get_latest().text().map_or(0.0, |t| t.detail);
1135        crate::nodes::text::to_int32(detail) & crate::constants::IS_DIRECTIONLESS != 0
1136    }
1137
1138    /// `isParentOf(targetNode)`: whether this node is an ancestor of
1139    /// `target`.
1140    pub fn is_parent_of(&self, target: &NodeRef) -> bool {
1141        if self == target {
1142            return false;
1143        }
1144        let mut node = target.get_parent();
1145        while let Some(n) = node {
1146            if &n == self {
1147                return true;
1148            }
1149            node = n.get_parent();
1150        }
1151        false
1152    }
1153
1154    /// `isSelected(selection)`: whether the node is among the nodes of
1155    /// `selection`, or of the current selection when `None`. An element or
1156    /// decorator isn't selected by a collapsed range between children, and
1157    /// an inline decorator that is its parent's last child isn't selected by
1158    /// an element range starting at the parent's end.
1159    pub fn is_selected(&self, selection: Option<&SelectionRef>) -> Result<bool, LexicalError> {
1160        let current;
1161        let target_selection = match selection {
1162            Some(selection) => selection,
1163            None => match get_selection() {
1164                Some(selection) => {
1165                    current = selection;
1166                    &current
1167                }
1168                None => return Ok(false),
1169            },
1170        };
1171        // `$isKeyInSelectionNodes(targetSelection, this.__key)`.
1172        let is_selected = target_selection
1173            .get_nodes()?
1174            .iter()
1175            .any(|node| node.get_key() == self.key);
1176        if !is_selected || self.is_text() {
1177            return Ok(is_selected);
1178        }
1179        // For inline images inside of element nodes.
1180        // Without this change the image will be selected if the cursor is
1181        // before or after it.
1182        if let Some(range) = target_selection.range()
1183            && range.anchor.point_type == PointType::Element
1184            && range.focus.point_type == PointType::Element
1185        {
1186            if range.is_collapsed() {
1187                return Ok(false);
1188            }
1189            let parent_node = self.get_parent();
1190            if let Some(parent_node) =
1191                parent_node.filter(|_| self.is_decorator() && self.is_inline())
1192            {
1193                let first_point = if target_selection.is_backward()? {
1194                    &range.focus
1195                } else {
1196                    &range.anchor
1197                };
1198                if first_point.key == parent_node.get_key()
1199                    && first_point.offset == parent_node.get_children_size()
1200                    && parent_node.get_last_child().as_ref() == Some(self)
1201                {
1202                    return Ok(false);
1203                }
1204            }
1205        }
1206        Ok(is_selected)
1207    }
1208
1209    /// `isBefore(targetNode)`: whether this node comes before `target` in
1210    /// the document.
1211    pub fn is_before(&self, target: &NodeRef) -> bool {
1212        match get_common_ancestor(self, target) {
1213            None => false,
1214            Some(CommonAncestorResult::Descendant { .. }) => true,
1215            Some(CommonAncestorResult::Branch { a, b, .. }) => {
1216                get_common_ancestor_result_branch_order(&a, &b) == Ordering::Less
1217            }
1218            Some(CommonAncestorResult::Same { .. } | CommonAncestorResult::Ancestor { .. }) => {
1219                false
1220            }
1221        }
1222    }
1223
1224    /// `getNodesBetween(targetNode)`: the nodes from this one to `target`,
1225    /// both included, in document order, with the ancestors the walk
1226    /// enters or leaves on the way.
1227    pub fn get_nodes_between(&self, target: &NodeRef) -> Vec<NodeRef> {
1228        let forward = self.is_before(target);
1229        let mut nodes = Vec::new();
1230        let mut node = Some(self.clone());
1231        let mut entering = true;
1232        let mut open_elements = 0usize;
1233        while let Some(current) = node {
1234            // Only ancestors above the starting point lack an enter event.
1235            // Count open elements to recognize their first visit without a
1236            // visited set.
1237            if entering || open_elements == 0 {
1238                nodes.push(current.clone());
1239            }
1240            if &current == target {
1241                break;
1242            }
1243            if !entering && open_elements > 0 {
1244                open_elements -= 1;
1245            }
1246            let child = if entering && current.is_element() {
1247                if forward {
1248                    current.get_first_child()
1249                } else {
1250                    current.get_last_child()
1251                }
1252            } else {
1253                None
1254            };
1255            if child.is_some() {
1256                open_elements += 1;
1257            }
1258            let adjacent = child.or_else(|| {
1259                if forward {
1260                    current.get_next_sibling()
1261                } else {
1262                    current.get_previous_sibling()
1263                }
1264            });
1265            entering = adjacent.is_some();
1266            node = adjacent.or_else(|| current.get_parent());
1267        }
1268        if !forward {
1269            nodes.reverse();
1270        }
1271        nodes
1272    }
1273
1274    /// `isSelected()` for a node selection. Range selections come with
1275    /// `getNodes`.
1276    fn is_selected_by_node_selection(&self, selection: &SelectionRef) -> bool {
1277        selection.with_node(|n| n.has(&self.key)).unwrap_or(false)
1278    }
1279
1280    /// `markDirty()`: marks the node dirty, so transforms run on it.
1281    pub fn mark_dirty(&self) {
1282        get_writable(&self.key);
1283    }
1284
1285    /// `remove(preserveEmptyParent)`.
1286    pub fn remove(&self, preserve_empty_parent: bool) -> Result<(), LexicalError> {
1287        self.get_latest().remove(self, preserve_empty_parent)
1288    }
1289
1290    /// `replace(replaceWith, includeChildren)`: puts `replace_with` where
1291    /// this node is, with this node's children when `include_children`.
1292    pub fn replace(
1293        &self,
1294        replace_with: &NodeRef,
1295        include_children: bool,
1296    ) -> Result<NodeRef, LexicalError> {
1297        self.get_latest()
1298            .replace(self, replace_with, include_children)
1299    }
1300
1301    /// `insertAfter(nodeToInsert, restoreSelection)`.
1302    pub fn insert_after(
1303        &self,
1304        node_to_insert: &NodeRef,
1305        restore_selection: bool,
1306    ) -> Result<NodeRef, LexicalError> {
1307        self.get_latest()
1308            .insert_after(self, node_to_insert, restore_selection)
1309    }
1310
1311    /// `ElementNode.getIndent()`.
1312    pub fn get_indent(&self) -> Result<f64, LexicalError> {
1313        self.get_latest().get_indent(self)
1314    }
1315
1316    /// `ElementNode.setIndent(indentLevel)`.
1317    pub fn set_indent(&self, indent: f64) -> Result<(), LexicalError> {
1318        self.get_latest().set_indent(self, indent)
1319    }
1320
1321    /// `getPreviousSiblings()`: the siblings before this node, in document
1322    /// order.
1323    pub fn get_previous_siblings(&self) -> Vec<NodeRef> {
1324        let mut siblings = Vec::new();
1325        let mut node = self.get_previous_sibling();
1326        while let Some(n) = node {
1327            node = n.get_previous_sibling();
1328            siblings.push(n);
1329        }
1330        siblings.reverse();
1331        siblings
1332    }
1333
1334    /// `getNextSiblings()`: the siblings after this node, in document order.
1335    pub fn get_next_siblings(&self) -> Vec<NodeRef> {
1336        let mut siblings = Vec::new();
1337        let mut node = self.get_next_sibling();
1338        while let Some(n) = node {
1339            node = n.get_next_sibling();
1340            siblings.push(n);
1341        }
1342        siblings
1343    }
1344
1345    /// `insertBefore(nodeToInsert, restoreSelection)`.
1346    pub fn insert_before(
1347        &self,
1348        node_to_insert: &NodeRef,
1349        restore_selection: bool,
1350    ) -> Result<NodeRef, LexicalError> {
1351        invariant!(
1352            !self.is_root(),
1353            "insertBefore: cannot be called on root nodes"
1354        );
1355        insert_sibling(self, false, node_to_insert, restore_selection)
1356    }
1357
1358    /// `select(anchorOffset, focusOffset)` of a text node or an element;
1359    /// `None` is JS's `undefined` (the end).
1360    pub fn select(
1361        &self,
1362        anchor_offset: Option<usize>,
1363        focus_offset: Option<usize>,
1364    ) -> Result<SelectionRef, LexicalError> {
1365        if self.is_text() {
1366            self.select_text(anchor_offset, focus_offset)
1367        } else if self.is_element() {
1368            self.select_element(anchor_offset, focus_offset)
1369        } else {
1370            Err(LexicalError::new(format!(
1371                "select: node {} is not a text node or an element",
1372                self.key
1373            )))
1374        }
1375    }
1376
1377    /// `selectStart()`.
1378    pub fn select_start(&self) -> Result<SelectionRef, LexicalError> {
1379        if self.is_text() {
1380            self.select(Some(0), Some(0))
1381        } else if self.is_element() {
1382            match self.get_first_descendant() {
1383                Some(first) => first.select_start(),
1384                None => self.select(None, None),
1385            }
1386        } else {
1387            self.select_previous(None, None)
1388        }
1389    }
1390
1391    /// `selectEnd()`.
1392    pub fn select_end(&self) -> Result<SelectionRef, LexicalError> {
1393        if self.is_text() {
1394            let size = self.get_text_content_size();
1395            self.select(Some(size), Some(size))
1396        } else if self.is_element() {
1397            match self.get_last_descendant() {
1398                Some(last) => last.select_end(),
1399                None => self.select(None, None),
1400            }
1401        } else {
1402            self.select_next(Some(0), Some(0))
1403        }
1404    }
1405
1406    /// `selectPrevious(anchorOffset, focusOffset)`.
1407    pub fn select_previous(
1408        &self,
1409        anchor_offset: Option<usize>,
1410        focus_offset: Option<usize>,
1411    ) -> Result<SelectionRef, LexicalError> {
1412        select_adjacent_node(self, false, anchor_offset, focus_offset)
1413    }
1414
1415    /// `selectNext(anchorOffset, focusOffset)`.
1416    pub fn select_next(
1417        &self,
1418        anchor_offset: Option<usize>,
1419        focus_offset: Option<usize>,
1420    ) -> Result<SelectionRef, LexicalError> {
1421        select_adjacent_node(self, true, anchor_offset, focus_offset)
1422    }
1423}
1424
1425/// `LexicalNode.remove(preserveEmptyParent)`, which nodes that override it
1426/// call as `super.remove`.
1427pub(crate) fn remove(this: &NodeRef, preserve_empty_parent: bool) -> Result<(), LexicalError> {
1428    invariant!(!this.is_root(), "remove: cannot be called on root nodes");
1429    remove_node(this, true, preserve_empty_parent)
1430}
1431
1432/// `LexicalNode.replace(replaceWith, includeChildren)`, which nodes that
1433/// override it call as `super.replace`.
1434pub(crate) fn replace(
1435    this: &NodeRef,
1436    replace_with: &NodeRef,
1437    include_children: bool,
1438) -> Result<NodeRef, LexicalError> {
1439    invariant!(!this.is_root(), "replace: cannot be called on root nodes");
1440    error_on_read_only();
1441    let selection = get_selection().map(|s| s.clone_selection());
1442    error_on_insert_text_node_on_root(this, replace_with)?;
1443    let to_replace_key = this.get_key().to_owned();
1444    if let Some(slot_host) = crate::slot::get_slot_host(this) {
1445        return Err(LexicalError::new(format!(
1446            "replace: node {to_replace_key} (type {}) is slotted into host {} (type {}); a slot value cannot be replaced through the tree API. Use $setSlot on its host to assign a replacement.",
1447            this.get_type(),
1448            slot_host.get_key(),
1449            slot_host.get_type()
1450        )));
1451    }
1452    get_writable(replace_with.get_key());
1453    let parent = this.get_parent_or_throw()?;
1454    get_writable(parent.get_key());
1455    crate::slot::error_on_slot_cycle_child(&parent, replace_with)?;
1456    let size = parent.get_children_size();
1457    let replace_with_old_parent = replace_with.get_parent();
1458    let range = selection.as_ref().filter(|s| s.is_range());
1459    detach_node_with_selection(replace_with, range)?;
1460    let prev_sibling = this.get_previous_sibling();
1461    let next_sibling = this.get_next_sibling();
1462    remove_node(this, false, true)?;
1463    if let Some(p) = &prev_sibling {
1464        get_writable(p.get_key());
1465    }
1466    if let Some(n) = &next_sibling {
1467        get_writable(n.get_key());
1468    }
1469    insert_node_between(
1470        parent.get_key(),
1471        replace_with.get_key(),
1472        prev_sibling.as_ref().map(NodeRef::get_key),
1473        next_sibling.as_ref().map(NodeRef::get_key),
1474    );
1475    // When replace_with was already a child of the same parent, two
1476    // children became one.
1477    let size = if replace_with_old_parent.as_ref() == Some(&parent) {
1478        size - 1
1479    } else {
1480        size
1481    };
1482    mutate(parent.get_key(), |p| {
1483        p.element_mut().expect("a parent is an element").size = size
1484    });
1485    let mut prev_size_before_children_transfer = 0;
1486    if include_children {
1487        invariant!(
1488            this.is_element() && replace_with.is_element(),
1489            "includeChildren should only be true for ElementNodes"
1490        );
1491        prev_size_before_children_transfer = replace_with.get_children_size();
1492        replace_with.splice(prev_size_before_children_transfer, 0, &this.get_children())?;
1493    }
1494    if let Some(selection) = range {
1495        set_selection(Some(selection.clone()));
1496        for which in [Which::Anchor, Which::Focus] {
1497            let point = selection.point(which).expect("a range selection");
1498            if point.key == to_replace_key {
1499                if include_children && point.point_type == PointType::Element {
1500                    selection.point_set(
1501                        which,
1502                        replace_with.get_key(),
1503                        prev_size_before_children_transfer + point.offset,
1504                        PointType::Element,
1505                    )?;
1506                } else {
1507                    move_selection_point_to_end(selection, which, replace_with)?;
1508                }
1509            }
1510        }
1511    }
1512    if crate::lexical_utils::get_composition_key().as_deref() == Some(to_replace_key.as_str()) {
1513        crate::lexical_utils::set_composition_key(Some(replace_with.get_key()));
1514    }
1515    Ok(replace_with.clone())
1516}
1517
1518/// `LexicalNode.insertAfter(nodeToInsert, restoreSelection)`, which nodes
1519/// that override it call as `super.insertAfter`.
1520pub(crate) fn insert_after(
1521    this: &NodeRef,
1522    node_to_insert: &NodeRef,
1523    restore_selection: bool,
1524) -> Result<NodeRef, LexicalError> {
1525    invariant!(
1526        !this.is_root(),
1527        "insertAfter: cannot be called on root nodes"
1528    );
1529    insert_sibling(this, true, node_to_insert, restore_selection)
1530}
1531
1532/// `$removeNode(nodeToRemove, restoreSelection, preserveEmptyParent)`.
1533pub(crate) fn remove_node(
1534    node_to_remove: &NodeRef,
1535    restore_selection: bool,
1536    preserve_empty_parent: bool,
1537) -> Result<(), LexicalError> {
1538    error_on_read_only();
1539    let key = node_to_remove.get_key().to_owned();
1540    let Some(parent) = node_to_remove.get_parent() else {
1541        let slot_host_key = crate::slot::get_slot_host_key(node_to_remove);
1542        invariant!(
1543            slot_host_key.is_none(),
1544            "$removeNode: node {key} is slotted into host {}; use removeSlot on the host instead of remove().",
1545            slot_host_key.unwrap_or_default()
1546        );
1547        return Ok(());
1548    };
1549    let selection = maybe_move_children_selection_to_parent(node_to_remove)?;
1550    let mut selection_moved = false;
1551    match &selection {
1552        Some(range) if range.is_range() && restore_selection => {
1553            for which in [Which::Anchor, Which::Focus] {
1554                if range.point(which).expect("a range selection").key == key {
1555                    move_selection_point_to_sibling(
1556                        range,
1557                        which,
1558                        node_to_remove,
1559                        &parent,
1560                        node_to_remove.get_previous_sibling().as_ref(),
1561                        node_to_remove.get_next_sibling().as_ref(),
1562                    )?;
1563                    selection_moved = true;
1564                }
1565            }
1566        }
1567        Some(nodes)
1568            if nodes.is_node()
1569                && restore_selection
1570                && node_to_remove.is_selected_by_node_selection(nodes) =>
1571        {
1572            node_to_remove.select_previous(None, None)?;
1573        }
1574        _ => {}
1575    }
1576
1577    get_writable(&key);
1578    let range = selection
1579        .as_ref()
1580        .filter(|s| restore_selection && !selection_moved && s.is_range());
1581    detach_node_with_selection(node_to_remove, range)?;
1582
1583    if !preserve_empty_parent
1584        && !is_root_or_shadow_root(&*parent.get_latest())
1585        && !parent.can_be_empty()
1586        && parent.is_empty()
1587    {
1588        remove_node(&parent, restore_selection, false)?;
1589    }
1590    if restore_selection && selection.is_some() && parent.is_root() && parent.is_empty() {
1591        parent.select_end()?;
1592    }
1593    Ok(())
1594}