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
//! `CodeNode.ts`: `CodeNode`, `$createCodeNode`, `$isCodeNode`,
//! `DEFAULT_CODE_LANGUAGE`, `getDefaultCodeLanguage` and
//! `$exitCodeNodeOnEnter`.

use super::code_highlight_node::{create_code_highlight_node, is_code_highlight_node};
use super::flat_structure_utils::get_first_code_node_of_line;
use super::generated_json::{export_code_node, export_compact_code_node, update_code_node};
use crate::LexicalError;
use crate::json::Object;
use crate::json::Value;
use crate::lexical_selection::{PointType, SelectionRef, Which};
use crate::lexical_utils::with_writable;
use crate::node::{LexicalNode, NodeBase, NodeRef};
use crate::nodes::element::ElementData;
use crate::nodes::line_break::{LineBreakNode, create_line_break_node};
use crate::nodes::paragraph::create_paragraph_node;
use crate::nodes::tab::{TabNode, create_tab_node};
use crate::schema::{
    NodeSchema, node_schema, nullable, optional, schema_getter, schema_setter, string_value,
    with_accessors,
};

/// `DEFAULT_CODE_LANGUAGE`.
pub const DEFAULT_CODE_LANGUAGE: &str = "javascript";

/// `getDefaultCodeLanguage()`.
pub fn get_default_code_language() -> &'static str {
    DEFAULT_CODE_LANGUAGE
}

/// `CodeNode`: a code block, holding [`CodeHighlightNode`]s, tabs and line
/// breaks.
///
/// [`CodeHighlightNode`]: super::CodeHighlightNode
#[derive(Clone, Debug, Default)]
pub struct CodeNode {
    base: NodeBase,
    pub(super) element: ElementData,
    /// `__language`: `None` where JS's is `undefined`. JS's constructor and
    /// setter turn every falsy language into `undefined`, so a `null` never
    /// stays.
    pub(super) language: Option<String>,
    /// `__theme`, as `language`.
    pub(super) theme: Option<String>,
    /// `__isSyntaxHighlightSupported`: set by a highlighter, not serialized,
    /// and carried across a clone (`afterCloneFrom`).
    pub(super) is_syntax_highlight_supported: bool,
}

impl CodeNode {
    /// `__language`.
    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    /// `__theme`.
    pub fn theme(&self) -> Option<&str> {
        self.theme.as_deref()
    }

    /// `__isSyntaxHighlightSupported`.
    pub fn is_syntax_highlight_supported(&self) -> bool {
        self.is_syntax_highlight_supported
    }
}

/// `language || undefined`.
fn truthy(value: Option<&str>) -> Option<String> {
    value.filter(|v| !v.is_empty()).map(str::to_owned)
}

/// `$createCodeNode(language, theme)`: `None` and `""` are both no
/// language (no theme).
pub fn create_code_node(language: Option<&str>, theme: Option<&str>) -> NodeRef {
    let node = crate::create::<CodeNode>();
    node.set_language(language);
    node.set_theme(theme);
    node
}

/// `$isCodeNode(node)`.
pub fn is_code_node(node: &NodeRef) -> bool {
    node.get_latest().is::<CodeNode>()
}

fn with_code<R>(node: &NodeRef, f: impl FnOnce(&CodeNode) -> R) -> Option<R> {
    node.get_latest().downcast_ref::<CodeNode>().map(f)
}

fn set_code(node: &NodeRef, f: impl FnOnce(&mut CodeNode)) {
    if is_code_node(node) {
        with_writable(node.get_key(), |n| {
            f(n.downcast_mut::<CodeNode>().expect("a code node"))
        });
    }
}

impl NodeRef {
    /// `CodeNode.getLanguage()`; `None` when it is `undefined`, or for any
    /// other node.
    pub fn get_language(&self) -> Option<String> {
        with_code(self, |c| c.language.clone()).flatten()
    }

