Skip to main content

lexical_ui/
selection_deletion.rs

1//! `deleteCharacter`, `deleteWord`, `deleteLine` and `modify` from
2//! `LexicalSelection.ts`.
3//!
4//! JS measures how far a deletion or a caret movement reaches inside text
5//! with the DOM's `Selection.modify` (`$extendSelectionForDeletion`,
6//! `modify`), after `$modifySelectionAroundDecoratorsAndBlocks` has resolved
7//! the moves that cross blocks in the model. That measurement starts with
8//! `getWindow(editor)`, which throws `window object not found` for an editor
9//! without a root element, so a headless JS editor fails the update whenever
10//! a deletion or `modify` needs it: within text, at a text node edge with a
11//! sibling in the deletion direction, and at the edges of the document.
12//! Only the model paths (merging blocks, removing a line break or an empty
13//! block, removing an expanded selection) succeed.
14//!
15//! An editor with a [`SelectionMovement`]
16//! ([`Editor::set_selection_movement`](crate::Editor::set_selection_movement))
17//! stands in for `Selection.modify`: it says where the caret lands, and the
18//! rest follows JS from there. The DOM points JS resolves back into the model
19//! (`applyDOMRange`) are model points here already, so only the model side
20//! of that resolution is ported. Without one, this port throws where
21//! headless JS does.
22//!
23//! Shadow roots other than the root are not ported, so the branches for
24//! them are no-ops (each is noted where JS has it), as are the parts that
25//! read a decorator's DOM. Slot boundaries are kept, the stop where the
26//! movement lands in another slot frame included.
27
28use crate::LexicalError;
29use crate::caret::{
30    CaretDirection, CaretRange, NodeCaret, PointCaret, RootMode, compare_point_caret_next,
31    extend_caret_to_range, get_caret_in_direction, get_caret_range, get_child_caret,
32    get_sibling_caret,
33};
34use crate::caret_utils::{
35    caret_from_point, caret_range_from_selection, get_caret_range_in_direction,
36    is_extendable_text_point_caret, normalize_caret, rewind_sibling_caret, set_point_from_caret,
37    set_selection_from_caret_range, update_range_selection_from_caret_range,
38};
39use crate::error::invariant;
40use crate::lexical_selection::{
41    Point, PointType, RangeSelection, SelectionRef, Which, create_node_selection, get_selection,
42    set_selection,
43};
44use crate::lexical_utils::{
45    get_root, is_block, is_shadow_root_node, restore_empty_container_paragraph,
46};
47use crate::node::NodeRef;
48use crate::nodes::element::is_root_or_shadow_root;
49use crate::nodes::line_break::LineBreakNode;
50use crate::nodes::paragraph::create_paragraph_node;
51use crate::selection_insert_nodes::{get_previous_selection, normalize_selection};
52use crate::updates::get_active_editor;
53use crate::utf16;
54use std::rc::Rc;
55
56/// `'character'`, `'word'`, `'line'` or `'lineboundary'`.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum SelectionGranularity {
59    Character,
60    Word,
61    Line,
62    LineBoundary,
63}
64
65/// `'move'` or `'extend'`.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum SelectionAlter {
68    Move,
69    Extend,
70}
71
72/// Where a caret lands when it moves one unit, which only text layout knows
73/// (the DOM's `Selection.modify` in JS). Called inside an update or read, so
74/// it can read nodes.
75pub trait SelectionMovement {
76    /// The point one `granularity` unit before (`is_backward`) or after
77    /// `from`, or `None` when it can't move.
78    fn landed_point(
79        &self,
80        from: &Point,
81        is_backward: bool,
82        granularity: SelectionGranularity,
83    ) -> Result<Option<Point>, LexicalError>;
84
85    /// Whether the window gives a DOM selection to measure with
86    /// (`getDOMSelection(getWindow(editor))` is not null). Where it gives
87    /// none, as in a window installed after Lexical loaded (the upstream
88    /// unit tests install jsdom's that way, so `CAN_USE_DOM` is false),
89    /// `$extendSelectionForDeletion` and `modify` stop after their model
90    /// step and leave the selection as it left it, and `landed_point` is
91    /// never asked. True by default.
92    fn has_dom_selection(&self) -> bool {
93        true
94    }
95}
96
97/// `deleteCharacter`'s scan for a block to merge with.
98enum MergeState {
99    /// `{type: 'initial'}`.
100    Initial,
101    /// `{type: 'merge-next-block', block}`.
102    MergeNextBlock(NodeRef),
103    /// `{type: 'merge-block', caret, block}`.
104    MergeBlock { caret: NodeCaret, block: NodeRef },
105}
106
107fn direction(is_backward: bool) -> CaretDirection {
108    if is_backward {
109        CaretDirection::Previous
110    } else {
111        CaretDirection::Next
112    }
113}
114
115impl SelectionRef {
116    /// `selection.deleteCharacter(isBackward)`: deletes one character, or
117    /// the selected content, and handles the boundaries of blocks.
118    pub fn delete_character(&self, is_backward: bool) -> Result<(), LexicalError> {
119        let Some(range) = self.range() else {
120            return Ok(());
121        };
122        let was_collapsed = range.is_collapsed();
123        if was_collapsed {
124            let anchor = range.anchor.clone();
125            let anchor_node = anchor.get_node()?;
126            if forward_deletion(&anchor, &anchor_node, is_backward) {
127                // Forward deletion stops at an adjacent shadow root, unless
128                // the anchor block is empty and the shadow root is its next
129                // sibling: the caret walk below then removes the empty block
130                // (#8075).
131                let next_sibling = if anchor_node.is_element() {
132                    anchor_node.get_next_sibling()
133                } else {
134                    None
135                };
136                if !(anchor_node.is_element()
137                    && anchor_node.is_empty()
138                    && next_sibling.is_some_and(|n| is_shadow_root_node(&n)))
139                {
140                    return Ok(());
141                }
142            }
143            let direction = direction(is_backward);
144            let initial_caret = caret_from_point(&anchor, direction)?;
145            let initial_range = extend_caret_to_range(&initial_caret)?;
146            if initial_range
147                .get_text_slices()
148                .iter()
149                .all(|slice| slice.as_ref().is_none_or(|s| s.distance == 0))
150            {
151                // The caret is an element point beside a node that renders a
152                // block cursor: the keystroke deletes that node.
153                if anchor.point_type == PointType::Element
154                    && let Some(adjacent) = initial_caret.get_node_at_caret()
155                    && adjacent.is_element()
156                    && needs_block_cursor_beside(&adjacent)
157                {
158                    let container = adjacent.get_parent();
159                    adjacent.remove(false)?;
160                    if let Some(restored) =
161                        restore_empty_container_paragraph(container.as_ref(), Some(&adjacent))?
162                    {
163                        restored.select_start()?;
164                    }
165                    return Ok(());
166                }
167                // There's no text in the direction of the deletion so we can
168                // explore our options.
169                let anchor_origin = initial_range.anchor.origin().clone();
170                let mut state = MergeState::Initial;
171                for caret in initial_range.iter_node_carets(RootMode::ShadowRoot) {
172                    let origin = caret.origin().clone();
173                    if caret.is_child_caret() {
174                        if origin.is_inline() {
175                            // fall through when descending an inline
176                        } else if origin.get_latest().is_shadow_root() {
177                            if matches!(state, MergeState::MergeBlock { .. }) {
178                                break;
179                            }
180                            // Don't merge with a shadow root block.
181                            if anchor_origin.is_element() && anchor_origin.is_empty() {
182                                // delete an empty paragraph like the
183                                // DecoratorNode case
184                                let norm_caret = normalize_caret(&caret);
185                                update_range_selection_from_caret_range(
186                                    self,
187                                    &get_caret_range(norm_caret.clone(), norm_caret)?,
188                                )?;
189                                anchor_origin.remove(false)?;
190                            }
191                            return Ok(());
192                        } else if let MergeState::MergeNextBlock(block)
193                        | MergeState::MergeBlock { block, .. } = &state
194                        {
195                            // Keep descending ChildCaret to find which block
196                            // to merge with.
197                            state = MergeState::MergeBlock {
198                                block: block.clone(),
199                                caret: caret.clone(),
200                            };
201                        }
202                    } else if matches!(state, MergeState::MergeBlock { .. }) {
203                        break;
204                    } else {
205                        if origin.is_element() {
206                            if !origin.is_inline() {
207                                state = MergeState::MergeNextBlock(origin);
208                            } else if !is_parent_of(&origin, &anchor_origin) {
209                                break;
210                            }
211                            continue;
212                        }
213                        if origin.is_decorator() {
214                            if origin.is_isolated() {
215                                // do nothing, shouldn't delete an isolated
216                                // decorator
217                            } else if matches!(state, MergeState::MergeNextBlock(_))
218                                && (origin.is_keyboard_selectable() || !origin.is_inline())
219                                && anchor_origin.is_element()
220                                && anchor_origin.is_empty()
221                            {
222                                // If the anchor is an empty element that is
223                                // adjacent to a decorator then we remove the
224                                // paragraph and select the decorator
225                                anchor_origin.remove(false)?;
226                                let node_selection = create_node_selection();
227                                node_selection.add(origin.get_key());
228                                set_selection(Some(node_selection));
229                            } else {
230                                // When the anchor is not an empty element
231                                // then the adjacent decorator is removed
232                                let container = origin.get_parent();
233                                origin.remove(false)?;
234                                if let Some(restored) = restore_empty_container_paragraph(
235                                    container.as_ref(),
236                                    Some(&origin),
237                                )? {
238                                    restored.select_start()?;
239                                }
240                            }
241                            // always stop when a decorator is encountered
242                            return Ok(());
243                        }
244                        if origin.get_latest().is::<LineBreakNode>() {
245                            // A LineBreakNode is a single deletable unit.
246                            origin.remove(false)?;
247                            return Ok(());
248                        }
249                        break;
250                    }
251                }
252                if let MergeState::MergeBlock { caret, block } = state {
253                    // Merging would remove `block`, and with it its slots:
254                    // leave the caret where it is.
255                    if !crate::slot::get_slot_names(&block).is_empty() {
256                        return Ok(());
257                    }
258                    let origin = caret.origin();
259                    // Empty adjacent block at the same nesting level: remove
260                    // it instead of merging, so the current block's type
261                    // survives.
262                    if origin.is_empty()
263                        && !block.is_empty()
264                        && origin.get_parent() == block.get_parent()
265                    {
266                        origin.remove(true)?;
267                        return Ok(());
268                    }
269                    let range_anchor = if !origin.is_empty() && block.is_empty() {
270                        rewind_sibling_caret(&get_sibling_caret(&block, caret.direction()))?
271                    } else {
272                        initial_range.anchor.clone()
273                    };
274                    update_range_selection_from_caret_range(
275                        self,
276                        &get_caret_range(range_anchor, caret)?,
277                    )?;
278                    return self.remove_text();
279                }
280                // Nothing in scope to delete: the caret sits at a slot edge
281                // when it is in a slot value, where the deletion stops.
282                let mut node = Some(self.range().expect("a range selection").anchor.get_node()?);
283                while let Some(n) = node {
284                    if crate::slot::get_slot_host_key(&n).is_some() {
285                        return Ok(());
286                    }
287                    if n.is_element() && n.get_latest().is_shadow_root() {
288                        break;
289                    }
290                    node = n.get_parent();
291                }
292            }
293
294            // Handle the deletion around decorators.
295            extend_selection_for_deletion(self, is_backward, SelectionGranularity::Character)?;
296
297            let range = self.range().expect("a range selection");
298            if !range.is_collapsed() {
299                let focus = &range.focus;
300                let anchor = &range.anchor;
301                let focus_node = match focus.point_type {
302                    PointType::Text => Some(focus.get_node()?),
303                    PointType::Element => None,
304                };
305                let anchor_node = match anchor.point_type {
306                    PointType::Text => Some(anchor.get_node()?),
307                    PointType::Element => None,
308                };
309                if let Some(focus_node) = focus_node.as_ref().filter(|n| n.is_segmented()) {
310                    let offset = focus.offset;
311                    let text_content_size = focus_node.get_text_content_size();
312                    if anchor_node.as_ref() == Some(focus_node)
313                        || (is_backward && offset != text_content_size)
314                        || (!is_backward && offset != 0)
315                    {
316                        return remove_segment(focus_node, is_backward, offset);
317                    }
318                } else if let Some(anchor_node) = anchor_node.as_ref().filter(|n| n.is_segmented())
319                {
320                    let offset = anchor.offset;
321                    let text_content_size = anchor_node.get_text_content_size();
322                    if focus_node.as_ref() == Some(anchor_node)
323                        || (is_backward && offset != 0)
324                        || (!is_backward && offset != text_content_size)
325                    {
326                        return remove_segment(anchor_node, is_backward, offset);
327                    }
328                }
329                update_caret_selection_for_unicode_character(self, is_backward)?;
330            } else if is_backward
331                && range.anchor.offset == 0
332                // Special handling around rich text nodes
333                && collapse_at_start(self, &range.anchor.get_node()?)?
334            {
335                return Ok(());
336            }
337        }
338        if !was_collapsed {
339            // Widen a whole-document range to the blocks themselves (#5835).
340            internal_expand_selection_to_whole_document(self)?;
341        }
342        self.remove_text()?;
343        if is_backward
344            && !was_collapsed
345            && self.range().is_some_and(|r| {
346                r.is_collapsed()
347                    && r.anchor.point_type == PointType::Element
348                    && r.anchor.offset == 0
349            })
350        {
351            ensure_root_has_paragraph()?;
352        }
353        Ok(())
354    }
355
356    /// `selection.deleteWord(isBackward)`.
357    pub fn delete_word(&self, is_backward: bool) -> Result<(), LexicalError> {
358        delete_text_by_granularity(self, is_backward, SelectionGranularity::Word)
359    }
360
361    /// `selection.deleteLine(isBackward)`.
362    pub fn delete_line(&self, is_backward: bool) -> Result<(), LexicalError> {
363        delete_text_by_granularity(self, is_backward, SelectionGranularity::LineBoundary)
364    }
365
366    /// `NodeSelection.deleteNodes()`: removes the selected nodes, first
367    /// moving the selection to just after the first of them when this is
368    /// the current (or last committed) selection, and gives an emptied root
369    /// a paragraph. Slotted nodes are fixed parts of their host, and are
370    /// left alone.
371    pub fn delete_nodes(&self) -> Result<(), LexicalError> {
372        let nodes: Vec<NodeRef> = self
373            .get_nodes()?
374            .into_iter()
375            .filter(|n| crate::slot::get_slot_host_key(n).is_none())
376            .collect();
377        let current = get_selection().or_else(get_previous_selection);
378        if let (Some(current), Some(first)) = (current, nodes.first())
379            && current.ptr_eq(self)
380        {
381            let first_caret = get_sibling_caret(first, CaretDirection::Next);
382            set_selection_from_caret_range(&get_caret_range(first_caret.clone(), first_caret)?)?;
383        }
384        for node in &nodes {
385            node.remove(false)?;
386        }
387        ensure_root_has_paragraph()
388    }
389}
390
391/// `selection.forwardDeletion(anchor, anchorNode, isBackward)`: whether a
392/// forward deletion at the end of the anchor node would reach a shadow
393/// root, which it must not merge into.
394fn forward_deletion(anchor: &Point, anchor_node: &NodeRef, is_backward: bool) -> bool {
395    let at_end = match anchor.point_type {
396        PointType::Element => {
397            anchor_node.is_element() && anchor.offset == anchor_node.get_children_size()
398        }
399        PointType::Text => anchor.offset == anchor_node.get_text_content_size(),
400    };
401    if !is_backward && at_end {
402        let next_sibling = anchor_node
403            .get_next_sibling()
404            .or_else(|| anchor_node.get_parent().and_then(|p| p.get_next_sibling()));
405        if next_sibling.is_some_and(|n| is_shadow_root_node(&n)) {
406            return true;
407        }
408    }
409    false
410}
411
412/// `$deleteTextByGranularity(selection, isBackward, granularity)`: word and
413/// line deletion.
414fn delete_text_by_granularity(
415    selection: &SelectionRef,
416    is_backward: bool,
417    granularity: SelectionGranularity,
418) -> Result<(), LexicalError> {
419    let Some(range) = selection.range() else {
420        return Ok(());
421    };
422    let was_collapsed = range.is_collapsed();
423    // Set when the deletion stops at a slot boundary, which it never crosses.
424    let mut stopped_at_slot = false;
425    if was_collapsed {
426        if granularity == SelectionGranularity::Word
427            && forward_deletion(&range.anchor, &range.anchor.get_node()?, is_backward)
428        {
429            return Ok(());
430        }
431        stopped_at_slot = extend_selection_for_deletion(selection, is_backward, granularity)?;
432        if granularity == SelectionGranularity::LineBoundary {
433            stop_line_deletion_at_line_break(selection)?;
434        }
435    }
436    // Line deletion must remain in one block; word deletion may cross blocks.
437    let range = selection.range().expect("a range selection");
438    if granularity == SelectionGranularity::LineBoundary
439        && !range.is_collapsed()
440        && find_block(&range.anchor.get_node()?) != find_block(&range.focus.get_node()?)
441    {
442        let anchor = &range.anchor;
443        selection.point_set(Which::Focus, &anchor.key, anchor.offset, anchor.point_type)?;
444    }
445    if selection.range().is_some_and(|r| r.is_collapsed()) {
446        // Stopped at a slot boundary with nothing before it: a no-op.
447        if !stopped_at_slot {
448            selection.delete_character(is_backward)?;
449        }
450    } else {
451        // An existing whole-document selection deletes its blocks (#5835).
452        if !was_collapsed {
453            internal_expand_selection_to_whole_document(selection)?;
454        }
455        selection.remove_text()?;
456    }
457    Ok(())
458}
459
460/// `$findMatchingParent(node, INTERNAL_$isBlock)`: the node or its nearest
461/// ancestor that is a block.
462fn find_block(node: &NodeRef) -> Option<NodeRef> {
463    let mut current = Some(node.clone());
464    while let Some(node) = current {
465        if is_block(&node) {
466            return Some(node);
467        }
468        current = node.get_parent();
469    }
470    None
471}
472
473/// `$stopLineDeletionAtLineBreak(selection)`: pulls a line deletion's focus
474/// back to the anchor's side of the first line break between them.
475fn stop_line_deletion_at_line_break(selection: &SelectionRef) -> Result<(), LexicalError> {
476    let range = selection.range().expect("a range selection");
477    for caret in caret_range_from_selection(&range)?.iter_node_carets(RootMode::ShadowRoot) {
478        if caret.is_sibling_caret() && caret.origin().get_latest().is::<LineBreakNode>() {
479            return set_point_from_caret(selection, Which::Focus, &rewind_sibling_caret(&caret)?);
480        }
481    }
482    Ok(())
483}
484
485/// The editor's [`SelectionMovement`], what JS reaches through
486/// `getDOMSelection(getWindow(editor))`: without one, `getWindow` throws as
487/// it does for an editor with no root element.
488fn selection_movement() -> Result<Rc<dyn SelectionMovement>, LexicalError> {
489    let editor =
490        get_active_editor().ok_or_else(|| LexicalError::new("Unable to find an active editor."))?;
491    editor
492        .selection_movement()
493        .ok_or_else(|| LexicalError::new("window object not found"))
494}
495
496/// Where the native `Selection.modify` leaves the caret it moves from
497/// `from`: the movement's landed point, or `from` when it can't move.
498fn landed_point(
499    movement: &dyn SelectionMovement,
500    from: &Point,
501    is_backward: bool,
502    granularity: SelectionGranularity,
503) -> Result<Point, LexicalError> {
504    Ok(movement
505        .landed_point(from, is_backward, granularity)?
506        .unwrap_or_else(|| from.clone()))
507}
508
509impl SelectionRef {
510    /// `selection.modify(alter, isBackward, granularity)`: moves (collapsed)
511    /// or extends the selection by one unit, across decorators and blocks
512    /// in the model and otherwise where the editor's [`SelectionMovement`]
513    /// lands. Without a movement this fails with `window object not found`
514    /// unless the model step handled it, as JS does with no root element.
515    pub fn modify(
516        &self,
517        alter: SelectionAlter,
518        is_backward: bool,
519        granularity: SelectionGranularity,
520    ) -> Result<(), LexicalError> {
521        let Some(range) = self.range() else {
522            return Ok(());
523        };
524        if modify_selection_around_decorators_and_blocks(
525            self,
526            alter,
527            is_backward,
528            granularity,
529            false,
530        )? {
531            return Ok(());
532        }
533        let collapse = alter == SelectionAlter::Move;
534        let movement = selection_movement()?;
535        // `if (!domSelection) return;`
536        if !movement.has_dom_selection() {
537            return Ok(());
538        }
539        // Removing the DOM block cursor element: there is no DOM. When the
540        // selection is dirty JS first syncs the DOM selection to it; the
541        // movement always measures from the model's focus.
542        let focus = range.focus.clone();
543        let focus_node = focus.get_node()?;
544        let mut from = focus.clone();
545        // When focus sits at a TextNode boundary, pre-normalize the caret
546        // into the adjacent sibling's text so the movement can cross
547        // inline-grid/flex spans (#7301).
548        if granularity == SelectionGranularity::Character
549            && focus_node.is_text()
550            && focus_node.is_unmergeable()
551        {
552            let at_boundary = if is_backward {
553                focus.offset == 0
554            } else {
555                focus.offset == focus_node.get_text_content_size()
556            };
557            if at_boundary
558                && let Some(sibling) = get_sibling_caret(&focus_node, direction(is_backward))
559                    .get_node_at_caret()
560                    .filter(NodeRef::is_text)
561            {
562                let sibling_size = sibling.get_text_content_size();
563                if collapse {
564                    let offset = if is_backward { sibling_size } else { 0 };
565                    from = Point::new(sibling.get_key(), offset, PointType::Text);
566                } else {
567                    // For extend (used by deleteCharacter), set the selection
568                    // directly instead of measuring.
569                    let offset = if is_backward {
570                        sibling_size.saturating_sub(1)
571                    } else {
572                        1
573                    };
574                    self.point_set(Which::Focus, sibling.get_key(), offset, PointType::Text)?;
575                    self.set_dirty(true);
576                    return Ok(());
577                }
578            }
579        }
580        let landed = landed_point(&*movement, &from, is_backward, granularity)?;
581        // The DOM selection after the native move: collapsed at the landed
582        // point, or from the anchor to it. Its range is in document order.
583        let (dom_anchor, dom_focus) = if collapse {
584            (landed.clone(), landed)
585        } else {
586            (range.anchor.clone(), landed)
587        };
588        let dom_is_backward = dom_focus.is_before(&dom_anchor)?;
589        let (start, end) = if dom_is_backward {
590            (dom_focus, dom_anchor)
591        } else {
592            (dom_anchor, dom_focus)
593        };
594        // Apply the DOM selection to our Lexical selection.
595        let anchor_node = self.range().expect("a range selection").anchor.get_node()?;
596        let root = if anchor_node.is_root() {
597            anchor_node
598        } else {
599            get_nearest_root_or_shadow_root(&anchor_node)?
600        };
601        apply_range(self, &start, &end)?;
602        self.set_dirty(true);
603        if !collapse {
604            shrink_selection_to_root(self, is_backward, &root)?;
605            // Because a range works on start and end, we might need to flip
606            // the anchor and focus points to match what the DOM has.
607            if dom_is_backward {
608                swap_points(self)?;
609            }
610        }
611        if granularity == SelectionGranularity::LineBoundary {
612            modify_selection_around_decorators_and_blocks(
613                self,
614                alter,
615                is_backward,
616                granularity,
617                true,
618            )?;
619        }
620        Ok(())
621    }
622}
623
624/// `$extendSelectionForDeletion(selection, isBackward, granularity)`:
625/// extends the collapsed selection over what the deletion removes. Returns
626/// true when the focus stopped at a slot boundary: a movement that lands in
627/// another slot frame is pulled back to the boundary in the anchor's frame,
628/// as JS's `'deletion'` mode of `$setPointAtSlotBoundary` pulls back a
629/// `Selection.modify` that crossed one.
630///
631/// The moves across blocks are resolved in the model; every other move is
632/// measured by the editor's [`SelectionMovement`] where JS uses the DOM
633/// selection of `getWindow(editor)`, and fails like JS without one.
634fn extend_selection_for_deletion(
635    selection: &SelectionRef,
636    is_backward: bool,
637    granularity: SelectionGranularity,
638) -> Result<bool, LexicalError> {
639    // Decorator/block handling, resolved in the model exactly as modify()
640    // does.
641    if modify_selection_around_decorators_and_blocks(
642        selection,
643        SelectionAlter::Extend,
644        is_backward,
645        granularity,
646        false,
647    )? {
648        return Ok(false);
649    }
650    let movement = selection_movement()?;
651    // `!domSelection`.
652    if !movement.has_dom_selection() {
653        return Ok(false);
654    }
655    // Removing the DOM block cursor element: there is no DOM.
656    let range = selection.range().expect("a range selection");
657    let anchor = range.anchor.clone();
658    let anchor_node = anchor.get_node()?;
659    // Measure from the focus, which the pre-pass above may have hopped past
660    // an inline decorator; for an untouched collapsed selection it is the
661    // anchor.
662    let was_collapsed = range.is_collapsed();
663    let landed = landed_point(&*movement, &range.focus, is_backward, granularity)?;
664    // JS resolves a line boundary that lands in an inline decorator's
665    // private DOM text at the decorator's edge; a movement lands on model
666    // points, never in a decorator's DOM.
667
668    // The movement may not cross inline-grid/flex span boundaries (#7301).
669    // When at the deletion-side edge of an unmergeable TextNode, extend into
670    // the adjacent sibling directly instead of relying on the movement.
671    if was_collapsed
672        && granularity == SelectionGranularity::Character
673        && anchor.point_type == PointType::Text
674        && anchor_node.is_unmergeable()
675    {
676        let boundary_offset = if is_backward {
677            0
678        } else {
679            anchor_node.get_text_content_size()
680        };
681        if anchor.offset == boundary_offset
682            && let Some(sibling) = get_sibling_caret(&anchor_node, direction(is_backward))
683                .get_node_at_caret()
684                .filter(NodeRef::is_text)
685        {
686            let sibling_offset = if is_backward {
687                sibling.get_text_content_size().saturating_sub(1)
688            } else {
689                1
690            };
691            selection.point_set(
692                Which::Focus,
693                sibling.get_key(),
694                sibling_offset,
695                PointType::Text,
696            )?;
697            selection.set_dirty(true);
698            return Ok(false);
699        }
700    }
701    // In-node character deletion (the common case): keep the focus in the
702    // anchor's own text node. Landing inside the anchor node uses that
703    // offset; landing anywhere else is clamped to the anchor's edge.
704    if was_collapsed
705        && granularity == SelectionGranularity::Character
706        && anchor.point_type == PointType::Text
707    {
708        // The deletion-side edge of the anchor's text.
709        let edge_offset = if is_backward {
710            0
711        } else {
712            anchor_node.get_text_content_size()
713        };
714        let clamped_offset = if landed.point_type == PointType::Text && landed.key == anchor.key {
715            Some(landed.offset)
716        } else if anchor.offset != edge_offset {
717            Some(edge_offset)
718        } else {
719            None
720        };
721        if let Some(clamped_offset) = clamped_offset {
722            if clamped_offset != anchor.offset {
723                selection.point_set(Which::Focus, &anchor.key, clamped_offset, PointType::Text)?;
724                selection.set_dirty(true);
725            }
726            return Ok(false);
727        }
728    }
729    // A slot boundary lives only in the model, so the movement can cross it.
730    // Deletion never does: stop the focus at the boundary instead. Resolving
731    // the range would clamp it into the landed point's frame and move the
732    // caret out of its slot.
733    if crate::slot::slots_used() {
734        let landed_node = landed.get_node()?;
735        let anchor_frame = crate::slot::get_slot_frame(&anchor_node);
736        let landed_frame = crate::slot::get_slot_frame(&landed_node);
737        if !crate::lexical_selection::is_same_frame(landed_frame.as_ref(), anchor_frame.as_ref())
738            && crate::lexical_selection::set_point_at_slot_boundary(
739                selection,
740                Which::Focus,
741                Some(&anchor_node),
742                anchor_frame.as_ref(),
743                landed_frame.as_ref(),
744                crate::lexical_selection::SlotBoundaryMode::Deletion,
745                || Ok(!is_backward),
746            )?
747        {
748            return Ok(true);
749        }
750    }
751
752    // General path: the [original .. landed] range a native extend would
753    // have produced, in document order.
754    let (start, end) = if is_backward {
755        (landed, anchor)
756    } else {
757        (anchor, landed)
758    };
759    let root = if anchor_node.is_root() {
760        anchor_node
761    } else {
762        get_nearest_root_or_shadow_root(&anchor_node)?
763    };
764    apply_range(selection, &start, &end)?;
765    selection.set_dirty(true);
766    if !shrink_selection_to_root(selection, is_backward, &root)? && is_backward {
767        // applyDOMRange set anchor = range start (the landed point); the
768        // deletion anchor must stay at the original caret, so restore that
769        // orientation.
770        swap_points(selection)?;
771    }
772    Ok(false)
773}
774
775/// `selection.applyDOMRange(range)` for a range whose ends are model points
776/// already: resolves them as `$internalResolveSelectionPoints` does
777/// (`$internalResolveSelectionPoint` and
778/// `$normalizeSelectionPointsForBoundaries`), sets them as the anchor and
779/// the focus, and normalizes the selection (`$normalizeSelection`).
780fn apply_range(selection: &SelectionRef, start: &Point, end: &Point) -> Result<(), LexicalError> {
781    let last_selection = get_active_editor()
782        .and_then(|editor| editor.get_editor_state().selection())
783        .and_then(|s| s.range());
784    let mut anchor = resolve_selection_point(start, last_selection.as_ref().map(|r| &r.anchor))?;
785    let mut focus = resolve_selection_point(end, last_selection.as_ref().map(|r| &r.focus))?;
786    // JS ignores a range whose element points are both inside decorators'
787    // DOM; model points are never inside one.
788    normalize_selection_points_for_boundaries(&mut anchor, &mut focus)?;
789    selection.point_set(Which::Anchor, &anchor.key, anchor.offset, anchor.point_type)?;
790    selection.point_set(Which::Focus, &focus.key, focus.offset, focus.point_type)?;
791    // Firefox will use an element point rather than a text point in some
792    // cases, so we normalize for that
793    normalize_selection(selection)
794}
795
796/// `$internalResolveSelectionPoint(dom, offset, lastPoint)` for the DOM
797/// position of a model point: a text point keeps its node (its offset
798/// clamped), and an element point resolves to the text at that child, as the
799/// DOM resolution of an element's child offset does (an element's DOM
800/// children are its children here, with no block cursor).
801fn resolve_selection_point(
802    point: &Point,
803    last_point: Option<&Point>,
804) -> Result<Point, LexicalError> {
805    let node = point.get_node()?;
806    if point.point_type == PointType::Text {
807        let offset = point.offset.min(node.get_text_content_size());
808        return Ok(Point::new(point.key.clone(), offset, PointType::Text));
809    }
810    let size = node.get_children_size();
811    let mut resolved_offset = point.offset;
812    // If the anchor is the same as length, then this means we need to select
813    // the very last text node.
814    let move_selection_to_end = resolved_offset == size && size > 0;
815    if move_selection_to_end {
816        resolved_offset = size - 1;
817    }
818    let text_point = |text: &NodeRef| {
819        let offset = if move_selection_to_end {
820            text.get_text_content_size()
821        } else {
822            0
823        };
824        Point::new(text.get_key(), offset, PointType::Text)
825    };
826    if let Some(text) = node
827        .get_child_at_index(resolved_offset)
828        .filter(NodeRef::is_text)
829    {
830        return Ok(text_point(&text));
831    }
832    let mut resolved_element = node;
833    let mut child = resolved_element.get_child_at_index(resolved_offset);
834    let element_child = child.clone().filter(|c| c.is_element());
835    if let Some(element) = element_child
836        && should_resolve_ancestor(&element, last_point)?
837    {
838        let descendant = if move_selection_to_end {
839            element.get_last_descendant()
840        } else {
841            element.get_first_descendant()
842        };
843        match descendant {
844            None => resolved_element = element,
845            Some(descendant) => {
846                resolved_element = if descendant.is_element() {
847                    descendant.clone()
848                } else {
849                    descendant.get_parent_or_throw()?
850                };
851                child = Some(descendant);
852            }
853        }
854        resolved_offset = 0;
855    }
856    if let Some(text) = child.as_ref().filter(|c| c.is_text()) {
857        return Ok(text_point(text));
858    }
859    if child.as_ref() != Some(&resolved_element) && move_selection_to_end {
860        resolved_offset = (resolved_offset + 1).min(resolved_element.get_children_size());
861    }
862    Ok(Point::new(
863        resolved_element.get_key(),
864        resolved_offset,
865        PointType::Element,
866    ))
867}
868
869/// `shouldResolveAncestor(resolvedElement, resolvedOffset, lastPoint)`.
870fn should_resolve_ancestor(
871    resolved_element: &NodeRef,
872    last_point: Option<&Point>,
873) -> Result<bool, LexicalError> {
874    let Some(last_point) = last_point else {
875        return Ok(true);
876    };
877    Ok(match resolved_element.get_parent() {
878        None => true,
879        Some(parent) => !parent.can_be_empty() || parent != last_point.get_node()?,
880    })
881}
882
883/// `$normalizeSelectionPointsForBoundaries(anchor, focus, lastSelection)`.
884fn normalize_selection_points_for_boundaries(
885    anchor: &mut Point,
886    focus: &mut Point,
887) -> Result<(), LexicalError> {
888    if anchor.point_type == PointType::Text && focus.point_type == PointType::Text {
889        let is_backward = anchor.is_before(focus)?;
890        let is_collapsed = anchor == focus;
891        // Attempt to normalize the offset to the previous sibling if we're
892        // at the start of a text node and the sibling is a text node or
893        // inline element.
894        resolve_selection_point_on_boundary(anchor, is_backward, is_collapsed)?;
895        resolve_selection_point_on_boundary(focus, !is_backward, is_collapsed)?;
896        if is_collapsed {
897            *focus = anchor.clone();
898        }
899    }
900    Ok(())
901}
902
903/// `$resolveSelectionPointOnBoundary(point, isBackward, isCollapsed)` (a
904/// headless editor never has an empty composition target).
905fn resolve_selection_point_on_boundary(
906    point: &mut Point,
907    is_backward: bool,
908    is_collapsed: bool,
909) -> Result<(), LexicalError> {
910    let node = point.get_node()?;
911    let before = point.offset == 0;
912    if !before && point.offset != node.get_text_content_size() {
913        return Ok(());
914    }
915    let direction = if before {
916        CaretDirection::Previous
917    } else {
918        CaretDirection::Next
919    };
920    let sibling = get_sibling_caret(&node, direction).get_node_at_caret();
921    if before != is_backward
922        && let Some(sibling) = sibling.as_ref().filter(|s| s.is_element() && s.is_inline())
923        && (!before || !is_collapsed)
924    {
925        let offset = if before {
926            sibling.get_children_size()
927        } else {
928            0
929        };
930        *point = Point::new(sibling.get_key(), offset, PointType::Element);
931    } else if before && !is_backward {
932        if let Some(sibling) = sibling.filter(NodeRef::is_text)
933            && !node.is_unmergeable()
934        {
935            *point = Point::new(
936                sibling.get_key(),
937                sibling.get_text_content_size(),
938                PointType::Text,
939            );
940        }
941    } else if sibling.is_none()
942        && (is_collapsed || (!before && is_backward))
943        && let Some(parent) = node.get_parent()
944        && parent.is_element()
945        && parent.is_inline()
946        && (before
947            || (!parent.get_latest().can_insert_text_after() && parent.get_text_content_size() > 1))
948        && let Some(parent_sibling) = get_sibling_caret(&parent, direction)
949            .get_node_at_caret()
950            .filter(NodeRef::is_text)
951    {
952        let offset = if before {
953            parent_sibling.get_text_content_size()
954        } else {
955            0
956        };
957        *point = Point::new(parent_sibling.get_key(), offset, PointType::Text);
958    }
959    Ok(())
960}
961
962/// `$shrinkSelectionToRoot(selection, isBackward, root)`: when part of the
963/// selection lies outside `root`, shrinks it to the edge of the part inside.
964/// Returns true if the selection was shrunk.
965fn shrink_selection_to_root(
966    selection: &SelectionRef,
967    is_backward: bool,
968    root: &NodeRef,
969) -> Result<bool, LexicalError> {
970    let nodes = selection.get_nodes()?;
971    let valid_nodes: Vec<&NodeRef> = nodes.iter().filter(|n| is_parent_of(root, n)).collect();
972    if valid_nodes.is_empty() || valid_nodes.len() == nodes.len() {
973        return Ok(false);
974    }
975    let edge_node = if is_backward {
976        valid_nodes[0]
977    } else {
978        valid_nodes[valid_nodes.len() - 1]
979    };
980    let edge_element = if edge_node.is_element() {
981        edge_node.clone()
982    } else {
983        edge_node.get_parent_or_throw()?
984    };
985    if is_backward {
986        edge_element.select_start()?;
987    } else {
988        edge_element.select_end()?;
989    }
990    Ok(true)
991}
992
993/// `$swapPoints(selection)`.
994fn swap_points(selection: &SelectionRef) -> Result<(), LexicalError> {
995    let range = selection.range().expect("a range selection");
996    let (anchor, focus) = (range.anchor, range.focus);
997    selection.point_set(Which::Anchor, &focus.key, focus.offset, focus.point_type)?;
998    selection.point_set(Which::Focus, &anchor.key, anchor.offset, anchor.point_type)
999}
1000
1001/// `$getNearestRootOrShadowRoot(node)`: the node itself when it is a slotted
1002/// element (a slot is the root of its own scope), or the nearest root or
1003/// shadow root above it.
1004pub(crate) fn get_nearest_root_or_shadow_root(node: &NodeRef) -> Result<NodeRef, LexicalError> {
1005    let mut current = node.clone();
1006    loop {
1007        if crate::slot::get_slot_host_key(&current).is_some() && current.is_element() {
1008            return Ok(current);
1009        }
1010        let parent = current.get_parent_or_throw()?;
1011        if is_root_or_shadow_root(&*parent.get_latest()) {
1012            return Ok(parent);
1013        }
1014        current = parent;
1015    }
1016}
1017
1018/// `$modifySelectionAroundDecoratorsAndBlocks(selection, alter, isBackward,
1019/// granularity, mode)`: resolves in the model a move or extension over a
1020/// decorator or out of the caret's block (`decorators_only` is the
1021/// `'decorators'` mode, which doesn't look for blocks), and returns true
1022/// when that handled it; false when the native measurement has to resolve
1023/// the move.
1024fn modify_selection_around_decorators_and_blocks(
1025    selection: &SelectionRef,
1026    alter: SelectionAlter,
1027    is_backward: bool,
1028    granularity: SelectionGranularity,
1029    decorators_only: bool,
1030) -> Result<bool, LexicalError> {
1031    let range = selection.range().expect("a range selection");
1032    if alter == SelectionAlter::Move
1033        && granularity == SelectionGranularity::Character
1034        && !range.is_collapsed()
1035    {
1036        // moving left or right when the selection isn't collapsed will just
1037        // set the anchor to the focus or vice versa depending on direction
1038        let (src, dst) = if is_backward == selection.is_backward()? {
1039            (&range.focus, Which::Anchor)
1040        } else {
1041            (&range.anchor, Which::Focus)
1042        };
1043        selection.point_set(dst, &src.key, src.offset, src.point_type)?;
1044        return Ok(true);
1045    }
1046    let initial_focus = caret_from_point(&range.focus, direction(is_backward))?;
1047    let is_line_boundary = granularity == SelectionGranularity::LineBoundary;
1048    let collapse = alter == SelectionAlter::Move;
1049    // `focus === initialFocus` in JS: `None` until another caret is chosen.
1050    let mut focus: Option<PointCaret> = None;
1051    let mut check_for_block = !decorators_only;
1052    // An isolated decorator stops the caret.
1053    let mut isolated = false;
1054    if !is_extendable_text_point_caret(&initial_focus) {
1055        for sibling_caret in initial_focus.iter() {
1056            check_for_block = false;
1057            let origin = sibling_caret.origin().clone();
1058            if origin.is_decorator() {
1059                if origin.is_isolated() {
1060                    isolated = true;
1061                    break;
1062                }
1063                focus = Some(sibling_caret);
1064                if is_line_boundary && origin.is_inline() {
1065                    continue;
1066                }
1067            }
1068            break;
1069        }
1070        if isolated {
1071            // Handled, with the selection deliberately left where it is.
1072            return Ok(true);
1073        }
1074        if check_for_block {
1075            let root_mode = match alter {
1076                SelectionAlter::Extend => RootMode::ShadowRoot,
1077                SelectionAlter::Move => RootMode::Root,
1078            };
1079            for next_caret in extend_caret_to_range(&initial_focus)?.iter_node_carets(root_mode) {
1080                if next_caret.is_child_caret() {
1081                    if !next_caret.origin().is_inline() {
1082                        focus = Some(next_caret);
1083                    }
1084                } else if next_caret.origin().is_element() {
1085                    continue;
1086                } else if next_caret.origin().is_decorator() && !next_caret.origin().is_inline() {
1087                    focus = Some(next_caret);
1088                }
1089                break;
1090            }
1091        }
1092    }
1093    let Some(focus) = focus else {
1094        return Ok(false);
1095    };
1096    // After this point checkForBlock is true if and only if we moved to a
1097    // different block, so we should stop regardless of the granularity
1098    if collapse
1099        && !is_line_boundary
1100        && focus.origin().is_decorator()
1101        && focus.origin().is_keyboard_selectable()
1102    {
1103        // Make it possible to move selection from range selection to node
1104        // selection on the node.
1105        let node_selection = create_node_selection();
1106        node_selection.add(focus.origin().get_key());
1107        set_selection(Some(node_selection));
1108        return Ok(true);
1109    }
1110    let focus = normalize_caret(&focus);
1111    if collapse {
1112        set_point_from_caret(selection, Which::Anchor, &focus)?;
1113    }
1114    set_point_from_caret(selection, Which::Focus, &focus)?;
1115    Ok(check_for_block || !is_line_boundary)
1116}
1117
1118/// `$needsBlockCursorBeside(node)`: whether a caret beside the node needs a
1119/// block cursor, as a block decorator, a top-level shadow root and an
1120/// element that can't be empty do.
1121pub(crate) fn needs_block_cursor_beside(node: &NodeRef) -> bool {
1122    if node.is_inline() {
1123        return false;
1124    }
1125    if node.is_decorator() {
1126        return true;
1127    }
1128    if node.is_element() {
1129        if node.get_latest().is_shadow_root() {
1130            return !node.get_parent().is_some_and(|p| is_shadow_root_node(&p));
1131        }
1132        return !node.can_be_empty();
1133    }
1134    false
1135}
1136
1137/// `node.isParentOf(targetNode)` (`$hasAncestor(targetNode, node)`).
1138fn is_parent_of(node: &NodeRef, target: &NodeRef) -> bool {
1139    let mut parent = target.get_parent();
1140    while let Some(p) = parent {
1141        if &p == node {
1142            return true;
1143        }
1144        parent = p.get_parent();
1145    }
1146    false
1147}
1148
1149/// `$collapseAtStart(selection, startNode)`: lets the elements the
1150/// selection is at the start of handle a backward deletion there.
1151fn collapse_at_start(selection: &SelectionRef, start_node: &NodeRef) -> Result<bool, LexicalError> {
1152    let mut node = Some(start_node.clone());
1153    while let Some(n) = node {
1154        if n.is_element() {
1155            if n.collapse_at_start(selection)? {
1156                return Ok(true);
1157            }
1158            if is_root_or_shadow_root(&*n.get_latest()) {
1159                break;
1160            }
1161        }
1162        if n.get_previous_sibling().is_some() {
1163            break;
1164        }
1165        node = n.get_parent();
1166    }
1167    Ok(false)
1168}
1169
1170/// `INTERNAL_$expandSelectionToWholeDocument(selection)`: widens a
1171/// selection that covers the whole document to the root's element points,
1172/// so a deletion removes the blocks rather than emptying them.
1173pub(crate) fn internal_expand_selection_to_whole_document(
1174    selection: &SelectionRef,
1175) -> Result<(), LexicalError> {
1176    let root = get_root();
1177    let range = selection.range().expect("a range selection");
1178    if root.is_empty() || !is_block_fully_selected(&root, &range)? {
1179        return Ok(());
1180    }
1181    selection.point_set(Which::Anchor, root.get_key(), 0, PointType::Element)?;
1182    selection.point_set(
1183        Which::Focus,
1184        root.get_key(),
1185        root.get_children_size(),
1186        PointType::Element,
1187    )
1188}
1189
1190/// `$isBlockFullySelected(blockNode, selection)`: whether the selection
1191/// covers everything in the block. A range in another slot frame never
1192/// does. [`is_block_fully_selected_by_caret_range`] takes a `CaretRange`,
1193/// as JS's also does.
1194pub fn is_block_fully_selected(
1195    block: &NodeRef,
1196    selection: &RangeSelection,
1197) -> Result<bool, LexicalError> {
1198    is_block_fully_selected_by_caret_range(block, &caret_range_from_selection(selection)?)
1199}
1200
1201/// `$isBlockFullySelected(blockNode, range)` with a `CaretRange`: whether
1202/// the range, in either direction, covers everything in the block.
1203pub fn is_block_fully_selected_by_caret_range(
1204    block: &NodeRef,
1205    range: &CaretRange,
1206) -> Result<bool, LexicalError> {
1207    let range = get_caret_range_in_direction(range, CaretDirection::Next)?;
1208    let anchor_frame = crate::slot::get_slot_frame(range.anchor.origin());
1209    let block_frame = crate::slot::get_slot_frame(block);
1210    if anchor_frame != block_frame {
1211        return Ok(false);
1212    }
1213    let block_start = normalize_caret(
1214        &get_child_caret(block, CaretDirection::Next).expect("a block is an element"),
1215    );
1216    let block_end = get_caret_in_direction(
1217        &normalize_caret(
1218            &get_child_caret(block, CaretDirection::Previous).expect("a block is an element"),
1219        ),
1220        CaretDirection::Next,
1221    )?;
1222    Ok(
1223        compare_point_caret_next(&range.anchor, &block_start)?.is_le()
1224            && compare_point_caret_next(&range.focus, &block_end)?.is_ge(),
1225    )
1226}
1227
1228/// `$ensureRootHasParagraph()`: gives an empty root a selected paragraph,
1229/// unless the selection is in a slot (a root slot does not replace the
1230/// document body).
1231fn ensure_root_has_paragraph() -> Result<(), LexicalError> {
1232    let root = get_root();
1233    if root.get_children_size() == 0
1234        && crate::slot::get_selection_slot_frame(get_selection().as_ref())?.is_none()
1235    {
1236        let paragraph = create_paragraph_node();
1237        root.append(std::slice::from_ref(&paragraph))?;
1238        paragraph.select(None, None)?;
1239    }
1240    Ok(())
1241}
1242
1243/// `$updateCaretSelectionForUnicodeCharacter(selection, isBackward)`:
1244/// narrows a deletion within one text node to one code unit, unless the
1245/// text holds a surrogate pair or an emoji.
1246fn update_caret_selection_for_unicode_character(
1247    selection: &SelectionRef,
1248    is_backward: bool,
1249) -> Result<(), LexicalError> {
1250    let range = selection.range().expect("a range selection");
1251    let anchor = &range.anchor;
1252    let focus = &range.focus;
1253    if anchor.key == focus.key
1254        && anchor.point_type == PointType::Text
1255        && focus.point_type == PointType::Text
1256    {
1257        // Handling of multibyte characters
1258        let anchor_offset = anchor.offset;
1259        let focus_offset = focus.offset;
1260        let is_before = anchor_offset < focus_offset;
1261        let start_offset = if is_before {
1262            anchor_offset
1263        } else {
1264            focus_offset
1265        };
1266        let end_offset = if is_before {
1267            focus_offset
1268        } else {
1269            anchor_offset
1270        };
1271        let character_offset = end_offset as isize - 1;
1272        if start_offset as isize != character_offset {
1273            let text = utf16::slice(
1274                &anchor.get_node()?.get_text_content(),
1275                start_offset,
1276                end_offset,
1277            );
1278            if should_delete_exactly_one_code_unit(&text)? {
1279                let character_offset = character_offset as usize;
1280                if is_backward {
1281                    selection.point_set(
1282                        Which::Focus,
1283                        &focus.key,
1284                        character_offset,
1285                        focus.point_type,
1286                    )?;
1287                } else {
1288                    selection.point_set(
1289                        Which::Anchor,
1290                        &anchor.key,
1291                        character_offset,
1292                        anchor.point_type,
1293                    )?;
1294                }
1295            }
1296        }
1297    }
1298    Ok(())
1299}
1300
1301/// `shouldDeleteExactlyOneCodeUnit(text)`.
1302fn should_delete_exactly_one_code_unit(text: &str) -> Result<bool, LexicalError> {
1303    // JS checks this in DEV builds, which the vectors come from.
1304    invariant!(
1305        utf16::len(text) > 1,
1306        "shouldDeleteExactlyOneCodeUnit: expecting to be called only with sequences of two or more code units"
1307    );
1308    Ok(!(does_contain_surrogate_pair(text) || does_contain_emoji(text)))
1309}
1310
1311/// `doesContainSurrogatePair(str)`: a character outside the BMP. (A half
1312/// pair is U+FFFD here, which JS's regex doesn't match either.)
1313fn does_contain_surrogate_pair(text: &str) -> bool {
1314    text.chars().any(|c| c.len_utf16() == 2)
1315}
1316
1317/// `doesContainEmoji(text)`: `/\p{Emoji}/u.test(text)`.
1318fn does_contain_emoji(text: &str) -> bool {
1319    text.chars().any(|c| {
1320        let c = u32::from(c);
1321        EMOJI
1322            .binary_search_by(|&(lo, hi)| {
1323                if hi < c {
1324                    std::cmp::Ordering::Less
1325                } else if lo > c {
1326                    std::cmp::Ordering::Greater
1327                } else {
1328                    std::cmp::Ordering::Equal
1329                }
1330            })
1331            .is_ok()
1332    })
1333}
1334
1335/// The Unicode `Emoji` property, as ranges of code points, from Node 24
1336/// (Unicode 17.0) `/\p{Emoji}/u`.
1337const EMOJI: &[(u32, u32)] = &[
1338    (0x23, 0x23),
1339    (0x2A, 0x2A),
1340    (0x30, 0x39),
1341    (0xA9, 0xA9),
1342    (0xAE, 0xAE),
1343    (0x203C, 0x203C),
1344    (0x2049, 0x2049),
1345    (0x2122, 0x2122),
1346    (0x2139, 0x2139),
1347    (0x2194, 0x2199),
1348    (0x21A9, 0x21AA),
1349    (0x231A, 0x231B),
1350    (0x2328, 0x2328),
1351    (0x23CF, 0x23CF),
1352    (0x23E9, 0x23F3),
1353    (0x23F8, 0x23FA),
1354    (0x24C2, 0x24C2),
1355    (0x25AA, 0x25AB),
1356    (0x25B6, 0x25B6),
1357    (0x25C0, 0x25C0),
1358    (0x25FB, 0x25FE),
1359    (0x2600, 0x2604),
1360    (0x260E, 0x260E),
1361    (0x2611, 0x2611),
1362    (0x2614, 0x2615),
1363    (0x2618, 0x2618),
1364    (0x261D, 0x261D),
1365    (0x2620, 0x2620),
1366    (0x2622, 0x2623),
1367    (0x2626, 0x2626),
1368    (0x262A, 0x262A),
1369    (0x262E, 0x262F),
1370    (0x2638, 0x263A),
1371    (0x2640, 0x2640),
1372    (0x2642, 0x2642),
1373    (0x2648, 0x2653),
1374    (0x265F, 0x2660),
1375    (0x2663, 0x2663),
1376    (0x2665, 0x2666),
1377    (0x2668, 0x2668),
1378    (0x267B, 0x267B),
1379    (0x267E, 0x267F),
1380    (0x2692, 0x2697),
1381    (0x2699, 0x2699),
1382    (0x269B, 0x269C),
1383    (0x26A0, 0x26A1),
1384    (0x26A7, 0x26A7),
1385    (0x26AA, 0x26AB),
1386    (0x26B0, 0x26B1),
1387    (0x26BD, 0x26BE),
1388    (0x26C4, 0x26C5),
1389    (0x26C8, 0x26C8),
1390    (0x26CE, 0x26CF),
1391    (0x26D1, 0x26D1),
1392    (0x26D3, 0x26D4),
1393    (0x26E9, 0x26EA),
1394    (0x26F0, 0x26F5),
1395    (0x26F7, 0x26FA),
1396    (0x26FD, 0x26FD),
1397    (0x2702, 0x2702),
1398    (0x2705, 0x2705),
1399    (0x2708, 0x270D),
1400    (0x270F, 0x270F),
1401    (0x2712, 0x2712),
1402    (0x2714, 0x2714),
1403    (0x2716, 0x2716),
1404    (0x271D, 0x271D),
1405    (0x2721, 0x2721),
1406    (0x2728, 0x2728),
1407    (0x2733, 0x2734),
1408    (0x2744, 0x2744),
1409    (0x2747, 0x2747),
1410    (0x274C, 0x274C),
1411    (0x274E, 0x274E),
1412    (0x2753, 0x2755),
1413    (0x2757, 0x2757),
1414    (0x2763, 0x2764),
1415    (0x2795, 0x2797),
1416    (0x27A1, 0x27A1),
1417    (0x27B0, 0x27B0),
1418    (0x27BF, 0x27BF),
1419    (0x2934, 0x2935),
1420    (0x2B05, 0x2B07),
1421    (0x2B1B, 0x2B1C),
1422    (0x2B50, 0x2B50),
1423    (0x2B55, 0x2B55),
1424    (0x3030, 0x3030),
1425    (0x303D, 0x303D),
1426    (0x3297, 0x3297),
1427    (0x3299, 0x3299),
1428    (0x1F004, 0x1F004),
1429    (0x1F0CF, 0x1F0CF),
1430    (0x1F170, 0x1F171),
1431    (0x1F17E, 0x1F17F),
1432    (0x1F18E, 0x1F18E),
1433    (0x1F191, 0x1F19A),
1434    (0x1F1E6, 0x1F1FF),
1435    (0x1F201, 0x1F202),
1436    (0x1F21A, 0x1F21A),
1437    (0x1F22F, 0x1F22F),
1438    (0x1F232, 0x1F23A),
1439    (0x1F250, 0x1F251),
1440    (0x1F300, 0x1F321),
1441    (0x1F324, 0x1F393),
1442    (0x1F396, 0x1F397),
1443    (0x1F399, 0x1F39B),
1444    (0x1F39E, 0x1F3F0),
1445    (0x1F3F3, 0x1F3F5),
1446    (0x1F3F7, 0x1F4FD),
1447    (0x1F4FF, 0x1F53D),
1448    (0x1F549, 0x1F54E),
1449    (0x1F550, 0x1F567),
1450    (0x1F56F, 0x1F570),
1451    (0x1F573, 0x1F57A),
1452    (0x1F587, 0x1F587),
1453    (0x1F58A, 0x1F58D),
1454    (0x1F590, 0x1F590),
1455    (0x1F595, 0x1F596),
1456    (0x1F5A4, 0x1F5A5),
1457    (0x1F5A8, 0x1F5A8),
1458    (0x1F5B1, 0x1F5B2),
1459    (0x1F5BC, 0x1F5BC),
1460    (0x1F5C2, 0x1F5C4),
1461    (0x1F5D1, 0x1F5D3),
1462    (0x1F5DC, 0x1F5DE),
1463    (0x1F5E1, 0x1F5E1),
1464    (0x1F5E3, 0x1F5E3),
1465    (0x1F5E8, 0x1F5E8),
1466    (0x1F5EF, 0x1F5EF),
1467    (0x1F5F3, 0x1F5F3),
1468    (0x1F5FA, 0x1F64F),
1469    (0x1F680, 0x1F6C5),
1470    (0x1F6CB, 0x1F6D2),
1471    (0x1F6D5, 0x1F6D8),
1472    (0x1F6DC, 0x1F6E5),
1473    (0x1F6E9, 0x1F6E9),
1474    (0x1F6EB, 0x1F6EC),
1475    (0x1F6F0, 0x1F6F0),
1476    (0x1F6F3, 0x1F6FC),
1477    (0x1F7E0, 0x1F7EB),
1478    (0x1F7F0, 0x1F7F0),
1479    (0x1F90C, 0x1F93A),
1480    (0x1F93C, 0x1F945),
1481    (0x1F947, 0x1F9FF),
1482    (0x1FA70, 0x1FA7C),
1483    (0x1FA80, 0x1FA8A),
1484    (0x1FA8E, 0x1FAC6),
1485    (0x1FAC8, 0x1FAC8),
1486    (0x1FACD, 0x1FADC),
1487    (0x1FADF, 0x1FAEA),
1488    (0x1FAEF, 0x1FAF8),
1489];
1490
1491/// A JS `\s` character (WhiteSpace or LineTerminator), what `trim()` and
1492/// `/\S/` use: Unicode `White_Space` without U+0085, plus U+FEFF.
1493pub(crate) fn is_js_whitespace(c: char) -> bool {
1494    (c.is_whitespace() && c != '\u{85}') || c == '\u{FEFF}'
1495}
1496
1497/// `$removeSegment(node, isBackward, offset)`: removes the
1498/// whitespace-separated segment of a segmented text node at `offset`.
1499fn remove_segment(node: &NodeRef, is_backward: bool, offset: usize) -> Result<(), LexicalError> {
1500    let text_content = node.get_text_content();
1501    // `textContent.split(/(?=\s)/g)`: split before each whitespace character
1502    // but the first.
1503    let mut split: Vec<&str> = Vec::new();
1504    let mut start = 0;
1505    for (i, c) in text_content.char_indices() {
1506        if i > 0 && is_js_whitespace(c) {
1507            split.push(&text_content[start..i]);
1508            start = i;
1509        }
1510    }
1511    split.push(&text_content[start..]);
1512    let split_length = split.len();
1513    let mut segment_offset = 0;
1514    let mut restore_offset = Some(0);
1515    for i in 0..split_length {
1516        let text = split[i];
1517        let is_last = i == split_length - 1;
1518        restore_offset = Some(segment_offset);
1519        segment_offset += utf16::len(text);
1520        if (is_backward && segment_offset == offset) || segment_offset > offset || is_last {
1521            split.remove(i);
1522            if is_last {
1523                restore_offset = None;
1524            }
1525            break;
1526        }
1527    }
1528    let joined = split.concat();
1529    let next_text_content = joined.trim_matches(is_js_whitespace);
1530    if next_text_content.is_empty() {
1531        node.remove(false)?;
1532    } else {
1533        node.set_text_content(next_text_content);
1534        node.select(restore_offset, restore_offset)?;
1535    }
1536    Ok(())
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541    use super::*;
1542    use crate::lexical_selection::{Selection, create_range_selection, set_selection};
1543    use crate::{
1544        CreateEditorArgs, UpdateOptions, create_editor, json, parse_serialized_node,
1545        reset_random_key,
1546    };
1547
1548    /// What JS does for one deletion on a headless editor.
1549    enum Want {
1550        /// The root's children (compact JSON) and the anchor and focus
1551        /// after it.
1552        Deleted(&'static str, &'static str, &'static str),
1553        /// The update throws `window object not found` and the editor keeps
1554        /// its state.
1555        NoWindow,
1556    }
1557    use Want::{Deleted, NoWindow};
1558
1559    /// `deleteCharacter` ('C'), `deleteWord` ('W') and `deleteLine` ('L')
1560    /// on a headless editor (`createEditor` with no root element), as JS
1561    /// gives them in the conformance package's Node environment: anything
1562    /// that needs the native `Selection.modify` measurement throws, and the
1563    /// moves the model resolves (merging and removing blocks, removing a line
1564    /// break, removing an expanded selection) succeed. Points are
1565    /// `key:offset:t|e`.
1566    #[test]
1567    fn headless_deletion_matches_js() {
1568        type Case = (char, bool, usize, &'static str, &'static str, Want);
1569        let docs = [
1570            r#"[{"type":"paragraph","children":[{"type":"text","text":"abc"}]}]"#,
1571            r#"[{"type":"paragraph","children":[{"type":"text","format":1,"text":"ab"},{"type":"text","text":"cd"}],"textFormat":1}]"#,
1572            r#"[{"type":"paragraph","children":[{"type":"text","text":"abc"}]},{"type":"paragraph","children":[{"type":"text","text":"def"}]}]"#,
1573            r#"[{"type":"paragraph","children":[{"type":"text","text":"a😀b"}]}]"#,
1574            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"},{"type":"text","text":"b"}]}]"#,
1575            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"tab"},{"type":"text","text":"b"}]}]"#,
1576            r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
1577            r#"[{"type":"paragraph","children":[]},{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
1578            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[]}]"#,
1579            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
1580            r#"[{"type":"paragraph","children":[]},{"type":"paragraph","children":[]}]"#,
1581            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"linebreak"}]}]"#,
1582            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"linebreak"},{"type":"text","text":"b"}]}]"#,
1583            r#"[{"type":"paragraph","children":[{"type":"text","mode":"token","text":"ab"}]},{"type":"paragraph","children":[{"type":"text","text":"cd"}]}]"#,
1584            r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]},{"type":"paragraph","children":[{"type":"text","mode":"segmented","text":"cd"}]}]"#,
1585            r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"text","mode":"segmented","text":"b c"},{"type":"text","text":"d"}]}]"#,
1586            r#"[{"type":"paragraph","children":[]}]"#,
1587            r#"[{"type":"paragraph","children":[]},{"type":"paragraph","children":[{"type":"text","text":"def"}]}]"#,
1588        ];
1589        let cases: &[Case] = &[
1590            ('C', true, 0, "2:1:t", "2:1:t", NoWindow), // mid text
1591            ('C', true, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
1592            ('C', true, 0, "2:3:t", "2:3:t", NoWindow), // text end, only node
1593            ('C', true, 1, "3:0:t", "3:0:t", NoWindow), // start of second text node
1594            ('C', true, 1, "2:2:t", "2:2:t", NoWindow), // end of first text node
1595            (
1596                'C',
1597                true,
1598                2,
1599                "4:0:t",
1600                "4:0:t",
1601                Deleted(
1602                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
1603                    "2:3:t",
1604                    "2:3:t",
1605                ),
1606            ), // start of second paragraph
1607            ('C', true, 2, "2:3:t", "2:3:t", NoWindow), // end of first paragraph
1608            ('C', true, 3, "2:3:t", "2:3:t", NoWindow), // after emoji
1609            ('C', true, 3, "2:1:t", "2:1:t", NoWindow), // before emoji
1610            ('C', true, 3, "2:2:t", "2:2:t", NoWindow), // inside surrogate pair
1611            (
1612                'C',
1613                true,
1614                4,
1615                "4:0:t",
1616                "4:0:t",
1617                Deleted(
1618                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]"#,
1619                    "2:1:t",
1620                    "2:1:t",
1621                ),
1622            ), // text after linebreak
1623            ('C', true, 4, "2:1:t", "2:1:t", NoWindow), // text before linebreak
1624            (
1625                'C',
1626                true,
1627                4,
1628                "1:2:e",
1629                "1:2:e",
1630                Deleted(
1631                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]"#,
1632                    "2:1:t",
1633                    "2:1:t",
1634                ),
1635            ), // element point after linebreak
1636            ('C', true, 5, "4:0:t", "4:0:t", NoWindow), // text after tab
1637            ('C', true, 5, "3:1:t", "3:1:t", NoWindow), // inside tab end
1638            ('C', true, 5, "2:1:t", "2:1:t", NoWindow), // text before tab
1639            (
1640                'C',
1641                true,
1642                6,
1643                "2:1:t",
1644                "2:4:t",
1645                Deleted(
1646                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1647                    "2:1:t",
1648                    "2:1:t",
1649                ),
1650            ), // non-collapsed
1651            (
1652                'C',
1653                true,
1654                6,
1655                "2:4:t",
1656                "2:1:t",
1657                Deleted(
1658                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1659                    "2:1:t",
1660                    "2:1:t",
1661                ),
1662            ), // non-collapsed backward
1663            (
1664                'C',
1665                true,
1666                2,
1667                "2:1:t",
1668                "4:2:t",
1669                Deleted(
1670                    r#"[{"type":"paragraph","children":[{"type":"text","text":"af"}]}]"#,
1671                    "2:1:t",
1672                    "2:1:t",
1673                ),
1674            ), // non-collapsed across blocks
1675            (
1676                'C',
1677                true,
1678                2,
1679                "2:0:t",
1680                "4:3:t",
1681                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "5:0:e", "5:0:e"),
1682            ), // whole document
1683            ('C', true, 7, "1:0:e", "1:0:e", NoWindow), // empty first paragraph
1684            (
1685                'C',
1686                true,
1687                8,
1688                "3:0:e",
1689                "3:0:e",
1690                Deleted(
1691                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
1692                    "2:1:t",
1693                    "2:1:t",
1694                ),
1695            ), // empty last paragraph
1696            (
1697                'C',
1698                true,
1699                9,
1700                "3:0:e",
1701                "3:0:e",
1702                Deleted(
1703                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
1704                    "2:1:t",
1705                    "2:1:t",
1706                ),
1707            ), // empty middle paragraph
1708            (
1709                'C',
1710                true,
1711                10,
1712                "2:0:e",
1713                "2:0:e",
1714                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "1:0:e", "1:0:e"),
1715            ), // two empty paragraphs
1716            (
1717                'C',
1718                true,
1719                11,
1720                "3:0:e",
1721                "3:0:e",
1722                Deleted(
1723                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"}]}]"#,
1724                    "2:1:t",
1725                    "2:1:t",
1726                ),
1727            ), // paragraph with only a linebreak
1728            ('C', true, 4, "1:1:e", "1:1:e", NoWindow), // element point before linebreak
1729            ('C', true, 12, "2:1:t", "2:1:t", NoWindow), // before a block starting with a linebreak
1730            (
1731                'C',
1732                true,
1733                13,
1734                "4:0:t",
1735                "4:0:t",
1736                Deleted(
1737                    r#"[{"type":"paragraph","children":[{"type":"text","mode":"token","text":"ab"},{"type":"text","text":"cd"}]}]"#,
1738                    "2:2:t",
1739                    "2:2:t",
1740                ),
1741            ), // after a token block
1742            ('C', true, 14, "2:2:t", "2:2:t", NoWindow), // before a segmented block
1743            (
1744                'C',
1745                true,
1746                15,
1747                "3:2:t",
1748                "3:1:t",
1749                Deleted(
1750                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
1751                    "2:2:t",
1752                    "2:2:t",
1753                ),
1754            ), // non-collapsed in segmented
1755            ('C', true, 16, "1:0:e", "1:0:e", NoWindow), // only empty paragraph
1756            (
1757                'C',
1758                true,
1759                17,
1760                "3:0:t",
1761                "3:0:t",
1762                Deleted(
1763                    r#"[{"type":"paragraph","children":[{"type":"text","text":"def"}]}]"#,
1764                    "3:0:t",
1765                    "3:0:t",
1766                ),
1767            ), // after empty paragraph
1768            ('C', true, 8, "2:1:t", "2:1:t", NoWindow), // before empty paragraph
1769            ('C', false, 0, "2:1:t", "2:1:t", NoWindow), // mid text
1770            ('C', false, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
1771            ('C', false, 0, "2:3:t", "2:3:t", NoWindow), // text end, only node
1772            ('C', false, 1, "3:0:t", "3:0:t", NoWindow), // start of second text node
1773            ('C', false, 1, "2:2:t", "2:2:t", NoWindow), // end of first text node
1774            ('C', false, 2, "4:0:t", "4:0:t", NoWindow), // start of second paragraph
1775            (
1776                'C',
1777                false,
1778                2,
1779                "2:3:t",
1780                "2:3:t",
1781                Deleted(
1782                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
1783                    "2:3:t",
1784                    "2:3:t",
1785                ),
1786            ), // end of first paragraph
1787            ('C', false, 3, "2:3:t", "2:3:t", NoWindow), // after emoji
1788            ('C', false, 3, "2:1:t", "2:1:t", NoWindow), // before emoji
1789            ('C', false, 3, "2:2:t", "2:2:t", NoWindow), // inside surrogate pair
1790            ('C', false, 4, "4:0:t", "4:0:t", NoWindow), // text after linebreak
1791            (
1792                'C',
1793                false,
1794                4,
1795                "2:1:t",
1796                "2:1:t",
1797                Deleted(
1798                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]"#,
1799                    "2:1:t",
1800                    "2:1:t",
1801                ),
1802            ), // text before linebreak
1803            ('C', false, 4, "1:2:e", "1:2:e", NoWindow), // element point after linebreak
1804            ('C', false, 5, "4:0:t", "4:0:t", NoWindow), // text after tab
1805            ('C', false, 5, "3:1:t", "3:1:t", NoWindow), // inside tab end
1806            ('C', false, 5, "2:1:t", "2:1:t", NoWindow), // text before tab
1807            (
1808                'C',
1809                false,
1810                6,
1811                "2:1:t",
1812                "2:4:t",
1813                Deleted(
1814                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1815                    "2:1:t",
1816                    "2:1:t",
1817                ),
1818            ), // non-collapsed
1819            (
1820                'C',
1821                false,
1822                6,
1823                "2:4:t",
1824                "2:1:t",
1825                Deleted(
1826                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1827                    "2:1:t",
1828                    "2:1:t",
1829                ),
1830            ), // non-collapsed backward
1831            (
1832                'C',
1833                false,
1834                2,
1835                "2:1:t",
1836                "4:2:t",
1837                Deleted(
1838                    r#"[{"type":"paragraph","children":[{"type":"text","text":"af"}]}]"#,
1839                    "2:1:t",
1840                    "2:1:t",
1841                ),
1842            ), // non-collapsed across blocks
1843            (
1844                'C',
1845                false,
1846                2,
1847                "2:0:t",
1848                "4:3:t",
1849                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "5:0:e", "5:0:e"),
1850            ), // whole document
1851            (
1852                'C',
1853                false,
1854                7,
1855                "1:0:e",
1856                "1:0:e",
1857                Deleted(
1858                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
1859                    "3:0:t",
1860                    "3:0:t",
1861                ),
1862            ), // empty first paragraph
1863            ('C', false, 8, "3:0:e", "3:0:e", NoWindow), // empty last paragraph
1864            (
1865                'C',
1866                false,
1867                9,
1868                "3:0:e",
1869                "3:0:e",
1870                Deleted(
1871                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
1872                    "root:1:e",
1873                    "root:1:e",
1874                ),
1875            ), // empty middle paragraph
1876            ('C', false, 10, "2:0:e", "2:0:e", NoWindow), // two empty paragraphs
1877            (
1878                'C',
1879                false,
1880                11,
1881                "3:0:e",
1882                "3:0:e",
1883                Deleted(
1884                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[]}]"#,
1885                    "3:0:e",
1886                    "3:0:e",
1887                ),
1888            ), // paragraph with only a linebreak
1889            (
1890                'C',
1891                false,
1892                4,
1893                "1:1:e",
1894                "1:1:e",
1895                Deleted(
1896                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]"#,
1897                    "2:1:t",
1898                    "2:1:t",
1899                ),
1900            ), // element point before linebreak
1901            (
1902                'C',
1903                false,
1904                12,
1905                "2:1:t",
1906                "2:1:t",
1907                Deleted(
1908                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"},{"type":"text","text":"b"}]}]"#,
1909                    "2:1:t",
1910                    "2:1:t",
1911                ),
1912            ), // before a block starting with a linebreak
1913            ('C', false, 13, "4:0:t", "4:0:t", NoWindow), // after a token block
1914            (
1915                'C',
1916                false,
1917                14,
1918                "2:2:t",
1919                "2:2:t",
1920                Deleted(
1921                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"},{"type":"text","mode":"segmented","text":"cd"}]}]"#,
1922                    "2:2:t",
1923                    "2:2:t",
1924                ),
1925            ), // before a segmented block
1926            (
1927                'C',
1928                false,
1929                15,
1930                "3:2:t",
1931                "3:1:t",
1932                Deleted(
1933                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
1934                    "2:2:t",
1935                    "2:2:t",
1936                ),
1937            ), // non-collapsed in segmented
1938            ('C', false, 16, "1:0:e", "1:0:e", NoWindow), // only empty paragraph
1939            ('C', false, 17, "3:0:t", "3:0:t", NoWindow), // after empty paragraph
1940            (
1941                'C',
1942                false,
1943                8,
1944                "2:1:t",
1945                "2:1:t",
1946                Deleted(
1947                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
1948                    "2:1:t",
1949                    "2:1:t",
1950                ),
1951            ), // before empty paragraph
1952            ('W', true, 0, "2:1:t", "2:1:t", NoWindow), // mid text
1953            ('W', true, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
1954            (
1955                'W',
1956                true,
1957                2,
1958                "4:0:t",
1959                "4:0:t",
1960                Deleted(
1961                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
1962                    "2:3:t",
1963                    "2:3:t",
1964                ),
1965            ), // start of second paragraph
1966            ('W', true, 4, "2:1:t", "2:1:t", NoWindow), // text before linebreak
1967            (
1968                'W',
1969                true,
1970                6,
1971                "2:1:t",
1972                "2:4:t",
1973                Deleted(
1974                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1975                    "2:1:t",
1976                    "2:1:t",
1977                ),
1978            ), // non-collapsed
1979            (
1980                'W',
1981                true,
1982                6,
1983                "2:4:t",
1984                "2:1:t",
1985                Deleted(
1986                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
1987                    "2:1:t",
1988                    "2:1:t",
1989                ),
1990            ), // non-collapsed backward
1991            (
1992                'W',
1993                true,
1994                2,
1995                "2:1:t",
1996                "4:2:t",
1997                Deleted(
1998                    r#"[{"type":"paragraph","children":[{"type":"text","text":"af"}]}]"#,
1999                    "2:1:t",
2000                    "2:1:t",
2001                ),
2002            ), // non-collapsed across blocks
2003            (
2004                'W',
2005                true,
2006                2,
2007                "2:0:t",
2008                "4:3:t",
2009                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "5:0:e", "5:0:e"),
2010            ), // whole document
2011            (
2012                'W',
2013                true,
2014                8,
2015                "3:0:e",
2016                "3:0:e",
2017                Deleted(
2018                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2019                    "2:1:t",
2020                    "2:1:t",
2021                ),
2022            ), // empty last paragraph
2023            (
2024                'W',
2025                true,
2026                9,
2027                "3:0:e",
2028                "3:0:e",
2029                Deleted(
2030                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
2031                    "2:1:t",
2032                    "2:1:t",
2033                ),
2034            ), // empty middle paragraph
2035            (
2036                'W',
2037                true,
2038                10,
2039                "2:0:e",
2040                "2:0:e",
2041                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "1:0:e", "1:0:e"),
2042            ), // two empty paragraphs
2043            (
2044                'W',
2045                true,
2046                11,
2047                "3:0:e",
2048                "3:0:e",
2049                Deleted(
2050                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"}]}]"#,
2051                    "2:1:t",
2052                    "2:1:t",
2053                ),
2054            ), // paragraph with only a linebreak
2055            (
2056                'W',
2057                true,
2058                13,
2059                "4:0:t",
2060                "4:0:t",
2061                Deleted(
2062                    r#"[{"type":"paragraph","children":[{"type":"text","mode":"token","text":"ab"},{"type":"text","text":"cd"}]}]"#,
2063                    "2:2:t",
2064                    "2:2:t",
2065                ),
2066            ), // after a token block
2067            (
2068                'W',
2069                true,
2070                15,
2071                "3:2:t",
2072                "3:1:t",
2073                Deleted(
2074                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
2075                    "2:2:t",
2076                    "2:2:t",
2077                ),
2078            ), // non-collapsed in segmented
2079            (
2080                'W',
2081                true,
2082                17,
2083                "3:0:t",
2084                "3:0:t",
2085                Deleted(
2086                    r#"[{"type":"paragraph","children":[{"type":"text","text":"def"}]}]"#,
2087                    "3:0:t",
2088                    "3:0:t",
2089                ),
2090            ), // after empty paragraph
2091            ('W', false, 0, "2:1:t", "2:1:t", NoWindow), // mid text
2092            ('W', false, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
2093            (
2094                'W',
2095                false,
2096                2,
2097                "2:3:t",
2098                "2:3:t",
2099                Deleted(
2100                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
2101                    "2:3:t",
2102                    "2:3:t",
2103                ),
2104            ), // end of first paragraph
2105            ('W', false, 4, "2:1:t", "2:1:t", NoWindow), // text before linebreak
2106            (
2107                'W',
2108                false,
2109                6,
2110                "2:1:t",
2111                "2:4:t",
2112                Deleted(
2113                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2114                    "2:1:t",
2115                    "2:1:t",
2116                ),
2117            ), // non-collapsed
2118            (
2119                'W',
2120                false,
2121                6,
2122                "2:4:t",
2123                "2:1:t",
2124                Deleted(
2125                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2126                    "2:1:t",
2127                    "2:1:t",
2128                ),
2129            ), // non-collapsed backward
2130            (
2131                'W',
2132                false,
2133                2,
2134                "2:1:t",
2135                "4:2:t",
2136                Deleted(
2137                    r#"[{"type":"paragraph","children":[{"type":"text","text":"af"}]}]"#,
2138                    "2:1:t",
2139                    "2:1:t",
2140                ),
2141            ), // non-collapsed across blocks
2142            (
2143                'W',
2144                false,
2145                2,
2146                "2:0:t",
2147                "4:3:t",
2148                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "5:0:e", "5:0:e"),
2149            ), // whole document
2150            (
2151                'W',
2152                false,
2153                7,
2154                "1:0:e",
2155                "1:0:e",
2156                Deleted(
2157                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2158                    "3:0:t",
2159                    "3:0:t",
2160                ),
2161            ), // empty first paragraph
2162            (
2163                'W',
2164                false,
2165                9,
2166                "3:0:e",
2167                "3:0:e",
2168                Deleted(
2169                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
2170                    "5:0:t",
2171                    "5:0:t",
2172                ),
2173            ), // empty middle paragraph
2174            (
2175                'W',
2176                false,
2177                12,
2178                "2:1:t",
2179                "2:1:t",
2180                Deleted(
2181                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"},{"type":"text","text":"b"}]}]"#,
2182                    "2:1:t",
2183                    "2:1:t",
2184                ),
2185            ), // before a block starting with a linebreak
2186            (
2187                'W',
2188                false,
2189                14,
2190                "2:2:t",
2191                "2:2:t",
2192                Deleted(
2193                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"},{"type":"text","mode":"segmented","text":"cd"}]}]"#,
2194                    "2:2:t",
2195                    "2:2:t",
2196                ),
2197            ), // before a segmented block
2198            (
2199                'W',
2200                false,
2201                15,
2202                "3:2:t",
2203                "3:1:t",
2204                Deleted(
2205                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
2206                    "2:2:t",
2207                    "2:2:t",
2208                ),
2209            ), // non-collapsed in segmented
2210            (
2211                'W',
2212                false,
2213                8,
2214                "2:1:t",
2215                "2:1:t",
2216                Deleted(
2217                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2218                    "2:1:t",
2219                    "2:1:t",
2220                ),
2221            ), // before empty paragraph
2222            ('L', true, 0, "2:1:t", "2:1:t", NoWindow), // mid text
2223            ('L', true, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
2224            (
2225                'L',
2226                true,
2227                2,
2228                "4:0:t",
2229                "4:0:t",
2230                Deleted(
2231                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
2232                    "2:3:t",
2233                    "2:3:t",
2234                ),
2235            ), // start of second paragraph
2236            ('L', true, 4, "2:1:t", "2:1:t", NoWindow), // text before linebreak
2237            (
2238                'L',
2239                true,
2240                6,
2241                "2:1:t",
2242                "2:4:t",
2243                Deleted(
2244                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2245                    "2:1:t",
2246                    "2:1:t",
2247                ),
2248            ), // non-collapsed
2249            (
2250                'L',
2251                true,
2252                6,
2253                "2:4:t",
2254                "2:1:t",
2255                Deleted(
2256                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2257                    "2:1:t",
2258                    "2:1:t",
2259                ),
2260            ), // non-collapsed backward
2261            (
2262                'L',
2263                true,
2264                8,
2265                "3:0:e",
2266                "3:0:e",
2267                Deleted(
2268                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2269                    "2:1:t",
2270                    "2:1:t",
2271                ),
2272            ), // empty last paragraph
2273            (
2274                'L',
2275                true,
2276                9,
2277                "3:0:e",
2278                "3:0:e",
2279                Deleted(
2280                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
2281                    "2:1:t",
2282                    "2:1:t",
2283                ),
2284            ), // empty middle paragraph
2285            (
2286                'L',
2287                true,
2288                10,
2289                "2:0:e",
2290                "2:0:e",
2291                Deleted(r#"[{"type":"paragraph","children":[]}]"#, "1:0:e", "1:0:e"),
2292            ), // two empty paragraphs
2293            (
2294                'L',
2295                true,
2296                11,
2297                "3:0:e",
2298                "3:0:e",
2299                Deleted(
2300                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"}]}]"#,
2301                    "2:1:t",
2302                    "2:1:t",
2303                ),
2304            ), // paragraph with only a linebreak
2305            (
2306                'L',
2307                true,
2308                13,
2309                "4:0:t",
2310                "4:0:t",
2311                Deleted(
2312                    r#"[{"type":"paragraph","children":[{"type":"text","mode":"token","text":"ab"},{"type":"text","text":"cd"}]}]"#,
2313                    "2:2:t",
2314                    "2:2:t",
2315                ),
2316            ), // after a token block
2317            (
2318                'L',
2319                true,
2320                15,
2321                "3:2:t",
2322                "3:1:t",
2323                Deleted(
2324                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
2325                    "2:2:t",
2326                    "2:2:t",
2327                ),
2328            ), // non-collapsed in segmented
2329            (
2330                'L',
2331                true,
2332                17,
2333                "3:0:t",
2334                "3:0:t",
2335                Deleted(
2336                    r#"[{"type":"paragraph","children":[{"type":"text","text":"def"}]}]"#,
2337                    "3:0:t",
2338                    "3:0:t",
2339                ),
2340            ), // after empty paragraph
2341            ('L', false, 0, "2:1:t", "2:1:t", NoWindow), // mid text
2342            ('L', false, 0, "2:0:t", "2:0:t", NoWindow), // text start, only node
2343            (
2344                'L',
2345                false,
2346                2,
2347                "2:3:t",
2348                "2:3:t",
2349                Deleted(
2350                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcdef"}]}]"#,
2351                    "2:3:t",
2352                    "2:3:t",
2353                ),
2354            ), // end of first paragraph
2355            ('L', false, 4, "2:1:t", "2:1:t", NoWindow), // text before linebreak
2356            (
2357                'L',
2358                false,
2359                6,
2360                "2:1:t",
2361                "2:4:t",
2362                Deleted(
2363                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2364                    "2:1:t",
2365                    "2:1:t",
2366                ),
2367            ), // non-collapsed
2368            (
2369                'L',
2370                false,
2371                6,
2372                "2:4:t",
2373                "2:1:t",
2374                Deleted(
2375                    r#"[{"type":"paragraph","children":[{"type":"text","text":"aef"}]}]"#,
2376                    "2:1:t",
2377                    "2:1:t",
2378                ),
2379            ), // non-collapsed backward
2380            (
2381                'L',
2382                false,
2383                7,
2384                "1:0:e",
2385                "1:0:e",
2386                Deleted(
2387                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2388                    "3:0:t",
2389                    "3:0:t",
2390                ),
2391            ), // empty first paragraph
2392            (
2393                'L',
2394                false,
2395                9,
2396                "3:0:e",
2397                "3:0:e",
2398                Deleted(
2399                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]},{"type":"paragraph","children":[{"type":"text","text":"b"}]}]"#,
2400                    "root:1:e",
2401                    "root:1:e",
2402                ),
2403            ), // empty middle paragraph
2404            (
2405                'L',
2406                false,
2407                12,
2408                "2:1:t",
2409                "2:1:t",
2410                Deleted(
2411                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"linebreak"},{"type":"text","text":"b"}]}]"#,
2412                    "2:1:t",
2413                    "2:1:t",
2414                ),
2415            ), // before a block starting with a linebreak
2416            (
2417                'L',
2418                false,
2419                14,
2420                "2:2:t",
2421                "2:2:t",
2422                Deleted(
2423                    r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"},{"type":"text","mode":"segmented","text":"cd"}]}]"#,
2424                    "2:2:t",
2425                    "2:2:t",
2426                ),
2427            ), // before a segmented block
2428            (
2429                'L',
2430                false,
2431                15,
2432                "3:2:t",
2433                "3:1:t",
2434                Deleted(
2435                    r#"[{"type":"paragraph","children":[{"type":"text","text":"abcd"}]}]"#,
2436                    "2:2:t",
2437                    "2:2:t",
2438                ),
2439            ), // non-collapsed in segmented
2440            (
2441                'L',
2442                false,
2443                8,
2444                "2:1:t",
2445                "2:1:t",
2446                Deleted(
2447                    r#"[{"type":"paragraph","children":[{"type":"text","text":"a"}]}]"#,
2448                    "2:1:t",
2449                    "2:1:t",
2450                ),
2451            ), // before empty paragraph
2452        ];
2453        let point = |spec: &str| {
2454            let mut parts = spec.split(':');
2455            let key = parts.next().unwrap().to_owned();
2456            let offset: usize = parts.next().unwrap().parse().unwrap();
2457            let point_type = match parts.next().unwrap() {
2458                "t" => PointType::Text,
2459                _ => PointType::Element,
2460            };
2461            Point::new(key, offset, point_type)
2462        };
2463        let show = |p: &Point| {
2464            let t = match p.point_type {
2465                PointType::Text => "t",
2466                PointType::Element => "e",
2467            };
2468            format!("{}:{}:{t}", p.key, p.offset)
2469        };
2470        let discrete = || UpdateOptions {
2471            discrete: true,
2472            ..UpdateOptions::default()
2473        };
2474        for (method, is_backward, doc, anchor, focus, want) in cases {
2475            let label = format!("{method} {is_backward} doc {doc} {anchor} {focus}");
2476            reset_random_key();
2477            let editor = create_editor(CreateEditorArgs::default());
2478            let children = json::parse(docs[*doc]).unwrap();
2479            editor
2480                .update(
2481                    move || {
2482                        let nodes: Vec<NodeRef> = children
2483                            .as_array()
2484                            .unwrap()
2485                            .iter()
2486                            .map(|n| parse_serialized_node(n).unwrap())
2487                            .collect();
2488                        get_root().append(&nodes)
2489                    },
2490                    discrete(),
2491                )
2492                .unwrap();
2493            let before = json::stringify(&editor.get_editor_state().to_json(true));
2494            let (anchor, focus, method, is_backward) =
2495                (point(anchor), point(focus), *method, *is_backward);
2496            let result = editor.update(
2497                move || {
2498                    let selection = create_range_selection();
2499                    selection.point_set(
2500                        Which::Anchor,
2501                        &anchor.key,
2502                        anchor.offset,
2503                        anchor.point_type,
2504                    )?;
2505                    selection.point_set(
2506                        Which::Focus,
2507                        &focus.key,
2508                        focus.offset,
2509                        focus.point_type,
2510                    )?;
2511                    set_selection(Some(selection.clone()));
2512                    match method {
2513                        'C' => selection.delete_character(is_backward),
2514                        'W' => selection.delete_word(is_backward),
2515                        _ => selection.delete_line(is_backward),
2516                    }
2517                },
2518                discrete(),
2519            );
2520            let state = editor.get_editor_state();
2521            let compact = json::stringify(&state.to_json(true)).unwrap();
2522            match want {
2523                NoWindow => {
2524                    assert_eq!(
2525                        result.map_err(|e| e.message().to_owned()),
2526                        Err("window object not found".to_owned()),
2527                        "{label}"
2528                    );
2529                    assert_eq!(Some(compact), before, "{label}");
2530                }
2531                Deleted(children, want_anchor, want_focus) => {
2532                    assert_eq!(result, Ok(()), "{label}");
2533                    assert_eq!(
2534                        compact,
2535                        format!(r#"{{"root":{{"type":"root","children":{children}}}}}"#),
2536                        "{label}"
2537                    );
2538                    let Some(Selection::Range(range)) = state.selection().map(|s| s.get()) else {
2539                        panic!("{label}: no range selection");
2540                    };
2541                    assert_eq!(
2542                        (show(&range.anchor), show(&range.focus)),
2543                        (want_anchor.to_string(), want_focus.to_string()),
2544                        "{label}"
2545                    );
2546                }
2547            }
2548        }
2549    }
2550
2551    /// A [`SelectionMovement`] that never leaves a text node: a character is
2552    /// a code point with the combining marks (U+0300 to U+036F) and variation
2553    /// selector 16 after it, a word is the spaces and then the non-spaces in
2554    /// the direction, and a line boundary is the text node's edge. The JS
2555    /// expectations below come from stubbing `Selection.prototype.modify`
2556    /// with the same rules in jsdom.
2557    struct TestMovement;
2558
2559    impl SelectionMovement for TestMovement {
2560        fn landed_point(
2561            &self,
2562            from: &Point,
2563            is_backward: bool,
2564            granularity: SelectionGranularity,
2565        ) -> Result<Option<Point>, LexicalError> {
2566            if from.point_type != PointType::Text {
2567                return Ok(None);
2568            }
2569            let text: Vec<u16> = from.get_node()?.get_text_content().encode_utf16().collect();
2570            let len = text.len();
2571            let is_mark = |c: u16| (0x300..=0x36f).contains(&c) || c == 0xfe0f;
2572            let is_high = |c: u16| (0xd800..=0xdbff).contains(&c);
2573            let is_low = |c: u16| (0xdc00..=0xdfff).contains(&c);
2574            let is_space = |c: u16| c == u16::from(b' ');
2575            let mut o = from.offset;
2576            match (granularity, is_backward) {
2577                (SelectionGranularity::Character, true) => {
2578                    while o > 0 && is_mark(text[o - 1]) {
2579                        o -= 1;
2580                    }
2581                    if o > 0 {
2582                        o -= 1;
2583                        if o > 0 && is_low(text[o]) && is_high(text[o - 1]) {
2584                            o -= 1;
2585                        }
2586                    }
2587                }
2588                (SelectionGranularity::Character, false) => {
2589                    if o < len {
2590                        o += if is_high(text[o]) && o + 1 < len && is_low(text[o + 1]) {
2591                            2
2592                        } else {
2593                            1
2594                        };
2595                        while o < len && is_mark(text[o]) {
2596                            o += 1;
2597                        }
2598                    }
2599                }
2600                (SelectionGranularity::Word, true) => {
2601                    while o > 0 && is_space(text[o - 1]) {
2602                        o -= 1;
2603                    }
2604                    while o > 0 && !is_space(text[o - 1]) {
2605                        o -= 1;
2606                    }
2607                }
2608                (SelectionGranularity::Word, false) => {
2609                    while o < len && is_space(text[o]) {
2610                        o += 1;
2611                    }
2612                    while o < len && !is_space(text[o]) {
2613                        o += 1;
2614                    }
2615                }
2616                (_, true) => o = 0,
2617                (_, false) => o = len,
2618            }
2619            Ok((o != from.offset).then(|| Point::new(from.key.clone(), o, PointType::Text)))
2620        }
2621    }
2622
2623    /// `key:offset:t|e` as a point.
2624    fn parse_point(spec: &str) -> Point {
2625        let mut parts = spec.split(':');
2626        let key = parts.next().unwrap().to_owned();
2627        let offset = parts.next().unwrap().parse().unwrap();
2628        let point_type = match parts.next().unwrap() {
2629            "t" => PointType::Text,
2630            _ => PointType::Element,
2631        };
2632        Point::new(key, offset, point_type)
2633    }
2634
2635    fn show_point(point: &Point) -> String {
2636        let t = match point.point_type {
2637            PointType::Text => "t",
2638            PointType::Element => "e",
2639        };
2640        format!("{}:{}:{t}", point.key, point.offset)
2641    }
2642
2643    /// `deleteCharacter`, `deleteWord`, `deleteLine` (`C`, `W`, `L`, `<`
2644    /// backward and `>` forward) and `modify` (`move` or `extend`, the
2645    /// direction, then `c`haracter, `w`ord or `l`ineboundary) with
2646    /// [`TestMovement`], as JS gives them for an editor with a root element in
2647    /// jsdom and `Selection.prototype.modify` stubbed to move the same way.
2648    /// Each line: the operation, the document, anchor and focus | the anchor,
2649    /// focus and format after it | the root's children after it (`=` when
2650    /// unchanged).
2651    #[test]
2652    fn deletion_and_modify_with_a_movement_match_js() {
2653        let docs = [
2654            r#"[{"type":"paragraph","children":[{"type":"text","text":"hello big world"}]}]"#,
2655            r#"[{"type":"paragraph","children":[{"type":"text","text":"a😀b"}]}]"#,
2656            r#"[{"type":"paragraph","children":[{"type":"text","text":"aéb"}]}]"#,
2657            r#"[{"type":"paragraph","children":[{"type":"text","text":"a❤️b"}]}]"#,
2658            r#"[{"type":"paragraph","children":[{"type":"text","format":1,"text":"ab"},{"type":"text","text":"cd"}],"textFormat":1}]"#,
2659            r#"[{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"},{"type":"text","detail":2,"text":"cd"}]}]"#,
2660            r#"[{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]"#,
2661            r#"[{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef gh"}]}]"#,
2662            r#"[{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo bar baz"},{"type":"text","text":" y"}]}]"#,
2663            r#"[{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"token","text":"tok"},{"type":"text","text":" y"}]}]"#,
2664            r#"[{"type":"paragraph","children":[{"type":"text","text":"ab"}]},{"type":"paragraph","children":[]}]"#,
2665        ];
2666        let cases = r#"
2667C< 0 2:7:t 2:7:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello ig world"}]}]
2668W< 0 2:7:t 2:7:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello ig world"}]}]
2669L< 0 2:7:t 2:7:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ig world"}]}]
2670C> 0 2:7:t 2:7:t | 2:7:t 2:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello bg world"}]}]
2671W> 0 2:7:t 2:7:t | 2:7:t 2:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello b world"}]}]
2672L> 0 2:7:t 2:7:t | 2:7:t 2:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello b"}]}]
2673move<c 0 2:7:t 2:7:t | 2:6:t 2:6:t 0 | =
2674move<w 0 2:7:t 2:7:t | 2:6:t 2:6:t 0 | =
2675move<l 0 2:7:t 2:7:t | 2:0:t 2:0:t 0 | =
2676move>c 0 2:7:t 2:7:t | 2:8:t 2:8:t 0 | =
2677move>w 0 2:7:t 2:7:t | 2:9:t 2:9:t 0 | =
2678move>l 0 2:7:t 2:7:t | 2:15:t 2:15:t 0 | =
2679extend<c 0 2:7:t 2:7:t | 2:7:t 2:6:t 0 | =
2680extend<w 0 2:7:t 2:7:t | 2:7:t 2:6:t 0 | =
2681extend<l 0 2:7:t 2:7:t | 2:7:t 2:0:t 0 | =
2682extend>c 0 2:7:t 2:7:t | 2:7:t 2:8:t 0 | =
2683extend>w 0 2:7:t 2:7:t | 2:7:t 2:9:t 0 | =
2684extend>l 0 2:7:t 2:7:t | 2:7:t 2:15:t 0 | =
2685C< 0 2:6:t 2:6:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hellobig world"}]}]
2686W< 0 2:6:t 2:6:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"big world"}]}]
2687L< 0 2:6:t 2:6:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"big world"}]}]
2688C> 0 2:6:t 2:6:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello ig world"}]}]
2689W> 0 2:6:t 2:6:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello  world"}]}]
2690L> 0 2:6:t 2:6:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello "}]}]
2691C< 0 2:5:t 2:5:t | 2:4:t 2:4:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hell big world"}]}]
2692W< 0 2:5:t 2:5:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":" big world"}]}]
2693L< 0 2:5:t 2:5:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":" big world"}]}]
2694C> 0 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hellobig world"}]}]
2695W> 0 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello world"}]}]
2696L> 0 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello"}]}]
2697C< 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2698W< 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2699L< 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2700C> 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ello big world"}]}]
2701W> 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":" big world"}]}]
2702L> 0 2:0:t 2:0:t | 1:0:e 1:0:e 0 | [{"type":"paragraph","children":[]}]
2703move<c 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2704move<w 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2705move<l 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2706move>c 0 2:0:t 2:0:t | 2:1:t 2:1:t 0 | =
2707move>w 0 2:0:t 2:0:t | 2:5:t 2:5:t 0 | =
2708move>l 0 2:0:t 2:0:t | 2:15:t 2:15:t 0 | =
2709extend<c 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2710extend<w 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2711extend<l 0 2:0:t 2:0:t | 2:0:t 2:0:t 0 | =
2712extend>c 0 2:0:t 2:0:t | 2:0:t 2:1:t 0 | =
2713extend>w 0 2:0:t 2:0:t | 2:0:t 2:5:t 0 | =
2714extend>l 0 2:0:t 2:0:t | 2:0:t 2:15:t 0 | =
2715C< 0 2:15:t 2:15:t | 2:14:t 2:14:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello big worl"}]}]
2716W< 0 2:15:t 2:15:t | 2:10:t 2:10:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"hello big "}]}]
2717L< 0 2:15:t 2:15:t | 1:0:e 1:0:e 0 | [{"type":"paragraph","children":[]}]
2718C> 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2719W> 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2720L> 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2721move<c 0 2:15:t 2:15:t | 2:14:t 2:14:t 0 | =
2722move<w 0 2:15:t 2:15:t | 2:10:t 2:10:t 0 | =
2723move<l 0 2:15:t 2:15:t | 2:0:t 2:0:t 0 | =
2724move>c 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2725move>w 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2726move>l 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2727extend<c 0 2:15:t 2:15:t | 2:15:t 2:14:t 0 | =
2728extend<w 0 2:15:t 2:15:t | 2:15:t 2:10:t 0 | =
2729extend<l 0 2:15:t 2:15:t | 2:15:t 2:0:t 0 | =
2730extend>c 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2731extend>w 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2732extend>l 0 2:15:t 2:15:t | 2:15:t 2:15:t 0 | =
2733move<c 0 2:2:t 2:8:t | 2:2:t 2:2:t 0 | =
2734move<w 0 2:2:t 2:8:t | 2:6:t 2:6:t 0 | =
2735move<l 0 2:2:t 2:8:t | 2:0:t 2:0:t 0 | =
2736move>c 0 2:2:t 2:8:t | 2:8:t 2:8:t 0 | =
2737move>w 0 2:2:t 2:8:t | 2:9:t 2:9:t 0 | =
2738move>l 0 2:2:t 2:8:t | 2:15:t 2:15:t 0 | =
2739extend<c 0 2:2:t 2:8:t | 2:2:t 2:7:t 0 | =
2740extend<w 0 2:2:t 2:8:t | 2:2:t 2:6:t 0 | =
2741extend<l 0 2:2:t 2:8:t | 2:2:t 2:0:t 0 | =
2742extend>c 0 2:2:t 2:8:t | 2:2:t 2:9:t 0 | =
2743extend>w 0 2:2:t 2:8:t | 2:2:t 2:9:t 0 | =
2744extend>l 0 2:2:t 2:8:t | 2:2:t 2:15:t 0 | =
2745move<c 0 2:8:t 2:2:t | 2:2:t 2:2:t 0 | =
2746move<w 0 2:8:t 2:2:t | 2:0:t 2:0:t 0 | =
2747move<l 0 2:8:t 2:2:t | 2:0:t 2:0:t 0 | =
2748move>c 0 2:8:t 2:2:t | 2:8:t 2:8:t 0 | =
2749move>w 0 2:8:t 2:2:t | 2:5:t 2:5:t 0 | =
2750move>l 0 2:8:t 2:2:t | 2:15:t 2:15:t 0 | =
2751extend<c 0 2:8:t 2:2:t | 2:8:t 2:1:t 0 | =
2752extend<w 0 2:8:t 2:2:t | 2:8:t 2:0:t 0 | =
2753extend<l 0 2:8:t 2:2:t | 2:8:t 2:0:t 0 | =
2754extend>c 0 2:8:t 2:2:t | 2:8:t 2:3:t 0 | =
2755extend>w 0 2:8:t 2:2:t | 2:8:t 2:5:t 0 | =
2756extend>l 0 2:8:t 2:2:t | 2:8:t 2:15:t 0 | =
2757C< 1 2:3:t 2:3:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2758W< 1 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2759L< 1 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2760C> 1 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2761W> 1 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2762L> 1 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2763C< 2 2:3:t 2:3:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"aeb"}]}]
2764W< 2 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2765L< 2 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2766C> 2 2:1:t 2:1:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"aeb"}]}]
2767W> 2 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2768L> 2 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2769C< 3 2:3:t 2:3:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2770W< 3 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2771L< 3 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"b"}]}]
2772C> 3 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2773W> 3 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2774L> 3 2:1:t 2:1:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"a"}]}]
2775C< 4 2:2:t 2:2:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"a"},{"type":"text","text":"cd"}],"textFormat":1}]
2776W< 4 2:2:t 2:2:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"cd"}]}]
2777L< 4 2:2:t 2:2:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"cd"}]}]
2778C> 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2779W> 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2780L> 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2781move<c 4 2:2:t 2:2:t | 2:1:t 2:1:t 0 | =
2782move<w 4 2:2:t 2:2:t | 2:0:t 2:0:t 0 | =
2783move<l 4 2:2:t 2:2:t | 2:0:t 2:0:t 0 | =
2784move>c 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2785move>w 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2786move>l 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2787extend<c 4 2:2:t 2:2:t | 2:2:t 2:1:t 0 | =
2788extend<w 4 2:2:t 2:2:t | 2:2:t 2:0:t 0 | =
2789extend<l 4 2:2:t 2:2:t | 2:2:t 2:0:t 0 | =
2790extend>c 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2791extend>w 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2792extend>l 4 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2793C< 4 3:0:t 3:0:t | 3:0:t 3:0:t 0 | =
2794W< 4 3:0:t 3:0:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"a"},{"type":"text","text":"cd"}],"textFormat":1}]
2795L< 4 3:0:t 3:0:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"a"},{"type":"text","text":"cd"}],"textFormat":1}]
2796C> 4 3:0:t 3:0:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"ab"},{"type":"text","text":"d"}],"textFormat":1}]
2797W> 4 3:0:t 3:0:t | 2:2:t 2:2:t 1 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"ab"}],"textFormat":1}]
2798L> 4 3:0:t 3:0:t | 2:2:t 2:2:t 1 | [{"type":"paragraph","children":[{"type":"text","format":1,"text":"ab"}],"textFormat":1}]
2799move<c 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2800move<w 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2801move<l 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2802move>c 4 3:0:t 3:0:t | 3:1:t 3:1:t 0 | =
2803move>w 4 3:0:t 3:0:t | 3:2:t 3:2:t 0 | =
2804move>l 4 3:0:t 3:0:t | 3:2:t 3:2:t 0 | =
2805extend<c 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2806extend<w 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2807extend<l 4 3:0:t 3:0:t | 2:2:t 2:2:t 0 | =
2808extend>c 4 3:0:t 3:0:t | 3:0:t 3:1:t 0 | =
2809extend>w 4 3:0:t 3:0:t | 3:0:t 3:2:t 0 | =
2810extend>l 4 3:0:t 3:0:t | 3:0:t 3:2:t 0 | =
2811C< 5 2:2:t 2:2:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"a"},{"type":"text","detail":2,"text":"cd"}]}]
2812W< 5 2:2:t 2:2:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"cd"}]}]
2813L< 5 2:2:t 2:2:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"cd"}]}]
2814C> 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"},{"type":"text","detail":2,"text":"d"}]}]
2815W> 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"},{"type":"text","detail":2,"text":"d"}]}]
2816L> 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"},{"type":"text","detail":2,"text":"d"}]}]
2817move<c 5 2:2:t 2:2:t | 2:1:t 2:1:t 0 | =
2818move<w 5 2:2:t 2:2:t | 2:0:t 2:0:t 0 | =
2819move<l 5 2:2:t 2:2:t | 2:0:t 2:0:t 0 | =
2820move>c 5 2:2:t 2:2:t | 3:1:t 3:1:t 0 | =
2821move>w 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2822move>l 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2823extend<c 5 2:2:t 2:2:t | 2:2:t 2:1:t 0 | =
2824extend<w 5 2:2:t 2:2:t | 2:2:t 2:0:t 0 | =
2825extend<l 5 2:2:t 2:2:t | 2:2:t 2:0:t 0 | =
2826extend>c 5 2:2:t 2:2:t | 2:2:t 3:1:t 0 | =
2827extend>w 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2828extend>l 5 2:2:t 2:2:t | 2:2:t 2:2:t 0 | =
2829C< 5 3:0:t 3:0:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"a"},{"type":"text","detail":2,"text":"cd"}]}]
2830W< 5 3:0:t 3:0:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"a"},{"type":"text","detail":2,"text":"cd"}]}]
2831L< 5 3:0:t 3:0:t | 2:1:t 2:1:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"a"},{"type":"text","detail":2,"text":"cd"}]}]
2832C> 5 3:0:t 3:0:t | 3:0:t 3:0:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"},{"type":"text","detail":2,"text":"d"}]}]
2833W> 5 3:0:t 3:0:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"}]}]
2834L> 5 3:0:t 3:0:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","detail":2,"text":"ab"}]}]
2835move<c 5 3:0:t 3:0:t | 2:1:t 2:1:t 0 | =
2836move<w 5 3:0:t 3:0:t | 3:0:t 3:0:t 0 | =
2837move<l 5 3:0:t 3:0:t | 3:0:t 3:0:t 0 | =
2838move>c 5 3:0:t 3:0:t | 3:1:t 3:1:t 0 | =
2839move>w 5 3:0:t 3:0:t | 3:2:t 3:2:t 0 | =
2840move>l 5 3:0:t 3:0:t | 3:2:t 3:2:t 0 | =
2841extend<c 5 3:0:t 3:0:t | 3:0:t 2:1:t 0 | =
2842extend<w 5 3:0:t 3:0:t | 3:0:t 3:0:t 0 | =
2843extend<l 5 3:0:t 3:0:t | 3:0:t 3:0:t 0 | =
2844extend>c 5 3:0:t 3:0:t | 3:0:t 3:1:t 0 | =
2845extend>w 5 3:0:t 3:0:t | 3:0:t 3:2:t 0 | =
2846extend>l 5 3:0:t 3:0:t | 3:0:t 3:2:t 0 | =
2847C< 6 4:3:t 4:3:t | 4:2:t 4:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"efgh"}]}]
2848W< 6 4:3:t 4:3:t | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"gh"}]}]
2849L< 6 4:3:t 4:3:t | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"gh"}]}]
2850C> 6 4:3:t 4:3:t | 4:3:t 4:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"ef h"}]}]
2851W> 6 4:3:t 4:3:t | 4:3:t 4:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"ef "}]}]
2852L> 6 4:3:t 4:3:t | 4:3:t 4:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"ef "}]}]
2853C< 6 2:3:t 2:3:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"abcd"},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2854W< 6 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"cd"},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2855L< 6 2:3:t 2:3:t | 2:0:t 2:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"cd"},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2856C> 6 2:3:t 2:3:t | 2:3:t 2:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab d"},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2857W> 6 2:3:t 2:3:t | 2:3:t 2:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab "},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2858L> 6 2:3:t 2:3:t | 2:3:t 2:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab "},{"type":"linebreak"},{"type":"text","text":"ef gh"}]}]
2859C< 6 1:2:e 1:2:e | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2860W< 6 1:2:e 1:2:e | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2861L< 6 1:2:e 1:2:e | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2862C> 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2863W> 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"f gh"}]}]
2864L> 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"},{"type":"linebreak"},{"type":"text","text":"f gh"}]}]
2865move<c 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2866move<w 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2867move<l 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2868move>c 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2869move>w 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2870move>l 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2871extend<c 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2872extend<w 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2873extend<l 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2874extend>c 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2875extend>w 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2876extend>l 6 1:2:e 1:2:e | 4:0:t 4:0:t 0 | =
2877C< 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2878W< 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2879L< 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2880C> 7 4:0:t 4:0:t | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"f gh"}]}]
2881W> 7 4:0:t 4:0:t | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":" gh"}]}]
2882L> 7 4:0:t 4:0:t | 3:0:e 3:0:e 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[]}]
2883move<c 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | =
2884move<w 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | =
2885move<l 7 4:0:t 4:0:t | 2:5:t 2:5:t 0 | =
2886move>c 7 4:0:t 4:0:t | 4:1:t 4:1:t 0 | =
2887move>w 7 4:0:t 4:0:t | 4:2:t 4:2:t 0 | =
2888move>l 7 4:0:t 4:0:t | 4:5:t 4:5:t 0 | =
2889extend<c 7 4:0:t 4:0:t | 4:0:t 2:5:t 0 | =
2890extend<w 7 4:0:t 4:0:t | 4:0:t 2:5:t 0 | =
2891extend<l 7 4:0:t 4:0:t | 4:0:t 2:5:t 0 | =
2892extend>c 7 4:0:t 4:0:t | 4:0:t 4:1:t 0 | =
2893extend>w 7 4:0:t 4:0:t | 4:0:t 4:2:t 0 | =
2894extend>l 7 4:0:t 4:0:t | 4:0:t 4:5:t 0 | =
2895C< 7 2:5:t 2:5:t | 2:4:t 2:4:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab c"}]},{"type":"paragraph","children":[{"type":"text","text":"ef gh"}]}]
2896W< 7 2:5:t 2:5:t | 2:3:t 2:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab "}]},{"type":"paragraph","children":[{"type":"text","text":"ef gh"}]}]
2897L< 7 2:5:t 2:5:t | 1:0:e 1:0:e 0 | [{"type":"paragraph","children":[]},{"type":"paragraph","children":[{"type":"text","text":"ef gh"}]}]
2898C> 7 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2899W> 7 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2900L> 7 2:5:t 2:5:t | 2:5:t 2:5:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cdef gh"}]}]
2901move<c 7 2:5:t 2:5:t | 2:4:t 2:4:t 0 | =
2902move<w 7 2:5:t 2:5:t | 2:3:t 2:3:t 0 | =
2903move<l 7 2:5:t 2:5:t | 2:0:t 2:0:t 0 | =
2904move>c 7 2:5:t 2:5:t | 4:0:t 4:0:t 0 | =
2905move>w 7 2:5:t 2:5:t | 4:0:t 4:0:t 0 | =
2906move>l 7 2:5:t 2:5:t | 4:0:t 4:0:t 0 | =
2907extend<c 7 2:5:t 2:5:t | 2:5:t 2:4:t 0 | =
2908extend<w 7 2:5:t 2:5:t | 2:5:t 2:3:t 0 | =
2909extend<l 7 2:5:t 2:5:t | 2:5:t 2:0:t 0 | =
2910extend>c 7 2:5:t 2:5:t | 2:5:t 4:0:t 0 | =
2911extend>w 7 2:5:t 2:5:t | 2:5:t 4:0:t 0 | =
2912extend>l 7 2:5:t 2:5:t | 2:5:t 4:0:t 0 | =
2913C< 7 4:4:t 4:4:t | 4:3:t 4:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef h"}]}]
2914W< 7 4:4:t 4:4:t | 4:3:t 4:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef h"}]}]
2915L< 7 4:4:t 4:4:t | 4:0:t 4:0:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"h"}]}]
2916C> 7 4:4:t 4:4:t | 4:4:t 4:4:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef g"}]}]
2917W> 7 4:4:t 4:4:t | 4:4:t 4:4:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef g"}]}]
2918L> 7 4:4:t 4:4:t | 4:4:t 4:4:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab cd"}]},{"type":"paragraph","children":[{"type":"text","text":"ef g"}]}]
2919C< 8 3:5:t 3:5:t | 3:3:t 3:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo baz"},{"type":"text","text":" y"}]}]
2920W< 8 3:5:t 3:5:t | 2:6:t 2:6:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x foo ar baz y"}]}]
2921L< 8 3:5:t 3:5:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x ar baz y"}]}]
2922C> 8 3:5:t 3:5:t | 3:3:t 3:3:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo baz"},{"type":"text","text":" y"}]}]
2923W> 8 3:5:t 3:5:t | 2:7:t 2:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x foo b baz y"}]}]
2924L> 8 3:5:t 3:5:t | 2:7:t 2:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x foo b y"}]}]
2925C< 8 3:11:t 3:11:t | 3:7:t 3:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo bar"},{"type":"text","text":" y"}]}]
2926W< 8 3:11:t 3:11:t | 2:10:t 2:10:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x foo bar  y"}]}]
2927L< 8 3:11:t 3:11:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2928C< 8 4:0:t 4:0:t | 4:0:t 4:0:t 0 | =
2929W< 8 4:0:t 4:0:t | 3:7:t 3:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo bar"},{"type":"text","text":" y"}]}]
2930L< 8 4:0:t 4:0:t | 3:7:t 3:7:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x "},{"type":"text","mode":"segmented","text":"foo bar"},{"type":"text","text":" y"}]}]
2931C< 9 3:3:t 3:3:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2932W< 9 3:3:t 3:3:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2933L< 9 3:3:t 3:3:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2934C> 9 3:1:t 3:1:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2935W> 9 3:1:t 3:1:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2936L> 9 3:1:t 3:1:t | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"x  y"}]}]
2937C< 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2938W< 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2939L< 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | [{"type":"paragraph","children":[{"type":"text","text":"ab"}]}]
2940C> 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2941W> 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2942L> 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2943move<c 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | =
2944move<w 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | =
2945move<l 10 3:0:e 3:0:e | 2:2:t 2:2:t 0 | =
2946move>c 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2947move>w 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2948move>l 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2949extend<c 10 3:0:e 3:0:e | 3:0:e 2:2:t 0 | =
2950extend<w 10 3:0:e 3:0:e | 3:0:e 2:2:t 0 | =
2951extend<l 10 3:0:e 3:0:e | 3:0:e 2:2:t 0 | =
2952extend>c 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2953extend>w 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2954extend>l 10 3:0:e 3:0:e | 3:0:e 3:0:e 0 | =
2955"#;
2956        let discrete = || UpdateOptions {
2957            discrete: true,
2958            ..UpdateOptions::default()
2959        };
2960        for line in cases.lines().filter(|l| !l.is_empty()) {
2961            let mut parts = line.splitn(3, " | ");
2962            let given: Vec<&str> = parts.next().unwrap().split(' ').collect();
2963            let want: Vec<&str> = parts.next().unwrap().split(' ').collect();
2964            let want_children = parts.next().unwrap();
2965            let (op, doc, anchor, focus) = (
2966                given[0].to_owned(),
2967                given[1].parse::<usize>().unwrap(),
2968                parse_point(given[2]),
2969                parse_point(given[3]),
2970            );
2971            reset_random_key();
2972            let editor = create_editor(CreateEditorArgs::default());
2973            editor.set_selection_movement(Some(Rc::new(TestMovement)));
2974            let children = json::parse(docs[doc]).unwrap();
2975            editor
2976                .update(
2977                    move || {
2978                        let nodes: Vec<NodeRef> = children
2979                            .as_array()
2980                            .unwrap()
2981                            .iter()
2982                            .map(|n| parse_serialized_node(n).unwrap())
2983                            .collect();
2984                        get_root().append(&nodes)
2985                    },
2986                    discrete(),
2987                )
2988                .unwrap();
2989            let before = json::stringify(&editor.get_editor_state().to_json(true)).unwrap();
2990            editor
2991                .update(
2992                    move || {
2993                        let selection = create_range_selection();
2994                        selection.point_set(
2995                            Which::Anchor,
2996                            &anchor.key,
2997                            anchor.offset,
2998                            anchor.point_type,
2999                        )?;
3000                        selection.point_set(
3001                            Which::Focus,
3002                            &focus.key,
3003                            focus.offset,
3004                            focus.point_type,
3005                        )?;
3006                        set_selection(Some(selection.clone()));
3007                        let is_backward = op.contains('<');
3008                        let granularity = match op.chars().last() {
3009                            Some('w') => SelectionGranularity::Word,
3010                            Some('l') => SelectionGranularity::LineBoundary,
3011                            _ => SelectionGranularity::Character,
3012                        };
3013                        match &op[..1] {
3014                            "C" => selection.delete_character(is_backward),
3015                            "W" => selection.delete_word(is_backward),
3016                            "L" => selection.delete_line(is_backward),
3017                            "m" => selection.modify(SelectionAlter::Move, is_backward, granularity),
3018                            _ => selection.modify(SelectionAlter::Extend, is_backward, granularity),
3019                        }
3020                    },
3021                    discrete(),
3022                )
3023                .unwrap_or_else(|e| panic!("{line}: {e}"));
3024            let state = editor.get_editor_state();
3025            let compact = json::stringify(&state.to_json(true)).unwrap();
3026            let want_compact = if want_children == "=" {
3027                before
3028            } else {
3029                format!(r#"{{"root":{{"type":"root","children":{want_children}}}}}"#)
3030            };
3031            assert_eq!(compact, want_compact, "{line}");
3032            let Some(Selection::Range(range)) = state.selection().map(|s| s.get()) else {
3033                panic!("{line}: no range selection");
3034            };
3035            assert_eq!(
3036                [
3037                    show_point(&range.anchor),
3038                    show_point(&range.focus),
3039                    range.format.to_string()
3040                ],
3041                [want[0], want[1], want[2]],
3042                "{line}"
3043            );
3044        }
3045    }
3046
3047    /// Without a movement, `modify` inside text fails as it does in JS on an
3048    /// editor with no root element.
3049    #[test]
3050    fn headless_modify_matches_js() {
3051        reset_random_key();
3052        let editor = create_editor(CreateEditorArgs::default());
3053        let result = editor.update(
3054            || {
3055                let paragraph = create_paragraph_node();
3056                let text = crate::create_text_node("hello big world");
3057                paragraph.append(std::slice::from_ref(&text))?;
3058                get_root().append(&[paragraph])?;
3059                let selection = text.select(Some(7), Some(7))?;
3060                selection.modify(SelectionAlter::Move, true, SelectionGranularity::Character)
3061            },
3062            UpdateOptions {
3063                discrete: true,
3064                ..UpdateOptions::default()
3065            },
3066        );
3067        assert_eq!(
3068            result.map_err(|e| e.message().to_owned()),
3069            Err("window object not found".to_owned())
3070        );
3071    }
3072
3073    /// A window that gives no DOM selection, as jsdom's does when installed
3074    /// after Lexical loaded (property.ts's `sequenceEditor`).
3075    struct WindowWithoutSelection;
3076
3077    impl SelectionMovement for WindowWithoutSelection {
3078        fn landed_point(
3079            &self,
3080            _from: &Point,
3081            _is_backward: bool,
3082            _granularity: SelectionGranularity,
3083        ) -> Result<Option<Point>, LexicalError> {
3084            unreachable!("nothing measures without a DOM selection")
3085        }
3086
3087        fn has_dom_selection(&self) -> bool {
3088            false
3089        }
3090    }
3091
3092    /// JS, with `sequenceEditor`'s window: `modify` past the model step
3093    /// returns at `if (!domSelection)`, leaving `abc` selected at 1 for both
3094    /// alters.
3095    #[test]
3096    fn modify_without_a_dom_selection_matches_js() {
3097        for alter in [SelectionAlter::Move, SelectionAlter::Extend] {
3098            reset_random_key();
3099            let editor = create_editor(CreateEditorArgs::default());
3100            editor.set_selection_movement(Some(Rc::new(WindowWithoutSelection)));
3101            let result = editor.update(
3102                move || {
3103                    let paragraph = create_paragraph_node();
3104                    let text = crate::create_text_node("abc");
3105                    paragraph.append(std::slice::from_ref(&text))?;
3106                    get_root().append(&[paragraph])?;
3107                    let selection = text.select(Some(1), Some(1))?;
3108                    selection.modify(alter, true, SelectionGranularity::Character)
3109                },
3110                UpdateOptions {
3111                    discrete: true,
3112                    ..UpdateOptions::default()
3113                },
3114            );
3115            assert_eq!(result.map_err(|e| e.message().to_owned()), Ok(()));
3116            let offsets = editor.read(|| {
3117                let range = get_selection().and_then(|s| s.range());
3118                range.map(|r| (r.anchor.offset, r.focus.offset))
3119            });
3120            assert_eq!(offsets.ok().flatten(), Some((1, 1)));
3121        }
3122    }
3123}