lexical-ui 0.1.2

A Rust port of Lexical's model and headless packages, at parity with the JS implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! `LexicalListNode.ts`: `ListNode`, `$createListNode` and `$isListNode`.

use super::format_list::{
    merge_nested_lists_at_seam, merge_next_sibling_list_if_same_type,
    update_children_list_item_value,
};
use super::generated_json::{export_compact_list_node, export_list_node, update_list_node};
use super::list_item_node::{create_list_item_node, is_list_item_node};
use crate::LexicalError;
use crate::json::Object;
use crate::lexical_utils::{set_node_key, with_writable};
use crate::node::{LexicalNode, NodeBase, NodeRef};
use crate::nodes::element::{self, ElementData};
use crate::schema::{
    NodeSchema, NumberValueOptions, aliased_value, enum_value, node_schema, number_value,
    schema_getter, schema_setter, with_accessors, with_field,
};

/// `ListType`: `'number'`, `'bullet'` or `'check'`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ListType {
    #[default]
    Number,
    Bullet,
    Check,
}

impl ListType {
    pub fn as_str(self) -> &'static str {
        match self {
            ListType::Number => "number",
            ListType::Bullet => "bullet",
            ListType::Check => "check",
        }
    }

    /// The list type a string names (`enumValue(['number', 'bullet',
    /// 'check'])`).
    pub fn parse(list_type: &str) -> Option<Self> {
        Some(match list_type {
            "number" => ListType::Number,
            "bullet" => ListType::Bullet,
            "check" => ListType::Check,
            _ => return None,
        })
    }

    /// `ListNodeTagType`: the tag a list of this type has, `ol` for
    /// `number` and `ul` otherwise (`setListType`).
    pub fn tag(self) -> &'static str {
        match self {
            ListType::Number => "ol",
            _ => "ul",
        }
    }
}

/// `ListNode`: an ordered (`number`), unordered (`bullet`) or check list,
/// whose children are [`ListItemNode`](super::ListItemNode)s.
///
/// JS stores the tag (`__tag`) beside the list type, and sets both together
/// wherever either changes; here the tag is read off the list type.
#[derive(Clone, Debug)]
pub struct ListNode {
    base: NodeBase,
    pub(super) element: ElementData,
    pub(super) list_type: ListType,
    pub(super) start: f64,
}

impl Default for ListNode {
    /// `new ListNode()`: a `number` list starting at 1.
    fn default() -> Self {
        ListNode {
            base: NodeBase::default(),
            element: ElementData::default(),
            list_type: ListType::Number,
            start: 1.0,
        }
    }
}

/// `$createListNode(listType = 'number', start = 1)`.
pub fn create_list_node(list_type: ListType, start: f64) -> NodeRef {
    crate::lexical_utils::replaced(set_node_key(Box::new(ListNode {
        list_type,
        start,
        ..ListNode::default()
    })))
}

/// `$isListNode(node)`.
pub fn is_list_node(node: &NodeRef) -> bool {
    node.get_latest().is::<ListNode>()
}

impl NodeRef {
    /// `ListNode.getListType()`; `None` for any other node.
    pub fn get_list_type(&self) -> Option<ListType> {
        self.get_latest()
            .downcast_ref::<ListNode>()
            .map(|l| l.list_type)
    }

    /// `ListNode.setListType(type)`. Does nothing to any other node.
    pub fn set_list_type(&self, list_type: ListType) {
        if is_list_node(self) {
            with_writable(self.get_key(), |n| {
                n.downcast_mut::<ListNode>().expect("a list").list_type = list_type;
            });
        }
    }

    /// `ListNode.getTag()`; `None` for any other node.
    pub fn get_list_tag(&self) -> Option<&'static str> {
        self.get_list_type().map(ListType::tag)
    }

    /// `ListNode.getStart()`; `None` for any other node.
    pub fn get_list_start(&self) -> Option<f64> {
        self.get_latest()
            .downcast_ref::<ListNode>()
            .map(|l| l.start)
    }

    /// `ListNode.setStart(start)`. Does nothing to any other node.
    pub fn set_list_start(&self, start: f64) {
        if is_list_node(self) {
            with_writable(self.get_key(), |n| {
                n.downcast_mut::<ListNode>().expect("a list").start = start;
            });
        }
    }
}