    /// `CodeNode.setLanguage(language)`: an empty one is `undefined`. Does
    /// nothing to any other node.
    pub fn set_language(&self, language: Option<&str>) {
        set_code(self, |c| c.language = truthy(language));
    }

    /// `CodeNode.getTheme()`; `None` when it is `undefined`, or for any
    /// other node.
    pub fn get_theme(&self) -> Option<String> {
        with_code(self, |c| c.theme.clone()).flatten()
    }

    /// `CodeNode.setTheme(theme)`: an empty one is `undefined`. Does nothing
    /// to any other node.
    pub fn set_theme(&self, theme: Option<&str>) {
        set_code(self, |c| c.theme = truthy(theme));
    }

    /// `CodeNode.getIsSyntaxHighlightSupported()`; false for any other node.
    pub fn get_is_syntax_highlight_supported(&self) -> bool {
        with_code(self, |c| c.is_syntax_highlight_supported).unwrap_or(false)
    }

    /// `CodeNode.setIsSyntaxHighlightSupported(isSupported)`. Does nothing
    /// to any other node.
    pub fn set_is_syntax_highlight_supported(&self, is_supported: bool) {
        set_code(self, |c| c.is_syntax_highlight_supported = is_supported);
    }
}

/// Whether the active editor was built with `CodeExtension`:
/// `getPeerDependencyFromEditor($getEditor(), '@lexical/code')`. Without the
/// `extension` feature no editor is.
fn has_code_extension() -> bool {
    #[cfg(feature = "extension")]
    {
        crate::updates::get_active_editor().is_some_and(|editor| {
            crate::extension::LexicalBuilder::maybe_from_editor(&editor)
                .is_some_and(|builder| builder.has_extension_by_name("@lexical/code"))
        })
    }
    #[cfg(not(feature = "extension"))]
    {
        false
    }
}

/// `CodeNode.insertNewAfter(selection, restoreSelection)`: a line break,
/// followed by the leading tabs and spaces of the line the selection starts
/// on, so the new line keeps its indentation. JS first exits the block
/// (`$exitCodeNodeOnEnter`) when the editor has no `CodeExtension`, which
/// handles that on `KEY_ENTER_COMMAND` instead, as here: an editor built
/// with [`code_extension`](super::code_extension) only adds the line.
fn insert_new_after(selection: &SelectionRef) -> Result<Option<NodeRef>, LexicalError> {
    if !has_code_extension() {
        // `noExtensionDeprecation()`.
        crate::warnings::warn_only_once("Using CodeNode without CodeExtension is deprecated");
        if let Some(el) = exit_code_node_on_enter(selection)? {
            return Ok(Some(el));
        }
    }
    // If the selection is within the codeblock, find all leading tabs and
    // spaces of the current line. Create a new line that has all those
    // tabs and spaces, such that leading indentation is preserved.
    let anchor = |s: &SelectionRef| s.point(Which::Anchor).expect("a range selection");
    let focus = selection.point(Which::Focus).expect("a range selection");
    let first_point = if anchor(selection).is_before(&focus)? {
        anchor(selection)
    } else {
        focus
    };
    let first_selection_node = first_point.get_node()?;
    if first_selection_node.is_text() {
        let mut node = Some(get_first_code_node_of_line(&first_selection_node));
        let mut insert_nodes = Vec::new();
        while let Some(n) = node {
            if n.get_latest().is::<TabNode>() {
                insert_nodes.push(create_tab_node());
                node = n.get_next_sibling();
            } else if is_code_highlight_node(&n) {
                let text = n.get_text_content();
                let text_size = n.get_text_content_size();
                // A space is one UTF-16 unit, so counting characters counts
                // units.
                let spaces = text.chars().take_while(|&c| c == ' ').count();
                if spaces != 0 {
                    insert_nodes.push(create_code_highlight_node(&" ".repeat(spaces), None));
                }
                if spaces != text_size {
                    break;
                }
                node = n.get_next_sibling();
            } else {
                break;
            }
        }
        let anchor_offset = anchor(selection).offset;
        // `splitText(...)[0]` of an empty node is `undefined`, which JS
        // then reads a property of.
        let Some(split) = first_selection_node
            .split_text(&[anchor_offset as i64])?
            .into_iter()
            .next()
        else {
            return Err(LexicalError::new(
                "Cannot read properties of undefined (reading 'getIndexWithinParent')",
            ));
        };
        // JS reads `anchor.offset` again here, after the split moved it.
        let x = if anchor(selection).offset == 0 { 0 } else { 1 };
        let index = split
            .get_index_within_parent()
            .expect("a split text node has a parent")
            + x;
        let code_node = first_selection_node.get_parent_or_throw()?;
        let mut nodes_to_insert = vec![create_line_break_node()];
        nodes_to_insert.extend(insert_nodes.iter().cloned());
        code_node.splice(index, 0, &nodes_to_insert)?;
        if let Some(last) = insert_nodes.last() {
            last.select(None, None)?;
        } else if anchor(selection).offset == 0 {
            split.select_previous(None, None)?;
        } else {
            split
                .get_next_sibling()
                .expect("the line break inserted after the split")
                .select_next(Some(0), Some(0))?;
        }
    }
    if is_code_node(&first_selection_node) {
        let offset = anchor(selection).offset;
        first_selection_node.splice(offset, 0, &[create_line_break_node()])?;
        first_selection_node.select(Some(offset + 1), Some(offset + 1))?;
    }
    Ok(None)
}

