lexical_ui/mark/
mark_node.rs1use 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#[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 pub fn ids(&self) -> &[String] {
24 &self.ids
25 }
26}
27
28pub 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
36pub fn is_mark_node(node: &NodeRef) -> bool {
38 node.get_latest().is::<MarkNode>()
39}
40
41fn 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 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 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 pub fn set_ids(&self, ids: &[String]) {
67 with_ids(self, |i| *i = ids.to_vec());
68 }
69
70 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 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
105pub 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 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 #[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 fn is_inline(&self) -> bool {
168 true
169 }
170
171 fn can_be_empty(&self) -> bool {
173 false
174 }
175
176 fn can_insert_text_before(&self) -> bool {
179 false
180 }
181
182 fn can_insert_text_after(&self) -> bool {
185 false
186 }
187
188 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 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 fn exclude_from_copy(&self, destination: &str) -> bool {
236 destination != "clone"
237 }
238
239 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 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 #[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}