Skip to main content

lexical_ui/list/
list_item_node.rs

1//! `LexicalListItemNode.ts`: `ListItemNode`, `$createListItemNode` and
2//! `$isListItemNode`.
3
4use super::format_list::{handle_indent, handle_outdent, merge_lists};
5use super::generated_json::{
6    export_compact_list_item_node, export_list_item_node, update_list_item_node,
7};
8use super::list_node::{ListType, create_list_node, is_list_node};
9use super::utils::{get_new_list_start, is_nested_list_node};
10use crate::LexicalError;
11use crate::caret::{CaretDirection, get_sibling_caret};
12use crate::caret_utils::{
13    SplitAtPointCaretNextOptions, insert_node_to_nearest_root_at_caret, rewind_sibling_caret,
14};
15use crate::error::invariant;
16use crate::json::Object;
17use crate::json::Value;
18use crate::lexical_selection::{PointType, SelectionRef, Which, get_selection};
19use crate::lexical_utils::{copy_node, set_node_key, with_writable};
20use crate::node::{self, LexicalNode, NodeBase, NodeRef};
21use crate::nodes::element::{ElementData, is_root_or_shadow_root};
22use crate::nodes::paragraph::{ParagraphNode, create_paragraph_node};
23use crate::schema::{
24    NodeSchema, NumberValueOptions, boolean_value, node_schema, number_value, optional,
25    schema_getter, schema_setter, with_accessors, with_field,
26};
27
28/// `ListItemNode`: an item of a [`ListNode`](super::ListNode). It holds
29/// inline content, or, to nest a list, only that list.
30#[derive(Clone, Debug)]
31pub struct ListItemNode {
32    base: NodeBase,
33    pub(super) element: ElementData,
34    pub(super) value: f64,
35    pub(super) checked: Option<bool>,
36}
37
38impl Default for ListItemNode {
39    /// `new ListItemNode()`: value 1, not a checkbox.
40    fn default() -> Self {
41        ListItemNode {
42            base: NodeBase::default(),
43            element: ElementData::default(),
44            value: 1.0,
45            checked: None,
46        }
47    }
48}
49
50/// `$createListItemNode(checked)`: `Some` makes it a checkbox, checked or
51/// not.
52pub fn create_list_item_node(checked: Option<bool>) -> NodeRef {
53    crate::lexical_utils::replaced(set_node_key(Box::new(ListItemNode {
54        checked,
55        ..ListItemNode::default()
56    })))
57}
58
59/// `$isListItemNode(node)`.
60pub fn is_list_item_node(node: &NodeRef) -> bool {
61    node.get_latest().is::<ListItemNode>()
62}
63
64fn with_item<R>(node: &NodeRef, f: impl FnOnce(&ListItemNode) -> R) -> Option<R> {
65    node.get_latest().downcast_ref::<ListItemNode>().map(f)
66}
67
68fn set_item(node: &NodeRef, f: impl FnOnce(&mut ListItemNode)) {
69    if is_list_item_node(node) {
70        with_writable(node.get_key(), |n| {
71            f(n.downcast_mut::<ListItemNode>().expect("a list item"))
72        });
73    }
74}
75
76impl NodeRef {
77    /// `ListItemNode.getValue()`; `None` for any other node.
78    pub fn get_list_item_value(&self) -> Option<f64> {
79        with_item(self, |i| i.value)
80    }
81
82    /// `ListItemNode.setValue(value)`. Does nothing to any other node.
83    pub fn set_list_item_value(&self, value: f64) {
84        set_item(self, |i| i.value = value);
85    }
86
87    /// `ListItemNode.getChecked()`: whether the item is checked when its
88    /// list is a check list, `None` otherwise (and for any other node).
89    pub fn get_checked(&self) -> Option<bool> {
90        let checked = with_item(self, |i| i.checked)?;
91        let list_type = self.get_parent().and_then(|p| p.get_list_type());
92        (list_type == Some(ListType::Check)).then_some(checked == Some(true))
93    }
94
95    /// `ListItemNode.setChecked(checked)`. Does nothing to any other node.
96    pub fn set_checked(&self, checked: Option<bool>) {
97        set_item(self, |i| i.checked = checked);
98    }
99
100    /// `ListItemNode.toggleChecked()`. Does nothing to any other node.
101    pub fn toggle_checked(&self) {
102        set_item(self, |i| i.checked = Some(i.checked != Some(true)));
103    }
104}
105
106/// `ListItemNode.getIndent()`: how deep the item is nested in lists, or its
107/// own `__indent` when it isn't attached.
108fn get_list_item_indent(this: &NodeRef, own: f64) -> Result<f64, LexicalError> {
109    // If we don't have a parent, we are likely serializing
110    let Some(parent) = this.get_parent() else {
111        return Ok(own);
112    };
113    if !this.is_attached() {
114        return Ok(own);
115    }
116    // ListItemNode should always have a ListNode for a parent.
117    let mut list_node_parent = parent.get_parent_or_throw()?;
118    let mut indent_level = 0.0;
119    while is_list_item_node(&list_node_parent) {
120        list_node_parent = list_node_parent
121            .get_parent_or_throw()?
122            .get_parent_or_throw()?;
123        indent_level += 1.0;
124    }
125    Ok(indent_level)
126}
127
128impl ListItemNode {
129    pub fn value(&self) -> f64 {
130        self.value
131    }
132
133    /// `__checked`, whatever the list's type.
134    pub fn checked(&self) -> Option<bool> {
135        self.checked
136    }
137
138    /// `getChecked()` and `getIndent()` for the export, which JS reads off
139    /// the tree. An item whose parent is the root can't have an indent
140    /// (`getParentOrThrow()` throws on the root), which JS's export throws
141    /// on too.
142    fn exported_checked_and_indent(&self) -> (Option<bool>, f64) {
143        let this = NodeRef::new(self.base.key.clone());
144        let checked = this.get_checked();
145        let indent =
146            get_list_item_indent(&this, self.element.indent).unwrap_or_else(|e| panic!("{e}"));
147        (checked, indent)
148    }
149
150    /// `ListItemNode.canMergeWith(node)`.
151    fn can_merge_with(node: &NodeRef) -> bool {
152        is_list_item_node(node) || node.get_latest().is::<ParagraphNode>()
153    }
154}
155
156/// `ListItemNode.INTERNAL_$liftsFromStructure(child, explicit)`: a nested
157/// list may only be all a list item holds; next to other content it is
158/// lifted out, the item split around it. In an update's normalization, only
159/// an item the update creates or changes itself is lifted (one that already
160/// held such a list keeps it through an edit elsewhere); the normalization of
161/// what code changed without transforms (`explicit`) lifts every such item.
162fn lifts_from_structure(
163    this: &NodeRef,
164    child: &NodeRef,
165    explicit: bool,
166) -> Result<bool, LexicalError> {
167    if !is_list_node(child) || this.get_children_size() <= 1 {
168        return Ok(false);
169    }
170    if explicit {
171        return Ok(true);
172    }
173    let Some(editor) = crate::updates::get_active_editor() else {
174        return Ok(true);
175    };
176    let committed = editor.get_editor_state();
177    // `editor._cloneNotNeeded.has(key)`: the node was made writable (or
178    // created) in this update.
179    let written_now =
180        this.get_latest().base().written_in == crate::updates::get_active_editor_state().0.id;
181    Ok(!committed.0.node_map.borrow().contains_key(this.get_key()) || written_now)
182}
183
184/// `$pointsAround(parent, items)`: for the selection's element points in
185/// `parent`, which holds the consecutive `items`, what puts each of them
186/// back once the items are moved into a list inserted in their place (a
187/// point before or after them stays so in `parent`; one between two of them
188/// goes to the end of the first).
189#[allow(clippy::type_complexity)]
190fn points_around(
191    parent: &NodeRef,
192    items: &[NodeRef],
193) -> Result<Option<Box<dyn FnOnce() -> Result<(), LexicalError>>>, LexicalError> {
194    let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
195        return Ok(None);
196    };
197    let parent_key = parent.get_key().to_owned();
198    let first = items[0].get_index_within_parent().unwrap_or(0);
199    let saved: Vec<(Which, usize)> = [Which::Anchor, Which::Focus]
200        .into_iter()
201        .filter_map(|which| {
202            let point = selection.point(which).expect("a range selection");
203            (point.point_type == PointType::Element && point.key == parent_key)
204                .then_some((which, point.offset))
205        })
206        .collect();
207    if saved.is_empty() {
208        return Ok(None);
209    }
210    let items = items.to_vec();
211    Ok(Some(Box::new(move || {
212        for (which, offset) in saved {
213            if offset <= first {
214                selection.point_set(which, &parent_key, offset, PointType::Element)?;
215            } else if offset < first + items.len() {
216                let item = &items[offset - first - 1];
217                selection.point_set(
218                    which,
219                    item.get_key(),
220                    item.get_children_size(),
221                    PointType::Element,
222                )?;
223            } else {
224                selection.point_set(
225                    which,
226                    &parent_key,
227                    offset - items.len() + 1,
228                    PointType::Element,
229                )?;
230            }
231        }
232        Ok(())
233    })))
234}
235
236thread_local! {
237    static LIST_ITEM_NODE_SCHEMA: NodeSchema =
238        build_list_item_node_schema().expect("ListItemNode's schema");
239}
240
241/// `MAX_LIST_ITEM_INDENT`: the deepest list nesting `setIndent` walks to.
242const MAX_LIST_ITEM_INDENT: f64 = 128.0;
243
244/// `listItemNodeSchema`: `checked`, read with `getChecked` (from the
245/// parent list's type) and written to the field; `indent`, ElementNode's
246/// bounded and clamped, read with `getIndent` (from the nesting) and
247/// derived; `value`, derived. JS applies `indent` with `setIndent`, which
248/// on the new node `importJSON` gives it (no parent) changes nothing, so
249/// the item keeps its own.
250pub fn list_item_node_schema() -> NodeSchema {
251    LIST_ITEM_NODE_SCHEMA.with(Clone::clone)
252}
253
254fn build_list_item_node_schema() -> Result<NodeSchema, LexicalError> {
255    node_schema(vec![
256        (
257            "checked",
258            with_accessors(
259                optional(boolean_value(false), false)?,
260                Some(schema_getter(|n: &ListItemNode| {
261                    n.exported_checked_and_indent()
262                        .0
263                        .map_or(Value::Undefined, Value::from)
264                })),
265                Some(schema_setter(|n: &mut ListItemNode, value| {
266                    n.checked = value.as_bool();
267                })),
268            )?,
269        ),
270        (
271            "indent",
272            with_accessors(
273                number_value(
274                    0.0,
275                    NumberValueOptions {
276                        clamp: true,
277                        integer: true,
278                        max: Some(MAX_LIST_ITEM_INDENT),
279                        min: Some(0.0),
280                    },
281                )?,
282                Some(schema_getter(|n: &ListItemNode| {
283                    n.exported_checked_and_indent().1.into()
284                })),
285                Some(schema_setter(|_: &mut ListItemNode, _| {})),
286            )?
287            .derived(),
288        ),
289        (
290            "value",
291            with_field(
292                number_value(1.0, NumberValueOptions::default())?,
293                |n: &ListItemNode| &n.value,
294                |n: &mut ListItemNode| &mut n.value,
295            )?
296            .derived(),
297        ),
298    ])
299}
300
301impl LexicalNode for ListItemNode {
302    fn json_schema_chain(&self) -> Vec<NodeSchema> {
303        vec![
304            list_item_node_schema(),
305            crate::nodes::element::element_node_schema(),
306        ]
307    }
308    /// The `$config()` of `ListItemNode`: `children: ['inline', ListNode]`,
309    /// and its schema's derived `indent` and `value`.
310    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
311        use crate::structure::{
312            NodeChildEntry, NodeChildrenConfig, NodeClassRef, NodeConfigLink, StaticNodeConfig,
313        };
314        vec![NodeConfigLink::new(
315            "listitem",
316            StaticNodeConfig {
317                children: Some(NodeChildrenConfig::List(vec![
318                    NodeChildEntry::Inline,
319                    NodeChildEntry::Class(NodeClassRef::of::<super::ListNode>()),
320                ])),
321                ..StaticNodeConfig::default()
322            },
323        )]
324    }
325
326    fn get_type(&self) -> &'static str {
327        "listitem"
328    }
329    #[cfg(feature = "html")]
330    fn create_dom(
331        &self,
332        this: &NodeRef,
333        config: &crate::EditorConfig,
334        _editor: &crate::Editor,
335    ) -> Result<crate::dom::DomNode, LexicalError> {
336        list_item_dom::create_dom(self, this, config)
337    }
338    #[cfg(feature = "html")]
339    fn export_dom(
340        &self,
341        this: &NodeRef,
342        editor: &crate::Editor,
343    ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
344        list_item_dom::export_dom(self, this, editor)
345    }
346    #[cfg(feature = "html")]
347    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
348        Some(list_item_dom::import_dom())
349    }
350    fn base(&self) -> &NodeBase {
351        &self.base
352    }
353    fn base_mut(&mut self) -> &mut NodeBase {
354        &mut self.base
355    }
356    fn element(&self) -> Option<&ElementData> {
357        Some(&self.element)
358    }
359    fn element_mut(&mut self) -> Option<&mut ElementData> {
360        Some(&mut self.element)
361    }
362
363    /// `ListItemNode.isParentRequired()`.
364    fn is_parent_required(&self) -> bool {
365        true
366    }
367
368    /// `ListItemNode.createParentElementNode()`: a bullet list.
369    fn create_parent_element_node(&self) -> NodeRef {
370        create_list_node(ListType::Bullet, 1.0)
371    }
372
373    /// `ListItemNode.canMergeWhenEmpty()`.
374    fn can_merge_when_empty(&self) -> bool {
375        true
376    }
377
378    /// `ListItemNode.extractWithChild(child, selection)`: an item goes with
379    /// a child of a range selection inside it that covers all of its text
380    /// (compared by UTF-16 length, as JS does).
381    fn extract_with_child(
382        &self,
383        this: &NodeRef,
384        _: &NodeRef,
385        selection: Option<&SelectionRef>,
386        _: &str,
387    ) -> Result<bool, LexicalError> {
388        let Some(selection) = selection.filter(|s| s.is_range()) else {
389            return Ok(false);
390        };
391        let range = selection.range().expect("a range selection");
392        let anchor_node = range.anchor.get_node()?;
393        let focus_node = range.focus.get_node()?;
394        Ok(this.is_parent_of(&anchor_node)
395            && this.is_parent_of(&focus_node)
396            && crate::utf16::len(&this.get_text_content())
397                == crate::utf16::len(&selection.get_text_content()?))
398    }
399
400    /// `exportListItemNode` and `exportCompactListItemNode`.
401    fn generated_export_json(&self, compact: bool) -> Option<Object> {
402        let (checked, indent) = self.exported_checked_and_indent();
403        Some(if compact {
404            export_compact_list_item_node(self, checked, indent)
405        } else {
406            export_list_item_node(self, checked, indent)
407        })
408    }
409
410    /// `updateListItemNode`.
411    fn generated_update_from_json(&mut self, json: &Object) -> bool {
412        update_list_item_node(self, json);
413        true
414    }
415
416    /// `ListItemNode.append(...nodes)`: a list item or paragraph appended
417    /// gives its children instead (`canMergeWith`), and is removed.
418    fn append(&self, this: &NodeRef, nodes: &[NodeRef]) -> Result<(), LexicalError> {
419        for node in nodes {
420            if node.is_element() && Self::can_merge_with(node) {
421                let children = node.get_children();
422                this.append(&children)?;
423                node.remove(false)?;
424            } else {
425                // `super.append(node)`.
426                this.splice(this.get_children_size(), 0, std::slice::from_ref(node))?;
427            }
428        }
429        Ok(())
430    }
431
432    /// `ListItemNode.replace(replaceWithNode, includeChildren)`: replaced by
433    /// anything but a list item, the item is outdented and the node goes
434    /// beside its list, splitting it if the item is in the middle.
435    fn replace(
436        &self,
437        this: &NodeRef,
438        replace_with: &NodeRef,
439        include_children: bool,
440    ) -> Result<NodeRef, LexicalError> {
441        if is_list_item_node(replace_with) {
442            return node::replace(this, replace_with, false);
443        }
444        this.set_indent(0.0)?;
445        let list = this.get_parent_or_throw()?;
446        if !is_list_node(&list) {
447            return Ok(replace_with.clone());
448        }
449        if list.get_first_child().as_ref() == Some(this) {
450            list.insert_before(replace_with, true)?;
451        } else if list.get_last_child().as_ref() == Some(this) {
452            list.insert_after(replace_with, true)?;
453        } else {
454            // Split the list
455            let new_list = copy_node(&list);
456            let mut next_sibling = this.get_next_sibling();
457            while let Some(node_to_append) = next_sibling {
458                next_sibling = node_to_append.get_next_sibling();
459                new_list.append(std::slice::from_ref(&node_to_append))?;
460            }
461            list.insert_after(replace_with, true)?;
462            replace_with.insert_after(&new_list, true)?;
463        }
464        let to_replace_key = this.get_key().to_owned();
465        let mut prev_size_before_children_transfer = 0;
466        if include_children {
467            invariant!(
468                replace_with.is_element(),
469                "includeChildren should only be true for ElementNodes"
470            );
471            prev_size_before_children_transfer = replace_with.get_children_size();
472            replace_with.splice(prev_size_before_children_transfer, 0, &this.get_children())?;
473        }
474        // The base LexicalNode.replace remaps element-anchored selection
475        // points from the replaced node to the replacement, but this
476        // override skips super and the trailing this.remove() would
477        // otherwise drop selection onto a sibling list item via
478        // moveSelectionPointToSibling. Mirror the base behavior here for
479        // the element-anchored case.
480        if include_children
481            && replace_with.is_element()
482            && let Some(selection) = get_selection().filter(SelectionRef::is_range)
483        {
484            for which in [Which::Anchor, Which::Focus] {
485                let point = selection.point(which).expect("a range selection");
486                if point.key == to_replace_key && point.point_type == PointType::Element {
487                    selection.point_set(
488                        which,
489                        replace_with.get_key(),
490                        prev_size_before_children_transfer + point.offset,
491                        PointType::Element,
492                    )?;
493                }
494            }
495        }
496        this.remove(false)?;
497        if list.get_children_size() == 0 {
498            list.remove(false)?;
499        }
500        Ok(replace_with.clone())
501    }
502
503    /// `ListItemNode.insertAfter(node, restoreSelection)`: anything but a
504    /// list item goes after the list, which splits around it.
505    fn insert_after(
506        &self,
507        this: &NodeRef,
508        node: &NodeRef,
509        restore_selection: bool,
510    ) -> Result<NodeRef, LexicalError> {
511        let list_node = this.get_parent_or_throw()?;
512        invariant!(
513            is_list_node(&list_node),
514            "insertAfter: list node is not parent of list item node"
515        );
516        if is_list_item_node(node) {
517            return node::insert_after(this, node, restore_selection);
518        }
519        let siblings = this.get_next_siblings();
520        // Split the lists and insert the node in between them
521        list_node.insert_after(node, restore_selection)?;
522        if let Some(first_sibling) = siblings.first() {
523            let new_list_node = copy_node(&list_node);
524            // $copyNode carries the original list's start, which would
525            // restart the numbering at the split. The items moving into the
526            // new list keep the numbers they were already rendered with, so
527            // the new list has to start from the first of them (see issue
528            // #7032).
529            if new_list_node.get_list_type() == Some(ListType::Number)
530                && is_list_item_node(first_sibling)
531            {
532                new_list_node.set_list_start(get_new_list_start(&list_node, first_sibling));
533            }
534            for sibling in &siblings {
535                new_list_node.append(std::slice::from_ref(sibling))?;
536            }
537            node.insert_after(&new_list_node, restore_selection)?;
538        }
539        Ok(node.clone())
540    }
541
542    /// `ListItemNode.remove(preserveEmptyParent)`: the nested lists on
543    /// either side, if of the same type, are joined.
544    fn remove(&self, this: &NodeRef, preserve_empty_parent: bool) -> Result<(), LexicalError> {
545        let prev_sibling = this.get_previous_sibling();
546        let next_sibling = this.get_next_sibling();
547        node::remove(this, preserve_empty_parent)?;
548        if let (Some(prev), Some(next)) = (prev_sibling, next_sibling)
549            && is_nested_list_node(&prev)
550            && is_nested_list_node(&next)
551        {
552            let prev_list = prev.get_first_child().expect("a nested list");
553            let next_list = next.get_first_child().expect("a nested list");
554            // Only join the surrounding sublists when they are the same kind
555            // of list, otherwise the second one loses its listType.
556            if prev_list.get_list_type() == next_list.get_list_type() {
557                merge_lists(&prev_list, &next_list)?;
558                next.remove(false)?;
559            }
560        }
561        Ok(())
562    }
563
564    /// `ListItemNode.resetOnCopyNodeFrom(original)`: a copy of a checked
565    /// item is unchecked.
566    fn reset_on_copy_node_from(&self, this: &NodeRef, original: &NodeRef) {
567        if original.get_checked() == Some(true) {
568            this.set_checked(Some(false));
569        }
570    }
571
572    /// `ListItemNode.insertNewAfter(selection, restoreSelection)`: a copy of
573    /// the item after it.
574    fn insert_new_after(
575        &self,
576        this: &NodeRef,
577        _: &SelectionRef,
578        restore_selection: bool,
579    ) -> Result<Option<NodeRef>, LexicalError> {
580        let new_element = copy_node(this);
581        this.insert_after(&new_element, restore_selection)?;
582        Ok(Some(new_element))
583    }
584
585    /// `ListItemNode.collapseAtStart(selection)`: a nested item outdents;
586    /// otherwise the item becomes a paragraph after its list, which splits.
587    fn collapse_at_start(&self, this: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
588        if is_nested_list_node(this) {
589            return Ok(false);
590        }
591        let list_node = this.get_parent_or_throw()?;
592        let list_node_parent = list_node.get_parent_or_throw()?;
593        if is_list_item_node(&list_node_parent) {
594            handle_outdent(this)?;
595            return Ok(true);
596        }
597        let paragraph = create_paragraph_node();
598        paragraph.append(&this.get_children())?;
599        let next_siblings = this.get_next_siblings();
600        if !next_siblings.is_empty() {
601            let new_list = copy_node(&list_node);
602            new_list.append(&next_siblings)?;
603            list_node.insert_after(&new_list, true)?;
604        }
605        list_node.insert_after(&paragraph, true)?;
606        this.remove(false)?;
607        if list_node.get_children_size() == 0 {
608            list_node.remove(false)?;
609        }
610        paragraph.select_start()?;
611        Ok(true)
612    }
613
614    /// `ListItemNode.getIndent()`.
615    fn get_indent(&self, this: &NodeRef) -> Result<f64, LexicalError> {
616        get_list_item_indent(this, self.element.indent)
617    }
618
619    /// `ListItemNode.setIndent(indent)`: nests or unwraps the item in lists
620    /// one level at a time until it is `indent` deep.
621    fn set_indent(&self, this: &NodeRef, indent: f64) -> Result<(), LexicalError> {
622        let indent = indent.floor();
623        // `indent >= 0`, which NaN fails.
624        invariant!(
625            indent.partial_cmp(&0.0).is_some_and(|o| o.is_ge()),
626            "Indent value must be non-negative."
627        );
628        let target = indent;
629        let mut current_indent = this.get_indent()?;
630        while current_indent != target {
631            if current_indent < target {
632                handle_indent(this)?;
633                current_indent += 1.0;
634            } else {
635                handle_outdent(this)?;
636                current_indent -= 1.0;
637            }
638        }
639        Ok(())
640    }
641
642    /// `ListItemNode.INTERNAL_$liftsFromStructure(child, explicit)`.
643    fn internal_lifts_from_structure(&self) -> Option<crate::structure::LiftsFromStructure> {
644        Some(lifts_from_structure)
645    }
646
647    /// The `$transform` of `ListItemNode.$config()`: an item outside a list
648    /// is wrapped, with the items beside it, in the list
649    /// `createParentElementNode` makes, lifted out of blocks to the nearest
650    /// root. Where `NodeStructureExtension` enforces declared structure, it
651    /// lifts the new list itself, and the selection's element points in the
652    /// parent move with the items (`$pointsAround`).
653    fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
654        let Some(parent) = this.get_parent() else {
655            return Ok(());
656        };
657        if is_list_node(&parent) {
658            if parent.get_list_type() != Some(ListType::Check) && this.get_checked().is_some() {
659                this.set_checked(None);
660            }
661            return Ok(());
662        }
663        let new_parent = this.create_parent_element_node();
664        invariant!(
665            is_list_node(&new_parent),
666            "ListItemNode.createParentElementNode() must return a ListNode"
667        );
668        // Insert an empty ListNode at the orphan's position, splitting any
669        // enclosing non-shadow-root blocks so the ListNode lifts to a valid
670        // container before we move the orphan in. The ListNode $transform
671        // merges adjacent same-type lists, so neighbouring orphans will
672        // coalesce once their own transforms run.
673        let mut children = vec![this.clone()];
674        for next in [false, true] {
675            children.reverse();
676            let mut sibling = if next {
677                this.get_next_sibling()
678            } else {
679                this.get_previous_sibling()
680            };
681            while let Some(origin) = sibling.filter(is_list_item_node) {
682                sibling = if next {
683                    origin.get_next_sibling()
684                } else {
685                    origin.get_previous_sibling()
686                };
687                children.push(origin);
688            }
689        }
690        let enforced = crate::structure::is_structure_enforced_on_active_editor();
691        let points = if enforced {
692            points_around(&parent, &children)?
693        } else {
694            None
695        };
696        this.insert_before(&new_parent, true)?;
697        new_parent.splice(0, 0, &children)?;
698        if let Some(points) = points {
699            points()?;
700        }
701        if enforced {
702            // The ancestors' own transforms run on the result (a list that
703            // holds the parent renumbers its items), as after a repair of
704            // the normalization.
705            let mut n = Some(parent.clone());
706            while let Some(current) = n.filter(|n| !is_root_or_shadow_root(&*n.get_latest())) {
707                current.mark_dirty();
708                n = current.get_parent();
709            }
710        }
711        if !is_root_or_shadow_root(&*parent.get_latest()) && !enforced {
712            insert_node_to_nearest_root_at_caret(
713                &new_parent,
714                &rewind_sibling_caret(&get_sibling_caret(&new_parent, CaretDirection::Next))?,
715                &SplitAtPointCaretNextOptions {
716                    should_split: |_, _| false,
717                    remove_empty_destination: true,
718                    ..SplitAtPointCaretNextOptions::default()
719                },
720            )?;
721            if parent.is_empty() && parent.is_attached() {
722                parent.remove(false)?;
723            }
724        }
725        Ok(())
726    }
727}
728
729// The DOM side of `ListItemNode` (the `html` feature).
730
731#[cfg(feature = "html")]
732pub(super) mod list_item_dom {
733    use super::super::list_node::{ListType, is_list_node};
734    use super::super::utils::is_nested_list_node;
735    use super::{ListItemNode, create_list_item_node};
736    use crate::dom::DomNode;
737    use crate::json::{Object, Value};
738    use crate::lexical_dom::{
739        DomConversionNode, DomConversionOutput, DomExportOutput, get_document,
740        normalize_class_names, set_direction_from_dom, set_format_from_dom,
741    };
742    use crate::node::NodeRef;
743    use crate::nodes::paragraph::ParagraphNode;
744    use crate::set_dom_style::{get_style_object_from_css, set_dom_style_from_css};
745    use crate::{EditorConfig, LexicalError};
746
747    /// `ListItemNode.createDOM(config)`: an `<li>`, through
748    /// `updateListItemDOM(null, element, config)`.
749    pub(crate) fn create_dom(
750        node: &ListItemNode,
751        this: &NodeRef,
752        config: &EditorConfig,
753    ) -> Result<DomNode, LexicalError> {
754        let dom = get_document().create_element("li");
755        update_list_item_checked(&dom, node, this);
756        // `dom.value = this.__value`: a `long`, written as its attribute.
757        dom.set_attribute(
758            "value",
759            &crate::nodes::text::to_int32(node.value).to_string(),
760        );
761        set_list_item_theme_class_names(&dom, &config.theme, node, this);
762        let style = node.element.get_style();
763        if !style.is_empty() {
764            set_dom_style_from_css(&dom.style(), style, "");
765        }
766        apply_marker_styles(&dom, node);
767        Ok(dom)
768    }
769
770    /// `applyMarkerStyles(dom, node, null)`: the text style as
771    /// `--listitem-marker-*` properties.
772    fn apply_marker_styles(dom: &DomNode, node: &ListItemNode) {
773        let style = dom.style();
774        for (k, v) in get_style_object_from_css(node.element.get_text_style()).iter() {
775            style.set_property(&format!("--listitem-marker-{k}"), v, "");
776        }
777    }
778
779    /// `ListItemNode.exportDOM(editor)`: `createDOM`'s element with the
780    /// alignment and the direction. A nested list's item moves its
781    /// children into the item before it.
782    pub(crate) fn export_dom(
783        node: &ListItemNode,
784        this: &NodeRef,
785        editor: &crate::Editor,
786    ) -> Result<DomExportOutput, LexicalError> {
787        let element = create_dom(node, this, editor.config())?;
788        let format_type = node.element.get_format_type();
789        if !format_type.is_empty() {
790            element.style().set_property("text-align", format_type, "");
791        }
792        if let Some(direction) = node.element.get_direction() {
793            element.set_dir(direction.as_str());
794        }
795        if is_nested_list_node(this) {
796            return Ok(DomExportOutput {
797                element: Some(element),
798                after: Some(Box::new(|container: &DomNode| {
799                    if container.is_element()
800                        && let Some(prev_sibling) = container.previous_element_sibling()
801                        && prev_sibling.node_name() == "LI"
802                    {
803                        while let Some(child) = container.first_child() {
804                            prev_sibling.append_child(&child);
805                        }
806                        container.remove();
807                    }
808                    Ok(Some(container.clone()))
809                })),
810                ..DomExportOutput::default()
811            });
812        }
813        Ok(DomExportOutput::element(element))
814    }
815
816    fn class_names_of(value: Option<&Value>) -> Vec<String> {
817        value
818            .and_then(Value::as_str)
819            .map(|v| normalize_class_names(&[v]))
820            .unwrap_or_default()
821    }
822
823    /// `$setListItemThemeClassNames(dom, editorThemeClasses, node)`.
824    fn set_list_item_theme_class_names(
825        dom: &DomNode,
826        theme: &Object,
827        node: &ListItemNode,
828        this: &NodeRef,
829    ) {
830        let Some(list_theme) = theme.get("list").filter(|t| {
831            !matches!(t, Value::Undefined | Value::Null | Value::Bool(false))
832                && t.as_str() != Some("")
833        }) else {
834            return;
835        };
836        let list_item_class_name = list_theme.get("listitem");
837        let nested_list_item_class_name = list_theme.get("nested").and_then(|n| n.get("listitem"));
838        let parent = this.get_parent();
839        let is_check_list = parent
840            .as_ref()
841            .is_some_and(|p| p.get_list_type() == Some(ListType::Check));
842        let checked = node.checked == Some(true);
843        let is_nested = this.get_children().iter().any(is_list_node);
844        let mut classes_to_remove = class_names_of(list_theme.get("listitemChecked"));
845        classes_to_remove.extend(class_names_of(list_theme.get("listitemUnchecked")));
846        classes_to_remove.extend(class_names_of(nested_list_item_class_name));
847        if !classes_to_remove.is_empty() {
848            dom.class_list().remove(&classes_to_remove);
849        }
850        let mut classes_to_add = class_names_of(list_item_class_name);
851        if is_check_list {
852            let key = if checked {
853                "listitemChecked"
854            } else {
855                "listitemUnchecked"
856            };
857            classes_to_add.extend(class_names_of(list_theme.get(key)));
858        }
859        if is_nested {
860            classes_to_add.extend(class_names_of(nested_list_item_class_name));
861        }
862        if !classes_to_add.is_empty() {
863            dom.class_list().add(&classes_to_add);
864        }
865    }
866
867    /// `updateListItemChecked(dom, listItemNode, null)`: a leaf item of a
868    /// check list is a checkbox.
869    fn update_list_item_checked(dom: &DomNode, node: &ListItemNode, this: &NodeRef) {
870        let is_checkbox = this
871            .get_parent()
872            .is_some_and(|p| p.get_list_type() == Some(ListType::Check))
873            && !this.get_first_child().is_some_and(|c| is_list_node(&c));
874        if !is_checkbox {
875            dom.remove_attribute("role");
876            dom.remove_attribute("tabIndex");
877            dom.remove_attribute("aria-checked");
878        } else {
879            dom.set_attribute("role", "checkbox");
880            dom.set_attribute("tabIndex", "-1");
881            dom.set_attribute(
882                "aria-checked",
883                if node.checked == Some(true) {
884                    "true"
885                } else {
886                    "false"
887                },
888            );
889        }
890    }
891
892    /// `ListItemNode`'s `importDOM`: `<li>`.
893    pub(crate) fn import_dom() -> crate::lexical_dom::DomConversionMap {
894        vec![(
895            "li".to_owned(),
896            crate::lexical_dom::importer(0, convert_list_item_element),
897        )]
898    }
899
900    /// `$convertListItemElement(domNode)`: a list item, checked or not for
901    /// a GitHub or Joplin task item or an `aria-checked` one.
902    fn convert_list_item_element(
903        dom_node: &DomNode,
904    ) -> Result<Option<DomConversionOutput>, LexicalError> {
905        if dom_node.class_list().contains("task-list-item") {
906            for child in dom_node.children() {
907                if child.tag_name() == "INPUT" {
908                    return convert_checkbox_input(&child);
909                }
910            }
911        }
912        if dom_node.class_list().contains("joplin-checkbox") {
913            for child in dom_node.children() {
914                let grandchildren = child.children();
915                if child.class_list().contains("checkbox-wrapper")
916                    && grandchildren
917                        .first()
918                        .is_some_and(|c| c.tag_name() == "INPUT")
919                {
920                    return convert_checkbox_input(&grandchildren[0]);
921                }
922            }
923        }
924        let checked = match dom_node.get_attribute("aria-checked").as_deref() {
925            Some("true") => Some(true),
926            Some("false") => Some(false),
927            _ => None,
928        };
929        let node = create_list_item_node(checked);
930        set_format_from_dom(&node, dom_node);
931        set_direction_from_dom(&node, dom_node);
932        Ok(Some(with_format_from_children(node)))
933    }
934
935    /// `$convertCheckboxInput(domNode)`.
936    fn convert_checkbox_input(
937        dom_node: &DomNode,
938    ) -> Result<Option<DomConversionOutput>, LexicalError> {
939        if dom_node.get_attribute("type").as_deref() != Some("checkbox") {
940            return Ok(Some(DomConversionOutput::node(None)));
941        }
942        let node = create_list_item_node(Some(dom_node.has_attribute("checked")));
943        Ok(Some(with_format_from_children(node)))
944    }
945
946    /// `{after: setFormatFromChildren.bind(null, node), node}`: an item
947    /// whose one child is an aligned paragraph (as Google Docs writes)
948    /// takes the paragraph's alignment and its children.
949    fn with_format_from_children(node: NodeRef) -> DomConversionOutput {
950        let list_item_node = node.clone();
951        DomConversionOutput {
952            node: DomConversionNode::One(node),
953            after: Some(Box::new(move |children: Vec<NodeRef>| {
954                if let [first_child] = children.as_slice()
955                    && first_child.get_latest().is::<ParagraphNode>()
956                    && list_item_node.element_data().get_format_type().is_empty()
957                {
958                    let format_type = first_child.element_data().get_format_type();
959                    if !format_type.is_empty() {
960                        list_item_node.set_element_format(format_type);
961                        return Ok(first_child.get_children());
962                    }
963                }
964                Ok(children)
965            })),
966            ..DomConversionOutput::default()
967        }
968    }
969}