thread_local! {
    static CODE_NODE_SCHEMA: NodeSchema = build_code_node_schema().expect("CodeNode's schema");
}

/// What `setLanguage`, `setTheme` and `setHighlightType` keep of a parsed
/// value: a non-empty string, any other (`null`, `undefined`, `''`) being
/// `undefined`.
pub(super) fn truthy_value(value: &Value) -> Option<String> {
    truthy(value.as_str())
}

/// `codeNodeSchema`: `language` and `theme`, read straight off the fields
/// and applied through the setters, which keep only a non-empty string.
pub fn code_node_schema() -> NodeSchema {
    CODE_NODE_SCHEMA.with(Clone::clone)
}

fn build_code_node_schema() -> Result<NodeSchema, LexicalError> {
    let field = |value: &Option<String>| value.as_deref().map_or(Value::Undefined, Value::from);
    node_schema(vec![
        (
            "language",
            with_accessors(
                optional(nullable(string_value(""), false)?, false)?,
                Some(schema_getter(move |n: &CodeNode| field(&n.language))),
                Some(schema_setter(|n: &mut CodeNode, value| {
                    n.language = truthy_value(&value);
                })),
            )?,
        ),
        (
            "theme",
            with_accessors(
                optional(string_value(""), false)?,
                Some(schema_getter(move |n: &CodeNode| field(&n.theme))),
                Some(schema_setter(|n: &mut CodeNode, value| {
                    n.theme = truthy_value(&value);
                })),
            )?,
        ),
    ])
}

