Skip to main content

lexical_ui/nodes/
text.rs

1//! `nodes/LexicalTextNode.ts`.
2
3use crate::constants::{
4    DETAIL_TYPE_TO_DETAIL, IS_DIRECTIONLESS, IS_NORMAL, IS_SEGMENTED, IS_TOKEN, IS_UNMERGEABLE,
5    TEXT_MODE_TO_TYPE, TEXT_TYPE_TO_FORMAT, lookup, name_of,
6};
7use crate::error::invariant;
8use crate::generated_json::{export_compact_text_node, export_text_node, update_text_node};
9use crate::json::{Object, Value};
10use crate::lexical_selection::{
11    Point, PointType, SelectionRef, Which, adjust_point_offset_for_merged_sibling, get_selection,
12    internal_make_range_selection, update_element_selection_on_create_delete_node,
13};
14use crate::lexical_utils::{
15    get_composition_key, get_writable, internal_mark_siblings_as_dirty, mutate,
16    set_composition_key, set_node_key, with_writable,
17};
18use crate::node::{LexicalNode, NodeBase, NodeRef};
19use crate::node_state::clone_node_state;
20use crate::nodes::tab::TabNode;
21use crate::schema::{
22    NodeSchema, NumberValueOptions, aliased_value, enum_value, node_schema, number_value,
23    string_value, with_accessors,
24};
25use crate::updates::error_on_read_only;
26use crate::{LexicalError, utf16};
27use std::rc::Rc;
28
29thread_local! {
30    static TEXT_NODE_SCHEMA: NodeSchema = build_text_node_schema().expect("TextNode's schema");
31}
32
33/// `textNodeSchema`: the properties of a text node's JSON, each one of its
34/// fields. `detail` and `format` also read the names of their flags
35/// (`DETAIL_TYPE_TO_DETAIL`, `TEXT_TYPE_TO_FORMAT`); `mode` is stored as
36/// its flag and written as its name (`TEXT_TYPE_TO_MODE`,
37/// `TEXT_MODE_TO_TYPE`).
38pub fn text_node_schema() -> NodeSchema {
39    TEXT_NODE_SCHEMA.with(Clone::clone)
40}
41
42pub(crate) fn text_of(node: &dyn LexicalNode) -> &TextData {
43    node.text().expect("a text node")
44}
45
46pub(crate) fn text_of_mut(node: &mut dyn LexicalNode) -> &mut TextData {
47    node.text_mut().expect("a text node")
48}
49
50/// An alias table of flag names, as `aliasedValue` takes it.
51fn flag_aliases(table: &[(&str, i32)]) -> Vec<(String, Value)> {
52    table
53        .iter()
54        .map(|(name, flag)| ((*name).to_owned(), Value::Number(*flag as f64)))
55        .collect()
56}
57
58fn build_text_node_schema() -> Result<NodeSchema, LexicalError> {
59    let number = || number_value(0.0, NumberValueOptions::default());
60    node_schema(vec![
61        (
62            "detail",
63            with_accessors(
64                aliased_value(number()?, flag_aliases(DETAIL_TYPE_TO_DETAIL))?,
65                Some(Rc::new(|node| text_of(node).detail.into())),
66                Some(Rc::new(|node, value| {
67                    text_of_mut(node).detail = value.as_f64().unwrap_or(0.0);
68                })),
69            )?,
70        ),
71        (
72            "format",
73            with_accessors(
74                aliased_value(number()?, flag_aliases(TEXT_TYPE_TO_FORMAT))?,
75                Some(Rc::new(|node| text_of(node).format.into())),
76                Some(Rc::new(|node, value| {
77                    text_of_mut(node).format = value.as_f64().unwrap_or(0.0);
78                })),
79            )?,
80        ),
81        (
82            "mode",
83            with_accessors(
84                enum_value(
85                    vec!["normal".into(), "token".into(), "segmented".into()],
86                    None,
87                )?,
88                Some(Rc::new(|node| {
89                    name_of(TEXT_MODE_TO_TYPE, text_of(node).mode)
90                        .map_or(Value::Undefined, Value::from)
91                })),
92                Some(Rc::new(|node, value| {
93                    text_of_mut(node).mode = value
94                        .as_str()
95                        .and_then(|name| lookup(TEXT_MODE_TO_TYPE, name))
96                        .unwrap_or(IS_NORMAL);
97                })),
98            )?,
99        ),
100        (
101            "style",
102            with_accessors(
103                string_value(""),
104                Some(Rc::new(|node| text_of(node).style.as_str().into())),
105                Some(Rc::new(|node, value| {
106                    text_of_mut(node).style = value.as_str().unwrap_or("").to_owned();
107                })),
108            )?,
109        ),
110        (
111            "text",
112            with_accessors(
113                string_value(""),
114                Some(Rc::new(|node| text_of(node).text.as_str().into())),
115                Some(Rc::new(|node, value| {
116                    text_of_mut(node).text = value.as_str().unwrap_or("").to_owned();
117                })),
118            )?,
119        ),
120    ])
121}
122
123/// The fields `TextNode` adds. `format` and `detail` are kept as the JS
124/// number they parsed to, so a document writes back exactly what JS writes;
125/// JS's bitwise operators read them as `ToInt32`.
126///
127/// `text` is a Rust string: offsets into it are UTF-16 code units, as in JS,
128/// converted where they are used (rust/DESIGN.md).
129#[derive(Clone, Debug)]
130pub struct TextData {
131    pub(crate) text: String,
132    pub(crate) format: f64,
133    pub(crate) style: String,
134    pub(crate) mode: u8,
135    pub(crate) detail: f64,
136}
137
138impl Default for TextData {
139    fn default() -> Self {
140        Self {
141            text: String::new(),
142            format: 0.0,
143            style: String::new(),
144            mode: 0,
145            detail: 0.0,
146        }
147    }
148}
149
150impl TextData {
151    pub fn get_text(&self) -> &str {
152        &self.text
153    }
154
155    pub fn get_format(&self) -> f64 {
156        self.format
157    }
158
159    pub fn get_style(&self) -> &str {
160        &self.style
161    }
162
163    pub fn get_detail(&self) -> f64 {
164        self.detail
165    }
166
167    /// `getMode()`: `'normal'`, `'token'` or `'segmented'`.
168    pub fn get_mode(&self) -> &'static str {
169        name_of(TEXT_MODE_TO_TYPE, self.mode).unwrap_or("normal")
170    }
171}
172
173#[derive(Clone, Debug, Default)]
174pub struct TextNode {
175    base: NodeBase,
176    text: TextData,
177}
178
179impl LexicalNode for TextNode {
180    fn get_type(&self) -> &'static str {
181        "text"
182    }
183    fn base(&self) -> &NodeBase {
184        &self.base
185    }
186    fn base_mut(&mut self) -> &mut NodeBase {
187        &mut self.base
188    }
189    fn text(&self) -> Option<&TextData> {
190        Some(&self.text)
191    }
192    fn text_mut(&mut self) -> Option<&mut TextData> {
193        Some(&mut self.text)
194    }
195    fn generated_export_json(&self, compact: bool) -> Option<Object> {
196        Some(if compact {
197            export_compact_text_node(self.get_type(), &self.text)
198        } else {
199            export_text_node(self.get_type(), &self.text)
200        })
201    }
202    fn generated_update_from_json(&mut self, json: &Object) -> bool {
203        update_text_node(&mut self.text, json);
204        true
205    }
206    #[cfg(feature = "html")]
207    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
208        Some(import_dom())
209    }
210}
211
212impl TextNode {
213    /// A text node holding `text` (`new TextNode(text)`), not yet in an
214    /// editor state.
215    pub fn new(text: impl Into<String>) -> Self {
216        Self {
217            base: NodeBase::default(),
218            text: TextData {
219                text: text.into(),
220                ..TextData::default()
221            },
222        }
223    }
224}
225
226/// `$createTextNode(text)`.
227pub fn create_text_node(text: &str) -> NodeRef {
228    crate::lexical_utils::replaced(set_node_key(Box::new(TextNode::new(text))))
229}
230
231/// `ToInt32(x)`, how JS's bitwise operators read a number.
232/// `getElementOuterTag(node, format)`.
233fn get_element_outer_tag(format: f64) -> Option<&'static str> {
234    use crate::constants::{IS_CODE, IS_HIGHLIGHT, IS_SUBSCRIPT, IS_SUPERSCRIPT};
235    let format = to_int32(format);
236    if format & IS_CODE != 0 {
237        Some("code")
238    } else if format & IS_HIGHLIGHT != 0 {
239        Some("mark")
240    } else if format & IS_SUBSCRIPT != 0 {
241        Some("sub")
242    } else if format & IS_SUPERSCRIPT != 0 {
243        Some("sup")
244    } else {
245        None
246    }
247}
248
249/// `getElementInnerTag(node, format)`.
250fn get_element_inner_tag(format: f64) -> &'static str {
251    use crate::constants::{IS_BOLD, IS_ITALIC};
252    let format = to_int32(format);
253    if format & IS_BOLD != 0 {
254        "strong"
255    } else if format & IS_ITALIC != 0 {
256        "em"
257    } else {
258        "span"
259    }
260}
261
262/// What `TextNode.updateDOM(prevNode, dom, config)` returns: true, so the
263/// reconciler makes the DOM again, when the text's outermost tag changes.
264pub(crate) fn update_dom(prev: &TextData, next: &TextData) -> bool {
265    let tag = |format: f64| get_element_outer_tag(format).unwrap_or(get_element_inner_tag(format));
266    tag(prev.format) != tag(next.format)
267}
268
269pub(crate) fn to_int32(x: f64) -> i32 {
270    if !x.is_finite() {
271        return 0;
272    }
273    x.trunc().rem_euclid(4_294_967_296.0) as u32 as i32
274}
275
276/// `toggleTextFormatType(format, type, alignWithFormat)`.
277pub fn toggle_text_format_type(
278    format: i32,
279    format_type: &str,
280    align_with_format: Option<i32>,
281) -> i32 {
282    let flag = |name| lookup(TEXT_TYPE_TO_FORMAT, name).unwrap_or(0);
283    let active_format = flag(format_type);
284    if let Some(align) = align_with_format
285        && (format & active_format) == (align & active_format)
286    {
287        return format;
288    }
289    let mut new_format = format ^ active_format;
290    match format_type {
291        "subscript" => new_format &= !flag("superscript"),
292        "superscript" => new_format &= !flag("subscript"),
293        "lowercase" => new_format &= !(flag("uppercase") | flag("capitalize")),
294        "uppercase" => new_format &= !(flag("lowercase") | flag("capitalize")),
295        "capitalize" => new_format &= !(flag("lowercase") | flag("uppercase")),
296        _ => {}
297    }
298    new_format
299}
300
301/// `text.slice(start)` with JS's negative `start` (from the end).
302fn slice_from_signed(text: &str, start: i64) -> String {
303    let start = if start < 0 {
304        (utf16::len(text) as i64 + start).max(0)
305    } else {
306        start
307    };
308    utf16::slice_from(text, start as usize)
309}
310
311/// `TextNode`'s methods, for a node that is a text node (a `TextNode` or a
312/// subclass such as `TabNode`). They panic on any other node, as calling
313/// them on one is a bug.
314impl NodeRef {
315    fn with_text<R>(&self, f: impl FnOnce(&TextData) -> R) -> R {
316        let node = self.get_latest();
317        f(node.text().expect("a text node"))
318    }
319
320    fn set_text_data(&self, f: impl FnOnce(&mut TextData)) {
321        with_writable(self.get_key(), |n| f(n.text_mut().expect("a text node")));
322    }
323
324    fn is_tab(&self) -> bool {
325        self.get_latest().is::<TabNode>()
326    }
327
328    /// The text node's fields (`getFormat()`, `getStyle()`, ...).
329    pub fn text_data(&self) -> TextData {
330        self.with_text(Clone::clone)
331    }
332
333    /// `isComposing()`: whether an input method is composing in this node.
334    pub fn is_composing(&self) -> bool {
335        get_composition_key().as_deref() == Some(self.get_key())
336    }
337
338    /// `isSimpleText()`: a plain `text` node in normal mode.
339    pub fn is_simple_text(&self) -> bool {
340        self.get_type() == "text" && self.with_text(|t| t.mode == IS_NORMAL)
341    }
342
343    /// `isUnmergeable()`.
344    pub fn is_unmergeable(&self) -> bool {
345        self.with_text(|t| to_int32(t.detail) & IS_UNMERGEABLE != 0)
346    }
347
348    /// `isToken()`.
349    pub fn is_token(&self) -> bool {
350        self.with_text(|t| t.mode == IS_TOKEN)
351    }
352
353    /// `isSegmented()`.
354    pub fn is_segmented(&self) -> bool {
355        self.with_text(|t| t.mode == IS_SEGMENTED)
356    }
357
358    /// `hasFormat(type)`.
359    pub fn has_format(&self, format_type: &str) -> bool {
360        let flag = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
361        self.with_text(|t| to_int32(t.format) & flag != 0)
362    }
363
364    /// `setFormat(format)` with a number, which a node class may override
365    /// ([`LexicalNode::set_format`]).
366    pub fn set_format(&self, format: f64) {
367        self.get_latest().set_format(self, format);
368    }
369
370    /// `setFormat(type)` with a name, such as `'bold'`.
371    pub fn set_format_type(&self, format_type: &str) {
372        let format = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
373        self.set_format(f64::from(format));
374    }
375
376    /// `setDetail(detail)` with a number. A tab only takes
377    /// `IS_UNMERGEABLE`, which it has.
378    pub fn set_detail(&self, detail: f64) -> Result<(), LexicalError> {
379        if self.is_tab() {
380            invariant!(
381                detail == f64::from(IS_UNMERGEABLE),
382                "TabNode does not support setDetail"
383            );
384            return Ok(());
385        }
386        self.set_text_data(|t| t.detail = detail);
387        Ok(())
388    }
389
390    /// `setDetail(type)` with a name: `'directionless'` or `'unmergeable'`.
391    pub fn set_detail_type(&self, detail_type: &str) -> Result<(), LexicalError> {
392        invariant!(!self.is_tab(), "TabNode does not support setDetail");
393        let detail = lookup(DETAIL_TYPE_TO_DETAIL, detail_type).unwrap_or(0);
394        self.set_detail(f64::from(detail))
395    }
396
397    /// `setStyle(style)`.
398    pub fn set_style(&self, style: &str) {
399        self.set_text_data(|t| t.style = style.to_owned());
400    }
401
402    /// `toggleFormat(type)`.
403    pub fn toggle_format(&self, format_type: &str) {
404        let format = to_int32(self.with_text(|t| t.format));
405        let new_format = toggle_text_format_type(format, format_type, None);
406        self.set_format(f64::from(new_format));
407    }
408
409    /// `toggleDirectionless()`.
410    pub fn toggle_directionless(&self) {
411        self.set_text_data(|t| t.detail = f64::from(to_int32(t.detail) ^ IS_DIRECTIONLESS));
412    }
413
414    /// `toggleUnmergeable()`.
415    pub fn toggle_unmergeable(&self) {
416        self.set_text_data(|t| t.detail = f64::from(to_int32(t.detail) ^ IS_UNMERGEABLE));
417    }
418
419    /// `setMode(type)`: `'normal'`, `'token'` or `'segmented'`. A tab is
420    /// always normal.
421    pub fn set_mode(&self, mode_type: &str) -> Result<(), LexicalError> {
422        if self.is_tab() {
423            invariant!(mode_type == "normal", "TabNode does not support setMode");
424            return Ok(());
425        }
426        let Some(mode) = lookup(TEXT_MODE_TO_TYPE, mode_type) else {
427            return Err(LexicalError::new(format!(
428                "setMode: unknown mode {mode_type}"
429            )));
430        };
431        if self.with_text(|t| t.mode) != mode {
432            self.set_text_data(|t| t.mode = mode);
433        }
434        Ok(())
435    }
436
437    /// `setTextContent(text)`. A tab keeps its `\t`.
438    pub fn set_text_content(&self, text: &str) {
439        let text = if self.is_tab() { "\t" } else { text };
440        if self.with_text(|t| t.text != text) {
441            self.set_text_data(|t| t.text = text.to_owned());
442        }
443    }
444
445    /// `TextNode.select(anchorOffset, focusOffset)`: a text range at those
446    /// UTF-16 offsets, the end by default.
447    pub fn select_text(
448        &self,
449        anchor_offset: Option<usize>,
450        focus_offset: Option<usize>,
451    ) -> Result<SelectionRef, LexicalError> {
452        error_on_read_only();
453        let selection = get_selection();
454        let last_offset = utf16::len(&self.get_text_content());
455        let anchor_offset = anchor_offset.unwrap_or(last_offset);
456        let focus_offset = focus_offset.unwrap_or(last_offset);
457        let key = self.get_key();
458        match selection.filter(SelectionRef::is_range) {
459            None => Ok(internal_make_range_selection(
460                Point::new(key, anchor_offset, PointType::Text),
461                Point::new(key, focus_offset, PointType::Text),
462            )),
463            Some(selection) => {
464                let composition_key = get_composition_key();
465                let range = selection.range().expect("a range selection");
466                if composition_key.is_some()
467                    && (composition_key.as_deref() == Some(range.anchor.key.as_str())
468                        || composition_key.as_deref() == Some(range.focus.key.as_str()))
469                {
470                    set_composition_key(Some(key));
471                }
472                selection.set_text_node_range(self, anchor_offset, self, focus_offset)?;
473                Ok(selection)
474            }
475        }
476    }
477
478    /// `spliceText(offset, delCount, newText, moveSelection)`: replaces
479    /// `del_count` UTF-16 units at `offset` with `new_text`, and moves a
480    /// range selection after it when `move_selection`.
481    pub fn splice_text(
482        &self,
483        offset: i64,
484        del_count: i64,
485        new_text: &str,
486        move_selection: bool,
487    ) -> Result<NodeRef, LexicalError> {
488        if self.is_tab() {
489            invariant!(
490                (new_text.is_empty() && del_count == 0) || (new_text == "\t" && del_count == 1),
491                "TabNode does not support spliceText"
492            );
493            return Ok(self.clone());
494        }
495        get_writable(self.get_key());
496        let text = self.get_text_content();
497        let handled_text_length = utf16::len(new_text) as i64;
498        let mut index = offset;
499        if index < 0 {
500            index = (handled_text_length + index).max(0);
501        }
502        if move_selection && let Some(selection) = get_selection().filter(SelectionRef::is_range) {
503            let new_offset = (offset + handled_text_length).max(0) as usize;
504            selection.set_text_node_range(self, new_offset, self, new_offset)?;
505        }
506        let updated_text = utf16::slice(&text, 0, index as usize)
507            + new_text
508            + &slice_from_signed(&text, index + del_count);
509        mutate(self.get_key(), |n| {
510            n.text_mut().expect("a text node").text = updated_text
511        });
512        Ok(self.clone())
513    }
514
515    /// `splitText(...splitOffsets)`: splits the text at those UTF-16
516    /// offsets into this node and new siblings with the same format, style
517    /// and detail, and returns the parts. A segmented node is replaced.
518    pub fn split_text(&self, split_offsets: &[i64]) -> Result<Vec<NodeRef>, LexicalError> {
519        error_on_read_only();
520        let text_content = self.get_text_content();
521        if text_content.is_empty() {
522            return Ok(Vec::new());
523        }
524        let key = self.get_key().to_owned();
525        let text_length = utf16::len(&text_content) as i64;
526        let mut offsets = split_offsets.to_vec();
527        offsets.sort_unstable();
528        offsets.push(text_length);
529        let mut parts = Vec::new();
530        let mut start = 0;
531        for &end in &offsets {
532            if start >= text_length {
533                break;
534            }
535            if end > start {
536                parts.push(utf16::slice(&text_content, start as usize, end as usize));
537                start = end;
538            }
539        }
540        if parts.len() == 1 {
541            return Ok(vec![self.clone()]);
542        }
543        let first_part = &parts[0];
544        let parent = self.get_parent();
545        // `self` in JS: the version the split starts from, whose NodeState
546        // the new nodes take (`$cloneNodeState`).
547        let self_version = self.get_latest();
548        let TextData {
549            format,
550            style,
551            detail,
552            ..
553        } = self.text_data();
554
555        // Prepare to handle selection
556        let selection = get_selection().filter(SelectionRef::is_range);
557        let mut start_text_point = None;
558        let mut end_text_point = None;
559        if let Some(selection) = &selection {
560            let (start_point, end_point) = if selection.is_backward()? {
561                (Which::Focus, Which::Anchor)
562            } else {
563                (Which::Anchor, Which::Focus)
564            };
565            let is_here = |which| {
566                let point = selection.point(which).expect("a range selection");
567                point.point_type == PointType::Text && point.key == key
568            };
569            if is_here(start_point) {
570                start_text_point = Some(start_point);
571            }
572            if is_here(end_point) {
573                end_text_point = Some(end_point);
574            }
575        }
576
577        let copy_fields = |node: &NodeRef| {
578            let state = clone_node_state(&*self_version, node.get_key());
579            mutate(node.get_key(), |n| {
580                let t = n.text_mut().expect("a text node");
581                t.format = format;
582                t.style = style.clone();
583                t.detail = detail;
584                n.base_mut().state = state;
585            });
586        };
587        let has_replaced_self = self.is_segmented();
588        let writable_node = if has_replaced_self {
589            let node = create_text_node(first_part);
590            copy_fields(&node);
591            node
592        } else {
593            self.set_text_content(first_part);
594            self.clone()
595        };
596
597        let composition_key = get_composition_key();
598        let mut split_nodes = vec![writable_node];
599        for part in &parts[1..] {
600            let sibling = create_text_node(part);
601            copy_fields(&sibling);
602            if composition_key.as_deref() == Some(key.as_str()) {
603                set_composition_key(Some(sibling.get_key()));
604            }
605            split_nodes.push(sibling);
606        }
607
608        // Move the selection to the best location in the split string. The
609        // end point is always left-biased, and the start point is generally
610        // left-biased unless the end point would land on a later node.
611        let offset_of = |which: Option<Which>| {
612            which.map(|w| {
613                selection
614                    .as_ref()
615                    .and_then(|s| s.point(w))
616                    .expect("a range selection")
617                    .offset
618            })
619        };
620        let original_start_offset = offset_of(start_text_point);
621        let original_end_offset = offset_of(end_text_point);
622        let mut start_offset = 0;
623        for node in &split_nodes {
624            if start_text_point.is_none() && end_text_point.is_none() {
625                break;
626            }
627            let selection = selection.as_ref().expect("a point is selected");
628            let end_offset = start_offset + node.get_text_content_size();
629            if let (Some(which), Some(original)) = (start_text_point, original_start_offset)
630                && original <= end_offset
631                && original >= start_offset
632            {
633                selection.point_set(
634                    which,
635                    node.get_key(),
636                    original - start_offset,
637                    PointType::Text,
638                )?;
639                if original < end_offset {
640                    // The start isn't on a border, so we can stop checking.
641                    start_text_point = None;
642                }
643            }
644            if let (Some(which), Some(original)) = (end_text_point, original_end_offset)
645                && original <= end_offset
646                && original >= start_offset
647            {
648                selection.point_set(
649                    which,
650                    node.get_key(),
651                    original - start_offset,
652                    PointType::Text,
653                )?;
654                break;
655            }
656            start_offset = end_offset;
657        }
658
659        // Insert the nodes into the parent's children.
660        if let Some(parent) = parent {
661            internal_mark_siblings_as_dirty(self);
662            get_writable(parent.get_key());
663            let insertion_index = self.get_index_within_parent().expect("a child");
664            if has_replaced_self {
665                parent.splice(insertion_index, 0, &split_nodes)?;
666                self.remove(false)?;
667            } else {
668                parent.splice(insertion_index, 1, &split_nodes)?;
669            }
670            if let Some(selection) = &selection {
671                update_element_selection_on_create_delete_node(
672                    selection,
673                    &parent,
674                    insertion_index,
675                    parts.len() as isize - 1,
676                )?;
677            }
678        }
679        Ok(split_nodes)
680    }
681
682    /// `mergeWithSibling(target)`: appends (or prepends) the text of an
683    /// adjacent text node and removes it, keeping the selection on the same
684    /// text.
685    pub fn merge_with_sibling(&self, target: &NodeRef) -> Result<NodeRef, LexicalError> {
686        let is_before = self.get_previous_sibling().as_ref() == Some(target);
687        invariant!(
688            is_before || self.get_next_sibling().as_ref() == Some(target),
689            "mergeWithSibling: sibling must be a previous or next sibling"
690        );
691        let key = self.get_key();
692        let target_key = target.get_key();
693        let text = self.get_text_content();
694        let text_length = utf16::len(&text);
695        if get_composition_key().as_deref() == Some(target_key) {
696            set_composition_key(Some(key));
697        }
698        if let Some(selection) = get_selection().filter(SelectionRef::is_range) {
699            for which in [Which::Anchor, Which::Focus] {
700                if selection.point(which).expect("a range selection").key == target_key {
701                    adjust_point_offset_for_merged_sibling(
702                        &selection,
703                        which,
704                        is_before,
705                        key,
706                        target,
707                        text_length,
708                    )?;
709                }
710            }
711        }
712        let target_text = target.get_text_content();
713        let new_text = if is_before {
714            target_text + &text
715        } else {
716            text + &target_text
717        };
718        self.set_text_content(&new_text);
719        get_writable(key);
720        target.remove(false)?;
721        Ok(self.clone())
722    }
723}
724
725// The DOM side of `TextNode` (the `html` feature).
726
727#[cfg(feature = "html")]
728pub(crate) use text_dom::{create_dom, export_dom, import_dom};
729
730#[cfg(feature = "html")]
731mod text_dom {
732    use super::{TEXT_TYPE_TO_FORMAT, create_text_node, to_int32, toggle_text_format_type};
733    use crate::constants::{
734        IS_BOLD, IS_CODE, IS_HIGHLIGHT, IS_ITALIC, IS_STRIKETHROUGH, IS_SUBSCRIPT, IS_SUPERSCRIPT,
735        IS_UNDERLINE,
736    };
737    use crate::dom::{CssStyle, DomNode};
738    use crate::json::Object;
739    use crate::lexical_dom::{
740        DomChildConversion, DomConversionMap, DomConversionOutput, DomExportOutput,
741        export_dom_base, get_cached_class_name_array, get_document, importer, is_inline_dom_node,
742        remove_empty_dom_attribute,
743    };
744    use crate::lexical_utils::get_composition_key;
745    use crate::node::{LexicalNode, NodeRef};
746    use crate::selection_insert_nodes::generate_nodes_from_raw_text;
747    use crate::set_dom_style::set_dom_style_from_css;
748    use crate::{Editor, EditorConfig, LexicalError};
749    use std::rc::Rc;
750
751    /// `getElementOuterTag(node, format)`.
752    fn get_element_outer_tag(format: i32) -> Option<&'static str> {
753        if format & IS_CODE != 0 {
754            Some("code")
755        } else if format & IS_HIGHLIGHT != 0 {
756            Some("mark")
757        } else if format & IS_SUBSCRIPT != 0 {
758            Some("sub")
759        } else if format & IS_SUPERSCRIPT != 0 {
760            Some("sup")
761        } else {
762            None
763        }
764    }
765
766    /// `getElementInnerTag(node, format)`.
767    fn get_element_inner_tag(format: i32) -> &'static str {
768        if format & IS_BOLD != 0 {
769            "strong"
770        } else if format & IS_ITALIC != 0 {
771            "em"
772        } else {
773            "span"
774        }
775    }
776
777    fn add_classes(dom: &DomNode, class_names: &[String]) {
778        if !class_names.is_empty() {
779            dom.class_list().add(class_names);
780        }
781    }
782
783    fn remove_classes(dom: &DomNode, class_names: &[String]) {
784        if !class_names.is_empty() {
785            dom.class_list().remove(class_names);
786        }
787    }
788
789    /// `setTextThemeClassNames(tag, prevFormat, nextFormat, dom,
790    /// textClassNames)`.
791    fn set_text_theme_class_names(
792        prev_format: i32,
793        next_format: i32,
794        dom: &DomNode,
795        text_class_names: &Object,
796    ) {
797        if let Some(class_names) = get_cached_class_name_array(text_class_names, "base") {
798            add_classes(dom, &class_names);
799        }
800        let mut has_underline_strikethrough = false;
801        let both = IS_UNDERLINE | IS_STRIKETHROUGH;
802        let prev_underline_strikethrough = prev_format & both == both;
803        let next_underline_strikethrough = next_format & both == both;
804        if let Some(class_names) =
805            get_cached_class_name_array(text_class_names, "underlineStrikethrough")
806        {
807            if next_underline_strikethrough {
808                has_underline_strikethrough = true;
809                if !prev_underline_strikethrough {
810                    add_classes(dom, &class_names);
811                }
812            } else if prev_underline_strikethrough {
813                remove_classes(dom, &class_names);
814            }
815        }
816        for &(key, flag) in TEXT_TYPE_TO_FORMAT {
817            let Some(class_names) = get_cached_class_name_array(text_class_names, key) else {
818                continue;
819            };
820            if next_format & flag != 0 {
821                if has_underline_strikethrough && (key == "underline" || key == "strikethrough") {
822                    if prev_format & flag != 0 {
823                        remove_classes(dom, &class_names);
824                    }
825                    continue;
826                }
827                if prev_format & flag == 0
828                    || (prev_underline_strikethrough && key == "underline")
829                    || key == "strikethrough"
830                {
831                    add_classes(dom, &class_names);
832                }
833            } else if prev_format & flag != 0 {
834                remove_classes(dom, &class_names);
835            }
836        }
837        remove_empty_dom_attribute(dom, "class");
838    }
839
840    /// `COMPOSITION_SUFFIX` (`LexicalConstants.ts`): a zero width space, as
841    /// outside Safari and iOS (a browser's flags have no counterpart here,
842    /// as for `IS_SAFARI`).
843    const COMPOSITION_SUFFIX: &str = "\u{200b}";
844
845    /// `$createTextInnerDOM(innerDOM, node, innerTag, format, text,
846    /// config)`, with `$setTextContent`'s text: the node's, and
847    /// [`COMPOSITION_SUFFIX`] after it while an input method composes in
848    /// the node. (A new element has no text child, so `$setTextContent`
849    /// inserts one; its update of an existing one is the reconciler's.)
850    fn create_text_inner_dom(
851        inner_dom: &DomNode,
852        is_composing: bool,
853        format: i32,
854        text: &str,
855        config: &EditorConfig,
856    ) {
857        // Always add a suffix if we're composing a node
858        let suffix = if is_composing { COMPOSITION_SUFFIX } else { "" };
859        inner_dom.append_child(&get_document().create_text_node(&format!("{text}{suffix}")));
860        if let Some(text_class_names) = config.theme.get("text").and_then(|t| t.as_object()) {
861            set_text_theme_class_names(0, format, inner_dom, text_class_names);
862        }
863    }
864
865    /// `TextNode.createDOM(config)`: the outer tag of the code, highlight,
866    /// subscript and superscript formats around the inner tag of bold and
867    /// italic, with the theme's class names and the node's style.
868    pub(crate) fn create_dom(
869        node: &dyn LexicalNode,
870        config: &EditorConfig,
871    ) -> Result<DomNode, LexicalError> {
872        let data = node.text().expect("a text node");
873        let format = to_int32(data.format);
874        let outer_tag = get_element_outer_tag(format);
875        let inner_tag = get_element_inner_tag(format);
876        let document = get_document();
877        let dom = document.create_element(outer_tag.unwrap_or(inner_tag));
878        let mut inner_dom = dom.clone();
879        if format & IS_CODE != 0 {
880            dom.set_attribute("spellcheck", "false");
881        }
882        if outer_tag.is_some() {
883            inner_dom = document.create_element(inner_tag);
884            dom.append_child(&inner_dom);
885        }
886        let is_composing = get_composition_key().as_deref() == Some(node.base().key.as_str());
887        create_text_inner_dom(&inner_dom, is_composing, format, &data.text, config);
888        if !data.style.is_empty() {
889            set_dom_style_from_css(&dom.style(), &data.style, "");
890        }
891        Ok(dom)
892    }
893
894    /// `$wrapElementWith(element, tag)`.
895    fn wrap_element_with(element: &DomNode, tag: &str) -> DomNode {
896        let el = get_document().create_element(tag);
897        el.append_child(element);
898        el
899    }
900
901    /// `TextNode.exportDOM(editor)`: the element `createDOM` makes, with
902    /// `white-space: pre-wrap` and the capitalization's `text-transform`,
903    /// inside `<b>`, `<i>`, `<s>` and `<u>` for those formats.
904    pub(crate) fn export_dom(
905        node: &dyn LexicalNode,
906        this: &NodeRef,
907        editor: &Editor,
908    ) -> Result<DomExportOutput, LexicalError> {
909        let output = export_dom_base(node, this, editor)?;
910        let mut element = match output.element {
911            Some(element) if element.is_element() => element,
912            _ => {
913                return Err(LexicalError::new(
914                    "Expected TextNode createDOM to always return a HTMLElement",
915                ));
916            }
917        };
918        let style = element.style();
919        style.set_property("white-space", "pre-wrap", "");
920        let format = to_int32(node.text().expect("a text node").format);
921        let has = |name: &str| {
922            format & crate::constants::lookup(TEXT_TYPE_TO_FORMAT, name).unwrap_or(0) != 0
923        };
924        if has("lowercase") {
925            style.set_property("text-transform", "lowercase", "");
926        } else if has("uppercase") {
927            style.set_property("text-transform", "uppercase", "");
928        } else if has("capitalize") {
929            style.set_property("text-transform", "capitalize", "");
930        }
931        for (name, tag) in [
932            ("bold", "b"),
933            ("italic", "i"),
934            ("strikethrough", "s"),
935            ("underline", "u"),
936        ] {
937            if has(name) {
938                element = wrap_element_with(&element, tag);
939            }
940        }
941        Ok(DomExportOutput::element(element))
942    }
943
944    /// `TextNode`'s `importDOM`: `#text`, and the inline formatting
945    /// elements, whose formats (and those their style implies) the text
946    /// inside them takes.
947    pub(crate) fn import_dom() -> DomConversionMap {
948        let mut map: DomConversionMap = vec![
949            ("#text".to_owned(), importer(0, convert_text_dom_node)),
950            (
951                "b".to_owned(),
952                importer(0, convert_bring_attention_to_element),
953            ),
954        ];
955        for name in ["code", "em", "i", "mark", "s"] {
956            map.push((name.to_owned(), importer(0, convert_text_format_element)));
957        }
958        map.push(("span".to_owned(), importer(0, convert_span_element)));
959        for name in ["strong", "sub", "sup", "u"] {
960            map.push((name.to_owned(), importer(0, convert_text_format_element)));
961        }
962        map
963    }
964
965    /// `convertSpanElement(domNode)`.
966    fn convert_span_element(
967        dom_node: &DomNode,
968    ) -> Result<Option<DomConversionOutput>, LexicalError> {
969        Ok(Some(DomConversionOutput {
970            for_child: Some(apply_text_format_from_style(&dom_node.style(), None)),
971            ..DomConversionOutput::default()
972        }))
973    }
974
975    /// `convertBringAttentionToElement(domNode)`: bold, unless the `<b>`
976    /// has `font-weight: normal` (as Google Docs wraps copied HTML).
977    fn convert_bring_attention_to_element(
978        dom_node: &DomNode,
979    ) -> Result<Option<DomConversionOutput>, LexicalError> {
980        let style = dom_node.style();
981        let has_normal_font_weight = style.get_property_value("font-weight") == "normal";
982        Ok(Some(DomConversionOutput {
983            for_child: Some(apply_text_format_from_style(
984                &style,
985                (!has_normal_font_weight).then_some("bold"),
986            )),
987            ..DomConversionOutput::default()
988        }))
989    }
990
991    /// `isNodePre(node)`.
992    fn is_node_pre(node: &DomNode) -> bool {
993        if !node.is_element() {
994            return false;
995        }
996        node.node_name() == "PRE"
997            || node
998                .style()
999                .get_property_value("white-space")
1000                .starts_with("pre")
1001    }
1002
1003    /// `findParentPreDOMNode(node)`: the nearest ancestor that keeps
1004    /// whitespace (`<pre>` or `white-space: pre*`). JS caches the walk;
1005    /// the import doesn't change the DOM, so the answer is the same.
1006    pub(crate) fn find_parent_pre_dom_node(node: &DomNode) -> Option<DomNode> {
1007        let mut parent = node.parent_node();
1008        while let Some(p) = parent {
1009            if is_node_pre(&p) {
1010                return Some(p);
1011            }
1012            parent = p.parent_node();
1013        }
1014        None
1015    }
1016
1017    /// `/[ \t\n]$/`.
1018    fn ends_with_collapsible_space(text: &str) -> bool {
1019        text.ends_with([' ', '\t', '\n'])
1020    }
1021
1022    /// `text.replace(/^( |\t|\r?\n)+/, '')`.
1023    fn trim_leading_whitespace_run(text: &str) -> &str {
1024        let mut rest = text;
1025        loop {
1026            if let Some(r) = rest.strip_prefix([' ', '\t', '\n']) {
1027                rest = r;
1028            } else if let Some(r) = rest.strip_prefix("\r\n") {
1029                rest = r;
1030            } else {
1031                return rest;
1032            }
1033        }
1034    }
1035
1036    /// `$convertTextDOMNode(domNode)`: the text with whitespace collapsed as
1037    /// a browser renders it, or raw text inside `pre`.
1038    fn convert_text_dom_node(
1039        dom_node: &DomNode,
1040    ) -> Result<Option<DomConversionOutput>, LexicalError> {
1041        crate::error::invariant!(
1042            dom_node.parent_element().is_some(),
1043            "Expected parentElement of Text not to be null"
1044        );
1045        let raw = dom_node.text_content();
1046        if find_parent_pre_dom_node(dom_node).is_some() {
1047            return Ok(Some(DomConversionOutput {
1048                node: crate::lexical_dom::DomConversionNode::Many(generate_nodes_from_raw_text(
1049                    &raw,
1050                )),
1051                ..DomConversionOutput::default()
1052            }));
1053        }
1054        // .replace(/\r/g, '').replace(/[ \t\n]+/g, ' ')
1055        let mut text_content = String::with_capacity(raw.len());
1056        for c in raw.chars().filter(|&c| c != '\r') {
1057            if matches!(c, ' ' | '\t' | '\n') {
1058                if !text_content.ends_with(' ') || text_content.is_empty() {
1059                    text_content.push(' ');
1060                }
1061            } else {
1062                text_content.push(c);
1063            }
1064        }
1065        if text_content.is_empty() {
1066            return Ok(Some(DomConversionOutput::node(None)));
1067        }
1068        if text_content.starts_with(' ') {
1069            let mut previous_text = Some(dom_node.clone());
1070            let mut is_start_of_line = true;
1071            while let Some(found) = previous_text
1072                .as_ref()
1073                .and_then(|t| find_text_in_line(t, false))
1074            {
1075                let previous_text_content = found.text_content();
1076                if !previous_text_content.is_empty() {
1077                    if ends_with_collapsible_space(&previous_text_content) {
1078                        text_content.remove(0);
1079                    }
1080                    is_start_of_line = false;
1081                    break;
1082                }
1083                previous_text = Some(found);
1084            }
1085            if is_start_of_line && !text_content.is_empty() {
1086                text_content.remove(0);
1087            }
1088        }
1089        if text_content.ends_with(' ') {
1090            let mut next_text = Some(dom_node.clone());
1091            let mut is_end_of_line = true;
1092            while let Some(found) = next_text.as_ref().and_then(|t| find_text_in_line(t, true)) {
1093                if !trim_leading_whitespace_run(&found.text_content()).is_empty() {
1094                    is_end_of_line = false;
1095                    break;
1096                }
1097                next_text = Some(found);
1098            }
1099            if is_end_of_line {
1100                text_content.pop();
1101            }
1102        }
1103        if text_content.is_empty() {
1104            return Ok(Some(DomConversionOutput::node(None)));
1105        }
1106        Ok(Some(DomConversionOutput::node(Some(create_text_node(
1107            &text_content,
1108        )))))
1109    }
1110
1111    /// `findTextInLine(text, forward)`: the next (or previous) text node on
1112    /// the same line, stopping at a block element or a `<br>`.
1113    fn find_text_in_line(text: &DomNode, forward: bool) -> Option<DomNode> {
1114        let mut node = text.clone();
1115        loop {
1116            let sibling = loop {
1117                let sibling = if forward {
1118                    node.next_sibling()
1119                } else {
1120                    node.previous_sibling()
1121                };
1122                match sibling {
1123                    Some(sibling) => break sibling,
1124                    None => node = node.parent_element()?,
1125                }
1126            };
1127            node = sibling;
1128            if node.is_element() {
1129                let display = node.style().get_property_value("display");
1130                if (display.is_empty() && !is_inline_dom_node(&node))
1131                    || (!display.is_empty() && !display.starts_with("inline"))
1132                {
1133                    return None;
1134                }
1135            }
1136            while let Some(descendant) = if forward {
1137                node.first_child()
1138            } else {
1139                node.last_child()
1140            } {
1141                node = descendant;
1142            }
1143            if node.is_text() {
1144                return Some(node);
1145            } else if node.node_name() == "BR" {
1146                return None;
1147            }
1148        }
1149    }
1150
1151    /// `nodeNameToTextFormat`.
1152    fn node_name_to_text_format(name: &str) -> Option<&'static str> {
1153        Some(match name {
1154            "code" => "code",
1155            "em" | "i" => "italic",
1156            "mark" => "highlight",
1157            "s" => "strikethrough",
1158            "strong" => "bold",
1159            "sub" => "subscript",
1160            "sup" => "superscript",
1161            "u" => "underline",
1162            _ => return None,
1163        })
1164    }
1165
1166    /// `convertTextFormatElement(domNode)`.
1167    fn convert_text_format_element(
1168        dom_node: &DomNode,
1169    ) -> Result<Option<DomConversionOutput>, LexicalError> {
1170        let Some(format) = node_name_to_text_format(&dom_node.node_name().to_lowercase()) else {
1171            return Ok(Some(DomConversionOutput::node(None)));
1172        };
1173        Ok(Some(DomConversionOutput {
1174            for_child: Some(apply_text_format_from_style(
1175                &dom_node.style(),
1176                Some(format),
1177            )),
1178            ..DomConversionOutput::default()
1179        }))
1180    }
1181
1182    /// `applyTextFormatFromStyle(style, shouldApply)`: a child conversion
1183    /// that gives a text node (or another inline formattable node) the
1184    /// formats the style implies, and `shouldApply`.
1185    pub(crate) fn apply_text_format_from_style(
1186        style: &CssStyle,
1187        should_apply: Option<&'static str>,
1188    ) -> DomChildConversion {
1189        let font_weight = style.get_property_value("font-weight");
1190        let text_decoration = style.get_property_value("text-decoration");
1191        let text_decoration: Vec<&str> = text_decoration.split(' ').collect();
1192        let vertical_align = style.get_property_value("vertical-align");
1193        let text_transform = style.get_property_value("text-transform");
1194        let mut formats: Vec<&'static str> = Vec::new();
1195        if font_weight == "700" || font_weight == "bold" {
1196            formats.push("bold");
1197        }
1198        if text_decoration.contains(&"line-through") {
1199            formats.push("strikethrough");
1200        }
1201        if style.get_property_value("font-style") == "italic" {
1202            formats.push("italic");
1203        }
1204        if text_decoration.contains(&"underline") {
1205            formats.push("underline");
1206        }
1207        if vertical_align == "sub" {
1208            formats.push("subscript");
1209        }
1210        if vertical_align == "super" {
1211            formats.push("superscript");
1212        }
1213        match text_transform.as_str() {
1214            "lowercase" => formats.push("lowercase"),
1215            "uppercase" => formats.push("uppercase"),
1216            "capitalize" => formats.push("capitalize"),
1217            _ => {}
1218        }
1219        formats.extend(should_apply);
1220        Rc::new(move |lexical_node: &NodeRef, _parent: Option<&NodeRef>| {
1221            let latest = lexical_node.get_latest();
1222            if lexical_node.is_text() {
1223                for format in &formats {
1224                    if !lexical_node.has_format(format) {
1225                        lexical_node.toggle_format(format);
1226                    }
1227                }
1228            } else if latest.is_inline_formattable() {
1229                for format in &formats {
1230                    let current = to_int32(lexical_node.get_latest().get_inline_format());
1231                    let flag = crate::constants::lookup(TEXT_TYPE_TO_FORMAT, format).unwrap_or(0);
1232                    if current & flag == 0 {
1233                        let next = toggle_text_format_type(current, format, None);
1234                        lexical_node
1235                            .get_latest()
1236                            .set_inline_format(lexical_node, f64::from(next))?;
1237                    }
1238                }
1239            }
1240            Ok(Some(lexical_node.clone()))
1241        })
1242    }
1243}