impl ListNode {
    pub fn list_type(&self) -> ListType {
        self.list_type
    }

    pub fn start(&self) -> f64 {
        self.start
    }
}

thread_local! {
    static LIST_NODE_SCHEMA: NodeSchema = build_list_node_schema().expect("ListNode's schema");
}

/// `listNodeSchema`: `listType` (with the legacy tags `ol` and `ul` as the
/// types they stand for), applied with `setListType`, which also keeps the
/// tag; `start`; and `tag`, written and derived on import.
pub fn list_node_schema() -> NodeSchema {
    LIST_NODE_SCHEMA.with(Clone::clone)
}

fn build_list_node_schema() -> Result<NodeSchema, LexicalError> {
    node_schema(vec![
        (
            "listType",
            with_accessors(
                aliased_value(
                    enum_value(vec!["number".into(), "bullet".into(), "check".into()], None)?,
                    vec![
                        ("ol".to_owned(), "number".into()),
                        ("ul".to_owned(), "bullet".into()),
                    ],
                )?,
                Some(schema_getter(|n: &ListNode| n.list_type.as_str().into())),
                Some(schema_setter(|n: &mut ListNode, value| {
                    n.list_type = value.as_str().and_then(ListType::parse).unwrap_or_default();
                })),
            )?,
        ),
        (
            "start",
            with_field(
                number_value(1.0, NumberValueOptions::default())?,
                |n: &ListNode| &n.start,
                |n: &mut ListNode| &mut n.start,
            )?,
        ),
        (
            "tag",
            with_accessors(
                enum_value(vec!["ul".into(), "ol".into()], None)?,
                Some(schema_getter(|n: &ListNode| n.list_type.tag().into())),
                None,
            )?,
        ),
    ])
}

