Skip to main content

lexical_ui/
selection_insert_text.rs

1//! `insertText` from `LexicalSelection.ts` (`$insertText`,
2//! `$insertTextAtPoint` and their helpers).
3//!
4//! While an input method composes (`$getCompositionKey()`), text goes into
5//! the composed node and the anchor stays before it, as in JS, where the
6//! browser has already drawn it. Without the text edit log,
7//! `$recordDeleted` and `$recordTextInserted` do nothing; `$carryNodeState`
8//! gives a segmented node's replacement its NodeState as in JS.
9
10use crate::LexicalError;
11use crate::caret::{CaretDirection, get_sibling_caret};
12use crate::error::invariant;
13use crate::lexical_selection::{PointType, SelectionRef, Which, get_selection, set_selection};
14use crate::lexical_utils::get_composition_key;
15use crate::node::NodeRef;
16use crate::node_state::carry_node_state;
17use crate::nodes::element::is_root_or_shadow_root;
18use crate::nodes::paragraph::{ParagraphNode, create_paragraph_node};
19use crate::nodes::tab::TabNode;
20use crate::nodes::text::create_text_node;
21use crate::updates::get_active_editor;
22
23impl SelectionRef {
24    /// `selection.insertText(text)`: inserts `text` at a range selection,
25    /// replacing what it covers; nothing for a node selection
26    /// (`NodeSelection.insertText()`).
27    pub fn insert_text(&self, text: &str) -> Result<(), LexicalError> {
28        if !self.is_range() {
29            return Ok(());
30        }
31        insert_text(self, text)
32    }
33}
34
35impl NodeRef {
36    /// `canInsertTextBefore()` of a text node or an element.
37    pub fn can_insert_text_before(&self) -> bool {
38        self.get_latest().can_insert_text_before()
39    }
40
41    /// `canInsertTextAfter()` of a text node or an element.
42    pub fn can_insert_text_after(&self) -> bool {
43        self.get_latest().can_insert_text_after()
44    }
45}
46
47/// `$isTokenOrSegmented(node)`: a tab, or a text node in token or
48/// segmented mode.
49pub(crate) fn is_token_or_segmented(node: &NodeRef) -> bool {
50    node.get_latest().is::<TabNode>() || node.is_token() || node.is_segmented()
51}
52
53/// `$isParagraphNode(node)`.
54fn is_paragraph_node(node: &NodeRef) -> bool {
55    node.get_latest().is::<ParagraphNode>()
56}
57
58/// `$insertText(selection, text, false)`.
59fn insert_text(selection: &SelectionRef, text: &str) -> Result<(), LexicalError> {
60    let range = selection.range().expect("a range selection");
61    // For non-collapsed selections, inherit format/style from the first
62    // selected text node so the replacement preserves the original styling.
63    let mut format = range.format;
64    let mut style = range.style.clone();
65    if !range.is_collapsed() {
66        let first_point = if range.focus.is_before(&range.anchor)? {
67            &range.focus
68        } else {
69            &range.anchor
70        };
71        let first_node = first_point.get_node()?;
72        if first_node.is_text() {
73            let data = first_node.text_data();
74            format = data.get_format();
75            style = data.get_style().to_owned();
76        }
77        selection.remove_text()?;
78        selection.with_range(|r| {
79            r.format = format;
80            r.style = style.clone();
81        });
82        if text.is_empty() {
83            return Ok(());
84        }
85        if get_composition_key().is_none() {
86            if selection.point(Which::Anchor).expect("a range").point_type == PointType::Element {
87                transfer_starting_element_point_to_text_point(selection, format, &style)?;
88            }
89            return insert_text_at_point(selection, text, format, &style);
90        }
91        // Composing: fall through to the collapsed code below.
92    }
93
94    if selection.point(Which::Anchor).expect("a range").point_type == PointType::Element {
95        transfer_starting_element_point_to_text_point(selection, format, &style)?;
96    }
97
98    let anchor = selection.point(Which::Anchor).expect("a range selection");
99    let anchor_node = anchor.get_node()?;
100    invariant!(
101        anchor_node.is_text(),
102        "insertText: anchor is not a text node"
103    );
104    let offset = anchor.offset;
105
106    let anchor_parent = anchor_node.get_parent_or_throw()?;
107    let anchor_size = anchor_node.get_text_content_size();
108    let needs_redirect = is_token_or_segmented(&anchor_node)
109        || (offset == 0
110            && (!anchor_node.can_insert_text_before()
111                || (!anchor_parent.can_insert_text_before()
112                    && anchor_node.get_previous_sibling().is_none())))
113        || (offset == anchor_size
114            && (!anchor_node.can_insert_text_after()
115                || (!anchor_parent.can_insert_text_after()
116                    && anchor_node.get_next_sibling().is_none())));
117
118    if needs_redirect {
119        // Token/segmented nodes and nodes whose parent forbids text insertion
120        // at the boundary: reposition the cursor to an adjacent insertable
121        // node, then recurse.
122
123        // Segmented node with cursor in the middle: convert to normal
124        // text node so that the recursive insertText can proceed.
125        if anchor_node.is_segmented() && offset != 0 && offset != anchor_size {
126            if get_composition_key().is_some() {
127                anchor_node.set_mode("normal")?;
128                anchor_node.set_format(format);
129                anchor_node.set_style(&style);
130                if let Some(editor) = get_active_editor() {
131                    editor.0.input_state.borrow_mut().composed_segmented_key =
132                        Some(anchor_node.get_key().to_owned());
133                }
134                if !text.is_empty() {
135                    insert_text(selection, text)?;
136                }
137                return Ok(());
138            }
139            let anchor_data = anchor_node.text_data();
140            let replacement = create_text_node(anchor_data.get_text());
141            replacement.set_format(format);
142            replacement.set_style(&style);
143            replacement.set_detail(anchor_data.get_detail())?;
144            // The characters keep their NodeState (comment ids, for example)
145            carry_node_state(&anchor_node, &replacement)?;
146            let is_current_selection = get_selection().is_some_and(|s| s.ptr_eq(selection));
147            anchor_node.replace(&replacement, false)?;
148            // replace() installs a clone of the active selection, so this
149            // selection is still anchored to the segmented node that was just
150            // detached. Move it onto the replacement and make it current
151            // again, otherwise the recursive insertText below resolves an
152            // anchor that is no longer in the tree.
153            selection.set_text_node_range(&replacement, offset, &replacement, offset)?;
154            if is_current_selection && !get_selection().is_some_and(|s| s.ptr_eq(selection)) {
155                set_selection(Some(selection.clone()));
156            }
157            if !text.is_empty() {
158                insert_text(selection, text)?;
159            }
160            return Ok(());
161        }
162        if text.is_empty() {
163            return Ok(());
164        }
165        if offset == 0 || offset == anchor_size {
166            let before = offset == 0;
167            let direction = if before {
168                CaretDirection::Previous
169            } else {
170                CaretDirection::Next
171            };
172            let sibling = get_sibling_caret(&anchor_node, direction).get_node_at_caret();
173            let target = match sibling.filter(|sibling| {
174                sibling.is_text()
175                    && (if before {
176                        sibling.can_insert_text_after()
177                    } else {
178                        sibling.can_insert_text_before()
179                    })
180                    && !is_token_or_segmented(sibling)
181            }) {
182                Some(sibling) => sibling,
183                None => {
184                    let target = create_text_node("");
185                    target.set_format(format);
186                    target.set_style(&style);
187                    let can_insert = if before {
188                        anchor_parent.can_insert_text_before()
189                    } else {
190                        anchor_parent.can_insert_text_after()
191                    };
192                    get_sibling_caret(
193                        if can_insert {
194                            &anchor_node
195                        } else {
196                            &anchor_parent
197                        },
198                        direction,
199                    )
200                    .insert(&target)?;
201                    target
202                }
203            };
204            let target_offset = if before { None } else { Some(0) };
205            target.select(target_offset, target_offset)?;
206            return insert_text(selection, text);
207        }
208        let new_node = create_text_node(text);
209        new_node.set_format(format);
210        new_node.set_style(&style);
211        // `$recordDeleted` and `$recordTextInserted`: the text edit log is
212        // not ported.
213        anchor_node.replace(&new_node, false)?;
214        new_node.select(None, None)?;
215        return Ok(());
216    }
217
218    if text.is_empty() {
219        return Ok(());
220    }
221
222    let at_start_of_inline =
223        anchor_parent.is_inline() && offset == 0 && anchor_node.get_previous_sibling().is_none();
224    let at_end_of_inline = anchor_parent.is_inline()
225        && offset == anchor_size
226        && anchor_node.get_next_sibling().is_none();
227    let anchor_data = anchor_node.text_data();
228    let format_differs = anchor_data.get_format() != format || anchor_data.get_style() != style;
229
230    if at_start_of_inline || at_end_of_inline || format_differs {
231        if anchor_data.get_text().is_empty() && !at_start_of_inline && !at_end_of_inline {
232            anchor_node.set_format(format);
233            anchor_node.set_style(&style);
234        } else {
235            return insert_text_at_point(selection, text, format, &style);
236        }
237    }
238
239    anchor_node.splice_text(offset as i64, 0, text, true)?;
240    move_anchor_back_if_composing(selection, &anchor_node, text)
241}
242
243/// While `node` is composed, the anchor goes back over the text just
244/// inserted, which the browser has drawn as the composition.
245fn move_anchor_back_if_composing(
246    selection: &SelectionRef,
247    node: &NodeRef,
248    text: &str,
249) -> Result<(), LexicalError> {
250    let anchor = selection.point(Which::Anchor).expect("a range selection");
251    if node.is_composing() && anchor.point_type == PointType::Text {
252        selection.point_set(
253            Which::Anchor,
254            &anchor.key,
255            anchor.offset.saturating_sub(crate::utf16::len(text)),
256            anchor.point_type,
257        )?;
258    }
259    Ok(())
260}
261
262/// `$insertTextAtPoint(selection, text, format, style)`: inserts `text` as
263/// a new text node with `format` and `style` at the selection's anchor,
264/// splitting the anchor's text node, and selects its end.
265fn insert_text_at_point(
266    selection: &SelectionRef,
267    text: &str,
268    format: f64,
269    style: &str,
270) -> Result<(), LexicalError> {
271    let anchor = selection.point(Which::Anchor).expect("a range selection");
272    let anchor_node = anchor.get_node()?;
273    invariant!(
274        anchor_node.is_text(),
275        "insertText: anchor is not a text node"
276    );
277    let offset = anchor.offset;
278    let text_node = create_text_node(text);
279    text_node.set_format(format);
280    text_node.set_style(style);
281    // `$recordTextInserted`: the text edit log is not ported.
282    let parent = anchor_node.get_parent_or_throw()?;
283    let before = offset == 0;
284    let at_boundary = before || offset == anchor_node.get_text_content_size();
285    let adjacent = if before {
286        anchor_node.get_previous_sibling()
287    } else {
288        anchor_node.get_next_sibling()
289    };
290    if at_boundary && parent.is_inline() && adjacent.is_none() {
291        let direction = if before {
292            CaretDirection::Previous
293        } else {
294            CaretDirection::Next
295        };
296        get_sibling_caret(&parent, direction).insert(&text_node)?;
297    } else {
298        let origin = if at_boundary {
299            anchor_node.clone()
300        } else {
301            anchor_node.split_text(&[offset as i64])?.swap_remove(0)
302        };
303        if before {
304            origin.insert_before(&text_node, false)?;
305        } else {
306            origin.insert_after(&text_node, false)?;
307        }
308    }
309    if anchor_node.get_text_content().is_empty() && anchor_node.is_attached() {
310        anchor_node.remove(false)?;
311    }
312    text_node.select_end()?;
313    move_anchor_back_if_composing(selection, &text_node, text)
314}
315
316/// `$transferStartingElementPointToTextPoint(start, end, format, style)`
317/// with the selection's anchor as `start` and its focus as `end`: puts an
318/// empty text node with `format` and `style` where the element point is,
319/// in a new paragraph where the element is a root, and moves the anchor
320/// (and the focus, when it is the same point) into it.
321fn transfer_starting_element_point_to_text_point(
322    selection: &SelectionRef,
323    format: f64,
324    style: &str,
325) -> Result<(), LexicalError> {
326    let start = selection.point(Which::Anchor).expect("a range selection");
327    let element = start.get_node()?;
328    let placement_node = element.get_child_at_index(start.offset);
329    let text_node = create_text_node("");
330    text_node.set_format(format);
331    text_node.set_style(style);
332    if let Some(placement_node) = placement_node {
333        if is_paragraph_node(&placement_node) {
334            placement_node.splice(0, 0, std::slice::from_ref(&text_node))?;
335        } else {
336            // root or shadow-root + element-mode anchor before a
337            // non-paragraph child (typically a sibling block decorator):
338            // wrap the new text in a paragraph so it stays a valid
339            // block-level child of the root or slot frame.
340            let target = if is_root_or_shadow_root(&*element.get_latest()) {
341                let paragraph = create_paragraph_node();
342                paragraph.append(std::slice::from_ref(&text_node))?;
343                paragraph
344            } else {
345                text_node.clone()
346            };
347            placement_node.insert_before(&target, true)?;
348        }
349    } else if is_root_or_shadow_root(&*element.get_latest()) {
350        // root or shadow-root + last-offset typing: reuse the empty trailing
351        // block when one exists instead of appending a fresh paragraph.
352        match element.get_last_child() {
353            Some(last_child)
354                if last_child.is_element() && !last_child.is_inline() && last_child.is_empty() =>
355            {
356                last_child.append(std::slice::from_ref(&text_node))?;
357            }
358            _ => {
359                let paragraph = create_paragraph_node();
360                paragraph.append(std::slice::from_ref(&text_node))?;
361                element.append(std::slice::from_ref(&paragraph))?;
362            }
363        }
364    } else {
365        element.append(std::slice::from_ref(&text_node))?;
366    }
367    // Transfer the element point to a text point.
368    let range = selection.range().expect("a range selection");
369    if range.anchor == range.focus {
370        selection.point_set(Which::Focus, text_node.get_key(), 0, PointType::Text)?;
371    }
372    selection.point_set(Which::Anchor, text_node.get_key(), 0, PointType::Text)
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::{
379        CreateEditorArgs, UpdateOptions, create_editor, get_root, json, parse_serialized_node,
380        reset_random_key,
381    };
382
383    /// The redirects around token, segmented and tab nodes and the
384    /// element-point transfer, which no vector reaches: the compact state
385    /// and the selection JS 0.53.0 gives for the same document, point and
386    /// text.
387    #[test]
388    fn insert_text_redirects_match_js() {
389        // The paragraph's children, the collapsed point, the text, then the
390        // state and the collapsed text point JS ends with.
391        type Case = (
392            &'static str,
393            (&'static str, usize, PointType),
394            &'static str,
395            &'static str,
396            (&'static str, usize),
397        );
398        let cases: &[Case] = &[
399            (
400                r#"{"type":"text","text":"a","mode":"token"},{"type":"text","text":"b","mode":"token"}"#,
401                ("2", 1, PointType::Text),
402                "X",
403                r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","mode":"token","text":"a"},{"type":"text","text":"X"},{"type":"text","mode":"token","text":"b"}]}]}}"#,
404                ("4", 1),
405            ),
406            (
407                r#"{"type":"text","text":"ab cd","mode":"segmented","format":1,"detail":2}"#,
408                ("2", 2, PointType::Text),
409                "X",
410                r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","detail":2,"text":"abX cd"}]}]}}"#,
411                ("3", 3),
412            ),
413            (
414                r#"{"type":"text","text":"a"},{"type":"tab"}"#,
415                ("3", 1, PointType::Text),
416                "X",
417                r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"a"},{"type":"tab"},{"type":"text","text":"X"}]}]}}"#,
418                ("4", 1),
419            ),
420            (
421                r#"{"type":"text","text":"a"}"#,
422                ("root", 0, PointType::Element),
423                "X",
424                r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"Xa"}]}]}}"#,
425                ("3", 1),
426            ),
427            (
428                r#"{"type":"text","text":"a"},{"type":"text","text":"b","format":1}"#,
429                ("1", 1, PointType::Element),
430                "X",
431                r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"aX"},{"type":"text","format":1,"text":"b"}]}]}}"#,
432                ("2", 2),
433            ),
434        ];
435        let discrete = || UpdateOptions {
436            discrete: true,
437            ..UpdateOptions::default()
438        };
439        for &(children, (key, offset, point_type), text, state, (end_key, end_offset)) in cases {
440            reset_random_key();
441            let editor = create_editor(CreateEditorArgs::default());
442            let doc = format!(r#"{{"type":"paragraph","children":[{children}]}}"#);
443            editor
444                .update(
445                    move || {
446                        let node = parse_serialized_node(&json::parse(&doc).unwrap())?;
447                        get_root().append(&[node])
448                    },
449                    discrete(),
450                )
451                .unwrap();
452            editor
453                .update(
454                    move || {
455                        let selection = crate::lexical_selection::create_range_selection();
456                        selection.point_set(Which::Anchor, key, offset, point_type)?;
457                        selection.point_set(Which::Focus, key, offset, point_type)?;
458                        set_selection(Some(selection.clone()));
459                        selection.insert_text(text)
460                    },
461                    discrete(),
462                )
463                .unwrap();
464            let editor_state = editor.get_editor_state();
465            assert_eq!(
466                json::stringify(&editor_state.to_json(true)).unwrap(),
467                state,
468                "{children}"
469            );
470            let range = editor_state.selection().unwrap().range().unwrap();
471            let end = crate::lexical_selection::Point::new(end_key, end_offset, PointType::Text);
472            assert_eq!(
473                (range.anchor, range.focus),
474                (end.clone(), end),
475                "{children}"
476            );
477        }
478    }
479}