impl LexicalNode for CodeNode {
    fn json_schema_chain(&self) -> Vec<NodeSchema> {
        vec![
            code_node_schema(),
            crate::nodes::element::element_node_schema(),
        ]
    }
    /// The `$config()` of `CodeNode`: `children: 'inline'`.
    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
        crate::structure::inline_holder_chain(self.get_type())
    }

    fn get_type(&self) -> &'static str {
        "code"
    }
    /// `CodeNode.createDOM(config)`: a `<code>`.
    #[cfg(feature = "html")]
    fn create_dom(
        &self,
        _this: &NodeRef,
        config: &crate::EditorConfig,
        _editor: &crate::Editor,
    ) -> Result<crate::dom::DomNode, LexicalError> {
        Ok(code_dom::code_element(self, "code", &config.theme))
    }
    /// `CodeNode.exportDOM(editor)`: a `<pre>`, with what `createDOM`
    /// writes and without the indent and direction.
    #[cfg(feature = "html")]
    fn export_dom(
        &self,
        _this: &NodeRef,
        editor: &crate::Editor,
    ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
        Ok(crate::lexical_dom::DomExportOutput::element(
            code_dom::code_element(self, "pre", &editor.config().theme),
        ))
    }
    #[cfg(feature = "html")]
    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
        Some(code_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)
    }

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

    /// `CodeNode.insertNewAfter(selection, restoreSelection)`.
    fn insert_new_after(
        &self,
        _: &NodeRef,
        selection: &SelectionRef,
        _: bool,
    ) -> Result<Option<NodeRef>, LexicalError> {
        insert_new_after(selection)
    }

    /// `CodeNode.collapseAtStart()`: the block becomes a paragraph with its
    /// children.
    fn collapse_at_start(&self, this: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
        let paragraph = create_paragraph_node();
        for child in this.get_children() {
            paragraph.append(std::slice::from_ref(&child))?;
        }
        this.replace(&paragraph, false)?;
        Ok(true)
    }

    /// `exportCodeNode` and `exportCompactCodeNode`.
    fn generated_export_json(&self, compact: bool) -> Option<Object> {
        Some(if compact {
            export_compact_code_node(self)
        } else {
            export_code_node(self)
        })
    }

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

/// `$exitCodeNodeOnEnter(selection)`: at the end of a code block that ends
/// with two line breaks, a collapsed selection removes them and moves to a
/// new paragraph after the block, which it returns.
pub fn exit_code_node_on_enter(selection: &SelectionRef) -> Result<Option<NodeRef>, LexicalError> {
    let Some(range) = selection.range() else {
        return Ok(None);
    };
    let anchor = &range.anchor;
    if range.is_collapsed() && anchor.point_type == PointType::Element {
        let code_node = anchor.get_node()?;
        if is_code_node(&code_node) {
            let children_size = code_node.get_children_size();
            if children_size >= 2 && anchor.offset == children_size {
                let last_child = code_node.get_last_child();
                let is_line_break = |n: &Option<NodeRef>| {
                    n.as_ref()
                        .is_some_and(|n| n.get_latest().is::<LineBreakNode>())
                };
                if is_line_break(&last_child)
                    && is_line_break(&last_child.as_ref().and_then(NodeRef::get_previous_sibling))
                {
                    let new_element = create_paragraph_node();
                    code_node.splice(children_size - 2, 2, &[])?;
                    code_node.insert_after(&new_element, false)?;
                    new_element.select(None, None)?;
                    return Ok(Some(new_element));
                }
            }
        }
    }
    Ok(None)
}

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

#[cfg(feature = "html")]
pub(super) mod code_dom {
    use super::{CodeNode, create_code_node};
    use crate::LexicalError;
    use crate::dom::DomNode;
    use crate::json::Object;
    use crate::lexical_dom::{
        DomConversion, DomConversionMap, DomConversionOutput, add_theme_class_names, closest,
        get_document, importer,
    };
    use crate::set_dom_style::set_dom_style_from_css;
    use std::rc::Rc;

    /// `LANGUAGE_DATA_ATTRIBUTE`.
    const LANGUAGE_DATA_ATTRIBUTE: &str = "data-language";
    /// `HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE`.
    const HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE: &str = "data-highlight-language";
    /// `THEME_DATA_ATTRIBUTE`.
    const THEME_DATA_ATTRIBUTE: &str = "data-theme";

    /// What `createDOM` (a `<code>`) and `exportDOM` (a `<pre>`) both
    /// write: the theme's `code` class names, `spellcheck`, the language
    /// and theme attributes, and the style.
    pub(crate) fn code_element(code: &CodeNode, tag: &str, theme: &Object) -> DomNode {
        let element = get_document().create_element(tag);
        add_theme_class_names(&element, theme, "code");
        element.set_attribute("spellcheck", "false");
        if let Some(language) = code.language() {
            element.set_attribute(LANGUAGE_DATA_ATTRIBUTE, language);
            if code.is_syntax_highlight_supported() {
                element.set_attribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
            }
        }
        if let Some(theme) = code.theme() {
            element.set_attribute(THEME_DATA_ATTRIBUTE, theme);
        }
        let style = code.element.get_style();
        if !style.is_empty() {
            set_dom_style_from_css(&element.style(), style, "");
        }
        element
    }

