1use 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
18pub type CustomPrintNodeFn<'a> = &'a dyn Fn(&NodeRef, bool) -> Option<String>;
22
23#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct LexicalCommandLogEntry {
29 pub index: usize,
30 pub command_type: String,
31 pub payload: String,
32}
33
34const NON_SINGLE_WIDTH_CHARS_REPLACEMENT: [(char, &str); 2] = [('\t', "\\t"), ('\n', "\\n")];
36
37const 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
45const 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
58pub 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
148fn 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
184fn 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(¤t)
190 && let Some(host) = get_slot_host(¤t)
191 {
192 return Some((slot_name, host));
193 }
194 cursor = current.get_parent().or_else(|| get_slot_host(¤t));
195 }
196 None
197}
198
199fn 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#[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
225fn print_node_selection(selection: &SelectionRef) -> String {
227 format!(": node\n └ [{}]", selection.node_keys().join(", "))
228}
229
230type Visitor<'a> =
233 dyn FnMut(&NodeRef, &[&'static str], Option<&str>) -> Result<(), LexicalError> + 'a;
234
235fn 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
277fn 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 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
301fn 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
312fn 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
368fn 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#[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
400fn 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
409fn 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
422fn 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
434fn 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
446fn 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
474fn 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 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 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 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 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#[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#[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
571fn 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
580fn 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 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 (start, end) = (0, text_length);
621 }
622 }
623
624 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}