Skip to main content

lexical_ui/code/
code_highlight_node.rs

1//! `CodeHighlightNode.ts`: `CodeHighlightNode`, `$createCodeHighlightNode`
2//! and `$isCodeHighlightNode`.
3
4use super::code_node::create_code_node;
5use super::generated_json::{
6    export_code_highlight_node, export_compact_code_highlight_node, update_code_highlight_node,
7};
8use crate::json::Object;
9use crate::json::Value;
10use crate::lexical_utils::{set_node_key, with_writable};
11use crate::node::{LexicalNode, NodeBase, NodeRef};
12use crate::nodes::text::TextData;
13use crate::schema::{
14    NodeSchema, node_schema, nullable, optional, schema_getter, schema_setter, string_value,
15    with_accessors,
16};
17use std::rc::Rc;
18
19/// `CodeHighlightNode`: a text node in a [`CodeNode`](super::CodeNode), with
20/// the token type a highlighter gave it. It takes no format.
21#[derive(Clone, Debug, Default)]
22pub struct CodeHighlightNode {
23    base: NodeBase,
24    pub(super) text: TextData,
25    /// `__highlightType`: `None` where JS's is `undefined`. JS's constructor
26    /// also keeps a `null` it is given; `setHighlightType` and the JSON
27    /// never make one, and here there is none.
28    pub(super) highlight_type: Option<String>,
29}
30
31impl CodeHighlightNode {
32    /// `__highlightType`.
33    pub fn highlight_type(&self) -> Option<&str> {
34        self.highlight_type.as_deref()
35    }
36}
37
38/// `$createCodeHighlightNode(text, highlightType)`: the highlight type as
39/// given, an empty one included (only `setHighlightType` drops it).
40pub fn create_code_highlight_node(text: &str, highlight_type: Option<&str>) -> NodeRef {
41    crate::lexical_utils::replaced(set_node_key(Box::new(CodeHighlightNode {
42        base: NodeBase::default(),
43        text: TextData {
44            text: text.to_owned(),
45            ..TextData::default()
46        },
47        highlight_type: highlight_type.map(str::to_owned),
48    })))
49}
50
51/// `$isCodeHighlightNode(node)`: `instanceof CodeHighlightNode`, so a
52/// class that extends it ([`LexicalNode::super_types`]) is one too.
53pub fn is_code_highlight_node(node: &NodeRef) -> bool {
54    let latest = node.get_latest();
55    latest.is::<CodeHighlightNode>() || latest.super_types().contains(&"code-highlight")
56}
57
58impl NodeRef {
59    /// `CodeHighlightNode.getHighlightType()`; `None` when it is
60    /// `undefined`, or for any other node (a class that extends it keeps no
61    /// highlight type of its own here).
62    pub fn get_highlight_type(&self) -> Option<String> {
63        self.get_latest()
64            .downcast_ref::<CodeHighlightNode>()
65            .and_then(|n| n.highlight_type.clone())
66    }
67
68    /// `CodeHighlightNode.setHighlightType(highlightType)`: an empty one is
69    /// `undefined`. Does nothing to any other node.
70    pub fn set_highlight_type(&self, highlight_type: Option<&str>) {
71        if self.get_latest().is::<CodeHighlightNode>() {
72            with_writable(self.get_key(), |n| {
73                n.downcast_mut::<CodeHighlightNode>()
74                    .expect("a code highlight node")
75                    .highlight_type = highlight_type.filter(|t| !t.is_empty()).map(str::to_owned);
76            });
77        }
78    }
79}
80
81thread_local! {
82    static CODE_HIGHLIGHT_NODE_SCHEMA: NodeSchema = node_schema(vec![(
83        "highlightType",
84        with_accessors(
85            optional(
86                nullable(string_value(""), false).expect("a nullable string"),
87                false,
88            )
89            .expect("an optional string"),
90            Some(schema_getter(|n: &CodeHighlightNode| {
91                n.highlight_type
92                    .as_deref()
93                    .map_or(Value::Undefined, Value::from)
94            })),
95            Some(schema_setter(|n: &mut CodeHighlightNode, value| {
96                n.highlight_type = super::code_node::truthy_value(&value);
97            })),
98        )
99        .expect("a field"),
100    )])
101    .expect("CodeHighlightNode's schema");
102}
103
104/// `codeHighlightNodeSchema`: `highlightType`, read straight off the field
105/// and applied through `setHighlightType`, which keeps only a non-empty
106/// string.
107pub fn code_highlight_node_schema() -> NodeSchema {
108    CODE_HIGHLIGHT_NODE_SCHEMA.with(Clone::clone)
109}
110
111impl LexicalNode for CodeHighlightNode {
112    /// Its own schema, then TextNode's as this class resolves it: it
113    /// overrides `setFormat` (a highlight's format is its theme's), so the
114    /// `format` the JSON carries is applied through that, which keeps the
115    /// node's.
116    fn json_schema_chain(&self) -> Vec<NodeSchema> {
117        vec![
118            code_highlight_node_schema(),
119            crate::nodes::text::text_node_schema().with_setter("format", Rc::new(|_, _| {})),
120        ]
121    }
122    fn get_type(&self) -> &'static str {
123        "code-highlight"
124    }
125    /// `CodeHighlightNode.createDOM(config)`: `TextNode`'s, with the
126    /// theme's `codeHighlight[highlightType]` class names.
127    #[cfg(feature = "html")]
128    fn create_dom(
129        &self,
130        _this: &NodeRef,
131        config: &crate::EditorConfig,
132        _editor: &crate::Editor,
133    ) -> Result<crate::dom::DomNode, crate::LexicalError> {
134        let element = crate::nodes::text::create_dom(self, config)?;
135        if let (Some(highlight_type), Some(crate::json::Value::Object(code_highlight))) = (
136            self.highlight_type.as_deref().filter(|t| !t.is_empty()),
137            config.theme.get("codeHighlight"),
138        ) {
139            crate::lexical_dom::add_theme_class_names(&element, code_highlight, highlight_type);
140        }
141        Ok(element)
142    }
143    fn base(&self) -> &NodeBase {
144        &self.base
145    }
146    fn base_mut(&mut self) -> &mut NodeBase {
147        &mut self.base
148    }
149    fn text(&self) -> Option<&TextData> {
150        Some(&self.text)
151    }
152    fn text_mut(&mut self) -> Option<&mut TextData> {
153        Some(&mut self.text)
154    }
155
156    /// `CodeHighlightNode.setFormat(format)`: does nothing (no bold,
157    /// underline...), and doesn't make the node writable.
158    fn set_format(&self, _: &NodeRef, _: f64) {}
159
160    /// `CodeHighlightNode.canHaveFormat()`.
161    fn can_have_format(&self) -> bool {
162        false
163    }
164
165    /// `CodeHighlightNode.isParentRequired()`.
166    fn is_parent_required(&self) -> bool {
167        true
168    }
169
170    /// `CodeHighlightNode.createParentElementNode()`: a code block with no
171    /// language.
172    fn create_parent_element_node(&self) -> NodeRef {
173        create_code_node(None, None)
174    }
175
176    /// `exportCodeHighlightNode` and `exportCompactCodeHighlightNode`.
177    fn generated_export_json(&self, compact: bool) -> Option<Object> {
178        Some(if compact {
179            export_compact_code_highlight_node(self)
180        } else {
181            export_code_highlight_node(self)
182        })
183    }
184
185    /// `updateCodeHighlightNode`.
186    fn generated_update_from_json(&mut self, json: &Object) -> bool {
187        update_code_highlight_node(self, json);
188        true
189    }
190}