Skip to main content

lexical_ui/
decorator_block.rs

1//! `@lexical/react`'s `DecoratorBlockNode` (the `decorator-block` feature),
2//! from `packages/lexical-react/src/LexicalDecoratorBlockNode.ts`: the base
3//! of block embeds (videos, tweets), a block decorator that keeps an element
4//! alignment (`format`) and is not indentable.
5//!
6//! JS's class is abstract, and an embed extends it. Here an embed is a node
7//! whose [`LexicalNode::decorator_block`] returns its [`DecoratorBlockData`],
8//! as a node that extends `ElementNode` returns its `ElementData`: the
9//! trait's defaults then make it a decorator ([`LexicalNode::is_decorator`])
10//! that is not inline and can't be indented, and [`export_decorator_block`]
11//! and [`update_decorator_block_from_json`] are its schema's JSON
12//! (`decoratorBlockNodeSchema`).
13//!
14//! With the `extension` feature, [`block_with_alignable_contents_extension`]
15//! is the alignment and selection that React's `BlockWithAlignableContents`
16//! (`LexicalBlockWithAlignableContents.tsx`) registers for each block, as
17//! Swift's `BlockWithAlignableContentsExtension` has them.
18//!
19//! Not ported: `createDOM` and `updateDOM`, which come with `html`, and the
20//! component's rendering (rust/PARITY.md).
21
22use 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
28/// The formats `decoratorBlockNodeSchema`'s `enumValue` takes, `''` (the
29/// default) first.
30const FORMATS: [&str; 7] = ["", "left", "start", "center", "right", "end", "justify"];
31
32/// The fields `DecoratorBlockNode` adds: `__format`, an
33/// `ElementFormatType`.
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
35pub struct DecoratorBlockData {
36    format: &'static str,
37}
38
39impl DecoratorBlockData {
40    /// `new DecoratorBlockNode(format)`'s fields: `format`, or `''` when it
41    /// names no format.
42    pub fn new(format: &str) -> Self {
43        DecoratorBlockData {
44            format: parse_format(format),
45        }
46    }
47
48    /// `__format`.
49    pub fn format(&self) -> &'static str {
50        self.format
51    }
52}
53
54/// `enumValue([...])`'s parse: the format, or `''` for anything else.
55fn 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
81/// `decoratorBlockNodeSchema`: the `format` field, which every node that
82/// extends `DecoratorBlockNode` composes with its own
83/// ([`LexicalNode::json_schema_chain`]'s default for one).
84pub fn decorator_block_node_schema() -> NodeSchema {
85    DECORATOR_BLOCK_NODE_SCHEMA.with(Clone::clone)
86}
87
88/// `exportJSON(compact)` of a node that extends `DecoratorBlockNode` and
89/// adds nothing to its JSON: `LexicalNode`'s (`type`, `version`) with
90/// `format`, which the compact form leaves out when it is `''`
91/// (`GENERATED_DECORATORBLOCK`). An embed that adds properties inserts them
92/// into the result.
93pub 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
109/// `updateFromJSON(json)`'s part for `DecoratorBlockNode`: `format`, `''`
110/// when it is missing or names no format.
111pub 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
118/// `$isDecoratorBlockNode(node)`: whether the node extends
119/// `DecoratorBlockNode`.
120pub fn is_decorator_block_node(node: &NodeRef) -> bool {
121    node.get_latest().decorator_block().is_some()
122}
123
124impl NodeRef {
125    /// `DecoratorBlockNode.getFormat()`; `None` for any other node.
126    pub fn get_decorator_block_format(&self) -> Option<&'static str> {
127        self.get_latest().decorator_block().map(|d| d.format)
128    }
129
130    /// `DecoratorBlockNode.setFormat(format)`: `''` for a string that names
131    /// no format. Does nothing to any other node.
132    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/// The commands of `LexicalBlockWithAlignableContents.tsx` as an extension
150/// (the `extension` feature, as Swift's `BlockWithAlignableContentsExtension`).
151#[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    /// `BlockWithAlignableContentsExtension`.
164    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                            // `clearSelection(); setSelected(!isSelected)`.
217                            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                                    // A range that covers the block selects
227                                    // it too, so even its deselection
228                                    // replaces the range with a node
229                                    // selection (`useLexicalNodeSelection`).
230                                    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    /// `BlockWithAlignableContentsExtension`: what React's
257    /// `BlockWithAlignableContents` registers for each block it draws, for
258    /// every `DecoratorBlockNode`, as Swift has it. While a block is
259    /// selected (`isSelected()`, which a range over it is too),
260    /// [`FORMAT_ELEMENT_COMMAND`] aligns it: under a node selection the
261    /// selected blocks, under a range each block in it and the nearest block
262    /// element of every other node. A [`CLICK_COMMAND`] whose
263    /// [`target_key`](crate::MouseEvent::target_key) is a block (JS: a click
264    /// on the component's `<div>`) selects only it, or deselects it when it
265    /// was selected; with Shift it adds it to the node selection or takes it
266    /// out. Both at [`COMMAND_PRIORITY_LOW`].
267    ///
268    /// React registers one handler per block, so of several blocks in a
269    /// node selection only the one whose handler runs first is aligned;
270    /// this aligns them all, as Swift does (rust/PARITY.md).
271    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    /// A block embed that adds nothing.
290    #[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    /// The blocks' keys: `[p1, e1, p2, e2, p1's text, p2's text]`.
322    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    /// The document `p1 e1 p2 e2` (`ab`, an embed, `cd`, an embed), then
353    /// `select` with its keys.
354    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    /// The four blocks' formats, and the selection: `node` and the indexes
390    /// of its blocks, `range`, or `none`.
391    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    // What JS records for a `DecoratorBlockNode` that renders
442    // `BlockWithAlignableContents` in a `LexicalComposer` with
443    // `RichTextPlugin` (jsdom, React 19), a click being one on the
444    // component's `<div>`: the formats of `p1 e1 p2 e2` and the selection
445    // after each step.
446    #[test]
447    fn format_element_command_aligns_selected_blocks() {
448        let editor = editor();
449        // A node selection of e1: only e1 is aligned.
450        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        // A range from p1 to p2 covers e1: each block in it is aligned.
461        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        // A range in p1 covers no block: rich text's handler aligns p1.
468        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            // Deselecting the last block leaves an empty node selection,
486            // which the commit makes no selection.
487            (&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        // A click on a block a range covers deselects it, leaving none.
496        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        // A caret elsewhere: the click selects the block.
500        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        // Shift with a covering range deselects it too.
504        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}