Skip to main content

lexical_ui/devtools/
generate_content.rs

1//! `packages/lexical-devtools-core/src/generateContent.ts`. The `exportDOM`
2//! form is built with the `html` feature, the link branch with `link` and
3//! the mark branch with `mark`, as without them no such node can exist.
4//!
5//! Not ported: table selections (`@lexical/table`).
6
7use crate::constants::{IS_DIRECTIONLESS, TEXT_TYPE_TO_FORMAT, lookup};
8use crate::node_state::{is_default, unparse};
9use crate::nodes::paragraph::ParagraphNode;
10use crate::nodes::text::to_int32;
11use crate::selection_deletion::is_js_whitespace;
12use crate::updates::read_editor_state;
13use crate::{
14    Editor, LexicalError, NodeRef, PointType, SelectionRef, get_root, get_selection, get_slot,
15    get_slot_host, get_slot_name_within_host, get_slot_names, utf16,
16};
17
18/// `CustomPrintNodeFn`: what to print for a node (given whether to
19/// obfuscate its text) instead of the default; `None` or an empty string
20/// for the default.
21pub type CustomPrintNodeFn<'a> = &'a dyn Fn(&NodeRef, bool) -> Option<String>;
22
23/// An entry of `LexicalCommandLog` (`useLexicalCommandsLog.ts`): a
24/// dispatched command's index in the log, its `type` and its payload as
25/// the tree view prints it (JS prints `String(payload)`, or an event's
26/// class name).
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct LexicalCommandLogEntry {
29    pub index: usize,
30    pub command_type: String,
31    pub payload: String,
32}
33
34/// `NON_SINGLE_WIDTH_CHARS_REPLACEMENT`.
35const NON_SINGLE_WIDTH_CHARS_REPLACEMENT: [(char, &str); 2] = [('\t', "\\t"), ('\n', "\\n")];
36
37/// `SYMBOLS`.
38const ANCESTOR_HAS_NEXT_SIBLING: &str = "|";
39const ANCESTOR_IS_LAST_CHILD: &str = " ";
40const HAS_NEXT_SIBLING: &str = "├";
41const IS_LAST_CHILD: &str = "└";
42const SELECTED_CHAR: &str = "^";
43const SELECTED_LINE: &str = ">";
44
45/// The formats `FORMAT_PREDICATES` and `FORMAT_PREDICATES_PARAGRAPH` ask
46/// about, in their order, with the names they print.
47const FORMATS: [(&str, &str); 8] = [
48    ("bold", "Bold"),
49    ("code", "Code"),
50    ("italic", "Italic"),
51    ("strikethrough", "Strikethrough"),
52    ("subscript", "Subscript"),
53    ("superscript", "Superscript"),
54    ("underline", "Underline"),
55    ("highlight", "Highlight"),
56];
57
58/// `generateContent(editor, commandsLog, exportDOM, customPrintNode,
59/// obfuscateText)`: the tree view's text: each node of the editor's state
60/// on a line (`>` when selected, with a line of `^` under a text node's
61/// selected characters), the selection, the commands logged and the
62/// editor's version, namespace and editable flag; slot values first under
63/// their host, with their slot's name. With `export_dom`, the state's HTML
64/// (`$generateHtmlFromNodes`), indented (`printPrettyHTML`); without the
65/// `html` feature that fails.
66pub fn generate_content(
67    editor: &Editor,
68    commands_log: &[LexicalCommandLogEntry],
69    export_dom: bool,
70    custom_print_node: Option<CustomPrintNodeFn<'_>>,
71    obfuscate_text: bool,
72) -> Result<String, LexicalError> {
73    let editor_state = editor.get_editor_state();
74
75    if export_dom {
76        #[cfg(feature = "html")]
77        return read_editor_state(Some(editor), &editor_state, || {
78            Ok(print_pretty_html(&crate::html::generate_html_from_nodes(
79                editor, None,
80            )?))
81        });
82        #[cfg(not(feature = "html"))]
83        return Err(LexicalError::new(
84            "generateContent: exportDOM needs @lexical/html (the `html` feature)",
85        ));
86    }
87
88    let mut res = String::from(" root\n");
89
90    let selection_string = read_editor_state(Some(editor), &editor_state, || {
91        let selection = get_selection();
92        visit_tree(&get_root(), &[], &mut |node, indent, slot_name| {
93            let node_key_display = format!("({})", node.get_key());
94            let type_display = node.get_type();
95            let is_selected = node.is_selected(None)?;
96            let slot_prefix = slot_name.map_or(String::new(), |name| format!("[slot: {name}] "));
97            let slot_meta = slot_value_meta_suffix(node, slot_name);
98            res.push_str(&format!(
99                "{} {} {node_key_display} {slot_prefix}{type_display}{slot_meta} {}\n",
100                if is_selected { SELECTED_LINE } else { " " },
101                indent.join(" "),
102                print_node(node, custom_print_node, obfuscate_text),
103            ));
104            res.push_str(&print_selected_chars_line(
105                indent,
106                is_selected,
107                node,
108                &node_key_display,
109                selection.as_ref(),
110                type_display,
111            )?);
112            Ok(())
113        })?;
114        Ok::<_, LexicalError>(match &selection {
115            None => ": null".to_owned(),
116            Some(selection) if selection.is_range() => print_range_selection(selection)?,
117            #[cfg(feature = "table")]
118            Some(selection) if selection.is_table() => print_table_selection(selection),
119            Some(selection) => print_node_selection(selection),
120        })
121    })?;
122
123    res.push_str("\n selection");
124    res.push_str(&selection_string);
125
126    res.push_str("\n\n commands:");
127
128    if commands_log.is_empty() {
129        res.push_str("\n  └ None dispatched.");
130    } else {
131        for entry in commands_log {
132            res.push_str(&format!(
133                "\n  └ {}. {{ type: {}, payload: {} }}",
134                entry.index, entry.command_type, entry.payload
135            ));
136        }
137    }
138    res.push_str(&format!("\n\n editor (v{}):", Editor::VERSION));
139    res.push_str(&format!("\n  └ namespace {}", editor.get_namespace()));
140    if let Some(composition_key) = editor.composition_key() {
141        res.push_str(&format!("\n  └ compositionKey {composition_key}"));
142    }
143    res.push_str(&format!("\n  └ editable {}", editor.is_editable()));
144
145    Ok(res)
146}
147
148/// `$printRangeSelection(selection)`.
149fn print_range_selection(selection: &SelectionRef) -> Result<String, LexicalError> {
150    let range = selection.range().expect("a range selection");
151    let format_text = print_format_properties(|format| selection.has_format(format));
152    let slot_suffix = match resolve_slot_context(&range.anchor.get_node()?) {
153        Some((name, host)) => format!(
154            " (in slot \"{name}\" of {} {{ key: {} }})",
155            host.get_type(),
156            host.get_key()
157        ),
158        None => String::new(),
159    };
160    let mut res = format!(
161        ": range{slot_suffix} {} {}",
162        if format_text.is_empty() {
163            String::new()
164        } else {
165            format!("{{ {format_text} }}")
166        },
167        if range.style.is_empty() {
168            String::new()
169        } else {
170            format!("{{ style: {} }} ", range.style)
171        },
172    );
173    for (line, point) in [("├ anchor", &range.anchor), ("└ focus", &range.focus)] {
174        res.push_str(&format!(
175            "\n  {line} {{ key: {}, offset: {}, type: {} }}",
176            point.key,
177            point.offset,
178            point.point_type.as_str()
179        ));
180    }
181    Ok(res)
182}
183
184/// `$resolveSlotContext(node)`: the name of the slot the node is in and
185/// its host, walking up through parents and slot hosts, or `None`.
186fn resolve_slot_context(node: &NodeRef) -> Option<(String, NodeRef)> {
187    let mut cursor = Some(node.clone());
188    while let Some(current) = cursor {
189        if let Some(slot_name) = get_slot_name_within_host(&current)
190            && let Some(host) = get_slot_host(&current)
191        {
192            return Some((slot_name, host));
193        }
194        cursor = current.get_parent().or_else(|| get_slot_host(&current));
195    }
196    None
197}
198
199/// `$slotValueMetaSuffix(node, slotName)`: ` [shadow-root]` for a shadow
200/// root element in a slot, ` [atomic decorator]` for a block decorator in
201/// one, and nothing for a node that isn't a slot value.
202fn slot_value_meta_suffix(node: &NodeRef, slot_name: Option<&str>) -> &'static str {
203    if slot_name.is_none() {
204        return "";
205    }
206    if crate::lexical_utils::is_shadow_root_node(node) {
207        return " [shadow-root]";
208    }
209    if node.is_decorator() && !node.is_inline() {
210        return " [atomic decorator]";
211    }
212    ""
213}
214
215/// `printTableSelection(selection)`.
216#[cfg(feature = "table")]
217fn print_table_selection(selection: &SelectionRef) -> String {
218    let table = selection.table().expect("a table selection");
219    format!(
220        ": table\n  └ {{ table: {}, anchorCell: {}, focusCell: {} }}",
221        table.table_key, table.anchor.key, table.focus.key
222    )
223}
224
225/// `printNodeSelection(selection)`.
226fn print_node_selection(selection: &SelectionRef) -> String {
227    format!(": node\n  └ [{}]", selection.node_keys().join(", "))
228}
229
230/// What `$visitTree` calls for each node, with its indent and, for a slot
231/// value, its slot's name.
232type Visitor<'a> =
233    dyn FnMut(&NodeRef, &[&'static str], Option<&str>) -> Result<(), LexicalError> + 'a;
234
235/// `$visitTree(currentNode, visitor, indent)`: each slot value of an
236/// element or decorator (in `$getSlotNames`' order), then each child, with
237/// its indent, then its own slot values and children.
238fn visit_tree(
239    current_node: &NodeRef,
240    indent: &[&'static str],
241    visitor: &mut Visitor<'_>,
242) -> Result<(), LexicalError> {
243    let slot_entries = get_slot_names(current_node)
244        .into_iter()
245        .filter_map(|name| get_slot(current_node, &name).map(|node| (Some(name), node)));
246    let child_nodes = if current_node.is_element() {
247        current_node.get_children()
248    } else {
249        Vec::new()
250    };
251    let entries: Vec<(Option<String>, NodeRef)> = slot_entries
252        .chain(child_nodes.into_iter().map(|node| (None, node)))
253        .collect();
254    let total_count = entries.len();
255    for (i, (slot_name, child_node)) in entries.iter().enumerate() {
256        let is_last = i + 1 == total_count;
257        let mut child_indent = indent.to_vec();
258        child_indent.push(if is_last {
259            IS_LAST_CHILD
260        } else {
261            HAS_NEXT_SIBLING
262        });
263        visitor(child_node, &child_indent, slot_name.as_deref())?;
264        if child_node.is_element() || child_node.is_decorator() {
265            let mut descendant_indent = indent.to_vec();
266            descendant_indent.push(if is_last {
267                ANCESTOR_IS_LAST_CHILD
268            } else {
269                ANCESTOR_HAS_NEXT_SIBLING
270            });
271            visit_tree(child_node, &descendant_indent, visitor)?;
272        }
273    }
274    Ok(())
275}
276
277/// `normalize(text, obfuscateText)`: tabs and newlines as escapes, and with
278/// `obfuscate_text` every other code unit that isn't whitespace as `*`.
279fn normalize(text: &str, obfuscate_text: bool) -> String {
280    let mut text_to_print = text.to_owned();
281    for (key, value) in NON_SINGLE_WIDTH_CHARS_REPLACEMENT {
282        text_to_print = text_to_print.replace(key, value);
283    }
284    if obfuscate_text {
285        // `/[^\s]/g` without `u` replaces each UTF-16 code unit.
286        return text_to_print
287            .chars()
288            .flat_map(|c| {
289                let n = if is_js_whitespace(c) {
290                    0
291                } else {
292                    c.len_utf16()
293                };
294                std::iter::repeat_n('*', n).chain((n == 0).then_some(c))
295            })
296            .collect();
297    }
298    text_to_print
299}
300
301/// `[title, properties].filter(Boolean).join(' ').trim()` with the
302/// properties in braces.
303fn title_and_properties(title: String, properties: &str) -> String {
304    let joined = if properties.is_empty() {
305        title
306    } else {
307        format!("{title} {{ {properties} }}")
308    };
309    joined.trim_matches(is_js_whitespace).to_owned()
310}
311
312/// `printNode(node, customPrintNode, obfuscateText)`.
313fn print_node(
314    node: &NodeRef,
315    custom_print_node: Option<CustomPrintNodeFn<'_>>,
316    obfuscate_text: bool,
317) -> String {
318    if let Some(custom_print) = custom_print_node
319        .and_then(|custom| custom(node, obfuscate_text))
320        .filter(|custom| !custom.is_empty())
321    {
322        return custom_print;
323    }
324
325    if node.is_text() {
326        let text = node.get_text_content();
327        let title = if text.is_empty() {
328            "(empty)".to_owned()
329        } else {
330            format!("\"{}\"", normalize(&text, obfuscate_text))
331        };
332        return title_and_properties(title, &print_all_text_node_properties(node));
333    }
334    #[cfg(feature = "link")]
335    if crate::link::is_link_node(node) {
336        let link = node.get_url().unwrap_or_default();
337        let title = if link.is_empty() {
338            "(empty)".to_owned()
339        } else {
340            format!("\"{}\"", normalize(&link, obfuscate_text))
341        };
342        return title_and_properties(title, &print_all_link_node_properties(node));
343    }
344    #[cfg(feature = "mark")]
345    if let Some(ids) = node.get_ids() {
346        return format!("ids: [ {} ]", ids.join(", "));
347    }
348    let latest = node.get_latest();
349    if latest.is::<ParagraphNode>() {
350        let element = latest.element().expect("a paragraph is an element");
351        let format_text = print_format_properties(|format| {
352            let flag = lookup(TEXT_TYPE_TO_FORMAT, format).unwrap_or(0);
353            to_int32(element.get_text_format()) & flag != 0
354        });
355        let mut paragraph_data = if format_text.is_empty() {
356            String::new()
357        } else {
358            format!("{{ {format_text} }}")
359        };
360        if !element.get_style().is_empty() {
361            paragraph_data.push_str(&format!("({})", element.get_style()));
362        }
363        return paragraph_data;
364    }
365    String::new()
366}
367
368/// `printAllTextNodeProperties(node)`.
369fn print_all_text_node_properties(node: &NodeRef) -> String {
370    [
371        print_format_properties(|format| node.has_format(format)),
372        print_detail_properties(node),
373        print_mode_properties(node),
374        print_state_properties(node),
375    ]
376    .into_iter()
377    .filter(|s| !s.is_empty())
378    .collect::<Vec<_>>()
379    .join(", ")
380}
381
382/// `printAllLinkNodeProperties(node)`, with `printTargetProperties`,
383/// `printRelProperties` and `printTitleProperties` (a `null` property is
384/// left out; an empty one is printed).
385#[cfg(feature = "link")]
386fn print_all_link_node_properties(node: &NodeRef) -> String {
387    [
388        node.get_target().map(|s| format!("target: {s}")),
389        node.get_rel().map(|s| format!("rel: {s}")),
390        node.get_title().map(|s| format!("title: {s}")),
391        Some(print_state_properties(node)),
392    ]
393    .into_iter()
394    .flatten()
395    .filter(|s| !s.is_empty())
396    .collect::<Vec<_>>()
397    .join(", ")
398}
399
400/// `predicates.map(...).filter(Boolean).join(', ').toLocaleLowerCase()`
401/// with `label: ` before it when not empty.
402fn print_properties(label: &str, names: &[&str]) -> String {
403    if names.is_empty() {
404        return String::new();
405    }
406    format!("{label}: {}", names.join(", ").to_lowercase())
407}
408
409/// `printDetailProperties(node)`.
410fn print_detail_properties(node: &NodeRef) -> String {
411    let detail = to_int32(node.text_data().get_detail());
412    let mut names = Vec::new();
413    if detail & IS_DIRECTIONLESS != 0 {
414        names.push("Directionless");
415    }
416    if node.is_unmergeable() {
417        names.push("Unmergeable");
418    }
419    print_properties("detail", &names)
420}
421
422/// `printModeProperties(node)`.
423fn print_mode_properties(node: &NodeRef) -> String {
424    let mut names = Vec::new();
425    if node.is_token() {
426        names.push("Token");
427    }
428    if node.is_segmented() {
429        names.push("Segmented");
430    }
431    print_properties("mode", &names)
432}
433
434/// `printFormatProperties(nodeOrSelection)` and
435/// `printTextFormatProperties(paragraph)`, by what `hasFormat` or
436/// `hasTextFormat` answers.
437fn print_format_properties(has_format: impl Fn(&str) -> bool) -> String {
438    let names: Vec<&str> = FORMATS
439        .iter()
440        .filter(|(format, _)| has_format(format))
441        .map(|(_, name)| *name)
442        .collect();
443    print_properties("format", &names)
444}
445
446/// `printStateProperties(node)`: the node's known NodeState values that
447/// aren't their default, as `JSON.stringify` writes their `unparse`.
448fn print_state_properties(node: &NodeRef) -> String {
449    let Some(state) = node.get_latest().base().state.clone() else {
450        return String::new();
451    };
452    let states: Vec<String> = state
453        .borrow()
454        .known_entries()
455        .iter()
456        .filter(|(config, value)| !is_default(config, value))
457        .map(|(config, value)| {
458            let unparsed = unparse(config, value);
459            let text_value = if unparsed.is_undefined() {
460                "undefined".to_owned()
461            } else {
462                unparsed.to_string()
463            };
464            format!("[{}: {text_value}]", config.key())
465        })
466        .collect();
467    let joined = states.join(",");
468    if joined.is_empty() {
469        return joined;
470    }
471    format!("state: {joined}")
472}
473
474/// `$printSelectedCharsLine(...)`: under a selected text node, a line with
475/// `^` under its selected characters, or nothing.
476fn print_selected_chars_line(
477    indent: &[&str],
478    is_selected: bool,
479    node: &NodeRef,
480    node_key_display: &str,
481    selection: Option<&SelectionRef>,
482    type_display: &str,
483) -> Result<String, LexicalError> {
484    // No selection or node is not selected.
485    let Some(range) = selection.and_then(SelectionRef::range) else {
486        return Ok(String::new());
487    };
488    if !node.is_text() || !is_selected || node.is_element() {
489        return Ok(String::new());
490    }
491
492    // No selected characters.
493    let anchor = &range.anchor;
494    let focus = &range.focus;
495
496    if node.get_text_content().is_empty()
497        || (anchor.key == focus.key && anchor.offset == focus.offset)
498    {
499        return Ok(String::new());
500    }
501
502    let (start, end) = get_selection_start_end(node, anchor, focus)?;
503
504    if start == end {
505        return Ok(String::new());
506    }
507
508    let selection_last_indent = if indent.last() == Some(&HAS_NEXT_SIBLING) {
509        ANCESTOR_HAS_NEXT_SIBLING
510    } else {
511        ANCESTOR_IS_LAST_CHILD
512    };
513
514    let mut indention_chars = indent[..indent.len().saturating_sub(1)].to_vec();
515    indention_chars.push(selection_last_indent);
516    // `Array(n)` throws for a negative length.
517    let (Ok(unselected), Ok(selected)) = (usize::try_from(start + 1), usize::try_from(end - start))
518    else {
519        return Err(LexicalError::new("Invalid array length"));
520    };
521    // 1 for the space after + 1 for the double quote.
522    let padding_length = utf16::len(type_display) + 2;
523    let node_print_spaces = utf16::len(node_key_display) + padding_length;
524
525    Ok(format!(
526        "{SELECTED_LINE} {} {}{}\n",
527        indention_chars.join(" "),
528        " ".repeat(node_print_spaces + unselected),
529        SELECTED_CHAR.repeat(selected),
530    ))
531}
532
533/// `printPrettyHTML(str)`: the HTML parsed into a `div` (trimmed), with
534/// each element on a line of its own, indented two spaces a level
535/// (`prettifyHTML`), as the `div`'s `innerHTML`.
536#[cfg(feature = "html")]
537fn print_pretty_html(str: &str) -> String {
538    let document = crate::dom::parse_from_string(&format!(
539        "<div>{}</div>",
540        str.trim_matches(is_js_whitespace)
541    ));
542    let Some(div) = document
543        .body()
544        .and_then(|body| body.children().into_iter().next())
545    else {
546        return String::new();
547    };
548    prettify_html(&div, 0, &document);
549    div.inner_html()
550}
551
552/// `prettifyHTML(node, level)`: a newline and the level's indent before
553/// each child element, and after the last one the parent's.
554#[cfg(feature = "html")]
555fn prettify_html(node: &crate::dom::DomNode, level: usize, document: &crate::dom::DomNode) {
556    let indent_before = "  ".repeat(level);
557    let indent_after = "  ".repeat(level.saturating_sub(1));
558    let children = node.children();
559    for (i, child) in children.iter().enumerate() {
560        node.insert_before(
561            &document.create_text_node(&format!("\n{indent_before}")),
562            Some(child),
563        );
564        prettify_html(child, level + 1, document);
565        if i + 1 == children.len() {
566            node.append_child(&document.create_text_node(&format!("\n{indent_after}")));
567        }
568    }
569}
570
571/// `String#slice(start, end)` on UTF-16 code units: clamped, and a negative
572/// index counts from the end.
573fn js_slice(units: &[u16], start: i64, end: i64) -> &[u16] {
574    let n = units.len() as i64;
575    let clamp = |i: i64| (if i < 0 { (n + i).max(0) } else { i.min(n) }) as usize;
576    let (a, b) = (clamp(start), clamp(end));
577    if a < b { &units[a..b] } else { &[] }
578}
579
580/// `$getSelectionStartEnd(node, selection)`: the selected UTF-16 range of
581/// `node`'s text, in printed characters (a tab or newline prints as two).
582fn get_selection_start_end(
583    node: &NodeRef,
584    anchor: &crate::Point,
585    focus: &crate::Point,
586) -> Result<(i64, i64), LexicalError> {
587    let text_content = node.get_text_content();
588    let units: Vec<u16> = text_content.encode_utf16().collect();
589    let text_length = units.len() as i64;
590
591    let mut start = -1;
592    let mut end = -1;
593
594    // Only one node is being selected.
595    if anchor.point_type == PointType::Text && focus.point_type == PointType::Text {
596        let anchor_node = anchor.get_node()?;
597        let focus_node = focus.get_node()?;
598        let (anchor_offset, focus_offset) = (anchor.offset as i64, focus.offset as i64);
599
600        if anchor_node == focus_node && node == &anchor_node && anchor_offset != focus_offset {
601            (start, end) = if anchor_offset < focus_offset {
602                (anchor_offset, focus_offset)
603            } else {
604                (focus_offset, anchor_offset)
605            };
606        } else if node == &anchor_node {
607            (start, end) = if anchor_node.is_before(&focus_node) {
608                (anchor_offset, text_length)
609            } else {
610                (0, anchor_offset)
611            };
612        } else if node == &focus_node {
613            (start, end) = if focus_node.is_before(&anchor_node) {
614                (focus_offset, text_length)
615            } else {
616                (0, focus_offset)
617            };
618        } else {
619            // Node is within selection but not the anchor nor focus.
620            (start, end) = (0, text_length);
621        }
622    }
623
624    // Account for non-single width characters.
625    let is_wide = |unit: &&u16| {
626        NON_SINGLE_WIDTH_CHARS_REPLACEMENT
627            .iter()
628            .any(|(c, _)| u32::from(**unit) == u32::from(*c))
629    };
630    let before = js_slice(&units, 0, start).iter().filter(is_wide).count() as i64;
631    let inside = js_slice(&units, start, end).iter().filter(is_wide).count() as i64;
632
633    Ok((start + before, end + before + inside))
634}