Skip to main content

lexical_ui/list/
list_node.rs

1//! `LexicalListNode.ts`: `ListNode`, `$createListNode` and `$isListNode`.
2
3use super::format_list::{
4    merge_nested_lists_at_seam, merge_next_sibling_list_if_same_type,
5    update_children_list_item_value,
6};
7use super::generated_json::{export_compact_list_node, export_list_node, update_list_node};
8use super::list_item_node::{create_list_item_node, is_list_item_node};
9use crate::LexicalError;
10use crate::json::Object;
11use crate::lexical_utils::{set_node_key, with_writable};
12use crate::node::{LexicalNode, NodeBase, NodeRef};
13use crate::nodes::element::{self, ElementData};
14use crate::schema::{
15    NodeSchema, NumberValueOptions, aliased_value, enum_value, node_schema, number_value,
16    schema_getter, schema_setter, with_accessors, with_field,
17};
18
19/// `ListType`: `'number'`, `'bullet'` or `'check'`.
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum ListType {
22    #[default]
23    Number,
24    Bullet,
25    Check,
26}
27
28impl ListType {
29    pub fn as_str(self) -> &'static str {
30        match self {
31            ListType::Number => "number",
32            ListType::Bullet => "bullet",
33            ListType::Check => "check",
34        }
35    }
36
37    /// The list type a string names (`enumValue(['number', 'bullet',
38    /// 'check'])`).
39    pub fn parse(list_type: &str) -> Option<Self> {
40        Some(match list_type {
41            "number" => ListType::Number,
42            "bullet" => ListType::Bullet,
43            "check" => ListType::Check,
44            _ => return None,
45        })
46    }
47
48    /// `ListNodeTagType`: the tag a list of this type has, `ol` for
49    /// `number` and `ul` otherwise (`setListType`).
50    pub fn tag(self) -> &'static str {
51        match self {
52            ListType::Number => "ol",
53            _ => "ul",
54        }
55    }
56}
57
58/// `ListNode`: an ordered (`number`), unordered (`bullet`) or check list,
59/// whose children are [`ListItemNode`](super::ListItemNode)s.
60///
61/// JS stores the tag (`__tag`) beside the list type, and sets both together
62/// wherever either changes; here the tag is read off the list type.
63#[derive(Clone, Debug)]
64pub struct ListNode {
65    base: NodeBase,
66    pub(super) element: ElementData,
67    pub(super) list_type: ListType,
68    pub(super) start: f64,
69}
70
71impl Default for ListNode {
72    /// `new ListNode()`: a `number` list starting at 1.
73    fn default() -> Self {
74        ListNode {
75            base: NodeBase::default(),
76            element: ElementData::default(),
77            list_type: ListType::Number,
78            start: 1.0,
79        }
80    }
81}
82
83/// `$createListNode(listType = 'number', start = 1)`.
84pub fn create_list_node(list_type: ListType, start: f64) -> NodeRef {
85    crate::lexical_utils::replaced(set_node_key(Box::new(ListNode {
86        list_type,
87        start,
88        ..ListNode::default()
89    })))
90}
91
92/// `$isListNode(node)`.
93pub fn is_list_node(node: &NodeRef) -> bool {
94    node.get_latest().is::<ListNode>()
95}
96
97impl NodeRef {
98    /// `ListNode.getListType()`; `None` for any other node.
99    pub fn get_list_type(&self) -> Option<ListType> {
100        self.get_latest()
101            .downcast_ref::<ListNode>()
102            .map(|l| l.list_type)
103    }
104
105    /// `ListNode.setListType(type)`. Does nothing to any other node.
106    pub fn set_list_type(&self, list_type: ListType) {
107        if is_list_node(self) {
108            with_writable(self.get_key(), |n| {
109                n.downcast_mut::<ListNode>().expect("a list").list_type = list_type;
110            });
111        }
112    }
113
114    /// `ListNode.getTag()`; `None` for any other node.
115    pub fn get_list_tag(&self) -> Option<&'static str> {
116        self.get_list_type().map(ListType::tag)
117    }
118
119    /// `ListNode.getStart()`; `None` for any other node.
120    pub fn get_list_start(&self) -> Option<f64> {
121        self.get_latest()
122            .downcast_ref::<ListNode>()
123            .map(|l| l.start)
124    }
125
126    /// `ListNode.setStart(start)`. Does nothing to any other node.
127    pub fn set_list_start(&self, start: f64) {
128        if is_list_node(self) {
129            with_writable(self.get_key(), |n| {
130                n.downcast_mut::<ListNode>().expect("a list").start = start;
131            });
132        }
133    }
134}
135
136impl ListNode {
137    pub fn list_type(&self) -> ListType {
138        self.list_type
139    }
140
141    pub fn start(&self) -> f64 {
142        self.start
143    }
144}
145
146thread_local! {
147    static LIST_NODE_SCHEMA: NodeSchema = build_list_node_schema().expect("ListNode's schema");
148}
149
150/// `listNodeSchema`: `listType` (with the legacy tags `ol` and `ul` as the
151/// types they stand for), applied with `setListType`, which also keeps the
152/// tag; `start`; and `tag`, written and derived on import.
153pub fn list_node_schema() -> NodeSchema {
154    LIST_NODE_SCHEMA.with(Clone::clone)
155}
156
157fn build_list_node_schema() -> Result<NodeSchema, LexicalError> {
158    node_schema(vec![
159        (
160            "listType",
161            with_accessors(
162                aliased_value(
163                    enum_value(vec!["number".into(), "bullet".into(), "check".into()], None)?,
164                    vec![
165                        ("ol".to_owned(), "number".into()),
166                        ("ul".to_owned(), "bullet".into()),
167                    ],
168                )?,
169                Some(schema_getter(|n: &ListNode| n.list_type.as_str().into())),
170                Some(schema_setter(|n: &mut ListNode, value| {
171                    n.list_type = value.as_str().and_then(ListType::parse).unwrap_or_default();
172                })),
173            )?,
174        ),
175        (
176            "start",
177            with_field(
178                number_value(1.0, NumberValueOptions::default())?,
179                |n: &ListNode| &n.start,
180                |n: &mut ListNode| &mut n.start,
181            )?,
182        ),
183        (
184            "tag",
185            with_accessors(
186                enum_value(vec!["ul".into(), "ol".into()], None)?,
187                Some(schema_getter(|n: &ListNode| n.list_type.tag().into())),
188                None,
189            )?,
190        ),
191    ])
192}
193
194impl LexicalNode for ListNode {
195    fn json_schema_chain(&self) -> Vec<NodeSchema> {
196        vec![list_node_schema(), element::element_node_schema()]
197    }
198    /// The `$config()` of `ListNode`: `children: [ListItemNode]` and
199    /// `mergeAdjacent: {by: ['listType']}`, what
200    /// `mergeNextSiblingListIfSameType` compares (`start` is not).
201    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
202        use crate::structure::{
203            MergeAdjacentDeclaration, MergeAdjacentEntry, NodeChildEntry, NodeChildrenConfig,
204            NodeClassRef, NodeConfigLink, StaticNodeConfig,
205        };
206        vec![NodeConfigLink::new(
207            "list",
208            StaticNodeConfig {
209                children: Some(NodeChildrenConfig::List(vec![NodeChildEntry::Class(
210                    NodeClassRef::of::<super::ListItemNode>(),
211                )])),
212                merge_adjacent: Some(MergeAdjacentDeclaration::By(vec![
213                    MergeAdjacentEntry::Field("listType"),
214                ])),
215                ..StaticNodeConfig::default()
216            },
217        )]
218    }
219    /// `ListNode.updateDOM(prevNode)`: a list of another tag or type is
220    /// made again (the tag follows the type here).
221    fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
222        prev_node
223            .downcast_ref::<ListNode>()
224            .is_some_and(|prev| prev.list_type != self.list_type)
225    }
226    fn get_type(&self) -> &'static str {
227        "list"
228    }
229    #[cfg(feature = "html")]
230    fn create_dom(
231        &self,
232        this: &NodeRef,
233        config: &crate::EditorConfig,
234        _editor: &crate::Editor,
235    ) -> Result<crate::dom::DomNode, LexicalError> {
236        list_dom::create_dom(self, this, config)
237    }
238    #[cfg(feature = "html")]
239    fn export_dom(
240        &self,
241        this: &NodeRef,
242        editor: &crate::Editor,
243    ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
244        list_dom::export_dom(self, this, editor)
245    }
246    #[cfg(feature = "html")]
247    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
248        Some(list_dom::import_dom())
249    }
250    fn base(&self) -> &NodeBase {
251        &self.base
252    }
253    fn base_mut(&mut self) -> &mut NodeBase {
254        &mut self.base
255    }
256    fn element(&self) -> Option<&ElementData> {
257        Some(&self.element)
258    }
259    fn element_mut(&mut self) -> Option<&mut ElementData> {
260        Some(&mut self.element)
261    }
262
263    /// `ListNode.canBeEmpty()`.
264    fn can_be_empty(&self) -> bool {
265        false
266    }
267
268    /// `ListNode.extractWithChild(child)`: a list goes with a list item
269    /// that is copied.
270    fn extract_with_child(
271        &self,
272        _: &NodeRef,
273        child: &NodeRef,
274        _: Option<&crate::lexical_selection::SelectionRef>,
275        _: &str,
276    ) -> Result<bool, LexicalError> {
277        Ok(is_list_item_node(child))
278    }
279
280    /// `ListNode.canIndent()`.
281    fn can_indent(&self) -> bool {
282        false
283    }
284
285    /// `exportListNode` and `exportCompactListNode`.
286    fn generated_export_json(&self, compact: bool) -> Option<Object> {
287        Some(if compact {
288            export_compact_list_node(self)
289        } else {
290            export_list_node(self)
291        })
292    }
293
294    /// `updateListNode`.
295    fn generated_update_from_json(&mut self, json: &Object) -> bool {
296        update_list_node(self, json);
297        true
298    }
299
300    /// `ListNode.splice(start, deleteCount, nodesToInsert)`: what isn't a
301    /// list item is wrapped in one (`createListItemNode()`), a block by its
302    /// children.
303    fn splice(
304        &self,
305        this: &NodeRef,
306        start: usize,
307        delete_count: usize,
308        nodes_to_insert: &[NodeRef],
309    ) -> Result<(), LexicalError> {
310        let mut list_item_nodes_to_insert = Vec::with_capacity(nodes_to_insert.len());
311        for node in nodes_to_insert {
312            if is_list_item_node(node) {
313                list_item_nodes_to_insert.push(node.clone());
314                continue;
315            }
316            let list_item = create_list_item_node(None);
317            if node.is_element() && !(is_list_node(node) || node.is_inline()) {
318                // A block can't stay a block inside a list item, so it is
319                // unwrapped into its own children.
320                list_item.append(&node.get_children())?;
321            } else {
322                list_item.append(std::slice::from_ref(node))?;
323            }
324            list_item_nodes_to_insert.push(list_item);
325        }
326        element::splice(this, start, delete_count, &list_item_nodes_to_insert)
327    }
328
329    /// The `$transform` of `ListNode.$config()`: merges the next list of the
330    /// same type into this one, then renumbers the items. Where
331    /// `NodeStructureExtension` enforces declared structure, it merges
332    /// adjacent lists itself (by `mergeAdjacent`, joining nested lists at the
333    /// seam as `mergeLists` does), the same way whichever list is dirty.
334    fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
335        let structure_merges = this
336            .get_next_sibling()
337            .is_some_and(|next| crate::structure::structure_merges(this, &next));
338        if !structure_merges {
339            merge_next_sibling_list_if_same_type(this)?;
340        }
341        update_children_list_item_value(this);
342        Ok(())
343    }
344
345    /// `ListNode.INTERNAL_$afterStructureMerge(last, first)`: joins nested
346    /// lists at the seam, as `mergeLists` does, but only items whose only
347    /// child is the nested list, so that nothing else in them is removed or
348    /// moved.
349    fn internal_after_structure_merge(
350        &self,
351        _: &NodeRef,
352        last: &NodeRef,
353        first: &NodeRef,
354    ) -> Result<bool, LexicalError> {
355        merge_nested_lists_at_seam(Some(last.clone()), Some(first.clone()), true)?;
356        Ok(true)
357    }
358
359    /// `ListNode.INTERNAL_$afterStructureSplit(original, preceding)`: an
360    /// ordered list part continues the numbering of the items that precede
361    /// it, so it starts at the next number.
362    fn internal_after_structure_split(
363        &self,
364        this: &NodeRef,
365        original: &NodeRef,
366        preceding: &[NodeRef],
367    ) -> Result<(), LexicalError> {
368        if self.list_type == ListType::Number {
369            let mut start = original.get_list_start().unwrap_or(1.0);
370            for node in preceding {
371                // As updateChildrenListItemValue counts: an item that only
372                // wraps a nested list has no number of its own.
373                if is_list_item_node(node)
374                    && !node.get_first_child().is_some_and(|c| is_list_node(&c))
375                {
376                    start += 1.0;
377                }
378            }
379            this.set_list_start(start);
380        }
381        Ok(())
382    }
383}
384
385// The DOM side of `ListNode` (the `html` feature).
386
387#[cfg(feature = "html")]
388pub(super) mod list_dom {
389    use super::super::list_item_node::{create_list_item_node, is_list_item_node};
390    use super::super::utils::get_list_depth;
391    use super::{ListNode, ListType, create_list_node, is_list_node};
392    use crate::dom::DomNode;
393    use crate::json::{Object, Value};
394    use crate::lexical_dom::{
395        DomConversionMap, DomConversionNode, DomConversionOutput, DomExportOutput, get_document,
396        importer, normalize_class_names, set_direction_from_dom,
397    };
398    use crate::node::NodeRef;
399    use crate::{EditorConfig, LexicalError};
400
401    /// `ListNode.createDOM(config)`: an `<ol>` or `<ul>`, with `start`
402    /// when it isn't 1 and the theme's class names.
403    pub(crate) fn create_dom(
404        node: &ListNode,
405        this: &NodeRef,
406        config: &EditorConfig,
407    ) -> Result<DomNode, LexicalError> {
408        let dom = get_document().create_element(node.list_type.tag());
409        if node.start != 1.0 {
410            dom.set_attribute("start", &crate::json::number_to_string(node.start));
411        }
412        set_list_theme_class_names(&dom, &config.theme, node, this)?;
413        Ok(dom)
414    }
415
416    /// `ListNode.exportDOM(editor)`: `createDOM`'s element, with
417    /// `__lexicalListType` for a check list and the direction.
418    pub(crate) fn export_dom(
419        node: &ListNode,
420        this: &NodeRef,
421        editor: &crate::Editor,
422    ) -> Result<DomExportOutput, LexicalError> {
423        let element = create_dom(node, this, editor.config())?;
424        if node.start != 1.0 {
425            element.set_attribute("start", &crate::json::number_to_string(node.start));
426        }
427        if node.list_type == ListType::Check {
428            element.set_attribute("__lexicalListType", "check");
429        }
430        if let Some(direction) = node.element.get_direction() {
431            element.set_dir(direction.as_str());
432        }
433        Ok(DomExportOutput::element(element))
434    }
435
436    /// The strings `normalizeClassNames(value)` takes from a theme value:
437    /// none unless it is a string.
438    fn class_names_of(value: Option<&Value>) -> Vec<String> {
439        value
440            .and_then(Value::as_str)
441            .map(|v| normalize_class_names(&[v]))
442            .unwrap_or_default()
443    }
444
445    /// `$setListThemeClassNames(dom, editorThemeClasses, node)`.
446    fn set_list_theme_class_names(
447        dom: &DomNode,
448        theme: &Object,
449        node: &ListNode,
450        this: &NodeRef,
451    ) -> Result<(), LexicalError> {
452        let mut classes_to_add: Vec<String> = Vec::new();
453        let mut classes_to_remove: Vec<String> = Vec::new();
454        if let Some(list_theme) = theme.get("list").filter(|v| !v.is_undefined()) {
455            let tag = node.list_type.tag();
456            let empty = Vec::new();
457            let list_levels_class_names = list_theme
458                .get(&format!("{tag}Depth"))
459                .and_then(Value::as_array)
460                .unwrap_or(&empty);
461            // `$getListDepth(node) - 1`, and `%` by the number of level
462            // classes (`NaN`, matching none, when there are none).
463            let list_depth = get_list_depth(this)? as i64 - 1;
464            let normalized_list_depth = (!list_levels_class_names.is_empty())
465                .then(|| list_depth.rem_euclid(list_levels_class_names.len() as i64) as usize);
466            let list_level_class_name =
467                normalized_list_depth.and_then(|i| list_levels_class_names.get(i));
468            if let Some(list_class_name) = list_theme.get(tag) {
469                classes_to_add.extend(class_names_of(Some(list_class_name)));
470            }
471            if node.list_type == ListType::Check {
472                classes_to_add.extend(class_names_of(list_theme.get("checklist")));
473            }
474            if let Some(list_level_class_name) = list_level_class_name {
475                classes_to_add.extend(class_names_of(Some(list_level_class_name)));
476                for (i, class_name) in list_levels_class_names.iter().enumerate() {
477                    if Some(i) != normalized_list_depth {
478                        classes_to_remove.extend(class_names_of(Some(class_name)));
479                    }
480                }
481            }
482            let nested_list_class_name = list_theme
483                .get("nested")
484                .and_then(|n| n.get("list"))
485                .filter(|l| l.as_str().is_some_and(|s| !s.is_empty()));
486            if nested_list_class_name.is_some() {
487                let nested_list_item_classes = class_names_of(nested_list_class_name);
488                if list_depth > 1 {
489                    classes_to_add.extend(nested_list_item_classes);
490                } else {
491                    classes_to_remove.extend(nested_list_item_classes);
492                }
493            }
494        }
495        if !classes_to_remove.is_empty() {
496            dom.class_list().remove(&classes_to_remove);
497        }
498        if !classes_to_add.is_empty() {
499            dom.class_list().add(&classes_to_add);
500        }
501        Ok(())
502    }
503
504    /// `ListNode`'s `importDOM`: `<ol>` and `<ul>`.
505    pub(crate) fn import_dom() -> DomConversionMap {
506        vec![
507            ("ol".to_owned(), importer(0, convert_list_node)),
508            ("ul".to_owned(), importer(0, convert_list_node)),
509        ]
510    }
511
512    /// `$normalizeChildren(nodes, listNode)`: the children of a list made
513    /// from HTML, each a list item holding one nested list or inline
514    /// content.
515    fn normalize_children(nodes: Vec<NodeRef>) -> Result<Vec<NodeRef>, LexicalError> {
516        let mut normalized_list_items = Vec::new();
517        for node in nodes {
518            if is_list_item_node(&node) {
519                normalized_list_items.push(node.clone());
520                let children = node.get_children();
521                if children.len() > 1 {
522                    for child in children {
523                        if is_list_node(&child) {
524                            let wrapper = create_list_item_node(None);
525                            wrapper.append(&[child])?;
526                            normalized_list_items.push(wrapper);
527                        }
528                    }
529                }
530            } else {
531                let wrapper = create_list_item_node(None);
532                wrapper.append(&[node])?;
533                normalized_list_items.push(wrapper);
534            }
535        }
536        Ok(normalized_list_items)
537    }
538
539    /// `isDomChecklist(domNode)`: a Lexical, GitHub, Joplin or Google Docs
540    /// check list.
541    fn is_dom_checklist(dom_node: &DomNode) -> bool {
542        if dom_node.get_attribute("__lexicallisttype").as_deref() == Some("check")
543            || dom_node.class_list().contains("contains-task-list")
544            || dom_node.get_attribute("data-is-checklist").as_deref() == Some("1")
545        {
546            return true;
547        }
548        dom_node
549            .child_nodes()
550            .iter()
551            .any(|child| child.is_element() && child.has_attribute("aria-checked"))
552    }
553
554    /// `HTMLOListElement.start`: the `start` attribute by the HTML rules
555    /// for parsing integers, or 1.
556    pub(crate) fn ol_start(element: &DomNode) -> f64 {
557        let Some(value) = element.get_attribute("start") else {
558            return 1.0;
559        };
560        let rest = value.trim_start_matches([' ', '\t', '\n', '\u{c}', '\r']);
561        let (sign, rest) = match rest.as_bytes().first() {
562            Some(b'-') => (-1, &rest[1..]),
563            Some(b'+') => (1, &rest[1..]),
564            _ => (1, rest),
565        };
566        let digits = &rest[..rest
567            .bytes()
568            .position(|b| !b.is_ascii_digit())
569            .unwrap_or(rest.len())];
570        match digits.parse::<i64>() {
571            Ok(n) if (-2_147_483_648..=2_147_483_647).contains(&(sign * n)) => (sign * n) as f64,
572            _ => 1.0,
573        }
574    }
575
576    /// `$convertListNode(domNode)`: a numbered list from `<ol>`, a check
577    /// list or a bullet list from `<ul>`, whose children become list items.
578    fn convert_list_node(dom_node: &DomNode) -> Result<Option<DomConversionOutput>, LexicalError> {
579        let node = if dom_node.is_element() && dom_node.local_name() == "ol" {
580            create_list_node(ListType::Number, ol_start(dom_node))
581        } else if is_dom_checklist(dom_node) {
582            create_list_node(ListType::Check, 1.0)
583        } else {
584            create_list_node(ListType::Bullet, 1.0)
585        };
586        set_direction_from_dom(&node, dom_node);
587        Ok(Some(DomConversionOutput {
588            node: DomConversionNode::One(node),
589            after: Some(Box::new(normalize_children)),
590            ..DomConversionOutput::default()
591        }))
592    }
593}