    /// `hasChildDOMNodeTag(node, tagName)`.
    fn has_child_dom_node_tag(node: &DomNode, tag_name: &str) -> bool {
        node.child_nodes().iter().any(|child| {
            (child.is_element() && child.tag_name() == tag_name)
                || has_child_dom_node_tag(child, tag_name)
        })
    }

    /// `CodeNode`'s `importDOM`: `<pre>`, a multi-line `<code>`, a `<div>`
    /// in a monospace font, and GitHub's code tables.
    pub(crate) fn import_dom() -> DomConversionMap {
        let noop = || -> crate::lexical_dom::DomConversionFn {
            Rc::new(|_| Ok(Some(DomConversionOutput::node(None))))
        };
        vec![
            (
                "code".to_owned(),
                Rc::new(|node: &DomNode| {
                    let is_multi_line =
                        node.text_content().contains('\n') || has_child_dom_node_tag(node, "BR");
                    is_multi_line.then(|| DomConversion {
                        conversion: Rc::new(convert_pre_element),
                        priority: 1,
                    })
                }),
            ),
            ("div".to_owned(), importer(1, convert_div_element)),
            ("pre".to_owned(), importer(0, convert_pre_element)),
            (
                "table".to_owned(),
                Rc::new(|node: &DomNode| {
                    is_git_hub_code_table(node).then(|| DomConversion {
                        conversion: Rc::new(|_| {
                            Ok(Some(DomConversionOutput::node(Some(create_code_node(
                                None, None,
                            )))))
                        }),
                        priority: 3,
                    })
                }),
            ),
            (
                "td".to_owned(),
                Rc::new(move |node: &DomNode| {
                    let table = closest(node, "table");
                    (is_git_hub_code_cell(node)
                        || table.as_ref().is_some_and(is_git_hub_code_table))
                    .then(|| DomConversion {
                        conversion: noop(),
                        priority: 3,
                    })
                }),
            ),
            (
                "tr".to_owned(),
                Rc::new(move |node: &DomNode| {
                    closest(node, "table")
                        .as_ref()
                        .is_some_and(is_git_hub_code_table)
                        .then(|| DomConversion {
                            conversion: noop(),
                            priority: 3,
                        })
                }),
            ),
        ]
    }

    /// `$convertPreElement(domNode)`: a code block with the element's
    /// language and theme.
    fn convert_pre_element(
        dom_node: &DomNode,
    ) -> Result<Option<DomConversionOutput>, LexicalError> {
        let language = dom_node.get_attribute(LANGUAGE_DATA_ATTRIBUTE);
        let theme = dom_node.get_attribute(THEME_DATA_ATTRIBUTE);
        Ok(Some(DomConversionOutput::node(Some(create_code_node(
            language.as_deref(),
            theme.as_deref(),
        )))))
    }

    /// `$convertDivElement(domNode)`: a code block for a `<div>` in a
    /// monospace font.
    fn convert_div_element(
        dom_node: &DomNode,
    ) -> Result<Option<DomConversionOutput>, LexicalError> {
        let is_code = is_code_element(dom_node);
        Ok(Some(DomConversionOutput::node(
            is_code.then(|| create_code_node(None, None)),
        )))
    }

    /// `isCodeElement(div)`: `font-family` names `monospace`.
    fn is_code_element(div: &DomNode) -> bool {
        div.style()
            .get_property_value("font-family")
            .contains("monospace")
    }

    /// `isGitHubCodeCell(cell)`.
    fn is_git_hub_code_cell(cell: &DomNode) -> bool {
        cell.class_list().contains("js-file-line")
    }

    /// `isGitHubCodeTable(table)`.
    fn is_git_hub_code_table(table: &DomNode) -> bool {
        table.class_list().contains("js-file-line-container")
    }
}