Skip to main content

lexical_ui/
selection_insert_nodes.rs

1//! `insertNodes`, `insertParagraph`, `insertLineBreak` and
2//! `insertRawText` from `LexicalSelection.ts`, for both selection kinds,
3//! with `$insertNodes`, `$generateNodesFromRawText` and `$selectAll`.
4//!
5//! A declared block container (`$isBlockContainer`, a class whose
6//! `$config` declares `children: 'block'` in an editor that enforces node
7//! structure) is taken where JS takes the root and shadow roots.
8
9use crate::LexicalError;
10use crate::caret::CaretDirection;
11use crate::caret_utils::{
12    SplitAtPointCaretNextOptions, caret_from_point, insert_node_to_nearest_root_at_caret,
13    normalize_caret, set_point_from_caret,
14};
15use crate::error::invariant;
16use crate::lexical_selection::{
17    Point, PointType, RangeSelection, Selection, SelectionRef, Which, get_selection, set_selection,
18};
19use crate::lexical_utils::{get_root, is_block};
20use crate::node::NodeRef;
21use crate::nodes::element::is_root_or_shadow_root;
22use crate::nodes::line_break::{LineBreakNode, create_line_break_node};
23use crate::nodes::paragraph::create_paragraph_node;
24use crate::nodes::tab::create_tab_node;
25use crate::nodes::text::create_text_node;
26use crate::updates::{get_active_editor, get_active_editor_state};
27use std::rc::Rc;
28
29impl SelectionRef {
30    /// `selection.insertNodes(nodes)`: `RangeSelection.insertNodes`, which
31    /// replaces the selected content with `nodes`, splitting blocks as
32    /// needed, and selects the end of what it inserted; or
33    /// `NodeSelection.insertNodes`, which inserts them after the last
34    /// selected node and removes the selected nodes.
35    pub fn insert_nodes(&self, nodes: Vec<NodeRef>) -> Result<(), LexicalError> {
36        #[cfg(feature = "table")]
37        if self.is_table() {
38            return crate::table::table_selection::insert_nodes(self, nodes);
39        }
40        if self.is_node() {
41            node_selection_insert_nodes(self, &nodes)
42        } else {
43            range_selection_insert_nodes(self, &nodes)
44        }
45    }
46
47    /// `selection.insertRawText(text)`: on a range selection, inserts the
48    /// text with its tabs and line breaks as nodes; on a node selection,
49    /// nothing.
50    pub fn insert_raw_text(&self, text: &str) -> Result<(), LexicalError> {
51        #[cfg(feature = "table")]
52        if self.is_table() {
53            return crate::table::table_selection::insert_raw_text(self, text);
54        }
55        if self.is_node() {
56            // `NodeSelection.insertRawText`: "Do nothing?"
57            return Ok(());
58        }
59        self.insert_nodes(generate_nodes_from_raw_text(text))
60    }
61
62    /// `selection.insertParagraph()`: splits the block at the selection,
63    /// and returns the new block, if one was inserted, with the selection at
64    /// its start.
65    pub fn insert_paragraph(&self) -> Result<Option<NodeRef>, LexicalError> {
66        // The root/shadow-root branch below only splices a paragraph in, so
67        // the selected content has to go first.
68        if !is_collapsed(self) {
69            self.remove_text()?;
70        }
71        let anchor = anchor_of(self);
72        let anchor_node = anchor.get_node()?;
73        if anchor.point_type == PointType::Element && is_block_container(&anchor_node) {
74            let paragraph = create_paragraph_node();
75            anchor_node.splice(anchor.offset, 0, std::slice::from_ref(&paragraph))?;
76            paragraph.select(None, None)?;
77            return Ok(Some(paragraph));
78        }
79        let (_, index) = remove_text_and_split_block(self, false)?;
80        let block = find_matching_parent(&anchor_of(self).get_node()?, is_block);
81        // A block that is a slot value has no room for a sibling paragraph:
82        // a no-op, as Enter in a single-line input.
83        if block
84            .as_ref()
85            .is_some_and(|b| crate::slot::get_slot_host_key(b).is_some())
86        {
87            return Ok(None);
88        }
89        let Some(block) = block.filter(NodeRef::is_element) else {
90            return Err(LexicalError::new(
91                "Expected ancestor to be a block ElementNode",
92            ));
93        };
94        let nodes_to_insert = match block.get_child_at_index(index) {
95            Some(first_to_append) => {
96                let mut nodes = vec![first_to_append.clone()];
97                nodes.extend(get_next_siblings(&first_to_append));
98                nodes
99            }
100            None => Vec::new(),
101        };
102        match block
103            .insert_new_after(self, false)?
104            .filter(NodeRef::is_element)
105        {
106            Some(new_block) => {
107                new_block.append(&nodes_to_insert)?;
108                new_block.select_start()?;
109                Ok(Some(new_block))
110            }
111            // A block that can't be split, such as a CodeNode.
112            None => Ok(None),
113        }
114    }
115
116    /// `selection.insertLineBreak(selectStart)`: inserts a line break,
117    /// with the selection after it, or before it when `select_start`.
118    pub fn insert_line_break(&self, select_start: bool) -> Result<(), LexicalError> {
119        let line_break = create_line_break_node();
120        self.insert_nodes(vec![line_break.clone()])?;
121        // this is used in MacOS with the command 'ctrl-O' (openLineBreak)
122        if select_start {
123            let parent = line_break.get_parent_or_throw()?;
124            let index = line_break.get_index_within_parent();
125            parent.select(index, index)?;
126        }
127        Ok(())
128    }
129}
130
131/// A range selection's anchor.
132fn anchor_of(selection: &SelectionRef) -> Point {
133    selection.point(Which::Anchor).expect("a range selection")
134}
135
136/// `isCollapsed()` of a range selection.
137fn is_collapsed(selection: &SelectionRef) -> bool {
138    selection.with_range(|r| r.is_collapsed()).unwrap_or(false)
139}
140
141/// `NodeSelection.insertNodes(nodes)`.
142fn node_selection_insert_nodes(
143    selection: &SelectionRef,
144    nodes: &[NodeRef],
145) -> Result<(), LexicalError> {
146    // Slotted nodes are fixed parts of their host: skip them.
147    let selected_nodes: Vec<NodeRef> = selection
148        .get_nodes()?
149        .into_iter()
150        .filter(|n| crate::slot::get_slot_host_key(n).is_none())
151        .collect();
152    let Some(last_selected_node) = selected_nodes.last() else {
153        return Ok(());
154    };
155    // Insert nodes
156    let selection_at_end = if last_selected_node.is_text() {
157        last_selected_node.select(None, None)?
158    } else {
159        let index = last_selected_node
160            .get_index_within_parent()
161            .map_or(0, |i| i + 1);
162        last_selected_node
163            .get_parent_or_throw()?
164            .select(Some(index), Some(index))?
165    };
166    selection_at_end.insert_nodes(nodes.to_vec())?;
167    // Remove selected nodes
168    for node in &selected_nodes {
169        node.remove(false)?;
170    }
171    Ok(())
172}
173
174/// `RangeSelection.insertNodes(nodes)`.
175fn range_selection_insert_nodes(
176    selection: &SelectionRef,
177    nodes: &[NodeRef],
178) -> Result<(), LexicalError> {
179    if nodes.is_empty() {
180        return Ok(());
181    }
182    if !is_collapsed(selection) {
183        selection.remove_text()?;
184    }
185    let anchor = anchor_of(selection);
186    let anchor_node = anchor.get_node()?;
187    // An anchor on a container slot value (a shadow root) redirects into
188    // the slot's subtree, at its first child.
189    if anchor.point_type == PointType::Element
190        && anchor_node.is_element()
191        && anchor_node.get_latest().is_shadow_root()
192        && crate::slot::get_slot_host_key(&anchor_node).is_some()
193    {
194        // An empty container has no child to redirect into: seed a
195        // paragraph first.
196        let mut first_child = match anchor_node.get_first_child() {
197            Some(child) => Some(child),
198            None => {
199                anchor_node.append(&[create_paragraph_node()])?;
200                anchor_node.get_first_child()
201            }
202        };
203        // A first child that is not an element would bring the caret back
204        // here: seed a paragraph before it.
205        if let Some(child) = first_child.clone().filter(|c| !c.is_element()) {
206            let seed = create_paragraph_node();
207            child.insert_before(&seed, true)?;
208            first_child = Some(seed);
209        }
210        if let Some(first_child) = first_child {
211            first_child.select_start()?;
212            let Some(redirected) = get_selection().filter(SelectionRef::is_range) else {
213                return Err(LexicalError::new(
214                    "Expected RangeSelection after redirecting into slot subtree",
215                ));
216            };
217            return range_selection_insert_nodes(&redirected, nodes);
218        }
219    }
220
221    // The anchor is an element point directly on a block container: splice
222    // the nodes in at the anchor offset, inline runs wrapped in a block.
223    if anchor.point_type == PointType::Element && is_block_container(&anchor_node) {
224        let blocks_parent = wrap_inline_nodes(nodes)?;
225        let node_to_select = blocks_parent.get_last_descendant();
226        anchor_node.splice(anchor.offset, 0, &blocks_parent.get_children())?;
227        if let Some(node_to_select) = node_to_select {
228            node_to_select.select_end()?;
229        }
230        return Ok(());
231    }
232
233    let first_point_which = if selection.is_backward()? {
234        Which::Focus
235    } else {
236        Which::Anchor
237    };
238    let first_point = selection
239        .point(first_point_which)
240        .expect("a range selection");
241    let mut first_node = first_point.get_node()?;
242    let mut first_block = find_matching_parent(&first_node, is_block);
243    // JS compares `firstBlock` with `lastInsertedBlock` by object identity
244    // below. The object it holds is the latest version only while no
245    // `getWritable` clones the node, which happens unless the node is
246    // already writable in this update.
247    let mut first_block_is_latest = first_block.as_ref().is_some_and(is_clone_not_needed);
248
249    let last = nodes.last().expect("not empty");
250
251    // CASE 1: insert inside a code block. JS asks for a `__language` field,
252    // which of the ported nodes only `CodeNode` has.
253    #[cfg(feature = "code")]
254    if let Some(first_block) = first_block
255        .as_ref()
256        .filter(|b| crate::code::is_code_node(b))
257    {
258        if crate::code::is_code_node(&nodes[0]) {
259            selection.insert_text(&nodes[0].get_text_content())?;
260        } else {
261            let (_, index) = remove_text_and_split_block(selection, false)?;
262            first_block.splice(index, 0, nodes)?;
263            last.select_end()?;
264        }
265        return Ok(());
266    }
267
268    // CASE 2: All elements of the array are inline
269    let not_inline =
270        |node: &NodeRef| (node.is_element() || node.is_decorator()) && !node.is_inline();
271
272    if !nodes.iter().any(not_inline) {
273        let Some(first_block) = first_block.filter(NodeRef::is_element) else {
274            return Err(expected_block_ancestor(&first_node, "block ElementNode"));
275        };
276        // The split walk normally ends on firstBlock, but it stops early on
277        // an inline ElementNode that cannot be split (#6477).
278        let (container, index) = remove_text_and_split_block(selection, true)?;
279        let insertion_parent = if container.is_element() {
280            container
281        } else {
282            first_block
283        };
284        insertion_parent.splice(index, 0, nodes)?;
285        last.select_end()?;
286        return Ok(());
287    }
288
289    // CASE 3a: there is non-inline content but no block ancestor to insert
290    // it relative to: a malformed document, where an inline-only element
291    // holds a block child (#8713) or a non-inline element reports
292    // `canBeEmpty() === false`. A non-inline node must never become the
293    // child of an inline-only element, so each block goes in with
294    // `$insertNodeToNearestRootAtCaret`, which splits the ancestors up to the
295    // nearest root or shadow root. (A list item is always a block ancestor,
296    // so lists fall through to CASE 3.)
297    let Some(found_block) = first_block.clone() else {
298        let blocks_parent = wrap_inline_nodes(nodes)?;
299        let node_to_select = blocks_parent.get_last_descendant();
300        let mut caret = caret_from_point(&anchor_of(selection), CaretDirection::Next)?;
301        for block in blocks_parent.get_children() {
302            caret = insert_node_to_nearest_root_at_caret(
303                &block,
304                &caret,
305                &SplitAtPointCaretNextOptions::default(),
306            )?;
307        }
308        if let Some(node_to_select) = node_to_select {
309            node_to_select.select_end()?;
310        }
311        return Ok(());
312    };
313
314    // CASE 3b: the block cannot receive block siblings (a slot value, whose
315    // virtual root holds one block, or a block inside an inline-only
316    // element, #8724). Flatten the incoming content.
317    if found_block.is_element()
318        && (crate::slot::get_slot_host_key(&found_block).is_some()
319            || (!found_block.is_parent_required()
320                && !is_block_container(&found_block.get_parent_or_throw()?)))
321    {
322        let (_, index) = remove_text_and_split_block(selection, false)?;
323        let inline_nodes = extract_inline_from_blocks(nodes);
324        found_block.splice(index, 0, &inline_nodes)?;
325        match inline_nodes.last() {
326            Some(last_inserted) => {
327                last_inserted.select_end()?;
328            }
329            None => {
330                found_block.select(Some(index), Some(index))?;
331            }
332        }
333        return Ok(());
334    }
335
336    // CASE 3: At least 1 element of the array is not inline
337    let blocks_parent = wrap_inline_nodes(nodes)?;
338    let node_to_select = blocks_parent
339        .get_last_descendant()
340        .ok_or_else(|| LexicalError::new("insertNodes: nothing to select"))?;
341    let blocks = blocks_parent.get_children();
342    // An empty line before the insertion point reads as a block boundary
343    // (#4815).
344    let is_after_empty_line = is_point_after_empty_line(&first_point)?;
345    let is_mergeable = |node: &NodeRef, first_block: Option<&NodeRef>| {
346        !is_after_empty_line
347            && node.is_element()
348            && is_block(node)
349            && !node.is_empty()
350            && first_block
351                .is_some_and(|b| b.is_element() && (!b.is_empty() || b.can_merge_when_empty()))
352    };
353
354    let should_insert = !found_block.is_element() || !found_block.is_empty();
355    let inserted_paragraph = if should_insert {
356        selection.insert_paragraph()?
357    } else {
358        None
359    };
360    if inserted_paragraph.is_some() && !found_block.is_attached() {
361        first_node = anchor_of(selection).get_node()?;
362        first_block = find_matching_parent(&first_node, is_block);
363        first_block_is_latest = first_block.as_ref().is_some_and(is_clone_not_needed);
364    }
365    let last_to_insert = blocks.last();
366    let mut first_to_insert = blocks.first();
367    if let Some(first) = first_to_insert
368        && is_mergeable(first, first_block.as_ref())
369    {
370        let Some(first_block) = first_block.as_ref().filter(|b| b.is_element()) else {
371            return Err(expected_block_ancestor(&first_node, "block ElementNode"));
372        };
373        first_block.append(&first.get_children())?;
374        first_to_insert = blocks.get(1);
375    }
376    if let Some(first_to_insert) = first_to_insert {
377        let Some(first_block) = &first_block else {
378            return Err(expected_block_ancestor(&first_node, "block"));
379        };
380        insert_range_after(first_block, first_to_insert)?;
381    }
382    let last_inserted_block = find_matching_parent(&node_to_select, is_block);
383
384    // Mark where the inserted content ends before the split-off content is
385    // moved in after it.
386    let insert_selection = node_to_select.select_end()?;
387
388    if let Some(inserted_paragraph) = &inserted_paragraph {
389        match last_inserted_block.as_ref().filter(|b| {
390            b.is_element()
391                && (inserted_paragraph.can_merge_when_empty()
392                    || last_to_insert.is_some_and(is_block))
393        }) {
394            Some(last_inserted_block) => {
395                last_inserted_block.append(&inserted_paragraph.get_children())?;
396                inserted_paragraph.remove(false)?;
397            }
398            None => {
399                // The split-off paragraph could not be merged into the last
400                // inserted block, but it holds no content either.
401                if inserted_paragraph.is_empty() {
402                    inserted_paragraph.remove(false)?;
403                }
404            }
405        }
406    }
407    if let Some(first_block) = first_block.as_ref().filter(|b| b.is_element())
408        && first_block.is_empty()
409    {
410        first_block.remove(false)?;
411    }
412
413    // To understand this take a look at the test "can wrap post-linebreak
414    // nodes into new element"
415    let last_child = first_block
416        .as_ref()
417        .filter(|b| b.is_element())
418        .and_then(NodeRef::get_last_child);
419    // `lastInsertedBlock !== firstBlock` compares objects: the same node
420    // differs from a `firstBlock` that has been cloned since.
421    let same_block =
422        first_block.is_some() && last_inserted_block == first_block && first_block_is_latest;
423    if let Some(last_child) = last_child
424        && last_child.get_latest().is::<LineBreakNode>()
425        && !same_block
426    {
427        last_child.remove(false)?;
428    }
429
430    // Resolve the marked caret onto the text beside it.
431    let normalized_caret = normalize_caret(&caret_from_point(
432        &anchor_of(&insert_selection),
433        CaretDirection::Next,
434    )?);
435    set_point_from_caret(&insert_selection, Which::Anchor, &normalized_caret)?;
436    set_point_from_caret(&insert_selection, Which::Focus, &normalized_caret)?;
437    Ok(())
438}
439
440/// The invariant `Expected node %s of type %s to have a block ElementNode
441/// ancestor` (or `a block ancestor`).
442fn expected_block_ancestor(node: &NodeRef, what: &str) -> LexicalError {
443    LexicalError::new(format!(
444        "Expected node {} of type {} to have a {what} ancestor",
445        node.get_latest().class_name(),
446        node.get_type()
447    ))
448}
449
450/// Whether the node is already writable in this update (JS's
451/// `_cloneNotNeeded`), so `getWritable` changes the object JS code holds
452/// rather than replacing it: nothing else, such as the previous editor
453/// state, shares its value.
454fn is_clone_not_needed(node: &NodeRef) -> bool {
455    get_active_editor_state()
456        .0
457        .node_map
458        .borrow()
459        .get(node.get_key())
460        .is_some_and(|n| Rc::strong_count(n) == 1)
461}
462
463/// `$isBlockContainer(node)` ([`crate::is_block_container`]).
464pub(crate) fn is_block_container(node: &NodeRef) -> bool {
465    crate::structure::is_block_container(node)
466}
467
468/// `$findMatchingParent(startingNode, findFn)`: the node or its nearest
469/// ancestor below the root that matches.
470pub fn find_matching_parent(
471    starting_node: &NodeRef,
472    find_fn: impl Fn(&NodeRef) -> bool,
473) -> Option<NodeRef> {
474    let mut curr = Some(starting_node.clone());
475    while let Some(node) = curr.filter(|n| !n.is_root()) {
476        if find_fn(&node) {
477            return Some(node);
478        }
479        curr = node.get_parent();
480    }
481    None
482}
483
484/// `getNextSiblings()`.
485fn get_next_siblings(node: &NodeRef) -> Vec<NodeRef> {
486    let mut siblings = Vec::new();
487    let mut sibling = node.get_next_sibling();
488    while let Some(s) = sibling {
489        sibling = s.get_next_sibling();
490        siblings.push(s);
491    }
492    siblings
493}
494
495/// `insertRangeAfter(node, firstToInsert)`: inserts `first_to_insert` and
496/// its next siblings after `node`.
497fn insert_range_after(node: &NodeRef, first_to_insert: &NodeRef) -> Result<(), LexicalError> {
498    let mut nodes_to_insert = vec![first_to_insert.clone()];
499    nodes_to_insert.extend(get_next_siblings(first_to_insert));
500    let mut current_node = node.clone();
501    for node_to_insert in &nodes_to_insert {
502        current_node = current_node.insert_after(node_to_insert, true)?;
503    }
504    Ok(())
505}
506
507/// `$getNodeBeforePoint(point)`: the node just before the point in its
508/// block, looking through the boundaries of inline elements.
509fn get_node_before_point(point: &Point) -> Result<Option<NodeRef>, LexicalError> {
510    let node = point.get_node()?;
511    if point.offset > 0 {
512        // An element point has the child before it; a text point has
513        // characters before it, so no node is adjacent.
514        return Ok(
515            if point.point_type == PointType::Element && node.is_element() {
516                node.get_child_at_index(point.offset - 1)
517            } else {
518                None
519            },
520        );
521    }
522    let mut child = Some(node);
523    while let Some(c) = child.filter(|c| !is_block(c) && !is_root_or_shadow_root(&*c.get_latest()))
524    {
525        if let Some(previous_sibling) = c.get_previous_sibling() {
526            return Ok(Some(previous_sibling));
527        }
528        child = c.get_parent();
529    }
530    Ok(None)
531}
532
533/// `$isPointAfterEmptyLine(point)`: whether two line breaks come just
534/// before the point.
535fn is_point_after_empty_line(point: &Point) -> Result<bool, LexicalError> {
536    let is_line_break = |node: &NodeRef| node.get_latest().is::<LineBreakNode>();
537    Ok(get_node_before_point(point)?.is_some_and(|node_before| {
538        is_line_break(&node_before)
539            && node_before
540                .get_previous_sibling()
541                .is_some_and(|n| is_line_break(&n))
542    }))
543}
544
545/// `$extractInlineFromBlocks(nodes)`: the inline content of `nodes`, with
546/// blocks replaced by their inline content and line breaks and block
547/// decorators dropped.
548fn extract_inline_from_blocks(nodes: &[NodeRef]) -> Vec<NodeRef> {
549    let mut inline_nodes = Vec::new();
550    for node in nodes {
551        if node.get_latest().is::<LineBreakNode>() {
552            continue;
553        }
554        if (node.is_element() || node.is_decorator()) && !node.is_inline() {
555            if node.is_element() {
556                inline_nodes.extend(extract_inline_from_blocks(&node.get_children()));
557            }
558            continue;
559        }
560        inline_nodes.push(node.clone());
561    }
562    inline_nodes
563}
564
565/// `$removeTextAndSplitBlock(selection, stopAtUnsplittableNode)`: removes
566/// the selected text and splits the ancestors of the anchor up to the
567/// nearest block, and returns the node to insert into and the index in it.
568fn remove_text_and_split_block(
569    selection: &SelectionRef,
570    stop_at_unsplittable_node: bool,
571) -> Result<(NodeRef, usize), LexicalError> {
572    let mut selection_ = selection.clone();
573    if !is_collapsed(selection) {
574        selection_.remove_text()?;
575    }
576    // A new selection can originate as a result of node replacement, in
577    // which case is registered via $setSelection
578    if let Some(new_selection) = get_selection().filter(SelectionRef::is_range) {
579        selection_ = new_selection;
580    }
581    let anchor = anchor_of(&selection_);
582    let mut node = anchor.get_node()?;
583    let mut offset = anchor.offset;
584    // A slotted node is the root of its scope: the walk stops there too.
585    while !is_block(&node) && crate::slot::get_slot_host_key(&node).is_none() {
586        let prev_node = node.clone();
587        (node, offset) = split_node_at_point(&node, offset, stop_at_unsplittable_node)?;
588        if prev_node == node {
589            break;
590        }
591    }
592    Ok((node, offset))
593}
594
595/// `$splitNodeAtPoint(node, offset, stopAtUnsplittableNode)`: splits
596/// `node` at `offset`, and returns the parent that holds the two halves and
597/// the index between them.
598fn split_node_at_point(
599    node: &NodeRef,
600    offset: usize,
601    stop_at_unsplittable_node: bool,
602) -> Result<(NodeRef, usize), LexicalError> {
603    let Some(parent) = node.get_parent() else {
604        let paragraph = create_paragraph_node();
605        get_root().append(std::slice::from_ref(&paragraph))?;
606        paragraph.select(None, None)?;
607        return Ok((get_root(), 0));
608    };
609    let index_within_parent = || {
610        node.get_index_within_parent()
611            .expect("a child of its parent")
612    };
613
614    if node.is_text() {
615        let split = node.split_text(&[offset as i64])?;
616        let Some(first) = split.first() else {
617            return Ok((parent, index_within_parent()));
618        };
619        let x = usize::from(offset != 0);
620        let index = first
621            .get_index_within_parent()
622            .expect("a child of its parent")
623            + x;
624        return Ok((parent, index));
625    }
626
627    if !node.is_element() || offset == 0 {
628        return Ok((parent, index_within_parent()));
629    }
630
631    if let Some(first_to_append) = node.get_child_at_index(offset) {
632        let insert_point = SelectionRef::new(Selection::Range(RangeSelection::new(
633            Point::new(node.get_key(), offset, PointType::Element),
634            Point::new(node.get_key(), offset, PointType::Element),
635            0.0,
636            "",
637        )));
638        // JS passes no `restoreSelection`, which `insertAfter` defaults to
639        // true.
640        match node.insert_new_after(&insert_point, true)? {
641            Some(new_element) if new_element.is_element() => {
642                let mut nodes = vec![first_to_append.clone()];
643                nodes.extend(get_next_siblings(&first_to_append));
644                new_element.append(&nodes)?;
645            }
646            _ if stop_at_unsplittable_node => return Ok((node.clone(), offset)),
647            _ => {}
648        }
649    }
650    Ok((parent, index_within_parent() + 1))
651}
652
653/// `$isInlineRunNode(node)`: a node `$wrapInlineNodes` puts in a block of
654/// its own run.
655fn is_inline_run_node(node: &NodeRef) -> bool {
656    let latest = node.get_latest();
657    latest.is::<LineBreakNode>()
658        // `$isInlineElementOrDecoratorNode`
659        || ((latest.element().is_some() || latest.is_decorator()) && latest.is_inline())
660        || latest.text().is_some()
661        || latest.is_parent_required()
662}
663
664/// `$wrapInlineNodes(nodes)`: a detached paragraph holding `nodes`, each
665/// run of inline nodes wrapped in its required parent (a paragraph).
666fn wrap_inline_nodes(nodes: &[NodeRef]) -> Result<NodeRef, LexicalError> {
667    // We temporarily insert the topLevelNodes into an arbitrary ElementNode,
668    // since insertAfter does not work on nodes that have no parent (TO-DO:
669    // fix that).
670    let virtual_root = create_paragraph_node();
671    let mut current_block: Option<NodeRef> = None;
672    for (i, node) in nodes.iter().enumerate() {
673        if is_inline_run_node(node) {
674            let block = match &current_block {
675                Some(block) => block.clone(),
676                None => {
677                    let block = node.create_parent_element_node();
678                    virtual_root.append(std::slice::from_ref(&block))?;
679                    current_block = Some(block.clone());
680                    // A LineBreakNode that is an entire run by itself
681                    // collapses to an empty paragraph, since the block
682                    // boundary already provides the visual newline.
683                    let next_node = nodes.get(i + 1);
684                    if node.get_latest().is::<LineBreakNode>()
685                        && next_node.is_none_or(|n| !is_inline_run_node(n))
686                    {
687                        continue;
688                    }
689                    block
690                }
691            };
692            block.append(std::slice::from_ref(node))?;
693        } else {
694            virtual_root.append(std::slice::from_ref(node))?;
695            current_block = None;
696        }
697    }
698    Ok(virtual_root)
699}
700
701/// `RawTextVisitor`: what [`tokenize_raw_text`] calls for each token.
702pub trait RawTextVisitor {
703    fn linebreak(&mut self);
704    fn tab(&mut self);
705    /// A non-empty run of text.
706    fn text(&mut self, text: &str);
707}
708
709/// `tokenizeRawText(text, visitor)`: splits `text` at `\n`, `\r\n` and
710/// `\t` (`text.split(/(\r?\n|\t)/)`), and calls the visitor for each token
711/// in order, skipping empty text runs.
712pub fn tokenize_raw_text(text: &str, visitor: &mut impl RawTextVisitor) {
713    let mut start = 0;
714    for (i, c) in text.char_indices() {
715        match c {
716            '\n' => {
717                let end = if text[..i].ends_with('\r') && i > start {
718                    i - 1
719                } else {
720                    i
721                };
722                if end > start {
723                    visitor.text(&text[start..end]);
724                }
725                visitor.linebreak();
726                start = i + 1;
727            }
728            '\t' => {
729                if i > start {
730                    visitor.text(&text[start..i]);
731                }
732                visitor.tab();
733                start = i + 1;
734            }
735            _ => {}
736        }
737    }
738    if text.len() > start {
739        visitor.text(&text[start..]);
740    }
741}
742
743/// `$generateNodesFromRawText(text)`: text, line break and tab nodes for
744/// `text`, split at `\n`, `\r\n` and `\t`.
745pub fn generate_nodes_from_raw_text(text: &str) -> Vec<NodeRef> {
746    struct Nodes(Vec<NodeRef>);
747    impl RawTextVisitor for Nodes {
748        fn linebreak(&mut self) {
749            self.0.push(create_line_break_node());
750        }
751        fn tab(&mut self) {
752            self.0.push(create_tab_node());
753        }
754        fn text(&mut self, text: &str) {
755            self.0.push(create_text_node(text));
756        }
757    }
758    let mut nodes = Nodes(Vec::new());
759    tokenize_raw_text(text, &mut nodes);
760    nodes.0
761}
762
763/// `$getPreviousSelection()`: the committed editor state's selection.
764pub(crate) fn get_previous_selection() -> Option<SelectionRef> {
765    let editor = get_active_editor()?;
766    editor.get_editor_state().0.selection.borrow().clone()
767}
768
769/// `$insertNodes(nodes)`: inserts `nodes` at the selection, the previous
770/// one if there is none, or else the end of the root.
771pub fn insert_nodes(nodes: Vec<NodeRef>) -> Result<(), LexicalError> {
772    let selection = match get_selection().or_else(get_previous_selection) {
773        Some(selection) => selection,
774        None => get_root().select_end()?,
775    };
776    selection.insert_nodes(nodes)
777}
778
779/// `$selectAll(selection)`: for a range selection, moves its points to the
780/// start and end of the root or shadow root that holds its anchor, down to
781/// text where they can be, and returns it (in a slot, the contents of the
782/// slot value); for a node selection, [`select_all`], which is
783/// `$selectAll()`.
784pub fn select_all_in(selection: &SelectionRef) -> Result<SelectionRef, LexicalError> {
785    let Some(anchor) = selection.point(Which::Anchor) else {
786        return select_all();
787    };
788    let anchor_node = anchor.get_node()?;
789    // `RootNode.getTopLevelElementOrThrow` always throws by design, so when
790    // the caret is at the root's element-level (typically after deleting
791    // every top-level child) fall through to the regular "select all root
792    // children" path before the throw fires.
793    let container = if anchor_node.is_root() {
794        anchor_node
795    } else {
796        // `getTopLevelElementOrThrow().getParent()`: the root or shadow
797        // root above the anchor.
798        let mut node = anchor_node.clone();
799        loop {
800            // `getTopLevelElement` stops at a slot value, whose parent is
801            // `null`: the selection is scoped to its contents.
802            if crate::slot::get_slot_host_key(&node).is_some() {
803                if node.is_element() {
804                    selection.point_set(Which::Anchor, node.get_key(), 0, PointType::Element)?;
805                    selection.point_set(
806                        Which::Focus,
807                        node.get_key(),
808                        node.get_children_size(),
809                        PointType::Element,
810                    )?;
811                    normalize_selection_for_select_all(selection, &node)?;
812                }
813                return Ok(selection.clone());
814            }
815            let Some(parent) = node.get_parent() else {
816                return Err(LexicalError::new(format!(
817                    "Expected node {} to have a top parent element.",
818                    anchor_node.get_key()
819                )));
820            };
821            if is_root_or_shadow_root(&*parent.get_latest()) {
822                invariant!(
823                    node.is_element() || (node == anchor_node && node.is_decorator()),
824                    "Children of root nodes must be elements or decorators"
825                );
826                break parent;
827            }
828            node = parent;
829        }
830    };
831    selection.point_set(Which::Anchor, container.get_key(), 0, PointType::Element)?;
832    selection.point_set(
833        Which::Focus,
834        container.get_key(),
835        container.get_children_size(),
836        PointType::Element,
837    )?;
838    normalize_selection_for_select_all(selection, &container)?;
839    Ok(selection.clone())
840}
841
842/// `$selectAll()`: selects the whole root, with the points moved down to
843/// text where they can be, and returns the selection. [`select_all_in`] is
844/// `$selectAll(selection)`, which scopes an existing selection.
845pub fn select_all() -> Result<SelectionRef, LexicalError> {
846    let root = get_root();
847    let new_selection = root.select(Some(0), Some(root.get_children_size()))?;
848    set_selection(Some(normalize_selection_for_select_all(
849        &new_selection,
850        &root,
851    )?));
852    Ok(new_selection)
853}
854
855/// `$normalizeSelectionForSelectAll(selection, container)`: normalizes the
856/// points, unless the select-all spans a document whose points would both
857/// descend into the same top-level shadow root (#6938).
858fn normalize_selection_for_select_all(
859    selection: &SelectionRef,
860    container: &NodeRef,
861) -> Result<SelectionRef, LexicalError> {
862    let range = selection.range().expect("a range selection");
863    normalize_selection(selection)?;
864    if !container.is_root() {
865        return Ok(selection.clone());
866    }
867    let anchor_top = get_root_child_ancestor(&anchor_of(selection).get_node()?);
868    let focus = selection.point(Which::Focus).expect("a range selection");
869    if let Some(anchor_top) = anchor_top
870        && anchor_top.is_element()
871        && anchor_top.get_latest().is_shadow_root()
872        && get_root_child_ancestor(&focus.get_node()?).as_ref() == Some(&anchor_top)
873    {
874        let (anchor, focus) = (&range.anchor, &range.focus);
875        selection.point_set(Which::Anchor, &anchor.key, anchor.offset, anchor.point_type)?;
876        selection.point_set(Which::Focus, &focus.key, focus.offset, focus.point_type)?;
877    }
878    Ok(selection.clone())
879}
880
881/// `$getRootChildAncestor(node)`: the node or its ancestor that is a child
882/// of the root.
883fn get_root_child_ancestor(node: &NodeRef) -> Option<NodeRef> {
884    let mut current = node.clone();
885    loop {
886        // A detached node.
887        let parent = current.get_parent()?;
888        if parent.is_root() {
889            return Some(current);
890        }
891        current = parent;
892    }
893}
894
895/// `$normalizeSelection(selection)` (`LexicalNormalization.ts`): moves
896/// element points down to the deepest text or element point.
897pub(crate) fn normalize_selection(selection: &SelectionRef) -> Result<(), LexicalError> {
898    normalize_point(selection, Which::Anchor)?;
899    normalize_point(selection, Which::Focus)
900}
901
902/// `$normalizePoint(point)`.
903fn normalize_point(selection: &SelectionRef, which: Which) -> Result<(), LexicalError> {
904    loop {
905        let point = selection.point(which).expect("a range selection");
906        if point.point_type != PointType::Element {
907            return Ok(());
908        }
909        let node = point.get_node()?;
910        let offset = point.offset;
911        let (next_node, next_offset_at_end) = if offset == node.get_children_size() {
912            (
913                offset
914                    .checked_sub(1)
915                    .and_then(|i| node.get_child_at_index(i)),
916                true,
917            )
918        } else {
919            (node.get_child_at_index(offset), false)
920        };
921        let Some(next_node) = next_node else {
922            return Ok(());
923        };
924        // `set(..., onlyIfChanged)` always changes the point here: the node
925        // differs.
926        if next_node.is_text() {
927            let offset = if next_offset_at_end {
928                next_node.get_text_content_size()
929            } else {
930                0
931            };
932            return selection.point_set(which, next_node.get_key(), offset, PointType::Text);
933        } else if !next_node.is_element() {
934            return Ok(());
935        }
936        let offset = if next_offset_at_end {
937            next_node.get_children_size()
938        } else {
939            0
940        };
941        selection.point_set(which, next_node.get_key(), offset, PointType::Element)?;
942    }
943}
944
945#[cfg(test)]
946mod tests {
947    use super::*;
948
949    struct Tokens(Vec<String>);
950    impl RawTextVisitor for Tokens {
951        fn linebreak(&mut self) {
952            self.0.push("<br>".to_owned());
953        }
954        fn tab(&mut self) {
955            self.0.push("<tab>".to_owned());
956        }
957        fn text(&mut self, text: &str) {
958            self.0.push(text.to_owned());
959        }
960    }
961
962    /// `tokenizeRawText` splits as `text.split(/(\r?\n|\t)/)` does: a
963    /// `\r` only goes with the `\n` right after it.
964    #[test]
965    fn tokenize_raw_text_matches_js_split() {
966        let tokens = |text: &str| {
967            let mut tokens = Tokens(Vec::new());
968            tokenize_raw_text(text, &mut tokens);
969            tokens.0
970        };
971        assert_eq!(
972            tokens("a\r\nb\tc\n"),
973            ["a", "<br>", "b", "<tab>", "c", "<br>"]
974        );
975        assert_eq!(tokens("\r\r\n\r"), ["\r", "<br>", "\r"]);
976        assert_eq!(tokens("\r\n\r\n"), ["<br>", "<br>"]);
977        assert_eq!(tokens("Ć©\t\tšŸ˜€"), ["Ć©", "<tab>", "<tab>", "šŸ˜€"]);
978        assert!(tokens("").is_empty());
979    }
980}