Skip to main content

lexical_ui/
lexical_selection.rs

1//! `LexicalSelection.ts`: points, `RangeSelection` and `NodeSelection`
2//! (with `getNodes` and `getTextContent`), and the helpers node methods use
3//! to keep a selection valid while they change the tree. Selection editing
4//! (`insertText`, `deleteCharacter`, ...) is in the `selection_*` modules.
5
6use crate::LexicalError;
7use crate::caret::{
8    CaretDirection, CaretRange, PointCaret, compare_point_caret_next, get_adjacent_child_caret,
9    get_child_caret,
10};
11use crate::caret_utils::{
12    caret_from_point, caret_range_from_selection, get_caret_range_in_direction,
13    get_text_point_caret_slice_for_node, normalize_caret,
14};
15use crate::error::invariant;
16use crate::lexical_utils::get_node_by_key;
17use crate::node::{NodeKey, NodeRef};
18use crate::nodes::line_break::LineBreakNode;
19use crate::ordered::OrderedSet;
20use crate::updates::{get_active_editor_state, is_currently_read_only_mode};
21use std::cell::RefCell;
22use std::rc::Rc;
23
24/// A point's type: inside a text node (an offset in UTF-16 code units) or
25/// between an element's children (a child index).
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum PointType {
28    Text,
29    Element,
30}
31
32impl PointType {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            PointType::Text => "text",
36            PointType::Element => "element",
37        }
38    }
39}
40
41/// `PointType`: a node key, an offset and a type.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Point {
44    pub key: NodeKey,
45    pub offset: usize,
46    pub point_type: PointType,
47}
48
49impl Point {
50    pub fn new(key: impl Into<NodeKey>, offset: usize, point_type: PointType) -> Self {
51        Self {
52            key: key.into(),
53            offset,
54            point_type,
55        }
56    }
57
58    /// `point.isBefore(b)`: whether this point comes before `b` in the
59    /// document.
60    pub fn is_before(&self, b: &Point) -> Result<bool, LexicalError> {
61        is_before(self, b)
62    }
63
64    /// `point.getNode()`.
65    pub fn get_node(&self) -> Result<NodeRef, LexicalError> {
66        get_node_by_key(&self.key).ok_or_else(|| LexicalError::new("Point.getNode: node not found"))
67    }
68}
69
70/// Which point of a range selection.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Which {
73    Anchor,
74    Focus,
75}
76
77/// `RangeSelection`'s fields.
78#[derive(Clone, Debug)]
79pub struct RangeSelection {
80    pub anchor: Point,
81    pub focus: Point,
82    pub format: f64,
83    pub style: String,
84    pub(crate) dirty: bool,
85    pub(crate) cached_is_backward: Option<bool>,
86    /// `_cachedNodes`.
87    pub(crate) cached_nodes: Option<Vec<NodeRef>>,
88}
89
90impl RangeSelection {
91    /// `new RangeSelection(anchor, focus, format, style)`.
92    pub fn new(anchor: Point, focus: Point, format: f64, style: impl Into<String>) -> Self {
93        Self {
94            anchor,
95            focus,
96            format,
97            style: style.into(),
98            dirty: false,
99            cached_is_backward: None,
100            cached_nodes: None,
101        }
102    }
103
104    pub fn point(&self, which: Which) -> &Point {
105        match which {
106            Which::Anchor => &self.anchor,
107            Which::Focus => &self.focus,
108        }
109    }
110
111    fn point_mut(&mut self, which: Which) -> &mut Point {
112        match which {
113            Which::Anchor => &mut self.anchor,
114            Which::Focus => &mut self.focus,
115        }
116    }
117
118    /// `is(selection)`: equal points, format and style.
119    pub fn is(&self, other: &RangeSelection) -> bool {
120        self.anchor == other.anchor
121            && self.focus == other.focus
122            && self.format == other.format
123            && self.style == other.style
124    }
125
126    pub fn is_collapsed(&self) -> bool {
127        self.anchor == self.focus
128    }
129}
130
131/// `NodeSelection`'s fields: the selected keys, in the order added.
132#[derive(Clone, Debug, Default)]
133pub struct NodeSelection {
134    pub(crate) nodes: OrderedSet,
135    pub(crate) dirty: bool,
136    /// `_cachedNodes`.
137    pub(crate) cached_nodes: Option<Vec<NodeRef>>,
138}
139
140impl NodeSelection {
141    pub fn keys(&self) -> impl Iterator<Item = &str> {
142        self.nodes.iter()
143    }
144
145    pub fn add(&mut self, key: &str) {
146        self.dirty = true;
147        self.nodes.add(key);
148        self.cached_nodes = None;
149    }
150
151    pub fn delete(&mut self, key: &str) {
152        self.dirty = true;
153        self.nodes.delete(key);
154        self.cached_nodes = None;
155    }
156
157    pub fn has(&self, key: &str) -> bool {
158        self.nodes.contains(key)
159    }
160
161    /// `clear()`: no node is selected.
162    pub fn clear(&mut self) {
163        self.dirty = true;
164        self.nodes = OrderedSet::new();
165        self.cached_nodes = None;
166    }
167}
168
169/// A selection's value.
170#[derive(Clone, Debug)]
171pub enum Selection {
172    Range(RangeSelection),
173    Node(NodeSelection),
174    /// `TableSelection` (`@lexical/table`, the `table` feature).
175    #[cfg(feature = "table")]
176    Table(crate::table::TableSelection),
177}
178
179impl Selection {
180    fn dirty_mut(&mut self) -> &mut bool {
181        match self {
182            Selection::Range(s) => &mut s.dirty,
183            Selection::Node(s) => &mut s.dirty,
184            #[cfg(feature = "table")]
185            Selection::Table(s) => &mut s.dirty,
186        }
187    }
188
189    /// `selection.is(other)`.
190    pub fn is(&self, other: &Selection) -> bool {
191        match (self, other) {
192            (Selection::Range(a), Selection::Range(b)) => a.is(b),
193            (Selection::Node(a), Selection::Node(b)) => {
194                a.nodes.len() == b.nodes.len() && a.nodes.iter().all(|k| b.nodes.contains(k))
195            }
196            #[cfg(feature = "table")]
197            (Selection::Table(a), Selection::Table(b)) => a.is(b),
198            _ => false,
199        }
200    }
201}
202
203/// A selection object, shared as JS shares it: `$getSelection()` returns the
204/// one the editor state holds, so a change through it is a change of the
205/// state's selection; [`clone_selection`](Self::clone_selection) makes a
206/// separate one.
207#[derive(Clone, Debug)]
208pub struct SelectionRef(Rc<RefCell<Selection>>);
209
210impl SelectionRef {
211    pub fn new(selection: Selection) -> Self {
212        Self(Rc::new(RefCell::new(selection)))
213    }
214
215    /// The selection's current value.
216    pub fn get(&self) -> Selection {
217        self.0.borrow().clone()
218    }
219
220    pub fn is_range(&self) -> bool {
221        matches!(*self.0.borrow(), Selection::Range(_))
222    }
223
224    pub fn is_node(&self) -> bool {
225        matches!(*self.0.borrow(), Selection::Node(_))
226    }
227
228    /// `$isTableSelection(selection)`.
229    #[cfg(feature = "table")]
230    pub fn is_table(&self) -> bool {
231        matches!(*self.0.borrow(), Selection::Table(_))
232    }
233
234    /// The table selection's value, `None` for any other selection.
235    #[cfg(feature = "table")]
236    pub fn table(&self) -> Option<crate::table::TableSelection> {
237        match &*self.0.borrow() {
238            Selection::Table(t) => Some(t.clone()),
239            _ => None,
240        }
241    }
242
243    #[cfg(feature = "table")]
244    pub(crate) fn with_table<R>(
245        &self,
246        f: impl FnOnce(&mut crate::table::TableSelection) -> R,
247    ) -> Option<R> {
248        match &mut *self.0.borrow_mut() {
249            Selection::Table(t) => Some(f(t)),
250            _ => None,
251        }
252    }
253
254    /// `selection.getStartEndPoints()`: the anchor and focus of a range or
255    /// table selection, `None` for a node selection.
256    pub fn get_start_end_points(&self) -> Option<(Point, Point)> {
257        match &*self.0.borrow() {
258            Selection::Range(r) => Some((r.anchor.clone(), r.focus.clone())),
259            Selection::Node(_) => None,
260            #[cfg(feature = "table")]
261            Selection::Table(t) => Some((t.anchor.clone(), t.focus.clone())),
262        }
263    }
264
265    /// The range selection's value, `None` for a node selection.
266    pub fn range(&self) -> Option<RangeSelection> {
267        match &*self.0.borrow() {
268            Selection::Range(r) => Some(r.clone()),
269            _ => None,
270        }
271    }
272
273    pub(crate) fn with_range<R>(&self, f: impl FnOnce(&mut RangeSelection) -> R) -> Option<R> {
274        match &mut *self.0.borrow_mut() {
275            Selection::Range(r) => Some(f(r)),
276            _ => None,
277        }
278    }
279
280    pub(crate) fn with_node<R>(&self, f: impl FnOnce(&mut NodeSelection) -> R) -> Option<R> {
281        match &mut *self.0.borrow_mut() {
282            Selection::Node(n) => Some(f(n)),
283            _ => None,
284        }
285    }
286
287    /// `nodeSelection.add(key)`; nothing on a range selection.
288    pub fn add(&self, key: &str) {
289        self.with_node(|n| n.add(key));
290    }
291
292    /// `nodeSelection.delete(key)`; nothing on a range selection.
293    pub fn delete(&self, key: &str) {
294        self.with_node(|n| n.delete(key));
295    }
296
297    /// `nodeSelection.clear()`; nothing on a range selection.
298    pub fn clear(&self) {
299        self.with_node(NodeSelection::clear);
300    }
301
302    /// A node selection's keys, in the order added; empty for a range
303    /// selection.
304    pub fn node_keys(&self) -> Vec<String> {
305        self.with_node(|n| n.keys().map(str::to_owned).collect())
306            .unwrap_or_default()
307    }
308
309    /// The point `which` of a range selection.
310    pub fn point(&self, which: Which) -> Option<Point> {
311        self.with_range(|r| r.point(which).clone())
312    }
313
314    pub fn is_dirty(&self) -> bool {
315        *self.0.borrow_mut().dirty_mut()
316    }
317
318    pub(crate) fn set_dirty(&self, dirty: bool) {
319        *self.0.borrow_mut().dirty_mut() = dirty;
320    }
321
322    /// `setCachedNodes(nodes)`.
323    pub(crate) fn set_cached_nodes(&self, nodes: Option<Vec<NodeRef>>) {
324        match &mut *self.0.borrow_mut() {
325            Selection::Range(r) => r.cached_nodes = nodes,
326            Selection::Node(n) => n.cached_nodes = nodes,
327            #[cfg(feature = "table")]
328            Selection::Table(t) => t.cached_nodes = nodes,
329        }
330    }
331
332    fn get_cached_nodes(&self) -> Option<Vec<NodeRef>> {
333        match &*self.0.borrow() {
334            Selection::Range(r) => r.cached_nodes.clone(),
335            Selection::Node(n) => n.cached_nodes.clone(),
336            #[cfg(feature = "table")]
337            Selection::Table(t) => t.cached_nodes.clone(),
338        }
339    }
340
341    /// `selection.getNodes()`: for a range selection, the nodes it covers in
342    /// document order, with the quirks of the original `getNodes`
343    /// (`$getNodesFromCaretRangeCompat`); for a node selection, its nodes
344    /// that exist, in the order added. Cached until the selection or a node
345    /// changes.
346    pub fn get_nodes(&self) -> Result<Vec<NodeRef>, LexicalError> {
347        #[cfg(feature = "table")]
348        if self.is_table() {
349            return crate::table::table_selection::get_nodes(self);
350        }
351        if let Some(cached) = self.get_cached_nodes() {
352            return Ok(cached);
353        }
354        let nodes = match self.range() {
355            Some(range) => {
356                let caret_range = get_caret_range_in_direction(
357                    &caret_range_from_selection(&range)?,
358                    CaretDirection::Next,
359                )?;
360                let nodes = get_nodes_from_caret_range_compat(&caret_range)?;
361                // JS checks this in DEV builds, which the vectors come from.
362                invariant!(
363                    !(range.is_collapsed() && nodes.len() > 1),
364                    "RangeSelection.getNodes() returned {} > 1 nodes in a collapsed selection",
365                    nodes.len()
366                );
367                nodes
368            }
369            None => self
370                .node_keys()
371                .iter()
372                .filter_map(|key| get_node_by_key(key))
373                .collect(),
374        };
375        if !is_currently_read_only_mode() {
376            self.set_cached_nodes(Some(nodes.clone()));
377        }
378        Ok(nodes)
379    }
380
381    /// `selection.getTextContent()`: for a range selection, the text it
382    /// covers, with a line break between blocks; for a node selection, the
383    /// text of its nodes.
384    pub fn get_text_content(&self) -> Result<String, LexicalError> {
385        #[cfg(feature = "table")]
386        if self.is_table() {
387            return crate::table::table_selection::get_text_content(self);
388        }
389        let Some(range) = self.range() else {
390            return Ok(self
391                .get_nodes()?
392                .iter()
393                .map(NodeRef::get_text_content)
394                .collect());
395        };
396        if range.is_collapsed() {
397            return Ok(String::new());
398        }
399        let nodes = self.get_nodes()?;
400        let slices = caret_range_from_selection(&range)?.get_text_slices();
401        let mut text_content = String::new();
402        let mut prev_was_element = true;
403        for node in &nodes {
404            if node.is_element() && !node.is_inline() {
405                if !prev_was_element {
406                    text_content.push('\n');
407                }
408                // `getNodes()` never goes into slots: a selection around the
409                // host carries their text here, first.
410                let mut slot_text = String::new();
411                for slot_name in crate::slot::get_slot_names(node) {
412                    if let Some(slot) = crate::slot::get_slot(node, &slot_name) {
413                        slot_text.push_str(&slot.get_text_content());
414                    }
415                }
416                if !slot_text.is_empty() {
417                    text_content.push_str(&slot_text);
418                    prev_was_element = false;
419                } else {
420                    prev_was_element = !node.is_empty();
421                }
422            } else {
423                prev_was_element = false;
424                if node.is_text() {
425                    match get_text_point_caret_slice_for_node(&slices, node) {
426                        Some(slice) => text_content.push_str(&slice.get_text_content()),
427                        None => text_content.push_str(&node.get_text_content()),
428                    }
429                } else if node.is_decorator() || node.get_latest().is::<LineBreakNode>() {
430                    text_content.push_str(&node.get_text_content());
431                }
432            }
433        }
434        Ok(text_content)
435    }
436
437    /// `selection.clone()`: a separate selection with the same value, not
438    /// dirty.
439    pub fn clone_selection(&self) -> SelectionRef {
440        let mut value = self.get();
441        match &mut value {
442            Selection::Range(r) => {
443                r.dirty = false;
444                r.cached_is_backward = None;
445                r.cached_nodes = None;
446            }
447            Selection::Node(n) => {
448                n.dirty = false;
449                n.cached_nodes = None;
450            }
451            #[cfg(feature = "table")]
452            Selection::Table(t) => {
453                t.dirty = false;
454                t.cached_nodes = None;
455            }
456        }
457        SelectionRef::new(value)
458    }
459
460    pub fn ptr_eq(&self, other: &SelectionRef) -> bool {
461        Rc::ptr_eq(&self.0, &other.0)
462    }
463
464    /// `point.set(key, offset, type)` on the point `which` of a range
465    /// selection; nothing on a node selection.
466    pub fn point_set(
467        &self,
468        which: Which,
469        key: &str,
470        offset: usize,
471        point_type: PointType,
472    ) -> Result<(), LexicalError> {
473        // JS checks this in DEV builds, which the vectors come from.
474        let node = get_node_by_key(key);
475        let matches = match (&node, point_type) {
476            (Some(n), PointType::Text) => n.is_text(),
477            (Some(n), PointType::Element) => n.is_element(),
478            (None, _) => false,
479        };
480        invariant!(
481            matches,
482            "PointType.set: node with key {key} is {} and can not be used for a {} point",
483            node.map_or("[not found]", |n| n.get_type()),
484            point_type.as_str()
485        );
486        let read_only = is_currently_read_only_mode();
487        let old_key = self.point(which).map(|p| p.key);
488        if !read_only && old_key.is_some() && crate::lexical_utils::get_composition_key() == old_key
489        {
490            crate::lexical_utils::set_composition_key(Some(key));
491        }
492        self.with_range(|r| {
493            *r.point_mut(which) = Point::new(key, offset, point_type);
494            if !read_only {
495                r.cached_nodes = None;
496                r.cached_is_backward = None;
497                r.dirty = true;
498            }
499        });
500        Ok(())
501    }
502
503    /// `setTextNodeRange(anchorNode, anchorOffset, focusNode, focusOffset)`.
504    pub(crate) fn set_text_node_range(
505        &self,
506        anchor: &NodeRef,
507        anchor_offset: usize,
508        focus: &NodeRef,
509        focus_offset: usize,
510    ) -> Result<(), LexicalError> {
511        self.point_set(
512            Which::Anchor,
513            anchor.get_key(),
514            anchor_offset,
515            PointType::Text,
516        )?;
517        self.point_set(Which::Focus, focus.get_key(), focus_offset, PointType::Text)
518    }
519
520    /// `isBackward()`: whether the focus comes before the anchor.
521    pub fn is_backward(&self) -> Result<bool, LexicalError> {
522        #[cfg(feature = "table")]
523        if let Some(table) = self.table() {
524            return is_before(&table.focus, &table.anchor);
525        }
526        let range = self.range().expect("a range selection");
527        if let Some(cached) = range.cached_is_backward {
528            return Ok(cached);
529        }
530        let is_backward = is_before(&range.focus, &range.anchor)?;
531        if !is_currently_read_only_mode() {
532            self.with_range(|r| r.cached_is_backward = Some(is_backward));
533        }
534        Ok(is_backward)
535    }
536}
537
538/// `a.isBefore(b)`.
539pub(crate) fn is_before(a: &Point, b: &Point) -> Result<bool, LexicalError> {
540    if a.key == b.key {
541        return Ok(a.offset < b.offset);
542    }
543    let a_caret = normalize_caret(&caret_from_point(a, CaretDirection::Next)?);
544    let b_caret = normalize_caret(&caret_from_point(b, CaretDirection::Next)?);
545    Ok(compare_point_caret_next(&a_caret, &b_caret)?.is_lt())
546}
547
548/// `$getNodesFromCaretRangeCompat(range)`: the nodes of a `next` caret
549/// range, with all the quirks of the original `RangeSelection.getNodes()`.
550fn get_nodes_from_caret_range_compat(range: &CaretRange) -> Result<Vec<NodeRef>, LexicalError> {
551    let mut nodes: Vec<NodeRef> = Vec::new();
552    let [before_slice, after_slice] = range.get_text_slices();
553    if let Some(slice) = &before_slice {
554        nodes.push(slice.caret.origin().clone());
555    }
556    let mut seen_ancestors: Vec<NodeRef> = Vec::new();
557    // Enter/exit events are nested. Only leading ancestors lack an included
558    // enter event, so a depth counter can skip repeated elements on exit.
559    let mut open_elements = 0usize;
560    for caret in range.iter() {
561        let origin = caret.origin().clone();
562        if caret.is_child_caret() {
563            // Emulate the leading under-selection behavior of getNodes by
564            // ignoring the 'enter' of any ElementNode until we've seen a
565            // SiblingCaret
566            if nodes.is_empty() {
567                if !seen_ancestors.contains(&origin) {
568                    seen_ancestors.push(origin);
569                }
570            } else {
571                open_elements += 1;
572                nodes.push(origin);
573            }
574        } else if !origin.is_element() || open_elements == 0 {
575            nodes.push(origin);
576        } else {
577            open_elements -= 1;
578        }
579    }
580    if let Some(slice) = &after_slice {
581        nodes.push(slice.caret.origin().clone());
582    }
583    // Emulate the trailing underselection behavior when the last offset of
584    // an element is selected
585    if range.focus.is_sibling_caret()
586        && range.focus.origin().is_element()
587        && range.focus.get_node_at_caret().is_none()
588    {
589        let mut reverse_caret = get_child_caret(range.focus.origin(), CaretDirection::Previous);
590        while let Some(rc) = reverse_caret.filter(|rc| {
591            rc.is_child_caret()
592                && seen_ancestors.contains(rc.origin())
593                && !rc.origin().is_empty()
594                && nodes.last() == Some(rc.origin())
595        }) {
596            seen_ancestors.retain(|n| n != rc.origin());
597            nodes.pop();
598            reverse_caret = get_adjacent_child_caret(Some(&rc));
599        }
600    }
601    while nodes.len() > 1 {
602        let last_included_node = nodes.last().expect("len > 1");
603        if last_included_node.is_element()
604            // A non-empty included element at the tail has not exited yet:
605            // otherwise one of its descendants would follow it in nodes.
606            && !(open_elements > 0
607                || last_included_node.is_empty()
608                || seen_ancestors.contains(last_included_node))
609        {
610            nodes.pop();
611            continue;
612        }
613        break;
614    }
615    if nodes.is_empty() && range.is_collapsed() {
616        // Emulate the collapsed behavior of getNodes by returning the
617        // descendant
618        let norm_caret = normalize_caret(&range.anchor);
619        let flipped_norm_caret = normalize_caret(&range.anchor.get_flipped()?);
620        let get_candidate = |caret: &PointCaret| -> Option<NodeRef> {
621            if caret.is_text_point_caret() {
622                Some(caret.origin().clone())
623            } else {
624                caret.get_node_at_caret()
625            }
626        };
627        let node = get_candidate(&norm_caret)
628            .or_else(|| get_candidate(&flipped_norm_caret))
629            .unwrap_or_else(|| {
630                if range.anchor.get_node_at_caret().is_some() {
631                    norm_caret.origin().clone()
632                } else {
633                    flipped_norm_caret.origin().clone()
634                }
635            });
636        nodes.push(node);
637    }
638    Ok(nodes)
639}
640
641/// `$getSelection()`.
642pub fn get_selection() -> Option<SelectionRef> {
643    get_active_editor_state().0.selection.borrow().clone()
644}
645
646/// `$setSelection(selection)`.
647pub fn set_selection(selection: Option<SelectionRef>) {
648    crate::updates::error_on_read_only();
649    if let Some(selection) = &selection {
650        selection.set_dirty(true);
651        selection.set_cached_nodes(None);
652        // A range selection set through the API must not straddle a slot
653        // boundary either.
654        if selection.is_range()
655            && crate::updates::get_active_editor().is_some_and(|e| e.0.slots_used.get())
656        {
657            clamp_range_selection_to_slot_frame(selection)
658                .expect("clamping a selection to its slot frame");
659        }
660    }
661    *get_active_editor_state().0.selection.borrow_mut() = selection;
662}
663
664/// `$getPointSlotFrame(point)`: the slot frame of the point's node.
665pub fn get_point_slot_frame(point: &Point) -> Option<NodeRef> {
666    get_node_by_key(&point.key).and_then(|node| crate::slot::get_slot_frame(&node))
667}
668
669/// `$isSameFrame(a, b)`.
670pub fn is_same_frame(a: Option<&NodeRef>, b: Option<&NodeRef>) -> bool {
671    a == b
672}
673
674/// `$setPointToFrameEdge(point, frame, atEnd)`.
675fn set_point_to_frame_edge(
676    selection: &SelectionRef,
677    which: Which,
678    frame: &NodeRef,
679    at_end: bool,
680) -> Result<(), LexicalError> {
681    if frame.is_element() {
682        let offset = if at_end { frame.get_children_size() } else { 0 };
683        selection.point_set(which, frame.get_key(), offset, PointType::Element)
684    } else {
685        let offset = if at_end {
686            frame.get_text_content_size()
687        } else {
688            0
689        };
690        selection.point_set(which, frame.get_key(), offset, PointType::Text)
691    }
692}
693
694/// `$getSlotHostInFrame(frame, target)`: the host whose own frame is
695/// `target` (`None` for the main tree) and that owns `frame`, directly or
696/// through nested slots.
697fn get_slot_host_in_frame(frame: &NodeRef, target: Option<&NodeRef>) -> Option<NodeRef> {
698    let mut host = crate::slot::get_slot_host(frame);
699    while let Some(h) = host {
700        let host_frame = crate::slot::get_slot_frame(&h);
701        if is_same_frame(host_frame.as_ref(), target) {
702            // A host outside every slot is in the main tree only when
703            // attached.
704            return (host_frame.is_some() || h.is_attached()).then_some(h);
705        }
706        host = host_frame.and_then(|f| crate::slot::get_slot_host(&f));
707    }
708    None
709}
710
711/// `$setPointAtSlotBoundary`'s `mode`.
712#[derive(Clone, Copy, PartialEq, Eq)]
713pub(crate) enum SlotBoundaryMode {
714    /// `'selection'`: beside a host, past it (the host stays whole).
715    Selection,
716    /// `'deletion'`: beside a host, before it (the deletion stops at it),
717    /// and the focus descends toward the anchor.
718    Deletion,
719}
720
721/// `$setPointAtSlotBoundary(point, anchorNode, anchorFrame, focusFrame,
722/// mode, resolveFocusAfterAnchor)`: sets the focus of a selection or
723/// deletion whose anchor is in `anchor_frame` and whose focus is in
724/// `focus_frame` to the slot boundary in the anchor's frame: the edge of the
725/// anchor's slot when the focus is outside it, the edge of the children of
726/// the host that owns `focus_frame` when that host is the frame's root or
727/// contains the anchor, and otherwise beside the host. Returns false when
728/// there is no boundary.
729pub(crate) fn set_point_at_slot_boundary(
730    selection: &SelectionRef,
731    which: Which,
732    anchor_node: Option<&NodeRef>,
733    anchor_frame: Option<&NodeRef>,
734    focus_frame: Option<&NodeRef>,
735    mode: SlotBoundaryMode,
736    resolve_focus_after_anchor: impl FnOnce() -> Result<bool, LexicalError>,
737) -> Result<bool, LexicalError> {
738    let host = focus_frame.and_then(|f| get_slot_host_in_frame(f, anchor_frame));
739    if host.is_none() && anchor_frame.is_none() {
740        return Ok(false);
741    }
742    let focus_after_anchor = resolve_focus_after_anchor()?;
743    let host_parent = host.as_ref().and_then(NodeRef::get_parent);
744    let (parent, offset) = match (&host, &host_parent) {
745        (Some(host), Some(host_parent))
746            if !anchor_node.is_some_and(|a| host == a || host.is_parent_of(a)) =>
747        {
748            let index = host.get_index_within_parent().unwrap_or(0);
749            let past = focus_after_anchor == (mode == SlotBoundaryMode::Selection);
750            (host_parent.clone(), index + usize::from(past))
751        }
752        _ => {
753            let edge = host.clone().or_else(|| anchor_frame.cloned());
754            let Some(edge) = edge.filter(NodeRef::is_element) else {
755                if let Some(edge) = host.or_else(|| anchor_frame.cloned()) {
756                    set_point_to_frame_edge(selection, which, &edge, focus_after_anchor)?;
757                }
758                return Ok(true);
759            };
760            let offset = if focus_after_anchor {
761                edge.get_children_size()
762            } else {
763                0
764            };
765            (edge, offset)
766        }
767    };
768    if mode == SlotBoundaryMode::Deletion {
769        set_deletion_focus(selection, which, parent, offset, !focus_after_anchor)?;
770    } else {
771        selection.point_set(which, parent.get_key(), offset, PointType::Element)?;
772    }
773    Ok(true)
774}
775
776/// `$setDeletionFocus(focus, parent, offset, isBackward)`: the focus at
777/// `offset` in `parent`, descending into the child on the anchor's side
778/// (before it for a forward deletion) down to text, but not into a shadow
779/// root or a non-element.
780fn set_deletion_focus(
781    selection: &SelectionRef,
782    which: Which,
783    mut parent: NodeRef,
784    mut offset: usize,
785    is_backward: bool,
786) -> Result<(), LexicalError> {
787    loop {
788        let child = if is_backward {
789            parent.get_child_at_index(offset)
790        } else {
791            offset
792                .checked_sub(1)
793                .and_then(|i| parent.get_child_at_index(i))
794        };
795        let Some(child) = child else { break };
796        if child.is_text() {
797            let at = if is_backward {
798                0
799            } else {
800                child.get_text_content_size()
801            };
802            return selection.point_set(which, child.get_key(), at, PointType::Text);
803        }
804        if !child.is_element() || crate::lexical_utils::is_root_or_shadow_root(&child) {
805            break;
806        }
807        offset = if is_backward {
808            0
809        } else {
810            child.get_children_size()
811        };
812        parent = child;
813    }
814    selection.point_set(which, parent.get_key(), offset, PointType::Element)
815}
816
817/// `$clampRangeSelectionToSlotFrame(selection)` (`@experimental`): keeps the
818/// focus of a range selection in the anchor's slot frame, at the boundary
819/// on the side the focus was, in the default slots-before-children order
820/// ([`compare_point_caret_next_across_slots`](crate::compare_point_caret_next_across_slots)).
821/// Returns whether it moved the focus, which marks the selection dirty.
822pub fn clamp_range_selection_to_slot_frame(selection: &SelectionRef) -> Result<bool, LexicalError> {
823    let Some(range) = selection.range() else {
824        return Ok(false);
825    };
826    let anchor_frame = get_point_slot_frame(&range.anchor);
827    let focus_frame = get_point_slot_frame(&range.focus);
828    if is_same_frame(anchor_frame.as_ref(), focus_frame.as_ref()) {
829        return Ok(false);
830    }
831    let anchor_node = get_node_by_key(&range.anchor.key);
832    let clamped = set_point_at_slot_boundary(
833        selection,
834        Which::Focus,
835        anchor_node.as_ref(),
836        anchor_frame.as_ref(),
837        focus_frame.as_ref(),
838        SlotBoundaryMode::Selection,
839        || {
840            // Points are not normalized: that would move a point just
841            // before an element host into its children, past its slots.
842            let anchor = caret_from_point(&range.anchor, CaretDirection::Next)?;
843            let focus = caret_from_point(&range.focus, CaretDirection::Next)?;
844            Ok(
845                crate::caret::compare_point_caret_next_across_slots(&anchor, &focus)
846                    != Some(std::cmp::Ordering::Greater),
847            )
848        },
849    )?;
850    if clamped {
851        selection.set_dirty(true);
852    }
853    Ok(clamped)
854}
855
856/// `$createRangeSelection()`: a selection at the start of the root, not
857/// set on the editor state.
858pub fn create_range_selection() -> SelectionRef {
859    SelectionRef::new(Selection::Range(RangeSelection::new(
860        Point::new("root", 0, PointType::Element),
861        Point::new("root", 0, PointType::Element),
862        0.0,
863        "",
864    )))
865}
866
867/// `$createNodeSelection()`.
868pub fn create_node_selection() -> SelectionRef {
869    SelectionRef::new(Selection::Node(NodeSelection::default()))
870}
871
872/// `applySelectionTransforms(nextEditorState, editor)`: each text node a
873/// range selection of the pending state has its anchor or focus in gets
874/// `selectionTransform` with the committed state's selection.
875pub(crate) fn apply_selection_transforms(
876    next_editor_state: &crate::EditorState,
877    editor: &crate::Editor,
878) -> Result<(), LexicalError> {
879    let prev_selection = editor.get_editor_state().selection();
880    let Some(next_selection) = next_editor_state.selection() else {
881        return Ok(());
882    };
883    let Some(range) = next_selection.range() else {
884        return Ok(());
885    };
886    let mut anchor_node = None;
887    if range.anchor.point_type == PointType::Text {
888        let node = range.anchor.get_node()?;
889        node.get_latest()
890            .selection_transform(&node, prev_selection.as_ref(), &next_selection)?;
891        anchor_node = Some(node);
892    }
893    if range.focus.point_type == PointType::Text {
894        let node = range.focus.get_node()?;
895        if anchor_node.as_ref() != Some(&node) {
896            node.get_latest().selection_transform(
897                &node,
898                prev_selection.as_ref(),
899                &next_selection,
900            )?;
901        }
902    }
903    Ok(())
904}
905
906/// `$internalMakeRangeSelection`: a new range selection, set on the active
907/// editor state.
908pub(crate) fn internal_make_range_selection(anchor: Point, focus: Point) -> SelectionRef {
909    let mut range = RangeSelection::new(anchor, focus, 0.0, "");
910    range.dirty = true;
911    let selection = SelectionRef::new(Selection::Range(range));
912    *get_active_editor_state().0.selection.borrow_mut() = Some(selection.clone());
913    selection
914}
915
916/// `selectPointOnNode(point, node)`.
917fn select_point_on_node(
918    selection: &SelectionRef,
919    which: Which,
920    node: &NodeRef,
921) -> Result<(), LexicalError> {
922    let mut key = node.get_key().to_owned();
923    let mut offset = selection.point(which).expect("a range selection").offset;
924    let mut point_type = PointType::Element;
925    if node.is_text() {
926        point_type = PointType::Text;
927        offset = offset.min(node.get_text_content_size());
928    } else if !node.is_element() {
929        match node.get_next_sibling().filter(NodeRef::is_text) {
930            Some(next) => {
931                key = next.get_key().to_owned();
932                offset = 0;
933                point_type = PointType::Text;
934            }
935            None => {
936                if let Some(parent) = node.get_parent() {
937                    key = parent.get_key().to_owned();
938                    offset = node.get_index_within_parent().map_or(0, |i| i + 1);
939                }
940            }
941        }
942    }
943    selection.point_set(which, &key, offset, point_type)
944}
945
946/// `$moveSelectionPointToEnd(point, node)`.
947pub(crate) fn move_selection_point_to_end(
948    selection: &SelectionRef,
949    which: Which,
950    node: &NodeRef,
951) -> Result<(), LexicalError> {
952    if node.is_element() {
953        match node.get_last_descendant() {
954            Some(last) if last.is_element() || last.is_text() => {
955                select_point_on_node(selection, which, &last)
956            }
957            _ => select_point_on_node(selection, which, node),
958        }
959    } else {
960        select_point_on_node(selection, which, node)
961    }
962}
963
964/// `$selectionTouchesElement(selection, parentNode)`.
965pub(crate) fn selection_touches_element(selection: &SelectionRef, parent: &NodeRef) -> bool {
966    selection
967        .with_range(|r| r.anchor.key == parent.get_key() || r.focus.key == parent.get_key())
968        .unwrap_or(false)
969}
970
971/// `$updateElementSelectionOnCreateDeleteNode(selection, parentNode,
972/// nodeOffset, times)`.
973pub(crate) fn update_element_selection_on_create_delete_node(
974    selection: &SelectionRef,
975    parent: &NodeRef,
976    node_offset: usize,
977    times: isize,
978) -> Result<(), LexicalError> {
979    if !selection_touches_element(selection, parent) {
980        return Ok(());
981    }
982    for which in [Which::Anchor, Which::Focus] {
983        let point = selection.point(which).expect("a range selection");
984        if point.key == parent.get_key()
985            && ((node_offset <= point.offset && times > 0)
986                || (node_offset < point.offset && times < 0))
987        {
988            let offset = (point.offset as isize + times).max(0) as usize;
989            selection.point_set(which, parent.get_key(), offset, PointType::Element)?;
990        }
991        let point = selection.point(which).expect("a range selection");
992        let node = point.get_node()?;
993        if node.is_element() {
994            let size = node.get_children_size();
995            let at_end = point.offset >= size;
996            let child = if at_end {
997                size.checked_sub(1).and_then(|i| node.get_child_at_index(i))
998            } else {
999                node.get_child_at_index(point.offset)
1000            };
1001            if let Some(child) = child.filter(NodeRef::is_text) {
1002                let offset = if at_end {
1003                    child.get_text_content_size()
1004                } else {
1005                    0
1006                };
1007                selection.point_set(which, child.get_key(), offset, PointType::Text)?;
1008            }
1009        }
1010    }
1011    Ok(())
1012}
1013
1014/// `moveSelectionPointToSibling(point, node, parent, prevSibling,
1015/// nextSibling)`.
1016pub(crate) fn move_selection_point_to_sibling(
1017    selection: &SelectionRef,
1018    which: Which,
1019    node: &NodeRef,
1020    parent: &NodeRef,
1021    prev_sibling: Option<&NodeRef>,
1022    next_sibling: Option<&NodeRef>,
1023) -> Result<(), LexicalError> {
1024    let sibling = prev_sibling.or(next_sibling);
1025    match sibling.filter(|s| s.is_text() || s.is_element()) {
1026        Some(sibling) => {
1027            let is_text = sibling.is_text();
1028            let offset = if prev_sibling.is_none() {
1029                0
1030            } else if is_text {
1031                sibling.get_text_content_size()
1032            } else {
1033                sibling.get_children_size()
1034            };
1035            let point_type = if is_text {
1036                PointType::Text
1037            } else {
1038                PointType::Element
1039            };
1040            selection.point_set(which, sibling.get_key(), offset, point_type)
1041        }
1042        None => {
1043            let offset = node
1044                .get_index_within_parent()
1045                .unwrap_or_else(|| parent.get_children_size());
1046            selection.point_set(which, parent.get_key(), offset, PointType::Element)
1047        }
1048    }
1049}
1050
1051/// `adjustPointOffsetForMergedSibling(point, isBefore, key, target,
1052/// textLength)`.
1053pub(crate) fn adjust_point_offset_for_merged_sibling(
1054    selection: &SelectionRef,
1055    which: Which,
1056    is_before: bool,
1057    key: &str,
1058    target: &NodeRef,
1059    text_length: usize,
1060) -> Result<(), LexicalError> {
1061    let point = selection.point(which).expect("a range selection");
1062    if point.point_type == PointType::Text {
1063        let offset = point.offset + if is_before { 0 } else { text_length };
1064        selection.point_set(which, key, offset, PointType::Text)
1065    } else if target
1066        .get_index_within_parent()
1067        .is_some_and(|i| point.offset > i)
1068    {
1069        selection.point_set(which, &point.key, point.offset - 1, PointType::Element)
1070    } else {
1071        Ok(())
1072    }
1073}
1074
1075/// `$hasAncestor(child, targetNode)`.
1076pub(crate) fn has_ancestor(child: &NodeRef, target: &NodeRef) -> bool {
1077    let mut parent = child.get_parent();
1078    while let Some(p) = parent {
1079        if &p == target {
1080            return true;
1081        }
1082        parent = p.get_parent();
1083    }
1084    false
1085}
1086
1087/// `$maybeMoveChildrenSelectionToParent(parentNode)`.
1088pub(crate) fn maybe_move_children_selection_to_parent(
1089    parent: &NodeRef,
1090) -> Result<Option<SelectionRef>, LexicalError> {
1091    let selection = get_selection();
1092    let Some(range) = selection.as_ref().filter(|s| s.is_range()) else {
1093        return Ok(selection);
1094    };
1095    if !parent.is_element() {
1096        return Ok(selection);
1097    }
1098    for which in [Which::Anchor, Which::Focus] {
1099        let node = range.point(which).expect("a range selection").get_node()?;
1100        if has_ancestor(&node, parent) {
1101            range.point_set(which, parent.get_key(), 0, PointType::Element)?;
1102        }
1103    }
1104    Ok(selection)
1105}
1106
1107/// `editorStateHasDirtySelection(editorState, editor)`.
1108pub(crate) fn has_dirty_selection(
1109    pending: Option<&SelectionRef>,
1110    current: Option<&SelectionRef>,
1111) -> bool {
1112    match (pending, current) {
1113        (Some(pending), current) => {
1114            pending.is_dirty() || current.is_none_or(|c| !pending.get().is(&c.get()))
1115        }
1116        (None, current) => current.is_some(),
1117    }
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122    use super::*;
1123    use crate::{CreateEditorArgs, UpdateOptions, create_editor, get_root, json, reset_random_key};
1124
1125    /// `getNodes()`, `getTextContent()` and `isBackward()` of range
1126    /// selections, and a node selection's nodes and text, as JS 0.53.0
1127    /// gives them for the same document (root > p 1 ["one" 2, bold "two"
1128    /// 3], p 4 ["three" 5, linebreak 6, "x" 7], empty p 8).
1129    #[test]
1130    fn get_nodes_and_text_content_match_js() {
1131        reset_random_key();
1132        let editor = create_editor(CreateEditorArgs::default());
1133        let discrete = || UpdateOptions {
1134            discrete: true,
1135            ..UpdateOptions::default()
1136        };
1137        editor
1138            .update(
1139                || {
1140                    let nodes = json::parse(
1141                        r#"[{"type":"paragraph","children":[{"type":"text","text":"one"},{"type":"text","text":"two","format":1}]},{"type":"paragraph","children":[{"type":"text","text":"three"},{"type":"linebreak"},{"type":"text","text":"x"}]},{"type":"paragraph","children":[]}]"#,
1142                    )
1143                    .unwrap();
1144                    let nodes: Vec<NodeRef> = nodes
1145                        .as_array()
1146                        .unwrap()
1147                        .iter()
1148                        .map(|n| crate::parse_serialized_node(n).unwrap())
1149                        .collect();
1150                    get_root().append(&nodes)
1151                },
1152                discrete(),
1153            )
1154            .unwrap();
1155        use PointType::{Element as E, Text as T};
1156        // Anchor, focus, then the expected nodes, text and `isBackward()`.
1157        type Spec = (&'static str, usize, PointType);
1158        type Case = (Spec, Spec, &'static [&'static str], &'static str, bool);
1159        let cases: &[Case] = &[
1160            (
1161                ("2", 1, T),
1162                ("5", 2, T),
1163                &["2", "3", "1", "4", "5"],
1164                "netwo\nth",
1165                false,
1166            ),
1167            (
1168                ("1", 0, E),
1169                ("8", 0, E),
1170                &["2", "3", "1", "4", "5", "6", "7", "8"],
1171                "onetwo\nthree\nx\n",
1172                false,
1173            ),
1174            (
1175                ("5", 4, T),
1176                ("2", 0, T),
1177                &["2", "3", "1", "4", "5"],
1178                "onetwo\nthre",
1179                true,
1180            ),
1181            (("2", 1, T), ("2", 1, T), &["2"], "", false),
1182            (
1183                ("root", 0, E),
1184                ("root", 3, E),
1185                &["2", "3", "1", "4", "5", "6", "7", "8"],
1186                "onetwo\nthree\nx\n",
1187                false,
1188            ),
1189            (("1", 1, E), ("4", 0, E), &["3", "1", "4"], "two\n", false),
1190            (("3", 3, T), ("4", 0, E), &["3", "1", "4"], "\n", false),
1191            (("4", 1, E), ("4", 3, E), &["6", "7"], "\nx", false),
1192            (("1", 2, E), ("1", 2, E), &["3"], "", false),
1193            (
1194                ("8", 0, E),
1195                ("1", 0, E),
1196                &["2", "3", "1", "4", "5", "6", "7", "8"],
1197                "onetwo\nthree\nx\n",
1198                true,
1199            ),
1200        ];
1201        editor
1202            .update(
1203                move || {
1204                    for (anchor, focus, nodes, text, backward) in cases {
1205                        let selection = create_range_selection();
1206                        selection.point_set(Which::Anchor, anchor.0, anchor.1, anchor.2)?;
1207                        selection.point_set(Which::Focus, focus.0, focus.1, focus.2)?;
1208                        set_selection(Some(selection.clone()));
1209                        let keys: Vec<String> = selection
1210                            .get_nodes()?
1211                            .iter()
1212                            .map(|n| n.get_key().to_owned())
1213                            .collect();
1214                        assert_eq!(keys, *nodes, "{anchor:?} {focus:?}");
1215                        assert_eq!(selection.get_text_content()?, *text, "{anchor:?} {focus:?}");
1216                        assert_eq!(selection.is_backward()?, *backward, "{anchor:?} {focus:?}");
1217                    }
1218                    let selection = create_node_selection();
1219                    for key in ["4", "2", "99"] {
1220                        selection.with_node(|n| n.add(key));
1221                    }
1222                    let keys: Vec<String> = selection
1223                        .get_nodes()?
1224                        .iter()
1225                        .map(|n| n.get_key().to_owned())
1226                        .collect();
1227                    assert_eq!(keys, ["4", "2"]);
1228                    assert_eq!(selection.get_text_content()?, "three\nxone");
1229                    Ok(())
1230                },
1231                discrete(),
1232            )
1233            .unwrap();
1234    }
1235}