Skip to main content

lexical_ui/
caret_utils.rs

1//! `caret/LexicalCaretUtils.ts`: carets from selection points and back,
2//! normalization, and removing the text and nodes of a caret range.
3//!
4//! The text edit log is not ported, so the parts of
5//! `$removeTextFromCaretRange` that record deletions do
6//! nothing here; a segmented node made plain text carries its NodeState
7//! (`$carryNodeState`) as in JS.
8
9use crate::LexicalError;
10use crate::caret::{
11    CaretDirection, CaretRange, CommonAncestorResult, NodeCaret, PointCaret, RootMode,
12    SiblingCaret, TextOffset, TextPointCaretSlice, compare_point_caret_next, flip_direction,
13    get_adjacent_child_caret, get_caret_in_direction, get_caret_range, get_child_caret,
14    get_collapsed_caret_range, get_common_ancestor, get_sibling_caret, get_text_node_offset,
15    get_text_point_caret, get_text_point_caret_at_end,
16};
17use crate::error::invariant;
18use crate::lexical_selection::{
19    Point, PointType, RangeSelection, SelectionRef, Which, create_range_selection, get_selection,
20    set_selection,
21};
22use crate::lexical_utils::{
23    copy_node, get_node_by_key_or_throw, get_root, is_block, is_shadow_root_node,
24    remove_from_parent, restore_empty_container_paragraph,
25};
26use crate::node::{NodeKey, NodeRef};
27use crate::node_state::carry_node_state;
28use crate::nodes::element::is_root_or_shadow_root;
29use crate::nodes::paragraph::create_paragraph_node;
30use crate::nodes::text::create_text_node;
31use crate::selection_insert_nodes::is_block_container;
32use std::collections::HashSet;
33
34/// `$caretFromPoint(point, direction)`: the caret at a selection point.
35pub fn caret_from_point(
36    point: &Point,
37    direction: CaretDirection,
38) -> Result<PointCaret, LexicalError> {
39    let node = get_node_by_key_or_throw(&point.key)?;
40    if point.point_type == PointType::Text {
41        invariant!(
42            node.is_text(),
43            "$caretFromPoint: Node with type {} and key {} that does not inherit from TextNode encountered for text point",
44            node.get_type(),
45            point.key
46        );
47        return get_text_point_caret(&node, direction, point.offset);
48    }
49    invariant!(
50        node.is_element(),
51        "$caretFromPoint: Node with type {} and key {} that does not inherit from ElementNode encountered for element point",
52        node.get_type(),
53        point.key
54    );
55    Ok(get_child_caret_at_index(&node, point.offset, direction))
56}
57
58/// `$setPointFromCaret(point, caret)`: sets the point `which` of a range
59/// selection to the caret's position.
60pub fn set_point_from_caret(
61    selection: &SelectionRef,
62    which: Which,
63    caret: &PointCaret,
64) -> Result<(), LexicalError> {
65    let origin = caret.origin();
66    let direction = caret.direction();
67    let is_next = direction == CaretDirection::Next;
68    if let Some(offset) = caret.offset() {
69        selection.point_set(which, origin.get_key(), offset, PointType::Text)
70    } else if caret.is_sibling_caret() {
71        if origin.is_text() {
72            let offset = get_text_node_offset(origin, direction.into(), false)?;
73            selection.point_set(which, origin.get_key(), offset, PointType::Text)
74        } else {
75            let parent = origin.get_parent_or_throw()?;
76            let index = origin
77                .get_index_within_parent()
78                .expect("a child of its parent");
79            selection.point_set(
80                which,
81                parent.get_key(),
82                index + usize::from(is_next),
83                PointType::Element,
84            )
85        }
86    } else {
87        assert!(
88            caret.is_child_caret() && origin.is_element(),
89            "$setPointFromCaret: exhaustiveness check"
90        );
91        let offset = if is_next {
92            0
93        } else {
94            origin.get_children_size()
95        };
96        selection.point_set(which, origin.get_key(), offset, PointType::Element)
97    }
98}
99
100/// `$setSelectionFromCaretRange(caretRange)`: sets the editor's range
101/// selection (the current one, or a new one) to the range, and returns it.
102pub fn set_selection_from_caret_range(
103    caret_range: &CaretRange,
104) -> Result<SelectionRef, LexicalError> {
105    let selection = get_selection()
106        .filter(SelectionRef::is_range)
107        .unwrap_or_else(create_range_selection);
108    update_range_selection_from_caret_range(&selection, caret_range)?;
109    set_selection(Some(selection.clone()));
110    Ok(selection)
111}
112
113/// `$updateRangeSelectionFromCaretRange(selection, caretRange)`.
114pub fn update_range_selection_from_caret_range(
115    selection: &SelectionRef,
116    caret_range: &CaretRange,
117) -> Result<(), LexicalError> {
118    set_point_from_caret(selection, Which::Anchor, &caret_range.anchor)?;
119    set_point_from_caret(selection, Which::Focus, &caret_range.focus)
120}
121
122/// `$caretRangeFromSelection(selection)`: the carets of a range selection,
123/// in the `previous` direction when the focus is before the anchor.
124pub fn caret_range_from_selection(selection: &RangeSelection) -> Result<CaretRange, LexicalError> {
125    let anchor_caret = caret_from_point(&selection.anchor, CaretDirection::Next)?;
126    let focus_caret = caret_from_point(&selection.focus, CaretDirection::Next)?;
127    let direction = if compare_point_caret_next(&anchor_caret, &focus_caret)?.is_le() {
128        CaretDirection::Next
129    } else {
130        CaretDirection::Previous
131    };
132    get_caret_range(
133        get_caret_in_direction(&anchor_caret, direction)?,
134        get_caret_in_direction(&focus_caret, direction)?,
135    )
136}
137
138/// `$rewindSiblingCaret(caret)`: the caret, in the same direction, whose
139/// adjacent caret is `caret`.
140pub fn rewind_sibling_caret(caret: &SiblingCaret) -> Result<NodeCaret, LexicalError> {
141    let direction = caret.direction();
142    let origin = caret.origin();
143    // Rotate the direction around the origin and get the adjacent node
144    let rewind_origin = get_sibling_caret(origin, flip_direction(direction)).get_node_at_caret();
145    Ok(match rewind_origin {
146        Some(rewind_origin) => get_sibling_caret(&rewind_origin, direction),
147        None => get_child_caret(&origin.get_parent_or_throw()?, direction)
148            .expect("a parent is an element"),
149    })
150}
151
152/// `$getAnchorCandidates(anchor, rootMode)`: the anchor, the caret pointing
153/// to it, and those pointing to each of its parents.
154fn get_anchor_candidates(
155    anchor: &PointCaret,
156    root_mode: RootMode,
157) -> Result<Vec<PointCaret>, LexicalError> {
158    // These candidates will be the anchor itself, the pointer to the anchor
159    // (if different), and then any parents of that
160    let mut carets = vec![anchor.clone()];
161    let mut parent = if anchor.is_child_caret() {
162        anchor.get_parent_caret(root_mode)
163    } else {
164        Some(anchor.get_sibling_caret())
165    };
166    while let Some(p) = parent {
167        carets.push(rewind_sibling_caret(&p)?);
168        parent = p.get_parent_caret(root_mode);
169    }
170    Ok(carets)
171}
172
173/// `$isCaretAttached(caret)`.
174fn is_caret_attached(caret: &PointCaret) -> bool {
175    caret.origin().is_attached()
176}
177
178/// The `sliceMode` of [`remove_text_from_caret_range`].
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub enum SliceMode {
181    /// `'removeEmptySlices'`: a text node whose text is all removed is
182    /// removed.
183    #[default]
184    RemoveEmptySlices,
185    /// `'preserveEmptyTextSliceCaret'`: the first such text node is kept,
186    /// empty, for an insertion.
187    PreserveEmptyTextSliceCaret,
188}
189
190/// `$removeTextFromCaretRange(initialRange, sliceMode)`: removes the text
191/// and nodes in the range, merging the rest of the later block into the
192/// earlier one when the range spans blocks. Returns the collapsed range
193/// where the removal was, in the initial range's direction.
194pub fn remove_text_from_caret_range(
195    initial_range: &CaretRange,
196    slice_mode: SliceMode,
197) -> Result<CaretRange, LexicalError> {
198    if initial_range.is_collapsed() {
199        return Ok(initial_range.clone());
200    }
201    // Always process removals in document order
202    let root_mode = RootMode::Root;
203    let next_direction = CaretDirection::Next;
204    let mut slice_state = slice_mode;
205    let range = get_caret_range_in_direction(initial_range, next_direction)?;
206
207    // The nearest root or shadow root the removal happens inside, captured
208    // before anything is detached; see the repair below.
209    let mut range_container = Some(range.anchor.origin().clone());
210    while let Some(container) = range_container
211        .as_ref()
212        .filter(|c| !is_root_or_shadow_root(&*c.get_latest()))
213    {
214        range_container = container.get_parent();
215    }
216    // A child of the container, sampled while it still has one: it is what
217    // tells $restoreEmptyContainerParagraph whether this container holds
218    // blocks (a table cell) or structure (a table's rows).
219    let range_container_child = range_container
220        .as_ref()
221        .filter(|c| c.is_element())
222        .and_then(NodeRef::get_first_child);
223
224    let mut anchor_candidates = get_anchor_candidates(&range.anchor, root_mode)?;
225    let mut focus_candidates = get_anchor_candidates(&range.focus.get_flipped()?, root_mode)?;
226
227    // Mark the start of each ElementNode
228    let mut seen_start: HashSet<NodeKey> = HashSet::new();
229    // Queue removals to avoid mutating the tree during iteration
230    let mut removed_nodes: Vec<NodeRef> = Vec::new();
231    for caret in range.iter_node_carets(root_mode) {
232        if caret.is_child_caret() {
233            seen_start.insert(caret.origin().get_key().to_owned());
234        } else if caret.is_sibling_caret() {
235            let origin = caret.origin();
236            if !origin.is_element() || seen_start.contains(origin.get_key()) {
237                removed_nodes.push(origin.clone());
238            }
239        }
240    }
241    // Selection is rebuilt from anchor/focus candidates below, so detach
242    // without restoring it for every removed node.
243    let mut removed_parents: Vec<NodeRef> = Vec::new();
244    for node in &removed_nodes {
245        // Track parents not in seenStart — those in seenStart are traversal
246        // boundaries handled by block-merge logic below.
247        if let Some(parent) = node.get_parent()
248            && !seen_start.contains(parent.get_key())
249            && !removed_parents.contains(&parent)
250        {
251            removed_parents.push(parent);
252        }
253        // `$recordDeleted(node)`: the text edit log isn't ported.
254        remove_from_parent(node)?;
255    }
256    // Remove inline wrappers (canBeEmpty=false) that became empty
257    for parent in &removed_parents {
258        if !parent.can_be_empty()
259            && !is_root_or_shadow_root(&*parent.get_latest())
260            && parent.is_empty()
261            && parent.is_attached()
262        {
263            parent.remove(false)?;
264        }
265    }
266
267    // Splice text at the anchor and/or origin.
268    // If the text is entirely selected then it is removed (unless it is the
269    // first slice and sliceMode is preserveEmptyTextSliceCaret).
270    // If it's a token with a non-empty selection then it is removed.
271    // Segmented nodes will be copied to a plain text node with the same
272    // format and style and set to normal mode.
273    for slice in range.get_text_slices().into_iter().flatten() {
274        let origin = slice.caret.origin().clone();
275        let content_size = origin.get_text_content_size();
276        let caret_before = rewind_sibling_caret(&get_sibling_caret(&origin, next_direction))?;
277        let mode = origin.text_data().get_mode();
278        if (slice.distance.unsigned_abs() == content_size
279            && slice_state == SliceMode::RemoveEmptySlices)
280            || (mode == "token" && slice.distance != 0)
281        {
282            // anchorCandidates[1] should still be valid, it is caretBefore
283            caret_before.remove()?;
284        } else if slice.distance != 0 {
285            slice_state = SliceMode::RemoveEmptySlices;
286            let mut next_caret = slice.remove_text_slice()?;
287            let slice_origin = slice.caret.origin();
288            if mode == "segmented" {
289                let src = next_caret.origin().clone();
290                let data = src.text_data();
291                let plain_text_node = create_text_node(data.get_text());
292                plain_text_node.set_style(data.get_style());
293                plain_text_node.set_format(data.get_format());
294                plain_text_node.set_detail(data.get_detail())?;
295                // The characters left keep their NodeState (comment ids,
296                // for example)
297                carry_node_state(&src, &plain_text_node)?;
298                caret_before.replace_or_insert(&plain_text_node, false)?;
299                next_caret = get_text_point_caret(
300                    &plain_text_node,
301                    next_direction,
302                    next_caret.offset().expect("a text point caret"),
303                )?;
304            }
305            if slice_origin == anchor_candidates[0].origin() {
306                anchor_candidates[0] = next_caret.clone();
307            }
308            if slice_origin == focus_candidates[0].origin() {
309                focus_candidates[0] = next_caret.get_flipped()?;
310            }
311        }
312    }
313
314    // Find the deepest anchor and focus candidates that are still attached
315    let anchor_candidate = get_attached_caret(anchor_candidates.iter());
316    let focus_candidate = get_attached_caret(focus_candidates.iter());
317
318    // Merge blocks if necessary
319    let merge_targets = get_block_merge_targets(
320        anchor_candidate.as_ref(),
321        focus_candidate.as_ref(),
322        &seen_start,
323    );
324    if let Some((anchor_block, focus_block)) = merge_targets {
325        // always merge blocks later in the document with blocks earlier in
326        // the document
327        get_child_caret(&anchor_block, CaretDirection::Previous)
328            .expect("a block is an element")
329            .splice(0, &focus_block.get_children(), CaretDirection::Next)?;
330        // remove empty parent node even if parent node is canBeEmpty
331        let mut parent = focus_block.get_parent();
332        focus_block.remove(true)?;
333        while let Some(p) = parent.filter(NodeRef::is_empty) {
334            parent = p.get_parent();
335            p.remove(true)?;
336        }
337    } else if let Some(focus_candidate) = &focus_candidate {
338        let focus_block = get_block_from_caret(focus_candidate);
339        let focus_block_parent = focus_block.as_ref().and_then(NodeRef::get_parent);
340        let topmost_shadow_root = focus_block
341            .as_ref()
342            .and_then(|b| b.get_parents().into_iter().rev().find(is_shadow_root_node));
343        if let (Some(focus_block), Some(focus_block_parent)) = (&focus_block, &focus_block_parent)
344            && !focus_block_parent.is_root()
345            && focus_block.is_empty()
346            && seen_start.contains(focus_block.get_key())
347            && crate::slot::get_slot_names(focus_block).is_empty()
348            && topmost_shadow_root.is_none_or(|r| seen_start.contains(r.get_key()))
349        {
350            focus_block.remove(true)?;
351            let mut parent = Some(focus_block_parent.clone());
352            while let Some(p) = parent.filter(|p| !p.is_root() && p.is_empty()) {
353                let grandparent = p.get_parent();
354                if let Some(g) = &grandparent
355                    && g.is_root()
356                    && g.get_children_size() <= 1
357                    // Only keep the root's last child when it is valid while
358                    // empty. One that declares `canBeEmpty()` false is
359                    // removed like any other emptied ancestor, and the empty
360                    // root is repaired below.
361                    && p.can_be_empty()
362                {
363                    break;
364                }
365                parent = grandparent;
366                p.remove(true)?;
367            }
368        }
369    }
370
371    // A range that covers every child of its container (a select-all over a
372    // document that is a single shadow root, or over everything inside one)
373    // removes them all and leaves nothing to put a caret in. Restore the
374    // empty paragraph the container would otherwise be missing, so that
375    // deleting all of a container's content behaves like deleting a document
376    // made of ordinary paragraphs. The range is always attached (the
377    // candidate walk above throws otherwise), so an empty container here is
378    // always this call's doing. `rangeContainer` is itself removed when the
379    // range covered it — the empty-ancestor walks above climb out of it — in
380    // which case the root is what needs the paragraph.
381    if restore_empty_container_paragraph(range_container.as_ref(), range_container_child.as_ref())?
382        .is_none()
383        && range_container.as_ref().is_some_and(|c| !c.is_attached())
384    {
385        restore_empty_container_paragraph(Some(&get_root()), None)?;
386    }
387
388    // note this caret can be in either direction
389    let best_candidate = get_attached_caret(
390        anchor_candidate
391            .iter()
392            .chain(&focus_candidate)
393            .chain(&anchor_candidates)
394            .chain(&focus_candidates),
395    );
396    if let Some(best_candidate) = best_candidate {
397        let anchor = get_caret_in_direction(&best_candidate, initial_range.direction())?;
398        return Ok(get_collapsed_caret_range(anchor));
399    }
400    let keys: Vec<String> = anchor_candidates
401        .iter()
402        .map(|c| format!("\"{}\"", c.origin().get_key()))
403        .collect();
404    Err(LexicalError::new(format!(
405        "$removeTextFromCaretRange: selection was lost, could not find a new anchor given candidates with keys: [{}]",
406        keys.join(",")
407    )))
408}
409
410/// `$getAttachedCaret(candidates)`: the first candidate still attached,
411/// normalized.
412fn get_attached_caret<'a>(
413    mut candidates: impl Iterator<Item = &'a PointCaret>,
414) -> Option<PointCaret> {
415    candidates
416        .find(|c| is_caret_attached(c))
417        .map(normalize_caret)
418}
419
420/// `$getBlockFromCaret(caret)`.
421fn get_block_from_caret(caret: &PointCaret) -> Option<NodeRef> {
422    if caret.is_child_caret() {
423        let origin = caret.origin();
424        is_block(origin).then(|| origin.clone())
425    } else {
426        caret.get_parent_at_caret().filter(is_block)
427    }
428}
429
430/// `$getBlockMergeTargets(anchor, focus, seenStart)`: the blocks closest to
431/// the common ancestor of the anchor's and the focus's parents, if they are
432/// distinct and no shadow root lies between them and their carets.
433fn get_block_merge_targets(
434    anchor: Option<&PointCaret>,
435    focus: Option<&PointCaret>,
436    seen_start: &HashSet<NodeKey>,
437) -> Option<(NodeRef, NodeRef)> {
438    let anchor_parent = anchor?.get_parent_at_caret()?;
439    let focus_parent = focus?.get_parent_at_caret()?;
440    let common = get_common_ancestor(&anchor_parent, &focus_parent)?;
441    if !matches!(common, CommonAncestorResult::Branch { .. }) {
442        return None;
443    }
444    let get_block = |parent: &NodeRef, selected_only: bool| -> Option<NodeRef> {
445        let mut block = None;
446        // Ascend to the common ancestor, retaining the outermost eligible
447        // block and rejecting any branch that crosses a shadow root.
448        let mut node = Some(parent.clone());
449        while let Some(n) = node.filter(|n| n != common.common_ancestor()) {
450            if is_root_or_shadow_root(&*n.get_latest()) {
451                return None;
452            }
453            if (!selected_only || seen_start.contains(n.get_key())) && is_block(&n) {
454                block = Some(n.clone());
455            }
456            node = n.get_parent();
457        }
458        block
459    };
460    let anchor_block = get_block(&anchor_parent, false)?;
461    let focus_block = get_block(&focus_parent, true)?;
462    // Removing a host must not silently discard its slots during a block
463    // merge.
464    crate::slot::get_slot_names(&focus_block)
465        .is_empty()
466        .then_some((anchor_block, focus_block))
467}
468
469/// `$getDeepestChildOrSelf(initialCaret)`: the deepest child caret under
470/// the caret's origin, or the caret.
471fn get_deepest_child_or_self(initial_caret: PointCaret) -> PointCaret {
472    let mut caret = initial_caret;
473    while caret.is_child_caret() {
474        match get_adjacent_child_caret(Some(&caret)) {
475            Some(adjacent) if adjacent.is_child_caret() => caret = adjacent,
476            _ => break,
477        }
478    }
479    caret
480}
481
482/// `$normalizeCaret(initialCaret)`: the deepest equivalent caret, a text
483/// point caret when there is text at the caret.
484pub fn normalize_caret(initial_caret: &PointCaret) -> PointCaret {
485    let caret = get_deepest_child_or_self(initial_caret.get_latest());
486    let direction = caret.direction();
487    if caret.origin().is_text() {
488        return if caret.is_text_point_caret() {
489            caret
490        } else {
491            get_text_point_caret_at_end(caret.origin(), direction, direction)
492        };
493    }
494    match caret.get_adjacent_caret() {
495        Some(adj) if adj.is_sibling_caret() && adj.origin().is_text() => {
496            get_text_point_caret_at_end(adj.origin(), direction, flip_direction(direction))
497        }
498        _ => caret,
499    }
500}
501
502/// `$isExtendableTextPointCaret(caret)`: a text point caret whose offset
503/// can move further in its direction without leaving the node.
504pub fn is_extendable_text_point_caret(caret: &PointCaret) -> bool {
505    caret.offset().is_some_and(|offset| {
506        get_text_node_offset(caret.origin(), TextOffset::End(caret.direction()), false)
507            .is_ok_and(|end| offset != end)
508    })
509}
510
511/// `$getCaretRangeInDirection(range, direction)`: the range, or the same
512/// part of the document iterated the other way.
513pub fn get_caret_range_in_direction(
514    range: &CaretRange,
515    direction: CaretDirection,
516) -> Result<CaretRange, LexicalError> {
517    if range.direction() == direction {
518        return Ok(range.clone());
519    }
520    get_caret_range(
521        // focus and anchor get flipped here
522        get_caret_in_direction(&range.focus, direction)?,
523        get_caret_in_direction(&range.anchor, direction)?,
524    )
525}
526
527/// `$getChildCaretAtIndex(parent, index, direction)`: a caret pointing to
528/// the child at `index`, or the last caret in `parent` past the end.
529pub fn get_child_caret_at_index(
530    parent: &NodeRef,
531    index: usize,
532    direction: CaretDirection,
533) -> NodeCaret {
534    let size = parent.get_children_size();
535    let offset = index.min(size);
536    let origin = match direction {
537        CaretDirection::Next => offset.checked_sub(1),
538        CaretDirection::Previous => Some(offset),
539    }
540    .filter(|&i| i < size)
541    .and_then(|i| parent.get_child_at_index(i));
542    match origin {
543        Some(origin) => get_sibling_caret(&origin, direction),
544        None => get_child_caret(parent, direction).expect("a parent is an element"),
545    }
546}
547
548/// `$getAdjacentSiblingOrParentSiblingCaret(startCaret, rootMode)`: the
549/// next caret in a depth first walk that doesn't descend into the start,
550/// with the change in depth.
551pub fn get_adjacent_sibling_or_parent_sibling_caret(
552    start_caret: &NodeCaret,
553    root_mode: RootMode,
554) -> Option<(NodeCaret, isize)> {
555    let mut depth_diff = 0;
556    let mut caret = start_caret.clone();
557    let mut next_caret = get_adjacent_child_caret(Some(&caret));
558    while next_caret.is_none() {
559        depth_diff -= 1;
560        caret = caret.get_parent_caret(root_mode)?;
561        next_caret = get_adjacent_child_caret(Some(&caret));
562    }
563    next_caret.map(|c| (c, depth_diff))
564}
565
566/// `$getTextPointCaretSliceForNode(slices, node)`: the slice of `node`
567/// among a caret range's text slices.
568pub fn get_text_point_caret_slice_for_node<'a>(
569    slices: &'a [Option<TextPointCaretSlice>],
570    node: &NodeRef,
571) -> Option<&'a TextPointCaretSlice> {
572    slices
573        .iter()
574        .flatten()
575        .find(|slice| slice.caret.origin() == node)
576}
577
578/// `$splitTextPointCaret(textPointCaret)`: splits the text at the caret, and
579/// returns the sibling caret between the two halves (or beside the text, at
580/// either end).
581pub fn split_text_point_caret(text_point_caret: &PointCaret) -> Result<NodeCaret, LexicalError> {
582    let origin = text_point_caret.origin();
583    let direction = text_point_caret.direction();
584    let offset = text_point_caret.offset().expect("a text point caret");
585    if offset == get_text_node_offset(origin, TextOffset::End(direction), false)? {
586        return Ok(text_point_caret.get_sibling_caret());
587    } else if offset
588        == get_text_node_offset(origin, TextOffset::End(flip_direction(direction)), false)?
589    {
590        return rewind_sibling_caret(&text_point_caret.get_sibling_caret());
591    }
592    let parts = origin.split_text(&[offset as i64])?;
593    let text_node = parts.first().filter(|n| n.is_text()).ok_or_else(|| {
594        LexicalError::new("$splitTextPointCaret: splitText must return at least one TextNode")
595    })?;
596    get_caret_in_direction(
597        &get_sibling_caret(text_node, CaretDirection::Next),
598        direction,
599    )
600}
601
602/// `SplitAtPointCaretNextOptions`. `$copyElementNode` and
603/// `$splitTextPointCaretNext` are always their defaults (`$copyNode` and
604/// [`split_text_point_caret`]).
605#[derive(Clone, Copy)]
606pub struct SplitAtPointCaretNextOptions {
607    /// If the parent matches `root_mode` a split will not occur (default
608    /// `'shadowRoot'`).
609    pub root_mode: RootMode,
610    /// `$shouldSplit(node, edge)`, with `edge` `"first"` or `"last"`: whether
611    /// to create an empty split of an element that can be empty (default
612    /// always).
613    pub should_split: fn(&NodeRef, &'static str) -> bool,
614    /// If the destination would create an empty split on both sides, then
615    /// remove it instead of splitting (default `false`).
616    pub remove_empty_destination: bool,
617}
618
619impl Default for SplitAtPointCaretNextOptions {
620    fn default() -> Self {
621        Self {
622            root_mode: RootMode::ShadowRoot,
623            should_split: |_, _| true,
624            remove_empty_destination: false,
625        }
626    }
627}
628
629/// `$getAdjacentNodes(initialCaret)`: the nodes after the caret, in its
630/// direction.
631pub(crate) fn get_adjacent_nodes(initial_caret: &NodeCaret) -> Vec<NodeRef> {
632    let next = initial_caret.direction() == CaretDirection::Next;
633    let mut siblings = Vec::new();
634    let mut node = initial_caret.get_node_at_caret();
635    while let Some(n) = node {
636        node = if next {
637            n.get_next_sibling()
638        } else {
639            n.get_previous_sibling()
640        };
641        siblings.push(n);
642    }
643    siblings
644}
645
646/// `$splitAtPointCaretNext(pointCaret, options)`: splits the node at the
647/// caret once, and returns the caret where it split, or `None` where it
648/// can't.
649pub fn split_at_point_caret_next(
650    point_caret: &PointCaret,
651    options: &SplitAtPointCaretNextOptions,
652) -> Result<Option<NodeCaret>, LexicalError> {
653    if point_caret.is_text_point_caret() {
654        return split_text_point_caret(point_caret).map(Some);
655    }
656    let parent_caret = point_caret.get_parent_caret(options.root_mode);
657    if let Some(parent_caret) = &parent_caret {
658        let origin = parent_caret.origin();
659        if point_caret.is_child_caret() {
660            let before_parent_caret = rewind_sibling_caret(parent_caret)?;
661            if options.remove_empty_destination && origin.is_empty() {
662                origin.remove(false)?;
663                return Ok(Some(before_parent_caret));
664            }
665            if !(origin.can_be_empty() && (options.should_split)(origin, "first")) {
666                return Ok(Some(before_parent_caret));
667            }
668        }
669        let siblings = get_adjacent_nodes(point_caret);
670        if !siblings.is_empty()
671            || (!options.remove_empty_destination
672                && origin.can_be_empty()
673                && (options.should_split)(origin, "last"))
674        {
675            // Split and insert the siblings into the new tree
676            let copy = copy_node(origin);
677            copy.splice(0, 0, &siblings)?;
678            parent_caret.insert(&copy)?;
679        }
680    }
681    Ok(parent_caret)
682}
683
684/// `$insertNodeToNearestRootAtCaret(node, caret, options)`: inserts `node`
685/// at the caret, splitting its ancestors up to the nearest block container
686/// (the root or a shadow root, with the default `root_mode`), and returns
687/// the caret after it.
688pub fn insert_node_to_nearest_root_at_caret(
689    node: &NodeRef,
690    caret: &PointCaret,
691    options: &SplitAtPointCaretNextOptions,
692) -> Result<NodeCaret, LexicalError> {
693    let mut insert_caret = get_caret_in_direction(caret, CaretDirection::Next)?;
694    // Normalize boundary cases for TextPointCaret
695    if let Some(offset) = insert_caret.offset() {
696        let origin = insert_caret.origin().clone();
697        if offset == 0 {
698            insert_caret = get_sibling_caret(&origin, CaretDirection::Previous).get_flipped()?;
699        } else if offset == origin.get_text_content_size() {
700            insert_caret = get_sibling_caret(&origin, CaretDirection::Next);
701        }
702    }
703    // Make sure we have a distinct node as the origin
704    if insert_caret.origin() == node {
705        invariant!(
706            insert_caret.is_sibling_caret(),
707            "$insertNodeToNearestRootAtCaret node {} of type {} can not be inserted into itself",
708            node.get_key(),
709            node.get_type()
710        );
711        insert_caret = rewind_sibling_caret(&insert_caret)?;
712    }
713    // Handle split boundary conditions where node is being inserted adjacent
714    // to itself
715    if insert_caret.get_node_at_caret().as_ref() == Some(node)
716        || insert_caret.get_flipped()?.get_node_at_caret().as_ref() == Some(node)
717    {
718        node.remove(true)?;
719    }
720    let stops_at_containers = options.root_mode == RootMode::ShadowRoot;
721    let mut next_caret = Some(insert_caret.clone());
722    while let Some(caret) = next_caret {
723        insert_caret = caret;
724        // A declared block container (see $isBlockContainer) is not split:
725        // the node goes in among its blocks, as in a shadow root.
726        let container = if insert_caret.is_child_caret() {
727            Some(insert_caret.origin().clone())
728        } else {
729            insert_caret.origin().get_parent()
730        };
731        if stops_at_containers
732            && !insert_caret.is_text_point_caret()
733            && container.as_ref().is_some_and(is_block_container)
734        {
735            break;
736        }
737        next_caret = split_at_point_caret_next(&insert_caret, options)?;
738    }
739    invariant!(
740        !insert_caret.is_text_point_caret(),
741        "$insertNodeToNearestRootAtCaret: An unattached TextNode can not be split"
742    );
743    if node.is_inline() {
744        let paragraph = create_paragraph_node();
745        paragraph.append(std::slice::from_ref(node))?;
746        insert_caret.insert(&paragraph)?;
747    } else {
748        insert_caret.insert(node)?;
749    }
750    get_caret_in_direction(
751        &get_sibling_caret(node, CaretDirection::Next),
752        caret.direction(),
753    )
754}