Skip to main content

lexical_ui/mark/
mark_node.rs

1//! `MarkNode.ts`: `MarkNode`, `$createMarkNode` and `$isMarkNode`.
2
3use super::generated_json::{export_compact_mark_node, export_mark_node, update_mark_node};
4use crate::json::Object;
5use crate::lexical_selection::SelectionRef;
6use crate::lexical_utils::{set_node_key, with_writable};
7use crate::node::{LexicalNode, NodeBase, NodeRef};
8use crate::nodes::element::ElementData;
9use crate::schema::{NodeSchema, array_value, node_schema, string_value, with_field};
10use crate::{LexicalError, utf16};
11
12/// `MarkNode`: an inline element over the content that one or more ids
13/// (comment threads, for example) annotate.
14#[derive(Clone, Debug, Default)]
15pub struct MarkNode {
16    base: NodeBase,
17    pub(super) element: ElementData,
18    pub(super) ids: Vec<String>,
19}
20
21impl MarkNode {
22    /// `__ids`.
23    pub fn ids(&self) -> &[String] {
24        &self.ids
25    }
26}
27
28/// `$createMarkNode(ids)`.
29pub fn create_mark_node(ids: &[String]) -> NodeRef {
30    crate::lexical_utils::replaced(set_node_key(Box::new(MarkNode {
31        ids: ids.to_vec(),
32        ..MarkNode::default()
33    })))
34}
35
36/// `$isMarkNode(node)`.
37pub fn is_mark_node(node: &NodeRef) -> bool {
38    node.get_latest().is::<MarkNode>()
39}
40
41/// Changes a mark's ids (`getWritable()`); does nothing to any other node.
42fn with_ids(node: &NodeRef, f: impl FnOnce(&mut Vec<String>)) {
43    if is_mark_node(node) {
44        with_writable(node.get_key(), |n| {
45            f(&mut n.downcast_mut::<MarkNode>().expect("a mark").ids)
46        });
47    }
48}
49
50impl NodeRef {
51    /// `MarkNode.hasID(id)`; false for any other node.
52    pub fn has_id(&self, id: &str) -> bool {
53        self.get_ids()
54            .is_some_and(|ids| ids.iter().any(|i| i == id))
55    }
56
57    /// `MarkNode.getIDs()`: a copy of the ids; `None` for any other node.
58    pub fn get_ids(&self) -> Option<Vec<String>> {
59        self.get_latest()
60            .downcast_ref::<MarkNode>()
61            .map(|m| m.ids.clone())
62    }
63
64    /// `MarkNode.setIDs(ids)`, as given (duplicates too). Does nothing to
65    /// any other node.
66    pub fn set_ids(&self, ids: &[String]) {
67        with_ids(self, |i| *i = ids.to_vec());
68    }
69
70    /// `MarkNode.addID(id)`: appends `id` unless the mark has it. The mark
71    /// is written either way. Does nothing to any other node.
72    pub fn add_id(&self, id: &str) {
73        with_ids(self, |ids| {
74            if !ids.iter().any(|i| i == id) {
75                ids.push(id.to_owned());
76            }
77        });
78    }
79
80    /// `MarkNode.deleteID(id)`: removes the first `id`, if any. The mark is
81    /// written either way, and stays when it has no ids left. Does nothing
82    /// to any other node.
83    pub fn delete_id(&self, id: &str) {
84        with_ids(self, |ids| {
85            if let Some(idx) = ids.iter().position(|i| i == id) {
86                ids.remove(idx);
87            }
88        });
89    }
90}
91
92thread_local! {
93    static MARK_NODE_SCHEMA: NodeSchema = node_schema(vec![(
94        "ids",
95        with_field(
96            array_value(string_value("")).expect("an array of strings"),
97            |n: &MarkNode| &n.ids,
98            |n: &mut MarkNode| &mut n.ids,
99        )
100        .expect("a field"),
101    )])
102    .expect("MarkNode's schema");
103}
104
105/// `markNodeSchema`: `ids`, read with `getIDs` (a copy of the field) and
106/// written to the field.
107pub fn mark_node_schema() -> NodeSchema {
108    MARK_NODE_SCHEMA.with(Clone::clone)
109}
110
111impl LexicalNode for MarkNode {
112    fn json_schema_chain(&self) -> Vec<NodeSchema> {
113        vec![
114            mark_node_schema(),
115            crate::nodes::element::element_node_schema(),
116        ]
117    }
118    /// The `$config()` of `MarkNode`: `inline: true`, `children: 'inline'`.
119    fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
120        use crate::structure::{NodeChildrenConfig, NodeConfigLink, StaticNodeConfig};
121        vec![NodeConfigLink::new(
122            "mark",
123            StaticNodeConfig {
124                inline: Some(true),
125                children: Some(NodeChildrenConfig::Inline),
126                ..StaticNodeConfig::default()
127            },
128        )]
129    }
130
131    fn get_type(&self) -> &'static str {
132        "mark"
133    }
134    fn base(&self) -> &NodeBase {
135        &self.base
136    }
137    fn base_mut(&mut self) -> &mut NodeBase {
138        &mut self.base
139    }
140    fn element(&self) -> Option<&ElementData> {
141        Some(&self.element)
142    }
143    fn element_mut(&mut self) -> Option<&mut ElementData> {
144        Some(&mut self.element)
145    }
146
147    /// `MarkNode.createDOM(config)`: a `<mark>` with the theme's `mark`
148    /// class names, and its `markOverlap` ones when the mark has more than
149    /// one id. (`updateDOM` is the reconciler's.)
150    #[cfg(feature = "html")]
151    fn create_dom(
152        &self,
153        _this: &NodeRef,
154        config: &crate::EditorConfig,
155        _editor: &crate::Editor,
156    ) -> Result<crate::dom::DomNode, crate::LexicalError> {
157        use crate::lexical_dom::{add_theme_class_names, get_document};
158        let element = get_document().create_element("mark");
159        add_theme_class_names(&element, &config.theme, "mark");
160        if self.ids.len() > 1 {
161            add_theme_class_names(&element, &config.theme, "markOverlap");
162        }
163        Ok(element)
164    }
165
166    /// `MarkNode.isInline()`.
167    fn is_inline(&self) -> bool {
168        true
169    }
170
171    /// `MarkNode.canBeEmpty()`: a mark left with no children is removed.
172    fn can_be_empty(&self) -> bool {
173        false
174    }
175
176    /// `MarkNode.canInsertTextBefore()`: text typed at the mark's start
177    /// goes before it.
178    fn can_insert_text_before(&self) -> bool {
179        false
180    }
181
182    /// `MarkNode.canInsertTextAfter()`: text typed at the mark's end goes
183    /// after it.
184    fn can_insert_text_after(&self) -> bool {
185        false
186    }
187
188    /// `MarkNode.insertNewAfter(selection, restoreSelection)`: a new mark
189    /// with the same ids, after it.
190    fn insert_new_after(
191        &self,
192        this: &NodeRef,
193        _: &SelectionRef,
194        restore_selection: bool,
195    ) -> Result<Option<NodeRef>, LexicalError> {
196        let mark_node = create_mark_node(&self.ids);
197        this.insert_after(&mark_node, restore_selection)?;
198        Ok(Some(mark_node))
199    }
200
201    /// `MarkNode.extractWithChild(child, selection, destination)`: a copy
202    /// (not to HTML) of a range selection whose points are both in the mark
203    /// takes the mark with it when the difference of their offsets is the
204    /// mark's text length (offsets in different nodes are compared as they
205    /// are, as in JS).
206    fn extract_with_child(
207        &self,
208        this: &NodeRef,
209        _: &NodeRef,
210        selection: Option<&SelectionRef>,
211        destination: &str,
212    ) -> Result<bool, LexicalError> {
213        let Some(selection) = selection.filter(|s| s.is_range()) else {
214            return Ok(false);
215        };
216        if destination == "html" {
217            return Ok(false);
218        }
219        let range = selection.range().expect("a range selection");
220        let anchor_node = range.anchor.get_node()?;
221        let focus_node = range.focus.get_node()?;
222        let (anchor, focus) = (range.anchor.offset as i64, range.focus.offset as i64);
223        let selection_length = if selection.is_backward()? {
224            anchor - focus
225        } else {
226            focus - anchor
227        };
228        Ok(this.is_parent_of(&anchor_node)
229            && this.is_parent_of(&focus_node)
230            && utf16::len(&this.get_text_content()) as i64 == selection_length)
231    }
232
233    /// `MarkNode.excludeFromCopy(destination)`: left out of every copy but
234    /// a clone.
235    fn exclude_from_copy(&self, destination: &str) -> bool {
236        destination != "clone"
237    }
238
239    /// `exportMarkNode` and `exportCompactMarkNode`.
240    fn generated_export_json(&self, compact: bool) -> Option<Object> {
241        Some(if compact {
242            export_compact_mark_node(self)
243        } else {
244            export_mark_node(self)
245        })
246    }
247
248    /// `updateMarkNode`.
249    fn generated_update_from_json(&mut self, json: &Object) -> bool {
250        update_mark_node(self, json);
251        true
252    }
253}
254
255#[cfg(all(test, feature = "html"))]
256mod tests {
257    use crate::json::Value;
258    use crate::{CreateEditorArgs, create_editor};
259
260    /// `createDOM`: the theme's `mark` class names, and its `markOverlap`
261    /// ones only with more than one id (as Swift's port; the HTML export
262    /// leaves marks out, so `html/export-mark` can't see them).
263    // upstream: lexical-mark/__tests__/unit/LexicalMarkNode.test.ts::MarkNode overlap theme class > createDOM adds the overlap class for more than one id
264    #[test]
265    fn create_dom_adds_the_theme_classes() {
266        let mut theme = crate::json::Object::new();
267        theme.insert("mark", Value::from("m"));
268        theme.insert("markOverlap", Value::from("o"));
269        let editor = create_editor(CreateEditorArgs {
270            nodes: super::super::mark_nodes(),
271            theme,
272            ..CreateEditorArgs::default()
273        });
274        let html = |ids: &[&str]| {
275            let ids: Vec<String> = ids.iter().map(|id| id.to_string()).collect();
276            let mark = super::MarkNode {
277                ids,
278                ..super::MarkNode::default()
279            };
280            crate::node::LexicalNode::create_dom(
281                &mark,
282                &crate::lexical_utils::get_root(),
283                editor.config(),
284                &editor,
285            )
286            .map(|dom| dom.outer_html())
287        };
288        let read_editor = editor.clone();
289        let classes = read_editor
290            .read(|| [html(&[]), html(&["a"]), html(&["a", "b"])])
291            .unwrap()
292            .map(Result::unwrap);
293        assert_eq!(
294            classes,
295            [
296                r#"<mark class="m"></mark>"#,
297                r#"<mark class="m"></mark>"#,
298                r#"<mark class="m o"></mark>"#,
299            ]
300        );
301    }
302}