impl LexicalNode for ListNode {
    fn json_schema_chain(&self) -> Vec<NodeSchema> {
        vec![list_node_schema(), element::element_node_schema()]
    }
    /// The `$config()` of `ListNode`: `children: [ListItemNode]` and
    /// `mergeAdjacent: {by: ['listType']}`, what
    /// `mergeNextSiblingListIfSameType` compares (`start` is not).
    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
        use crate::structure::{
            MergeAdjacentDeclaration, MergeAdjacentEntry, NodeChildEntry, NodeChildrenConfig,
            NodeClassRef, NodeConfigLink, StaticNodeConfig,
        };
        vec![NodeConfigLink::new(
            "list",
            StaticNodeConfig {
                children: Some(NodeChildrenConfig::List(vec![NodeChildEntry::Class(
                    NodeClassRef::of::<super::ListItemNode>(),
                )])),
                merge_adjacent: Some(MergeAdjacentDeclaration::By(vec![
                    MergeAdjacentEntry::Field("listType"),
                ])),
                ..StaticNodeConfig::default()
            },
        )]
    }
    /// `ListNode.updateDOM(prevNode)`: a list of another tag or type is
    /// made again (the tag follows the type here).
    fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
        prev_node
            .downcast_ref::<ListNode>()
            .is_some_and(|prev| prev.list_type != self.list_type)
    }
    fn get_type(&self) -> &'static str {
        "list"
    }
    #[cfg(feature = "html")]
    fn create_dom(
        &self,
        this: &NodeRef,
        config: &crate::EditorConfig,
        _editor: &crate::Editor,
    ) -> Result<crate::dom::DomNode, LexicalError> {
        list_dom::create_dom(self, this, config)
    }
    #[cfg(feature = "html")]
    fn export_dom(
        &self,
        this: &NodeRef,
        editor: &crate::Editor,
    ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
        list_dom::export_dom(self, this, editor)
    }
    #[cfg(feature = "html")]
    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
        Some(list_dom::import_dom())
    }
    fn base(&self) -> &NodeBase {
        &self.base
    }
    fn base_mut(&mut self) -> &mut NodeBase {
        &mut self.base
    }
    fn element(&self) -> Option<&ElementData> {
        Some(&self.element)
    }
    fn element_mut(&mut self) -> Option<&mut ElementData> {
        Some(&mut self.element)
    }

    /// `ListNode.canBeEmpty()`.
    fn can_be_empty(&self) -> bool {
        false
    }

    /// `ListNode.extractWithChild(child)`: a list goes with a list item
    /// that is copied.
    fn extract_with_child(
        &self,
        _: &NodeRef,
        child: &NodeRef,
        _: Option<&crate::lexical_selection::SelectionRef>,
        _: &str,
    ) -> Result<bool, LexicalError> {
        Ok(is_list_item_node(child))
    }

    /// `ListNode.canIndent()`.
    fn can_indent(&self) -> bool {
        false
    }

    /// `exportListNode` and `exportCompactListNode`.
    fn generated_export_json(&self, compact: bool) -> Option<Object> {
        Some(if compact {
            export_compact_list_node(self)
        } else {
            export_list_node(self)
        })
    }

    /// `updateListNode`.
    fn generated_update_from_json(&mut self, json: &Object) -> bool {
        update_list_node(self, json);
        true
    }

    /// `ListNode.splice(start, deleteCount, nodesToInsert)`: what isn't a
    /// list item is wrapped in one (`createListItemNode()`), a block by its
    /// children.
    fn splice(
        &self,
        this: &NodeRef,
        start: usize,
        delete_count: usize,
        nodes_to_insert: &[NodeRef],
    ) -> Result<(), LexicalError> {
        let mut list_item_nodes_to_insert = Vec::with_capacity(nodes_to_insert.len());
        for node in nodes_to_insert {
            if is_list_item_node(node) {
                list_item_nodes_to_insert.push(node.clone());
                continue;
            }
            let list_item = create_list_item_node(None);
            if node.is_element() && !(is_list_node(node) || node.is_inline()) {
                // A block can't stay a block inside a list item, so it is
                // unwrapped into its own children.
                list_item.append(&node.get_children())?;
            } else {
                list_item.append(std::slice::from_ref(node))?;
            }
            list_item_nodes_to_insert.push(list_item);
        }
        element::splice(this, start, delete_count, &list_item_nodes_to_insert)
    }

    /// The `$transform` of `ListNode.$config()`: merges the next list of the
    /// same type into this one, then renumbers the items. Where
    /// `NodeStructureExtension` enforces declared structure, it merges
    /// adjacent lists itself (by `mergeAdjacent`, joining nested lists at the
    /// seam as `mergeLists` does), the same way whichever list is dirty.
    fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
        let structure_merges = this
            .get_next_sibling()
            .is_some_and(|next| crate::structure::structure_merges(this, &next));
        if !structure_merges {
            merge_next_sibling_list_if_same_type(this)?;
        }
        update_children_list_item_value(this);
        Ok(())
    }

    /// `ListNode.INTERNAL_$afterStructureMerge(last, first)`: joins nested
    /// lists at the seam, as `mergeLists` does, but only items whose only
    /// child is the nested list, so that nothing else in them is removed or
    /// moved.
    fn internal_after_structure_merge(
        &self,
        _: &NodeRef,
        last: &NodeRef,
        first: &NodeRef,
    ) -> Result<bool, LexicalError> {
        merge_nested_lists_at_seam(Some(last.clone()), Some(first.clone()), true)?;
        Ok(true)
    }

    /// `ListNode.INTERNAL_$afterStructureSplit(original, preceding)`: an
    /// ordered list part continues the numbering of the items that precede
    /// it, so it starts at the next number.
    fn internal_after_structure_split(
        &self,
        this: &NodeRef,
        original: &NodeRef,
        preceding: &[NodeRef],
    ) -> Result<(), LexicalError> {
        if self.list_type == ListType::Number {
            let mut start = original.get_list_start().unwrap_or(1.0);
            for node in preceding {
                // As updateChildrenListItemValue counts: an item that only
                // wraps a nested list has no number of its own.
                if is_list_item_node(node)
                    && !node.get_first_child().is_some_and(|c| is_list_node(&c))
                {
                    start += 1.0;
                }
            }
            this.set_list_start(start);
        }
        Ok(())
    }
}

