Skip to main content

lexical_ui/
editor_state.rs

1//! `LexicalEditorState.ts`.
2
3use crate::json::{Object, Value};
4use crate::lexical_selection::SelectionRef;
5use crate::lexical_utils::get_root;
6use crate::node::{LexicalNode, NodeKey, NodeRef};
7use crate::nodes::root::RootNode;
8use crate::ordered::KeyMap;
9use crate::serialized_export::{export_node_json, with_compact_export};
10use crate::updates::read_editor_state;
11use std::cell::{Cell, RefCell};
12use std::rc::Rc;
13
14pub(crate) type NodeMap = KeyMap<NodeKey, Rc<dyn LexicalNode>>;
15
16/// An editor state: the node map and the selection. A handle; cloning it
17/// shares the same state. Once read-only (committed or parsed), nothing
18/// changes it: an update works on a clone whose node map shares the nodes,
19/// and a node is copied before its first change (`getWritable`).
20#[derive(Clone, Debug)]
21pub struct EditorState(pub(crate) Rc<EditorStateInner>);
22
23#[derive(Debug)]
24pub(crate) struct EditorStateInner {
25    pub(crate) node_map: RefCell<NodeMap>,
26    pub(crate) selection: RefCell<Option<SelectionRef>>,
27    pub(crate) read_only: Cell<bool>,
28    /// `_flushSync`: commit at the end of the update (`discrete`).
29    pub(crate) flush_sync: Cell<bool>,
30    /// `_parsed`: made by `parseEditorState`, so no transform has run on it.
31    pub(crate) parsed: Cell<bool>,
32    /// `_slotsUsed`: the state was built with slots, which an editor it is
33    /// given latches.
34    pub(crate) slots_used: Cell<bool>,
35    /// Tells this state from every other on the thread: a node version
36    /// records the one it was made writable in (`NodeBase::written_in`),
37    /// which is how a NodeState knows its version, as JS knows its object.
38    pub(crate) id: u64,
39    /// `cachedNodeMaps.get(editorState)`: what
40    /// [`get_cached_type_to_node_map`](crate::get_cached_type_to_node_map)
41    /// computed for this read-only state.
42    pub(crate) type_to_node_map: RefCell<Option<Rc<crate::TypeToNodeMap>>>,
43}
44
45thread_local! {
46    static NEXT_EDITOR_STATE_ID: Cell<u64> = const { Cell::new(1) };
47}
48
49fn new_editor_state(node_map: NodeMap) -> EditorState {
50    EditorState(Rc::new(EditorStateInner {
51        node_map: RefCell::new(node_map),
52        selection: RefCell::new(None),
53        read_only: Cell::new(false),
54        flush_sync: Cell::new(false),
55        parsed: Cell::new(false),
56        slots_used: Cell::new(false),
57        id: NEXT_EDITOR_STATE_ID.with(|n| n.replace(n.get() + 1)),
58        type_to_node_map: RefCell::new(None),
59    }))
60}
61
62/// `createEmptyEditorState()`.
63pub(crate) fn create_empty_editor_state() -> EditorState {
64    let mut node_map = NodeMap::default();
65    node_map.insert("root".to_owned(), Rc::new(RootNode::new()));
66    new_editor_state(node_map)
67}
68
69/// `cloneEditorState(current)`: the same nodes, no selection, writable.
70pub(crate) fn clone_editor_state(current: &EditorState) -> EditorState {
71    let state = new_editor_state(current.0.node_map.borrow().clone());
72    state.0.slots_used.set(current.0.slots_used.get());
73    state
74}
75
76/// `$exportNodeToJSON(node)`: the node, its children and its slots
77/// (`$slots`).
78fn export_node_to_json(node: &NodeRef) -> Value {
79    let mut serialized_node: Object = export_node_json(&*node.get_latest());
80    if node.is_element() {
81        let children: Vec<Value> = node
82            .get_children()
83            .iter()
84            .map(export_node_to_json)
85            .collect();
86        serialized_node.insert("children", Value::Array(children));
87    }
88    let slot_names = crate::slot::get_slot_names(node);
89    if !slot_names.is_empty() {
90        let mut serialized_slots = Object::new();
91        for name in slot_names {
92            let Some(slot_node) = crate::slot::get_slot(node, &name) else {
93                panic!(
94                    "LexicalNode: Node {} has slot \"{name}\" but it resolved to no node during export.",
95                    node.get_type()
96                );
97            };
98            serialized_slots.insert(&name, export_node_to_json(&slot_node));
99        }
100        serialized_node.insert("$slots", Value::Object(serialized_slots));
101    }
102    Value::Object(serialized_node)
103}
104
105impl EditorState {
106    /// `isEmpty()`: nothing but the root, and no selection.
107    pub fn is_empty(&self) -> bool {
108        self.0.node_map.borrow().len() <= 1 && self.0.selection.borrow().is_none()
109    }
110
111    /// The state's selection (`editorState._selection`).
112    pub fn selection(&self) -> Option<SelectionRef> {
113        self.0.selection.borrow().clone()
114    }
115
116    /// The node keys in the order JS's node map holds them, the order nodes
117    /// were created in: the root, then by key, as keys come from a counter.
118    pub(crate) fn keys_in_creation_order(&self) -> Vec<String> {
119        let mut keys: Vec<String> = self.0.node_map.borrow().keys().cloned().collect();
120        keys.sort_by_key(|k| (k != "root", k.parse::<u64>().unwrap_or(u64::MAX), k.clone()));
121        keys
122    }
123
124    /// `clone(selection)`: a read-only state with the same nodes, and
125    /// `selection` (`None` is JS's `undefined`, this state's selection;
126    /// `Some(None)` is `null`). It is parsed when this one is, so
127    /// `setEditorState(parsed.clone(null))` still runs transforms on it.
128    /// (`Clone::clone` shares this state itself.)
129    pub fn clone_with_selection(&self, selection: Option<Option<SelectionRef>>) -> EditorState {
130        let state = new_editor_state(self.0.node_map.borrow().clone());
131        *state.0.selection.borrow_mut() = selection.unwrap_or_else(|| self.selection());
132        state.0.slots_used.set(self.0.slots_used.get());
133        state.0.read_only.set(true);
134        state.0.parsed.set(self.0.parsed.get());
135        state
136    }
137
138    /// Whether `self` and `other` are the same state.
139    pub fn ptr_eq(&self, other: &EditorState) -> bool {
140        Rc::ptr_eq(&self.0, &other.0)
141    }
142
143    /// `read(callbackFn)`: runs `f` with this state active, read-only.
144    pub fn read<R>(&self, f: impl FnOnce() -> R) -> R {
145        read_editor_state(None, self, f)
146    }
147
148    /// `toJSON(compact)`: the document's JSON, in the compact form or the
149    /// legacy form that writes every property. `to_json(false).to_string()`
150    /// is `JSON.stringify(editorState.toJSON())`.
151    pub fn to_json(&self, compact: bool) -> Value {
152        with_compact_export(compact, || {
153            read_editor_state(None, self, || {
154                let mut json = Object::new();
155                json.insert("root", export_node_to_json(&get_root()));
156                Value::Object(json)
157            })
158        })
159    }
160}