1use crate::json::{Object, Value};
23use crate::lexical_utils::with_writable;
24use crate::node::{LexicalNode, NodeRef};
25use crate::schema::{NodeSchema, enum_value, node_schema, with_accessors};
26use std::rc::Rc;
27
28const FORMATS: [&str; 7] = ["", "left", "start", "center", "right", "end", "justify"];
31
32#[derive(Clone, Debug, Default, PartialEq, Eq)]
35pub struct DecoratorBlockData {
36 format: &'static str,
37}
38
39impl DecoratorBlockData {
40 pub fn new(format: &str) -> Self {
43 DecoratorBlockData {
44 format: parse_format(format),
45 }
46 }
47
48 pub fn format(&self) -> &'static str {
50 self.format
51 }
52}
53
54fn parse_format(format: &str) -> &'static str {
56 FORMATS.into_iter().find(|f| *f == format).unwrap_or("")
57}
58
59thread_local! {
60 static DECORATOR_BLOCK_NODE_SCHEMA: NodeSchema = node_schema(vec![(
61 "format",
62 with_accessors(
63 enum_value(FORMATS.map(Value::from).to_vec(), None).expect("the formats"),
64 Some(Rc::new(|node| {
65 node.decorator_block()
66 .expect("a DecoratorBlockNode")
67 .format
68 .into()
69 })),
70 Some(Rc::new(|node, value| {
71 node.decorator_block_mut()
72 .expect("a DecoratorBlockNode")
73 .format = value.as_str().map_or("", parse_format);
74 })),
75 )
76 .expect("a field"),
77 )])
78 .expect("DecoratorBlockNode's schema");
79}
80
81pub fn decorator_block_node_schema() -> NodeSchema {
85 DECORATOR_BLOCK_NODE_SCHEMA.with(Clone::clone)
86}
87
88pub fn export_decorator_block(node: &dyn LexicalNode, compact: bool) -> Object {
94 let format = node.decorator_block().expect("a DecoratorBlockNode").format;
95 let mut json = Object::new();
96 if compact {
97 json.insert("type", node.get_type().into());
98 if !format.is_empty() {
99 json.insert("format", format.into());
100 }
101 } else {
102 json.insert("format", format.into());
103 json.insert("type", node.get_type().into());
104 json.insert("version", 1.0.into());
105 }
106 json
107}
108
109pub fn update_decorator_block_from_json(data: &mut DecoratorBlockData, json: &Object) {
112 data.format = json
113 .get("format")
114 .and_then(Value::as_str)
115 .map_or("", parse_format);
116}
117
118pub fn is_decorator_block_node(node: &NodeRef) -> bool {
121 node.get_latest().decorator_block().is_some()
122}
123
124impl NodeRef {
125 pub fn get_decorator_block_format(&self) -> Option<&'static str> {
127 self.get_latest().decorator_block().map(|d| d.format)
128 }
129
130 pub fn set_decorator_block_format(&self, format: &str) {
133 if is_decorator_block_node(self) {
134 let format = parse_format(format);
135 with_writable(self.get_key(), |n| {
136 n.decorator_block_mut()
137 .expect("a DecoratorBlockNode")
138 .format = format;
139 });
140 }
141 }
142}
143
144#[cfg(feature = "extension")]
145pub use block_with_alignable_contents::{
146 BlockWithAlignableContentsExtensionType, block_with_alignable_contents_extension,
147};
148
149#[cfg(feature = "extension")]
152mod block_with_alignable_contents {
153 use super::is_decorator_block_node;
154 use crate::extension_core::{LexicalExtension, define_extension};
155 use crate::node::NodeRef;
156 use crate::utils::get_nearest_block_element_ancestor_or_throw;
157 use crate::{
158 CLICK_COMMAND, COMMAND_PRIORITY_LOW, FORMAT_ELEMENT_COMMAND, create_node_selection,
159 get_node_by_key, get_selection, merge_register, set_selection,
160 };
161 use std::rc::Rc;
162
163 pub type BlockWithAlignableContentsExtensionType = LexicalExtension;
165
166 fn make() -> Rc<BlockWithAlignableContentsExtensionType> {
167 define_extension(LexicalExtension {
168 register: Some(Rc::new(|editor, _, _| {
169 Ok(merge_register(vec![
170 editor.register_command(
171 &FORMAT_ELEMENT_COMMAND,
172 |format, _| {
173 let Some(selection) = get_selection() else {
174 return Ok(false);
175 };
176 let nodes = selection.get_nodes()?;
177 let mut selected = Vec::new();
178 for node in nodes.iter().filter(|n| is_decorator_block_node(n)) {
179 if node.is_selected(None)? {
180 selected.push(node.clone());
181 }
182 }
183 if selected.is_empty() {
184 return Ok(false);
185 }
186 if selection.is_node() {
187 for block in &selected {
188 block.set_decorator_block_format(format);
189 }
190 } else if selection.is_range() {
191 for node in &nodes {
192 if is_decorator_block_node(node) {
193 node.set_decorator_block_format(format);
194 } else {
195 get_nearest_block_element_ancestor_or_throw(node)?
196 .set_element_format(format);
197 }
198 }
199 }
200 Ok(true)
201 },
202 COMMAND_PRIORITY_LOW,
203 ),
204 editor.register_command(
205 &CLICK_COMMAND,
206 |event, _| {
207 let Some(block) = event
208 .target_key
209 .as_deref()
210 .and_then(get_node_by_key)
211 .filter(is_decorator_block_node)
212 else {
213 return Ok(false);
214 };
215 event.prevent_default();
216 let is_selected = block.is_selected(None)?;
218 let selection = match get_selection().filter(|s| s.is_node()) {
219 Some(current) => {
220 if !event.shift_key {
221 current.clear();
222 }
223 current
224 }
225 None => {
226 let selection = create_node_selection();
231 set_selection(Some(selection.clone()));
232 selection
233 }
234 };
235 let key = NodeRef::get_key(&block);
236 if is_selected {
237 selection.delete(key);
238 } else {
239 selection.add(key);
240 }
241 Ok(true)
242 },
243 COMMAND_PRIORITY_LOW,
244 ),
245 ]))
246 })),
247 ..LexicalExtension::new("@lexical/react/BlockWithAlignableContents", ())
248 })
249 }
250
251 thread_local! {
252 static BLOCK_WITH_ALIGNABLE_CONTENTS_EXTENSION:
253 Rc<BlockWithAlignableContentsExtensionType> = make();
254 }
255
256 pub fn block_with_alignable_contents_extension() -> Rc<BlockWithAlignableContentsExtensionType>
272 {
273 BLOCK_WITH_ALIGNABLE_CONTENTS_EXTENSION.with(Rc::clone)
274 }
275}
276
277#[cfg(all(test, feature = "extension", feature = "rich-text"))]
278mod tests {
279 use super::*;
280 use crate::extension::build_editor_from_extensions;
281 use crate::extension_core::{LexicalExtension, define_extension};
282 use crate::node::NodeBase;
283 use crate::{
284 CLICK_COMMAND, Editor, FORMAT_ELEMENT_COMMAND, MouseEvent, NodeClass, PointType,
285 UpdateOptions, Which, create, create_node_selection, create_paragraph_node,
286 create_range_selection, create_text_node, get_root, get_selection, set_selection,
287 };
288
289 #[derive(Clone, Debug, Default)]
291 struct EmbedNode {
292 base: NodeBase,
293 block: DecoratorBlockData,
294 }
295
296 impl LexicalNode for EmbedNode {
297 fn get_type(&self) -> &'static str {
298 "embed"
299 }
300 fn base(&self) -> &NodeBase {
301 &self.base
302 }
303 fn base_mut(&mut self) -> &mut NodeBase {
304 &mut self.base
305 }
306 fn decorator_block(&self) -> Option<&DecoratorBlockData> {
307 Some(&self.block)
308 }
309 fn decorator_block_mut(&mut self) -> Option<&mut DecoratorBlockData> {
310 Some(&mut self.block)
311 }
312 fn generated_export_json(&self, compact: bool) -> Option<Object> {
313 Some(export_decorator_block(self, compact))
314 }
315 fn generated_update_from_json(&mut self, json: &Object) -> bool {
316 update_decorator_block_from_json(&mut self.block, json);
317 true
318 }
319 }
320
321 type Keys = Vec<String>;
323
324 fn editor() -> crate::extension::LexicalEditorWithDispose {
325 build_editor_from_extensions([
326 crate::rich_text::rich_text_extension().into(),
327 block_with_alignable_contents_extension().into(),
328 define_extension(LexicalExtension {
329 nodes: vec![NodeClass::of::<EmbedNode>()],
330 ..LexicalExtension::<(), (), ()>::new("embed", ())
331 })
332 .into(),
333 ])
334 .unwrap()
335 }
336
337 fn update(editor: &Editor, f: impl FnOnce() + 'static) {
338 editor
339 .update(
340 move || {
341 f();
342 Ok(())
343 },
344 UpdateOptions {
345 discrete: true,
346 ..UpdateOptions::default()
347 },
348 )
349 .unwrap();
350 }
351
352 fn reset(editor: &Editor, select: impl FnOnce(&Keys) + 'static) -> Keys {
355 let keys = Rc::new(std::cell::RefCell::new(Vec::new()));
356 let out = keys.clone();
357 update(editor, move || {
358 let (e1, e2) = (create::<EmbedNode>(), create::<EmbedNode>());
359 let (t1, t2) = (create_text_node("ab"), create_text_node("cd"));
360 let p1 = create_paragraph_node();
361 p1.append(std::slice::from_ref(&t1)).unwrap();
362 let p2 = create_paragraph_node();
363 p2.append(std::slice::from_ref(&t2)).unwrap();
364 let root = get_root();
365 root.clear().unwrap();
366 root.append(&[p1.clone(), e1.clone(), p2.clone(), e2.clone()])
367 .unwrap();
368 *out.borrow_mut() = [&p1, &e1, &p2, &e2, &t1, &t2]
369 .iter()
370 .map(|n| n.get_key().to_owned())
371 .collect();
372 });
373 let keys = keys.borrow().clone();
374 let selected = keys.clone();
375 update(editor, move || select(&selected));
376 keys
377 }
378
379 fn select_range(keys: &Keys, anchor: (usize, usize), focus: (usize, usize)) {
380 let selection = create_range_selection();
381 for (which, (i, offset)) in [(Which::Anchor, anchor), (Which::Focus, focus)] {
382 selection
383 .point_set(which, &keys[i], offset, PointType::Text)
384 .unwrap();
385 }
386 set_selection(Some(selection));
387 }
388
389 fn snapshot(editor: &Editor, keys: &Keys) -> (Vec<&'static str>, String) {
392 let keys = keys.clone();
393 editor
394 .read(move || {
395 let formats = get_root()
396 .get_children()
397 .iter()
398 .map(|n| {
399 n.get_decorator_block_format().unwrap_or_else(|| {
400 n.get_latest().element().expect("a block").get_format_type()
401 })
402 })
403 .collect();
404 let selection = match get_selection() {
405 None => "none".to_owned(),
406 Some(s) if s.is_node() => {
407 let nodes = s.get_nodes().unwrap();
408 let names: Vec<String> = nodes
409 .iter()
410 .map(|n| {
411 let i = keys.iter().position(|k| k == n.get_key()).unwrap();
412 ["p1", "e1", "p2", "e2"][i].to_owned()
413 })
414 .collect();
415 format!("node {}", names.join(","))
416 }
417 Some(_) => "range".to_owned(),
418 };
419 (formats, selection)
420 })
421 .unwrap()
422 }
423
424 fn format(editor: &Editor, format: &str) -> bool {
425 editor
426 .dispatch_command(&FORMAT_ELEMENT_COMMAND, format.to_owned())
427 .unwrap()
428 }
429
430 fn click(editor: &Editor, key: &str, shift_key: bool) {
431 let event = MouseEvent {
432 target_key: Some(key.to_owned()),
433 shift_key,
434 ..MouseEvent::default()
435 };
436 editor
437 .dispatch_command(&CLICK_COMMAND, Rc::new(event))
438 .unwrap();
439 }
440
441 #[test]
447 fn format_element_command_aligns_selected_blocks() {
448 let editor = editor();
449 let keys = reset(&editor, |keys| {
451 let selection = create_node_selection();
452 selection.add(&keys[1]);
453 set_selection(Some(selection));
454 });
455 assert!(format(&editor, "center"));
456 assert_eq!(
457 snapshot(&editor, &keys),
458 (vec!["", "center", "", ""], "node e1".to_owned())
459 );
460 let keys = reset(&editor, |keys| select_range(keys, (4, 1), (5, 1)));
462 assert!(format(&editor, "right"));
463 assert_eq!(
464 snapshot(&editor, &keys),
465 (vec!["right", "right", "right", ""], "range".to_owned())
466 );
467 let keys = reset(&editor, |keys| select_range(keys, (4, 0), (4, 2)));
469 assert!(format(&editor, "justify"));
470 assert_eq!(
471 snapshot(&editor, &keys),
472 (vec!["justify", "", "", ""], "range".to_owned())
473 );
474 }
475
476 #[test]
477 fn click_command_toggles_a_block() {
478 let editor = editor();
479 let keys = reset(&editor, |_| set_selection(None));
480 let (e1, e2) = (keys[1].clone(), keys[3].clone());
481 let steps: [(&str, bool, &str); 6] = [
482 (&e1, false, "node e1"),
483 (&e2, true, "node e1,e2"),
484 (&e1, true, "node e2"),
485 (&e2, false, "none"),
488 (&e1, false, "node e1"),
489 (&e2, false, "node e2"),
490 ];
491 for (key, shift, expected) in steps {
492 click(&editor, key, shift);
493 assert_eq!(snapshot(&editor, &keys).1, expected, "click {key} {shift}");
494 }
495 let keys = reset(&editor, |keys| select_range(keys, (4, 1), (5, 1)));
497 click(&editor, &keys[1], false);
498 assert_eq!(snapshot(&editor, &keys).1, "none");
499 let keys = reset(&editor, |keys| select_range(keys, (4, 1), (4, 1)));
501 click(&editor, &keys[1], false);
502 assert_eq!(snapshot(&editor, &keys).1, "node e1");
503 let keys = reset(&editor, |keys| select_range(keys, (4, 1), (5, 1)));
505 click(&editor, &keys[1], true);
506 assert_eq!(snapshot(&editor, &keys).1, "none");
507 }
508}