// The DOM side of `ListNode` (the `html` feature).

#[cfg(feature = "html")]
pub(super) mod list_dom {
    use super::super::list_item_node::{create_list_item_node, is_list_item_node};
    use super::super::utils::get_list_depth;
    use super::{ListNode, ListType, create_list_node, is_list_node};
    use crate::dom::DomNode;
    use crate::json::{Object, Value};
    use crate::lexical_dom::{
        DomConversionMap, DomConversionNode, DomConversionOutput, DomExportOutput, get_document,
        importer, normalize_class_names, set_direction_from_dom,
    };
    use crate::node::NodeRef;
    use crate::{EditorConfig, LexicalError};

    /// `ListNode.createDOM(config)`: an `<ol>` or `<ul>`, with `start`
    /// when it isn't 1 and the theme's class names.
    pub(crate) fn create_dom(
        node: &ListNode,
        this: &NodeRef,
        config: &EditorConfig,
    ) -> Result<DomNode, LexicalError> {
        let dom = get_document().create_element(node.list_type.tag());
        if node.start != 1.0 {
            dom.set_attribute("start", &crate::json::number_to_string(node.start));
        }
        set_list_theme_class_names(&dom, &config.theme, node, this)?;
        Ok(dom)
    }

    /// `ListNode.exportDOM(editor)`: `createDOM`'s element, with
    /// `__lexicalListType` for a check list and the direction.
    pub(crate) fn export_dom(
        node: &ListNode,
        this: &NodeRef,
        editor: &crate::Editor,
    ) -> Result<DomExportOutput, LexicalError> {
        let element = create_dom(node, this, editor.config())?;
        if node.start != 1.0 {
            element.set_attribute("start", &crate::json::number_to_string(node.start));
        }
        if node.list_type == ListType::Check {
            element.set_attribute("__lexicalListType", "check");
        }
        if let Some(direction) = node.element.get_direction() {
            element.set_dir(direction.as_str());
        }
        Ok(DomExportOutput::element(element))
    }

    /// The strings `normalizeClassNames(value)` takes from a theme value:
    /// none unless it is a string.
    fn class_names_of(value: Option<&Value>) -> Vec<String> {
        value
            .and_then(Value::as_str)
            .map(|v| normalize_class_names(&[v]))
            .unwrap_or_default()
    }

    /// `$setListThemeClassNames(dom, editorThemeClasses, node)`.
    fn set_list_theme_class_names(
        dom: &DomNode,
        theme: &Object,
        node: &ListNode,
        this: &NodeRef,
    ) -> Result<(), LexicalError> {
        let mut classes_to_add: Vec<String> = Vec::new();
        let mut classes_to_remove: Vec<String> = Vec::new();
        if let Some(list_theme) = theme.get("list").filter(|v| !v.is_undefined()) {
            let tag = node.list_type.tag();
            let empty = Vec::new();
            let list_levels_class_names = list_theme
                .get(&format!("{tag}Depth"))
                .and_then(Value::as_array)
                .unwrap_or(&empty);
            // `$getListDepth(node) - 1`, and `%` by the number of level
            // classes (`NaN`, matching none, when there are none).
            let list_depth = get_list_depth(this)? as i64 - 1;
            let normalized_list_depth = (!list_levels_class_names.is_empty())
                .then(|| list_depth.rem_euclid(list_levels_class_names.len() as i64) as usize);
            let list_level_class_name =
                normalized_list_depth.and_then(|i| list_levels_class_names.get(i));
            if let Some(list_class_name) = list_theme.get(tag) {
                classes_to_add.extend(class_names_of(Some(list_class_name)));
            }
            if node.list_type == ListType::Check {
                classes_to_add.extend(class_names_of(list_theme.get("checklist")));
            }
            if let Some(list_level_class_name) = list_level_class_name {
                classes_to_add.extend(class_names_of(Some(list_level_class_name)));
                for (i, class_name) in list_levels_class_names.iter().enumerate() {
                    if Some(i) != normalized_list_depth {
                        classes_to_remove.extend(class_names_of(Some(class_name)));
                    }
                }
            }
            let nested_list_class_name = list_theme
                .get("nested")
                .and_then(|n| n.get("list"))
                .filter(|l| l.as_str().is_some_and(|s| !s.is_empty()));
            if nested_list_class_name.is_some() {
                let nested_list_item_classes = class_names_of(nested_list_class_name);
                if list_depth > 1 {
                    classes_to_add.extend(nested_list_item_classes);
                } else {
                    classes_to_remove.extend(nested_list_item_classes);
                }
            }
        }
        if !classes_to_remove.is_empty() {
            dom.class_list().remove(&classes_to_remove);
        }
        if !classes_to_add.is_empty() {
            dom.class_list().add(&classes_to_add);
        }
        Ok(())
    }

