Skip to main content

lexical_ui/nodes/
element.rs

1//! `nodes/LexicalElementNode.ts`: the fields and base behavior of nodes that
2//! have children.
3
4use crate::caret_tree::{detach_node, detach_sibling_range, insert_node_between};
5use crate::constants::{DOUBLE_LINE_BREAK, ELEMENT_TYPE_TO_FORMAT, lookup, name_of};
6use crate::error::invariant;
7use crate::json::Value;
8use crate::lexical_selection::{
9    Point, PointType, SelectionRef, Which, get_selection, internal_make_range_selection,
10    move_selection_point_to_sibling,
11};
12use crate::lexical_utils::{get_writable, mutate, with_writable};
13use crate::node::{LexicalNode, NodeKey, NodeRef, sibling_key_at};
14use crate::nodes::root::RootNode;
15use crate::schema::{
16    NodeSchema, NumberValueOptions, enum_value, node_schema, number_value, string_value,
17    with_accessors,
18};
19use crate::updates::error_on_read_only;
20use crate::{LexicalError, utf16};
21use std::collections::HashSet;
22use std::rc::Rc;
23
24/// `ElementNode`'s text direction (`'ltr' | 'rtl'`; `null` is `None`).
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Direction {
27    Ltr,
28    Rtl,
29}
30
31impl Direction {
32    pub fn as_str(self) -> &'static str {
33        match self {
34            Direction::Ltr => "ltr",
35            Direction::Rtl => "rtl",
36        }
37    }
38}
39
40/// The fields `ElementNode` adds. Numbers a document can set
41/// (`indent`, `textFormat`) are kept as the JS number they parsed to, so a
42/// document writes back exactly what JS writes.
43#[derive(Clone, Debug, Default)]
44pub struct ElementData {
45    pub(crate) first: Option<NodeKey>,
46    pub(crate) last: Option<NodeKey>,
47    pub(crate) size: usize,
48    pub(crate) format: u8,
49    pub(crate) style: String,
50    pub(crate) indent: f64,
51    pub(crate) dir: Option<Direction>,
52    pub(crate) text_format: f64,
53    pub(crate) text_style: String,
54}
55
56impl ElementData {
57    /// `getFormatType()`: `''`, `'left'`, `'start'`, `'center'`, `'right'`,
58    /// `'end'` or `'justify'`.
59    pub fn get_format_type(&self) -> &'static str {
60        name_of(ELEMENT_TYPE_TO_FORMAT, self.format).unwrap_or("")
61    }
62
63    /// `getFormat()`: the alignment flag.
64    pub fn get_format(&self) -> u8 {
65        self.format
66    }
67
68    pub fn get_style(&self) -> &str {
69        &self.style
70    }
71
72    pub fn get_indent(&self) -> f64 {
73        self.indent
74    }
75
76    pub fn get_direction(&self) -> Option<Direction> {
77        self.dir
78    }
79
80    pub fn get_text_format(&self) -> f64 {
81        self.text_format
82    }
83
84    pub fn get_text_style(&self) -> &str {
85        &self.text_style
86    }
87
88    pub fn get_children_size(&self) -> usize {
89        self.size
90    }
91}
92
93/// `$isRootOrShadowRoot(node)`.
94pub(crate) fn is_root_or_shadow_root(node: &dyn LexicalNode) -> bool {
95    node.is::<RootNode>() || (node.element().is_some() && node.is_shadow_root())
96}
97
98/// `ElementNode.getTextContent()`: the slots' text first, then the
99/// children's.
100pub fn get_text_content(node: &dyn LexicalNode) -> String {
101    let children = NodeRef::new(node.get_key()).get_children();
102    let length = children.len();
103    let mut text_content = crate::slot::get_slots_text_content(node);
104    for (i, child) in children.iter().enumerate() {
105        let child = child.get_latest();
106        text_content.push_str(&child.get_text_content());
107        if child.element().is_some() && i != length - 1 && !child.is_inline() {
108            text_content.push_str(DOUBLE_LINE_BREAK);
109        }
110    }
111    text_content
112}
113
114/// `ElementNode.getTextContentSize()`: the slots' size first, then the
115/// children's.
116pub fn get_text_content_size(node: &dyn LexicalNode) -> usize {
117    let children = NodeRef::new(node.get_key()).get_children();
118    let length = children.len();
119    let mut size = crate::slot::get_slots_text_content_size(node);
120    for (i, child) in children.iter().enumerate() {
121        size += child.get_text_content_size();
122        if child.is_element() && i != length - 1 && !child.is_inline() {
123            size += utf16::len(DOUBLE_LINE_BREAK);
124        }
125    }
126    size
127}
128
129/// `ElementNode.shouldSerializeTextStyles()`: whether the element has no
130/// text to derive its text format and style from, so they are written.
131pub fn should_serialize_text_styles(node: &dyn LexicalNode) -> bool {
132    if is_root_or_shadow_root(node) {
133        return false;
134    }
135    !has_text_child(&NodeRef::new(node.get_key()), node.is_inline())
136}
137
138/// `$hasTextChild(element, deep)`. JS caches the deep walk during an export;
139/// the result is the same without it.
140fn has_text_child(element: &NodeRef, deep: bool) -> bool {
141    if deep {
142        return has_text_inside(element);
143    }
144    element.get_children().iter().any(NodeRef::is_text)
145}
146
147/// `$hasTextInside`.
148fn has_text_inside(element: &NodeRef) -> bool {
149    element
150        .get_children()
151        .iter()
152        .any(|child| child.is_text() || (child.is_element() && has_text_inside(child)))
153}
154
155/// `isPointRemoved(point, nodesToRemoveKeySet, nodesToInsertKeySet)`.
156fn is_point_removed(
157    point: &Point,
158    removed: &HashSet<&str>,
159    inserted: &HashSet<&str>,
160) -> Result<bool, LexicalError> {
161    let mut node = Some(point.get_node()?);
162    while let Some(n) = node {
163        if removed.contains(n.get_key()) && !inserted.contains(n.get_key()) {
164            return Ok(true);
165        }
166        node = n.get_parent();
167    }
168    Ok(false)
169}
170
171/// `ElementNode`'s methods, for a node that is an element. They panic on
172/// any other node, as calling them on one is a bug.
173impl NodeRef {
174    fn with_element<R>(&self, f: impl FnOnce(&ElementData) -> R) -> R {
175        let node = self.get_latest();
176        f(node.element().expect("an element"))
177    }
178
179    fn set_element(&self, f: impl FnOnce(&mut ElementData)) {
180        with_writable(self.get_key(), |n| f(n.element_mut().expect("an element")));
181    }
182
183    /// The element's fields (`getFormat()`, `getIndent()`, ...).
184    pub fn element_data(&self) -> ElementData {
185        self.with_element(Clone::clone)
186    }
187
188    /// `isEmpty()`: no children and no slots (a host that holds content in
189    /// its slots only is not empty).
190    pub fn is_empty(&self) -> bool {
191        self.get_children_size() == 0
192            && crate::slot::slots_field(&*self.get_latest()).is_none_or(|s| s.len() == 0)
193    }
194
195    /// `getAllTextNodes()`: the text nodes of the slots, then the children's.
196    pub fn get_all_text_nodes(&self) -> Vec<NodeRef> {
197        let mut text_nodes = Vec::new();
198        for name in crate::slot::get_slot_names(self) {
199            if let Some(slot) = crate::slot::get_slot(self, &name)
200                && slot.is_element()
201            {
202                text_nodes.extend(slot.get_all_text_nodes());
203            }
204        }
205        let mut child = self.get_first_child();
206        while let Some(c) = child {
207            if c.is_text() {
208                text_nodes.push(c.clone());
209            } else if c.is_element() {
210                text_nodes.extend(c.get_all_text_nodes());
211            }
212            child = c.get_next_sibling();
213        }
214        text_nodes
215    }
216
217    /// `getChildAtIndex(index)`.
218    pub fn get_child_at_index(&self, index: usize) -> Option<NodeRef> {
219        // From the nearer end.
220        let size = self.get_children_size();
221        let key = if 2 * index < size {
222            sibling_key_at(self.get_first_child()?.get_key(), index, true)
223        } else if index < size {
224            sibling_key_at(self.get_last_child()?.get_key(), size - 1 - index, false)
225        } else {
226            None
227        };
228        key.map(NodeRef::new)
229    }
230
231    /// `getFirstDescendant()`.
232    pub fn get_first_descendant(&self) -> Option<NodeRef> {
233        let mut node = self.get_first_child()?;
234        while node.is_element() {
235            match node.get_first_child() {
236                Some(child) => node = child,
237                None => break,
238            }
239        }
240        Some(node)
241    }
242
243    /// `getLastDescendant()`.
244    pub fn get_last_descendant(&self) -> Option<NodeRef> {
245        let mut node = self.get_last_child()?;
246        while node.is_element() {
247            match node.get_last_child() {
248                Some(child) => node = child,
249                None => break,
250            }
251        }
252        Some(node)
253    }
254
255    /// `getDescendantByIndex(index)`: the first descendant of the child at
256    /// `index`, or the last descendant of the last child for an index past
257    /// the end; the child itself when it is not an element or is empty.
258    pub fn get_descendant_by_index(&self, index: usize) -> Option<NodeRef> {
259        let at_end = index >= self.get_children_size();
260        let child = if at_end {
261            self.get_last_child()
262        } else {
263            self.get_child_at_index(index)
264        }?;
265        let descendant = if !child.is_element() {
266            None
267        } else if at_end {
268            child.get_last_descendant()
269        } else {
270            child.get_first_descendant()
271        };
272        Some(descendant.unwrap_or(child))
273    }
274
275    /// `ElementNode.select(anchorOffset, focusOffset)`: an element range at
276    /// those child offsets, the end by default.
277    pub fn select_element(
278        &self,
279        anchor_offset: Option<usize>,
280        focus_offset: Option<usize>,
281    ) -> Result<SelectionRef, LexicalError> {
282        error_on_read_only();
283        let selection = get_selection();
284        let children_count = self.get_children_size();
285        if !self.can_be_empty() {
286            if anchor_offset == Some(0) && focus_offset == Some(0) {
287                if let Some(first) = self
288                    .get_first_child()
289                    .filter(|c| c.is_text() || c.is_element())
290                {
291                    return first.select(Some(0), Some(0));
292                }
293            } else if anchor_offset.is_none_or(|o| o == children_count)
294                && focus_offset.is_none_or(|o| o == children_count)
295                && let Some(last) = self
296                    .get_last_child()
297                    .filter(|c| c.is_text() || c.is_element())
298            {
299                return last.select(None, None);
300            }
301        }
302        let anchor_offset = anchor_offset.unwrap_or(children_count);
303        let focus_offset = focus_offset.unwrap_or(children_count);
304        let key = self.get_key();
305        match selection.filter(SelectionRef::is_range) {
306            None => Ok(internal_make_range_selection(
307                Point::new(key, anchor_offset, PointType::Element),
308                Point::new(key, focus_offset, PointType::Element),
309            )),
310            Some(selection) => {
311                selection.point_set(Which::Anchor, key, anchor_offset, PointType::Element)?;
312                selection.point_set(Which::Focus, key, focus_offset, PointType::Element)?;
313                selection.set_dirty(true);
314                Ok(selection)
315            }
316        }
317    }
318
319    /// `clear()`: removes every child.
320    pub fn clear(&self) -> Result<(), LexicalError> {
321        get_writable(self.get_key());
322        for child in self.get_children() {
323            child.remove(false)?;
324        }
325        Ok(())
326    }
327
328    /// `append(...nodesToAppend)`.
329    pub fn append(&self, nodes: &[NodeRef]) -> Result<(), LexicalError> {
330        self.get_latest().append(self, nodes)
331    }
332
333    /// `setDirection(direction)`.
334    pub fn set_direction(&self, direction: Option<Direction>) {
335        self.set_element(|e| e.dir = direction);
336    }
337
338    /// `setFormat(type)`: an alignment by name (`'center'`, ...); `''` and
339    /// unknown names clear it.
340    pub fn set_element_format(&self, format_type: &str) {
341        let format = lookup(ELEMENT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
342        self.set_element(|e| e.format = format);
343    }
344
345    /// `setStyle(style)`.
346    pub fn set_element_style(&self, style: &str) {
347        self.set_element(|e| e.style = style.to_owned());
348    }
349
350    /// `setTextFormat(type)`.
351    pub fn set_text_format(&self, text_format: f64) {
352        self.set_element(|e| e.text_format = text_format);
353    }
354
355    /// `setTextStyle(style)`.
356    pub fn set_text_style(&self, style: &str) {
357        self.set_element(|e| e.text_style = style.to_owned());
358    }
359
360    /// `splice(start, deleteCount, nodesToInsert)`: removes `delete_count`
361    /// children from `start` and inserts `nodes` there (moving any that are
362    /// in the tree already), repairing the selection when children are
363    /// removed.
364    pub fn splice(
365        &self,
366        start: usize,
367        delete_count: usize,
368        nodes_to_insert: &[NodeRef],
369    ) -> Result<(), LexicalError> {
370        self.get_latest()
371            .splice(self, start, delete_count, nodes_to_insert)
372    }
373}
374
375thread_local! {
376    static ELEMENT_NODE_SCHEMA: NodeSchema = build_element_node_schema()
377        .expect("ElementNode's schema");
378}
379
380/// `elementNodeSchema`: the properties every element's JSON has.
381/// `direction`, `format` (the name of its alignment flag, through the
382/// tables `FORMAT_GETTER_TABLE` and `FORMAT_SETTER_TABLE`) and `indent` (a
383/// whole number at least 0) are its fields; `textFormat` and `textStyle`
384/// are written only for an element whose text doesn't give them
385/// (`when: 'shouldSerializeTextStyles'`).
386pub fn element_node_schema() -> NodeSchema {
387    ELEMENT_NODE_SCHEMA.with(Clone::clone)
388}
389
390fn element_of(node: &dyn LexicalNode) -> &ElementData {
391    node.element().expect("an element")
392}
393
394fn element_of_mut(node: &mut dyn LexicalNode) -> &mut ElementData {
395    node.element_mut().expect("an element")
396}
397
398fn build_element_node_schema() -> Result<NodeSchema, LexicalError> {
399    let element_formats = ["", "left", "start", "center", "right", "end", "justify"];
400    let serialize_text_styles = |node: &dyn LexicalNode| node.should_serialize_text_styles();
401    node_schema(vec![
402        (
403            "direction",
404            with_accessors(
405                enum_value(vec![Value::Null, "ltr".into(), "rtl".into()], None)?,
406                Some(Rc::new(|node| {
407                    element_of(node)
408                        .dir
409                        .map_or(Value::Null, |d| d.as_str().into())
410                })),
411                Some(Rc::new(|node, value| {
412                    element_of_mut(node).dir = match value.as_str() {
413                        Some("ltr") => Some(Direction::Ltr),
414                        Some("rtl") => Some(Direction::Rtl),
415                        _ => None,
416                    };
417                })),
418            )?,
419        ),
420        (
421            "format",
422            with_accessors(
423                enum_value(element_formats.map(Value::from).to_vec(), None)?,
424                Some(Rc::new(|node| {
425                    name_of(ELEMENT_TYPE_TO_FORMAT, element_of(node).format)
426                        .map_or(Value::Undefined, Value::from)
427                })),
428                Some(Rc::new(|node, value| {
429                    element_of_mut(node).format = value
430                        .as_str()
431                        .and_then(|name| lookup(ELEMENT_TYPE_TO_FORMAT, name))
432                        .unwrap_or(0);
433                })),
434            )?,
435        ),
436        (
437            "indent",
438            with_accessors(
439                number_value(
440                    0.0,
441                    NumberValueOptions {
442                        integer: true,
443                        min: Some(0.0),
444                        ..NumberValueOptions::default()
445                    },
446                )?,
447                Some(Rc::new(|node| element_of(node).indent.into())),
448                Some(Rc::new(|node, value| {
449                    element_of_mut(node).indent = value.as_f64().unwrap_or(0.0);
450                })),
451            )?,
452        ),
453        (
454            "textFormat",
455            with_accessors(
456                number_value(0.0, NumberValueOptions::default())?,
457                Some(Rc::new(|node| element_of(node).text_format.into())),
458                Some(Rc::new(|node, value| {
459                    element_of_mut(node).text_format = value.as_f64().unwrap_or(0.0);
460                })),
461            )?
462            .when(serialize_text_styles),
463        ),
464        (
465            "textStyle",
466            with_accessors(
467                string_value(""),
468                Some(Rc::new(|node| element_of(node).text_style.as_str().into())),
469                Some(Rc::new(|node, value| {
470                    element_of_mut(node).text_style = value.as_str().unwrap_or("").to_owned();
471                })),
472            )?
473            .when(serialize_text_styles),
474        ),
475    ])
476}
477
478/// `ElementNode.exportJSON(compact)`, which a node that extends
479/// `ElementNode` calls as `super.exportJSON()` and adds its own properties
480/// to: the element's properties in both JSON forms (`exportElementNode`,
481/// `exportCompactElementNode`), with an empty `children` array.
482pub fn export_json(node: &dyn LexicalNode, compact: bool) -> crate::json::Object {
483    if compact {
484        crate::generated_json::export_compact_element_node(node)
485    } else {
486        crate::generated_json::export_element_node(node)
487    }
488}
489
490/// `ElementNode.updateFromJSON(serializedNode)` (`updateElementNode`) on
491/// the element's data, which a node that extends `ElementNode` calls as
492/// `super.updateFromJSON()`.
493pub fn update_from_json(data: &mut ElementData, json: &crate::json::Object) {
494    crate::generated_json::update_element_node(data, json);
495}
496
497/// `ElementNode.splice(start, deleteCount, nodesToInsert)`, which nodes that
498/// override it call as `super.splice`, and code that bypasses an override
499/// (`ElementNode.prototype.splice.call`), as the node structure
500/// normalization's `$append` does, calls directly. `RootNode.splice`'s check
501/// is the root's own override.
502pub fn splice(
503    this: &NodeRef,
504    start: usize,
505    delete_count: usize,
506    nodes_to_insert: &[NodeRef],
507) -> Result<(), LexicalError> {
508    let old_size = this.get_children_size();
509    get_writable(this.get_key());
510    invariant!(
511        start + delete_count <= old_size,
512        "ElementNode.splice: start + deleteCount > oldSize ({start} + {delete_count} > {old_size})"
513    );
514    for node_to_insert in nodes_to_insert {
515        crate::slot::error_on_slot_cycle_child(this, node_to_insert)?;
516    }
517    let self_key = this.get_key();
518    let mut nodes_to_insert_keys: Vec<String> = Vec::new();
519    let mut nodes_to_remove_keys = Vec::new();
520    let mut node_after_range = this.get_child_at_index(start + delete_count);
521    let mut node_before_range = None;
522    let mut new_size = (old_size - delete_count + nodes_to_insert.len()) as isize;
523
524    if start != 0 {
525        if start == old_size {
526            node_before_range = this.get_last_child();
527        } else if let Some(node) = this.get_child_at_index(start) {
528            node_before_range = node.get_previous_sibling();
529        }
530    }
531
532    if delete_count > 0 {
533        let first = match &node_before_range {
534            None => this.get_first_child(),
535            Some(before) => before.get_next_sibling(),
536        };
537        nodes_to_remove_keys =
538            detach_sibling_range(this, first, delete_count, node_before_range.as_ref())?;
539    }
540
541    // The writable insertion tail.
542    let mut writable_prev_node = match &node_before_range {
543        Some(before) if !nodes_to_insert.is_empty() => {
544            get_writable(before.get_key());
545            Some(before.clone())
546        }
547        _ => None,
548    };
549    for node_to_insert in nodes_to_insert {
550        if writable_prev_node.as_ref() == Some(node_to_insert) {
551            node_before_range = node_to_insert.get_previous_sibling();
552            writable_prev_node = node_before_range.clone();
553            if let Some(prev) = &writable_prev_node {
554                get_writable(prev.get_key());
555            }
556        }
557        if node_after_range.as_ref() == Some(node_to_insert) {
558            node_after_range = node_to_insert.get_next_sibling();
559        }
560        get_writable(node_to_insert.get_key());
561        if node_to_insert.get_parent().as_ref() == Some(this) {
562            new_size -= 1;
563        }
564        detach_node(node_to_insert)?;
565        if let Some(after) = &node_after_range {
566            get_writable(after.get_key());
567        }
568        insert_node_between(
569            self_key,
570            node_to_insert.get_key(),
571            writable_prev_node.as_ref().map(NodeRef::get_key),
572            node_after_range.as_ref().map(NodeRef::get_key),
573        );
574        invariant!(
575            node_to_insert.get_key() != self_key,
576            "append: attempting to append this"
577        );
578        nodes_to_insert_keys.push(node_to_insert.get_key().to_owned());
579        writable_prev_node = Some(node_to_insert.clone());
580    }
581
582    let new_size = usize::try_from(new_size).expect("size >= 0");
583    mutate(self_key, |n| {
584        n.element_mut().expect("an element").size = new_size
585    });
586
587    // Removing children moves the selection out of them, and removes an
588    // element that can't be empty.
589    if !nodes_to_remove_keys.is_empty()
590        && let Some(selection) = get_selection().filter(SelectionRef::is_range)
591    {
592        let removed: HashSet<&str> = nodes_to_remove_keys.iter().map(String::as_str).collect();
593        let inserted: HashSet<&str> = nodes_to_insert_keys.iter().map(String::as_str).collect();
594        for which in [Which::Anchor, Which::Focus] {
595            let point = selection.point(which).expect("a range selection");
596            if is_point_removed(&point, &removed, &inserted)? {
597                move_selection_point_to_sibling(
598                    &selection,
599                    which,
600                    &point.get_node()?,
601                    this,
602                    node_before_range.as_ref(),
603                    node_after_range.as_ref(),
604                )?;
605            }
606        }
607        if new_size == 0 && !this.can_be_empty() && !is_root_or_shadow_root(&*this.get_latest()) {
608            this.remove(false)?;
609        }
610    }
611    Ok(())
612}
613
614/// `ElementNode.exportDOM(editor)`: `LexicalNode`'s export, with the
615/// indent (as `padding-inline-start` in steps of 40px and
616/// `data-lexical-indent`) and the direction on an element.
617#[cfg(feature = "html")]
618pub fn export_dom(
619    node: &dyn LexicalNode,
620    this: &NodeRef,
621    editor: &crate::Editor,
622) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
623    let output = crate::lexical_dom::export_dom_base(node, this, editor)?;
624    if let Some(element) = output.element.as_ref().filter(|e| e.is_element()) {
625        let data = node.element().expect("an element");
626        let indent = data.get_indent();
627        if indent > 0.0 {
628            element.style().set_property(
629                "padding-inline-start",
630                &format!("{}px", crate::json::number_to_string(indent * 40.0)),
631                "",
632            );
633            element.set_attribute(
634                "data-lexical-indent",
635                &crate::json::number_to_string(indent),
636            );
637        }
638        if let Some(direction) = data.get_direction() {
639            element.set_attribute("dir", direction.as_str());
640        }
641    }
642    Ok(output)
643}