Skip to main content

lexical_ui/
selection_editing.rs

1//! `RangeSelection`'s editing methods from `LexicalSelection.ts`: the
2//! pending format and style, `removeText`, which the other editing methods
3//! build on, and `extract`.
4
5use crate::LexicalError;
6use crate::caret_utils::{
7    SliceMode, caret_range_from_selection, get_text_point_caret_slice_for_node,
8    remove_text_from_caret_range, update_range_selection_from_caret_range,
9};
10use crate::lexical_selection::{PointType, SelectionRef, Which, get_selection, set_selection};
11use crate::node::NodeRef;
12use crate::nodes::text::{to_int32, toggle_text_format_type};
13use crate::selection_format::split_text_point_caret_slice;
14
15impl SelectionRef {
16    /// `toggleFormat(format)`: toggles a format on the selection's pending
17    /// format, the one text typed at a collapsed selection gets.
18    pub fn toggle_format(&self, format_type: &str) {
19        self.with_range(|r| {
20            r.format = f64::from(toggle_text_format_type(
21                to_int32(r.format),
22                format_type,
23                None,
24            ));
25            r.dirty = true;
26        });
27    }
28
29    /// `setFormat(format)`: sets the selection's pending format.
30    pub fn set_format(&self, format: f64) {
31        self.with_range(|r| {
32            r.format = format;
33            r.dirty = true;
34        });
35    }
36
37    /// `setStyle(style)`: sets the selection's pending style.
38    pub fn set_style(&self, style: &str) {
39        self.with_range(|r| {
40            r.style = style.to_owned();
41            r.dirty = true;
42        });
43    }
44
45    /// `hasFormat(type)`: whether the pending format has `format_type`.
46    pub fn has_format(&self, format_type: &str) -> bool {
47        let flag = toggle_text_format_type(0, format_type, None);
48        self.with_range(|r| to_int32(r.format) & flag != 0)
49            .unwrap_or(false)
50    }
51
52    /// `removeText()`: removes the selected content and collapses the
53    /// selection where it was. When the caret lands in another node, the
54    /// pending format and style come from that node.
55    pub fn remove_text(&self) -> Result<(), LexicalError> {
56        let Some(range) = self.range() else {
57            return Ok(());
58        };
59        let is_current_selection = get_selection().is_some_and(|s| s.ptr_eq(self));
60        let previous_anchor_key = range.anchor.key.clone();
61        let new_range = remove_text_from_caret_range(
62            &caret_range_from_selection(&range)?,
63            SliceMode::RemoveEmptySlices,
64        )?;
65        update_range_selection_from_caret_range(self, &new_range)?;
66        if self.range().is_some_and(|r| r.is_collapsed()) {
67            internal_refresh_selection_format_and_style(self, &previous_anchor_key)?;
68        }
69        if is_current_selection && !get_selection().is_some_and(|s| s.ptr_eq(self)) {
70            set_selection(Some(self.clone()));
71        }
72        Ok(())
73    }
74
75    /// `extract()`: the selected nodes, with the text nodes at the ends of
76    /// a range selection split so that only the selected text is returned.
77    /// A range over part of one text node then covers that whole node. For a
78    /// node selection, its nodes (`NodeSelection.extract()`).
79    pub fn extract(&self) -> Result<Vec<NodeRef>, LexicalError> {
80        let nodes = self.get_nodes()?;
81        let Some(range) = self.range() else {
82            return Ok(nodes);
83        };
84        if range.is_collapsed() {
85            return Ok(nodes);
86        }
87        let backward = self.is_backward()?;
88        let slices = caret_range_from_selection(&range)?.get_text_slices();
89        let mut extracted = Vec::with_capacity(nodes.len());
90        for node in &nodes {
91            let replacement = match get_text_point_caret_slice_for_node(&slices, node) {
92                Some(slice) => split_text_point_caret_slice(slice, Some(self))?,
93                None => Some(node.clone()),
94            };
95            if let Some(replacement) = replacement {
96                extracted.push(replacement);
97            }
98        }
99        // Preserve extract's single-text-node selection convention, including
100        // ranges originally expressed with element points.
101        if nodes.len() == 1 && extracted.len() == 1 && extracted[0].is_text() {
102            let node = &extracted[0];
103            let (start, end) = if backward {
104                (Which::Focus, Which::Anchor)
105            } else {
106                (Which::Anchor, Which::Focus)
107            };
108            self.point_set(start, node.get_key(), 0, PointType::Text)?;
109            self.point_set(
110                end,
111                node.get_key(),
112                node.get_text_content_size(),
113                PointType::Text,
114            )?;
115        }
116        Ok(extracted)
117    }
118}
119
120/// `$internalRefreshSelectionFormatAndStyle(selection, previousAnchorKey)`:
121/// when the anchor moved to another node, takes the pending format and
122/// style from the node it is in now.
123pub(crate) fn internal_refresh_selection_format_and_style(
124    selection: &SelectionRef,
125    previous_anchor_key: &str,
126) -> Result<(), LexicalError> {
127    let Some(range) = selection.range() else {
128        return Ok(());
129    };
130    if range.anchor.key == previous_anchor_key {
131        return Ok(());
132    }
133    let anchor_node = range.anchor.get_node()?;
134    let (format, style) = if anchor_node.is_text() {
135        let data = anchor_node.text_data();
136        (data.get_format(), data.get_style().to_owned())
137    } else if anchor_node.is_element() {
138        let data = anchor_node.element_data();
139        (data.get_text_format(), data.get_text_style().to_owned())
140    } else {
141        (0.0, String::new())
142    };
143    selection.with_range(|r| {
144        if r.format != format || r.style != style {
145            r.format = format;
146            r.style = style;
147            r.dirty = true;
148        }
149    });
150    Ok(())
151}