    /// `ListNode`'s `importDOM`: `<ol>` and `<ul>`.
    pub(crate) fn import_dom() -> DomConversionMap {
        vec![
            ("ol".to_owned(), importer(0, convert_list_node)),
            ("ul".to_owned(), importer(0, convert_list_node)),
        ]
    }

    /// `$normalizeChildren(nodes, listNode)`: the children of a list made
    /// from HTML, each a list item holding one nested list or inline
    /// content.
    fn normalize_children(nodes: Vec<NodeRef>) -> Result<Vec<NodeRef>, LexicalError> {
        let mut normalized_list_items = Vec::new();
        for node in nodes {
            if is_list_item_node(&node) {
                normalized_list_items.push(node.clone());
                let children = node.get_children();
                if children.len() > 1 {
                    for child in children {
                        if is_list_node(&child) {
                            let wrapper = create_list_item_node(None);
                            wrapper.append(&[child])?;
                            normalized_list_items.push(wrapper);
                        }
                    }
                }
            } else {
                let wrapper = create_list_item_node(None);
                wrapper.append(&[node])?;
                normalized_list_items.push(wrapper);
            }
        }
        Ok(normalized_list_items)
    }

    /// `isDomChecklist(domNode)`: a Lexical, GitHub, Joplin or Google Docs
    /// check list.
    fn is_dom_checklist(dom_node: &DomNode) -> bool {
        if dom_node.get_attribute("__lexicallisttype").as_deref() == Some("check")
            || dom_node.class_list().contains("contains-task-list")
            || dom_node.get_attribute("data-is-checklist").as_deref() == Some("1")
        {
            return true;
        }
        dom_node
            .child_nodes()
            .iter()
            .any(|child| child.is_element() && child.has_attribute("aria-checked"))
    }

    /// `HTMLOListElement.start`: the `start` attribute by the HTML rules
    /// for parsing integers, or 1.
    pub(crate) fn ol_start(element: &DomNode) -> f64 {
        let Some(value) = element.get_attribute("start") else {
            return 1.0;
        };
        let rest = value.trim_start_matches([' ', '\t', '\n', '\u{c}', '\r']);
        let (sign, rest) = match rest.as_bytes().first() {
            Some(b'-') => (-1, &rest[1..]),
            Some(b'+') => (1, &rest[1..]),
            _ => (1, rest),
        };
        let digits = &rest[..rest
            .bytes()
            .position(|b| !b.is_ascii_digit())
            .unwrap_or(rest.len())];
        match digits.parse::<i64>() {
            Ok(n) if (-2_147_483_648..=2_147_483_647).contains(&(sign * n)) => (sign * n) as f64,
            _ => 1.0,
        }
    }

    /// `$convertListNode(domNode)`: a numbered list from `<ol>`, a check
    /// list or a bullet list from `<ul>`, whose children become list items.
    fn convert_list_node(dom_node: &DomNode) -> Result<Option<DomConversionOutput>, LexicalError> {
        let node = if dom_node.is_element() && dom_node.local_name() == "ol" {
            create_list_node(ListType::Number, ol_start(dom_node))
        } else if is_dom_checklist(dom_node) {
            create_list_node(ListType::Check, 1.0)
        } else {
            create_list_node(ListType::Bullet, 1.0)
        };
        set_direction_from_dom(&node, dom_node);
        Ok(Some(DomConversionOutput {
            node: DomConversionNode::One(node),
            after: Some(Box::new(normalize_children)),
            ..DomConversionOutput::default()
        }))
    }
}