1use super::code_highlight_node::{create_code_highlight_node, is_code_highlight_node};
6use super::flat_structure_utils::get_first_code_node_of_line;
7use super::generated_json::{export_code_node, export_compact_code_node, update_code_node};
8use crate::LexicalError;
9use crate::json::Object;
10use crate::json::Value;
11use crate::lexical_selection::{PointType, SelectionRef, Which};
12use crate::lexical_utils::with_writable;
13use crate::node::{LexicalNode, NodeBase, NodeRef};
14use crate::nodes::element::ElementData;
15use crate::nodes::line_break::{LineBreakNode, create_line_break_node};
16use crate::nodes::paragraph::create_paragraph_node;
17use crate::nodes::tab::{TabNode, create_tab_node};
18use crate::schema::{
19 NodeSchema, node_schema, nullable, optional, schema_getter, schema_setter, string_value,
20 with_accessors,
21};
22
23pub const DEFAULT_CODE_LANGUAGE: &str = "javascript";
25
26pub fn get_default_code_language() -> &'static str {
28 DEFAULT_CODE_LANGUAGE
29}
30
31#[derive(Clone, Debug, Default)]
36pub struct CodeNode {
37 base: NodeBase,
38 pub(super) element: ElementData,
39 pub(super) language: Option<String>,
43 pub(super) theme: Option<String>,
45 pub(super) is_syntax_highlight_supported: bool,
48}
49
50impl CodeNode {
51 pub fn language(&self) -> Option<&str> {
53 self.language.as_deref()
54 }
55
56 pub fn theme(&self) -> Option<&str> {
58 self.theme.as_deref()
59 }
60
61 pub fn is_syntax_highlight_supported(&self) -> bool {
63 self.is_syntax_highlight_supported
64 }
65}
66
67fn truthy(value: Option<&str>) -> Option<String> {
69 value.filter(|v| !v.is_empty()).map(str::to_owned)
70}
71
72pub fn create_code_node(language: Option<&str>, theme: Option<&str>) -> NodeRef {
75 let node = crate::create::<CodeNode>();
76 node.set_language(language);
77 node.set_theme(theme);
78 node
79}
80
81pub fn is_code_node(node: &NodeRef) -> bool {
83 node.get_latest().is::<CodeNode>()
84}
85
86fn with_code<R>(node: &NodeRef, f: impl FnOnce(&CodeNode) -> R) -> Option<R> {
87 node.get_latest().downcast_ref::<CodeNode>().map(f)
88}
89
90fn set_code(node: &NodeRef, f: impl FnOnce(&mut CodeNode)) {
91 if is_code_node(node) {
92 with_writable(node.get_key(), |n| {
93 f(n.downcast_mut::<CodeNode>().expect("a code node"))
94 });
95 }
96}
97
98impl NodeRef {
99 pub fn get_language(&self) -> Option<String> {
102 with_code(self, |c| c.language.clone()).flatten()
103 }
104
105 pub fn set_language(&self, language: Option<&str>) {
108 set_code(self, |c| c.language = truthy(language));
109 }
110
111 pub fn get_theme(&self) -> Option<String> {
114 with_code(self, |c| c.theme.clone()).flatten()
115 }
116
117 pub fn set_theme(&self, theme: Option<&str>) {
120 set_code(self, |c| c.theme = truthy(theme));
121 }
122
123 pub fn get_is_syntax_highlight_supported(&self) -> bool {
125 with_code(self, |c| c.is_syntax_highlight_supported).unwrap_or(false)
126 }
127
128 pub fn set_is_syntax_highlight_supported(&self, is_supported: bool) {
131 set_code(self, |c| c.is_syntax_highlight_supported = is_supported);
132 }
133}
134
135fn has_code_extension() -> bool {
139 #[cfg(feature = "extension")]
140 {
141 crate::updates::get_active_editor().is_some_and(|editor| {
142 crate::extension::LexicalBuilder::maybe_from_editor(&editor)
143 .is_some_and(|builder| builder.has_extension_by_name("@lexical/code"))
144 })
145 }
146 #[cfg(not(feature = "extension"))]
147 {
148 false
149 }
150}
151
152fn insert_new_after(selection: &SelectionRef) -> Result<Option<NodeRef>, LexicalError> {
159 if !has_code_extension() {
160 crate::warnings::warn_only_once("Using CodeNode without CodeExtension is deprecated");
162 if let Some(el) = exit_code_node_on_enter(selection)? {
163 return Ok(Some(el));
164 }
165 }
166 let anchor = |s: &SelectionRef| s.point(Which::Anchor).expect("a range selection");
170 let focus = selection.point(Which::Focus).expect("a range selection");
171 let first_point = if anchor(selection).is_before(&focus)? {
172 anchor(selection)
173 } else {
174 focus
175 };
176 let first_selection_node = first_point.get_node()?;
177 if first_selection_node.is_text() {
178 let mut node = Some(get_first_code_node_of_line(&first_selection_node));
179 let mut insert_nodes = Vec::new();
180 while let Some(n) = node {
181 if n.get_latest().is::<TabNode>() {
182 insert_nodes.push(create_tab_node());
183 node = n.get_next_sibling();
184 } else if is_code_highlight_node(&n) {
185 let text = n.get_text_content();
186 let text_size = n.get_text_content_size();
187 let spaces = text.chars().take_while(|&c| c == ' ').count();
190 if spaces != 0 {
191 insert_nodes.push(create_code_highlight_node(&" ".repeat(spaces), None));
192 }
193 if spaces != text_size {
194 break;
195 }
196 node = n.get_next_sibling();
197 } else {
198 break;
199 }
200 }
201 let anchor_offset = anchor(selection).offset;
202 let Some(split) = first_selection_node
205 .split_text(&[anchor_offset as i64])?
206 .into_iter()
207 .next()
208 else {
209 return Err(LexicalError::new(
210 "Cannot read properties of undefined (reading 'getIndexWithinParent')",
211 ));
212 };
213 let x = if anchor(selection).offset == 0 { 0 } else { 1 };
215 let index = split
216 .get_index_within_parent()
217 .expect("a split text node has a parent")
218 + x;
219 let code_node = first_selection_node.get_parent_or_throw()?;
220 let mut nodes_to_insert = vec![create_line_break_node()];
221 nodes_to_insert.extend(insert_nodes.iter().cloned());
222 code_node.splice(index, 0, &nodes_to_insert)?;
223 if let Some(last) = insert_nodes.last() {
224 last.select(None, None)?;
225 } else if anchor(selection).offset == 0 {
226 split.select_previous(None, None)?;
227 } else {
228 split
229 .get_next_sibling()
230 .expect("the line break inserted after the split")
231 .select_next(Some(0), Some(0))?;
232 }
233 }
234 if is_code_node(&first_selection_node) {
235 let offset = anchor(selection).offset;
236 first_selection_node.splice(offset, 0, &[create_line_break_node()])?;
237 first_selection_node.select(Some(offset + 1), Some(offset + 1))?;
238 }
239 Ok(None)
240}
241
242thread_local! {
243 static CODE_NODE_SCHEMA: NodeSchema = build_code_node_schema().expect("CodeNode's schema");
244}
245
246pub(super) fn truthy_value(value: &Value) -> Option<String> {
250 truthy(value.as_str())
251}
252
253pub fn code_node_schema() -> NodeSchema {
256 CODE_NODE_SCHEMA.with(Clone::clone)
257}
258
259fn build_code_node_schema() -> Result<NodeSchema, LexicalError> {
260 let field = |value: &Option<String>| value.as_deref().map_or(Value::Undefined, Value::from);
261 node_schema(vec![
262 (
263 "language",
264 with_accessors(
265 optional(nullable(string_value(""), false)?, false)?,
266 Some(schema_getter(move |n: &CodeNode| field(&n.language))),
267 Some(schema_setter(|n: &mut CodeNode, value| {
268 n.language = truthy_value(&value);
269 })),
270 )?,
271 ),
272 (
273 "theme",
274 with_accessors(
275 optional(string_value(""), false)?,
276 Some(schema_getter(move |n: &CodeNode| field(&n.theme))),
277 Some(schema_setter(|n: &mut CodeNode, value| {
278 n.theme = truthy_value(&value);
279 })),
280 )?,
281 ),
282 ])
283}
284
285impl LexicalNode for CodeNode {
286 fn json_schema_chain(&self) -> Vec<NodeSchema> {
287 vec![
288 code_node_schema(),
289 crate::nodes::element::element_node_schema(),
290 ]
291 }
292 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
294 crate::structure::inline_holder_chain(self.get_type())
295 }
296
297 fn get_type(&self) -> &'static str {
298 "code"
299 }
300 #[cfg(feature = "html")]
302 fn create_dom(
303 &self,
304 _this: &NodeRef,
305 config: &crate::EditorConfig,
306 _editor: &crate::Editor,
307 ) -> Result<crate::dom::DomNode, LexicalError> {
308 Ok(code_dom::code_element(self, "code", &config.theme))
309 }
310 #[cfg(feature = "html")]
313 fn export_dom(
314 &self,
315 _this: &NodeRef,
316 editor: &crate::Editor,
317 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
318 Ok(crate::lexical_dom::DomExportOutput::element(
319 code_dom::code_element(self, "pre", &editor.config().theme),
320 ))
321 }
322 #[cfg(feature = "html")]
323 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
324 Some(code_dom::import_dom())
325 }
326 fn base(&self) -> &NodeBase {
327 &self.base
328 }
329 fn base_mut(&mut self) -> &mut NodeBase {
330 &mut self.base
331 }
332 fn element(&self) -> Option<&ElementData> {
333 Some(&self.element)
334 }
335 fn element_mut(&mut self) -> Option<&mut ElementData> {
336 Some(&mut self.element)
337 }
338
339 fn can_indent(&self) -> bool {
341 false
342 }
343
344 fn insert_new_after(
346 &self,
347 _: &NodeRef,
348 selection: &SelectionRef,
349 _: bool,
350 ) -> Result<Option<NodeRef>, LexicalError> {
351 insert_new_after(selection)
352 }
353
354 fn collapse_at_start(&self, this: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
357 let paragraph = create_paragraph_node();
358 for child in this.get_children() {
359 paragraph.append(std::slice::from_ref(&child))?;
360 }
361 this.replace(¶graph, false)?;
362 Ok(true)
363 }
364
365 fn generated_export_json(&self, compact: bool) -> Option<Object> {
367 Some(if compact {
368 export_compact_code_node(self)
369 } else {
370 export_code_node(self)
371 })
372 }
373
374 fn generated_update_from_json(&mut self, json: &Object) -> bool {
376 update_code_node(self, json);
377 true
378 }
379}
380
381pub fn exit_code_node_on_enter(selection: &SelectionRef) -> Result<Option<NodeRef>, LexicalError> {
385 let Some(range) = selection.range() else {
386 return Ok(None);
387 };
388 let anchor = &range.anchor;
389 if range.is_collapsed() && anchor.point_type == PointType::Element {
390 let code_node = anchor.get_node()?;
391 if is_code_node(&code_node) {
392 let children_size = code_node.get_children_size();
393 if children_size >= 2 && anchor.offset == children_size {
394 let last_child = code_node.get_last_child();
395 let is_line_break = |n: &Option<NodeRef>| {
396 n.as_ref()
397 .is_some_and(|n| n.get_latest().is::<LineBreakNode>())
398 };
399 if is_line_break(&last_child)
400 && is_line_break(&last_child.as_ref().and_then(NodeRef::get_previous_sibling))
401 {
402 let new_element = create_paragraph_node();
403 code_node.splice(children_size - 2, 2, &[])?;
404 code_node.insert_after(&new_element, false)?;
405 new_element.select(None, None)?;
406 return Ok(Some(new_element));
407 }
408 }
409 }
410 }
411 Ok(None)
412}
413
414#[cfg(feature = "html")]
417pub(super) mod code_dom {
418 use super::{CodeNode, create_code_node};
419 use crate::LexicalError;
420 use crate::dom::DomNode;
421 use crate::json::Object;
422 use crate::lexical_dom::{
423 DomConversion, DomConversionMap, DomConversionOutput, add_theme_class_names, closest,
424 get_document, importer,
425 };
426 use crate::set_dom_style::set_dom_style_from_css;
427 use std::rc::Rc;
428
429 const LANGUAGE_DATA_ATTRIBUTE: &str = "data-language";
431 const HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE: &str = "data-highlight-language";
433 const THEME_DATA_ATTRIBUTE: &str = "data-theme";
435
436 pub(crate) fn code_element(code: &CodeNode, tag: &str, theme: &Object) -> DomNode {
440 let element = get_document().create_element(tag);
441 add_theme_class_names(&element, theme, "code");
442 element.set_attribute("spellcheck", "false");
443 if let Some(language) = code.language() {
444 element.set_attribute(LANGUAGE_DATA_ATTRIBUTE, language);
445 if code.is_syntax_highlight_supported() {
446 element.set_attribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
447 }
448 }
449 if let Some(theme) = code.theme() {
450 element.set_attribute(THEME_DATA_ATTRIBUTE, theme);
451 }
452 let style = code.element.get_style();
453 if !style.is_empty() {
454 set_dom_style_from_css(&element.style(), style, "");
455 }
456 element
457 }
458
459 fn has_child_dom_node_tag(node: &DomNode, tag_name: &str) -> bool {
461 node.child_nodes().iter().any(|child| {
462 (child.is_element() && child.tag_name() == tag_name)
463 || has_child_dom_node_tag(child, tag_name)
464 })
465 }
466
467 pub(crate) fn import_dom() -> DomConversionMap {
470 let noop = || -> crate::lexical_dom::DomConversionFn {
471 Rc::new(|_| Ok(Some(DomConversionOutput::node(None))))
472 };
473 vec![
474 (
475 "code".to_owned(),
476 Rc::new(|node: &DomNode| {
477 let is_multi_line =
478 node.text_content().contains('\n') || has_child_dom_node_tag(node, "BR");
479 is_multi_line.then(|| DomConversion {
480 conversion: Rc::new(convert_pre_element),
481 priority: 1,
482 })
483 }),
484 ),
485 ("div".to_owned(), importer(1, convert_div_element)),
486 ("pre".to_owned(), importer(0, convert_pre_element)),
487 (
488 "table".to_owned(),
489 Rc::new(|node: &DomNode| {
490 is_git_hub_code_table(node).then(|| DomConversion {
491 conversion: Rc::new(|_| {
492 Ok(Some(DomConversionOutput::node(Some(create_code_node(
493 None, None,
494 )))))
495 }),
496 priority: 3,
497 })
498 }),
499 ),
500 (
501 "td".to_owned(),
502 Rc::new(move |node: &DomNode| {
503 let table = closest(node, "table");
504 (is_git_hub_code_cell(node)
505 || table.as_ref().is_some_and(is_git_hub_code_table))
506 .then(|| DomConversion {
507 conversion: noop(),
508 priority: 3,
509 })
510 }),
511 ),
512 (
513 "tr".to_owned(),
514 Rc::new(move |node: &DomNode| {
515 closest(node, "table")
516 .as_ref()
517 .is_some_and(is_git_hub_code_table)
518 .then(|| DomConversion {
519 conversion: noop(),
520 priority: 3,
521 })
522 }),
523 ),
524 ]
525 }
526
527 fn convert_pre_element(
530 dom_node: &DomNode,
531 ) -> Result<Option<DomConversionOutput>, LexicalError> {
532 let language = dom_node.get_attribute(LANGUAGE_DATA_ATTRIBUTE);
533 let theme = dom_node.get_attribute(THEME_DATA_ATTRIBUTE);
534 Ok(Some(DomConversionOutput::node(Some(create_code_node(
535 language.as_deref(),
536 theme.as_deref(),
537 )))))
538 }
539
540 fn convert_div_element(
543 dom_node: &DomNode,
544 ) -> Result<Option<DomConversionOutput>, LexicalError> {
545 let is_code = is_code_element(dom_node);
546 Ok(Some(DomConversionOutput::node(
547 is_code.then(|| create_code_node(None, None)),
548 )))
549 }
550
551 fn is_code_element(div: &DomNode) -> bool {
553 div.style()
554 .get_property_value("font-family")
555 .contains("monospace")
556 }
557
558 fn is_git_hub_code_cell(cell: &DomNode) -> bool {
560 cell.class_list().contains("js-file-line")
561 }
562
563 fn is_git_hub_code_table(table: &DomNode) -> bool {
565 table.class_list().contains("js-file-line-container")
566 }
567}