Skip to main content

lexical_ui/
updates.rs

1//! `LexicalUpdates.ts`: the active editor and editor state that `$`
2//! functions read, the update cycle (`editor.update`, transforms, the
3//! commit and its listeners), command dispatch, and `parseEditorState`.
4//!
5//! Without a root element the reconciler, mutation listeners and decorator
6//! listeners never run, as in JS's headless editor; with one, the
7//! reconciler's model half (`reconciler.rs`) does. Selection-change
8//! notifications and the DOM selection never run here. Where JS commits a
9//! non-discrete update in a microtask, Rust commits it at the next
10//! [`Editor::read`] or discrete update, which JS also does when one comes
11//! first.
12
13use crate::editor::{
14    DirtyType, LexicalCommand, MutationListenerPayload, NodeClass, Transform,
15    UpdateListenerPayload, UpdateOptions,
16};
17use crate::editor_state::{clone_editor_state, create_empty_editor_state};
18use crate::error::invariant;
19use crate::gc::garbage_collect_detached_nodes;
20use crate::json::Value;
21use crate::lexical_selection::{SelectionRef, has_dirty_selection};
22use crate::lexical_utils::{get_editors_to_propagate, get_node_by_key, get_root};
23use crate::node::NodeRef;
24use crate::node_state::{apply_flat_states, update_state_from_json};
25use crate::nodes::element::is_root_or_shadow_root;
26use crate::normalization::normalize_text_node;
27use crate::ordered::{OrderedMap, OrderedSet};
28use crate::{Editor, EditorState, LexicalError};
29use std::cell::{Cell, RefCell};
30use std::collections::{HashMap, HashSet};
31use std::rc::Rc;
32
33/// JS's module-scope `activeEditor`, `activeEditorState` and
34/// `isReadOnlyMode`, per thread.
35#[derive(Clone, Default)]
36struct Active {
37    editor: Option<Editor>,
38    editor_state: Option<EditorState>,
39    read_only: bool,
40    /// The editor whose node classes `$getEditor()` finds while
41    /// `parseEditorState` runs, which JS makes the active editor and Rust
42    /// doesn't (so nothing is marked dirty in it).
43    registry: Option<Editor>,
44}
45
46thread_local! {
47    static ACTIVE: RefCell<Active> = RefCell::new(Active::default());
48    static INFINITE_TRANSFORM_COUNT: Cell<u32> = const { Cell::new(0) };
49    /// `isCommittingPendingUpdates`: true for the whole of
50    /// `$commitPendingUpdates`, so commands dispatched by the commit (the
51    /// selection notification, mutation listeners) don't reset the update
52    /// cascade budget.
53    static IS_COMMITTING_PENDING_UPDATES: Cell<bool> = const { Cell::new(false) };
54    /// `editorsWithPendingSelectionChange`, by the editors' addresses.
55    static EDITORS_WITH_PENDING_SELECTION_CHANGE: RefCell<HashSet<usize>> =
56        RefCell::new(HashSet::new());
57    /// How many `triggerCommandListeners` calls are running, and the turn:
58    /// a count of the outermost dispatches that returned. JS's microtasks
59    /// run once the application's call returns; a dispatch is the port's
60    /// nearest stand-in for that synchronous turn (`@lexical/mark`'s
61    /// `forgetSoon`).
62    static COMMAND_DISPATCH: Cell<(usize, u64)> = const { Cell::new((0, 0)) };
63}
64
65/// The turn of the running command dispatch, or `None` outside one: edits
66/// recorded during a dispatch are those of the same synchronous turn until
67/// the outermost dispatch returns (`@lexical/mark`'s `forgetSoon`).
68#[cfg(all(feature = "mark", feature = "extension"))]
69pub(crate) fn command_dispatch_turn() -> Option<u64> {
70    let (depth, turn) = COMMAND_DISPATCH.with(Cell::get);
71    (depth > 0).then_some(turn)
72}
73
74/// Counts a running dispatch until dropped.
75struct CommandDispatchGuard;
76
77impl CommandDispatchGuard {
78    fn enter() -> Self {
79        COMMAND_DISPATCH.with(|c| {
80            let (depth, turn) = c.get();
81            c.set((depth + 1, turn));
82        });
83        CommandDispatchGuard
84    }
85}
86
87impl Drop for CommandDispatchGuard {
88    fn drop(&mut self) {
89        COMMAND_DISPATCH.with(|c| {
90            let (depth, turn) = c.get();
91            c.set(if depth == 1 {
92                (0, turn + 1)
93            } else {
94                (depth - 1, turn)
95            });
96        });
97    }
98}
99
100/// Runs `f` with `active` in place, restoring the previous one afterwards,
101/// even when `f` panics.
102fn with_active<R>(active: Active, f: impl FnOnce() -> R) -> R {
103    struct Restore(Option<Active>);
104    impl Drop for Restore {
105        fn drop(&mut self) {
106            let previous = self.0.take().expect("previous");
107            ACTIVE.with(|a| *a.borrow_mut() = previous);
108        }
109    }
110    let previous = ACTIVE.with(|a| std::mem::replace(&mut *a.borrow_mut(), active));
111    let _restore = Restore(Some(previous));
112    f()
113}
114
115/// `getActiveEditorState()`.
116pub(crate) fn get_active_editor_state() -> EditorState {
117    ACTIVE
118        .with(|a| a.borrow().editor_state.clone())
119        .unwrap_or_else(|| {
120            panic!(
121                "Unable to find an active editor state. State helpers or node methods can only be used synchronously during the callback of editor.update(), editor.read(), or editorState.read()."
122            )
123        })
124}
125
126/// `INTERNAL_getActiveEditorState()`: the editor state of the update or
127/// read that is running, if any.
128#[cfg_attr(not(feature = "text"), allow(dead_code))]
129pub(crate) fn internal_get_active_editor_state() -> Option<EditorState> {
130    ACTIVE.with(|a| a.borrow().editor_state.clone())
131}
132
133/// `internalGetActiveEditor()`: the editor whose update or read is running,
134/// if any. Reading an editor state on its own ([`EditorState::read`],
135/// parsing) has none.
136pub(crate) fn get_active_editor() -> Option<Editor> {
137    ACTIVE.with(|a| a.borrow().editor.clone())
138}
139
140/// `$getEditor()` for the node classes: the active editor, or the one
141/// `parseEditorState` parses for.
142pub(crate) fn get_registry_editor() -> Option<Editor> {
143    ACTIVE.with(|a| {
144        let a = a.borrow();
145        a.editor.clone().or_else(|| a.registry.clone())
146    })
147}
148
149/// `isCurrentlyReadOnlyMode()`.
150pub(crate) fn is_currently_read_only_mode() -> bool {
151    ACTIVE.with(|a| a.borrow().read_only)
152}
153
154/// `errorOnReadOnly()`.
155pub(crate) fn error_on_read_only() {
156    if is_currently_read_only_mode() {
157        panic!("Cannot use method in read-only mode.");
158    }
159}
160
161/// `$flushSyncAfterUpdate()`: the running update commits when it ends, as
162/// a discrete one does, rather than at the next read or discrete update.
163#[cfg_attr(not(feature = "rich-text"), allow(dead_code))]
164pub(crate) fn flush_sync_after_update() {
165    let editor_state = get_active_editor_state();
166    error_on_read_only();
167    editor_state.0.flush_sync.set(true);
168}
169
170/// `$onUpdate(updateFn)` (`LexicalUtils.ts`): runs `update_fn` once the
171/// update that is running commits, after its listeners.
172pub fn on_update(update_fn: impl FnOnce() + 'static) {
173    error_on_read_only();
174    let editor = get_active_editor().unwrap_or_else(|| {
175        panic!("Unable to find an active editor. This method can only be used synchronously during the callback of editor.update() or editor.read().")
176    });
177    editor.0.deferred.borrow_mut().push(Box::new(update_fn));
178}
179
180/// `triggerDeferredUpdateCallbacks(editor, deferred)`.
181fn trigger_deferred_update_callbacks(editor: &Editor, deferred: Vec<Box<dyn FnOnce()>>) {
182    if !deferred.is_empty() {
183        with_updating(editor, || {
184            for callback in deferred {
185                callback();
186            }
187        });
188    }
189}
190
191/// `errorOnInfiniteTransforms()`.
192pub(crate) fn error_on_infinite_transforms() {
193    if INFINITE_TRANSFORM_COUNT.with(Cell::get) > 99 {
194        panic!(
195            "One or more transforms are endlessly triggering additional transforms. May have encountered infinite recursion caused by transforms that have their preconditions too lose and/or conflict with each other."
196        );
197    }
198}
199
200fn bump_infinite_transform_count() {
201    INFINITE_TRANSFORM_COUNT.with(|c| c.set(c.get() + 1));
202}
203
204/// `readEditorState(editor, editorState, callbackFn)`.
205pub(crate) fn read_editor_state<R>(
206    editor: Option<&Editor>,
207    editor_state: &EditorState,
208    f: impl FnOnce() -> R,
209) -> R {
210    with_active(
211        Active {
212            editor: editor.cloned(),
213            editor_state: Some(editor_state.clone()),
214            read_only: true,
215            registry: None,
216        },
217        f,
218    )
219}
220
221/// `$applyTransforms(editor, node, transformsCache)`.
222fn apply_transforms(
223    editor: &Editor,
224    node: &NodeRef,
225    cache: &mut HashMap<&'static str, Vec<Transform>>,
226) -> Result<(), LexicalError> {
227    // The class's own `$transform` (`getTransformSetFromKlass` walks the
228    // class chain from the node's class up), then `ElementNode`'s.
229    node.get_latest().transform(node)?;
230    if !node.is_attached() {
231        return Ok(());
232    }
233    if node.is_element() {
234        normalize_shadow_root_children(node)?;
235        if !node.is_attached() {
236            return Ok(());
237        }
238    }
239    let node_type = node.get_type();
240    let transforms = cache
241        .entry(node_type)
242        .or_insert_with(|| editor.transforms_of(node_type))
243        .clone();
244    for transform in &transforms {
245        transform(node)?;
246        if !node.is_attached() {
247            break;
248        }
249    }
250    Ok(())
251}
252
253/// `$normalizeShadowRootChildren(node)` (`LexicalElementNode.ts`), the
254/// `$transform` every `ElementNode` has: wraps each run of inline children
255/// of a root or shadow root in the block the first one's
256/// `createParentElementNode` makes, for documents parsed from outside.
257/// Where `NodeStructureExtension` enforces declared structure, it wraps
258/// these children itself (a root or shadow root holds blocks), after their
259/// own repairs: an empty inline element it removes is then never wrapped,
260/// which it would be here if this transform ran first.
261fn normalize_shadow_root_children(node: &NodeRef) -> Result<(), LexicalError> {
262    if !is_root_or_shadow_root(&*node.get_latest())
263        || crate::structure::is_structure_enforced_on_active_editor()
264    {
265        return Ok(());
266    }
267    let mut block: Option<NodeRef> = None;
268    for child in node.get_children() {
269        block = if child.is_inline() {
270            let block = match block {
271                Some(block) => block,
272                None => child.replace(&child.create_parent_element_node(), false)?,
273            };
274            block.append(&[child])?;
275            Some(block)
276        } else {
277            None
278        };
279    }
280    Ok(())
281}
282
283/// Whether a dirty leaf is normalized: attached, simple, mergeable text.
284fn should_normalize(node: &NodeRef) -> bool {
285    node.is_text() && node.is_attached() && node.is_simple_text() && !node.is_unmergeable()
286}
287
288/// `$normalizeAllDirtyTextNodes(editorState, editor)`. Iterates the dirty
289/// leaves as JS's `for...of` does, seeing those added meanwhile.
290fn normalize_all_dirty_text_nodes(editor: &Editor) -> Result<(), LexicalError> {
291    let mut i = 0;
292    loop {
293        let key = editor
294            .0
295            .dirty
296            .borrow()
297            .leaves
298            .key_at(&mut i)
299            .map(str::to_owned);
300        let Some(key) = key else { break };
301        if let Some(node) = get_node_by_key(&key)
302            && should_normalize(&node)
303        {
304            normalize_text_node(&node)?;
305        }
306        i += 1;
307    }
308    Ok(())
309}
310
311/// `$applyAllTransforms(editorState, editor)`: transforms dirty leaves
312/// first, repeating while they dirty more leaves, then the elements marked
313/// dirty themselves, the root last, and again from the leaves while
314/// anything new is dirty.
315///
316/// JS swaps the editor's dirty sets for fresh ones to see what each round
317/// dirties, and accumulates the full record in the sets it started with;
318/// in the first round the full record is the editor's own set, which is
319/// why `full_*` is `None` until the editor's set is first swapped out.
320fn apply_all_transforms(editor: &Editor) -> Result<(), LexicalError> {
321    let mut cache = HashMap::new();
322    // `$isNodeValidForTransform`: nodes being composed aren't transformed.
323    let composition_key = crate::lexical_utils::get_composition_key();
324    let is_composing = |node: &NodeRef| composition_key.as_deref() == Some(node.get_key());
325    let mut full_leaves: Option<OrderedSet> = None;
326    let mut full_elements: Option<OrderedMap<bool>> = None;
327
328    loop {
329        let (leaves_len, elements_len) = {
330            let dirty = editor.0.dirty.borrow();
331            (dirty.leaves.len(), dirty.elements.len())
332        };
333        if leaves_len == 0 && elements_len == 0 {
334            break;
335        }
336        if leaves_len > 0 {
337            let untransformed = std::mem::take(&mut editor.0.dirty.borrow_mut().leaves);
338            let keys: Vec<String> = untransformed.iter().map(str::to_owned).collect();
339            full_leaves.get_or_insert(untransformed);
340            for key in &keys {
341                if let Some(node) = get_node_by_key(key) {
342                    if should_normalize(&node) {
343                        normalize_text_node(&node)?;
344                    }
345                    if !is_composing(&node) && node.is_attached() {
346                        apply_transforms(editor, &node, &mut cache)?;
347                    }
348                }
349                full_leaves.as_mut().expect("set above").add(key);
350            }
351            // Leaf transforms come before element transforms.
352            if !editor.0.dirty.borrow().leaves.is_empty() {
353                bump_infinite_transform_count();
354                continue;
355            }
356        }
357
358        let (previous_leaves, mut untransformed) = {
359            let mut dirty = editor.0.dirty.borrow_mut();
360            (
361                std::mem::take(&mut dirty.leaves),
362                std::mem::take(&mut dirty.elements),
363            )
364        };
365        full_leaves.get_or_insert(previous_leaves);
366        // The root is always considered intentionally dirty if any attached
367        // node is dirty, and moving it last applies its transforms last.
368        if untransformed.delete("root").is_some() {
369            untransformed.set("root", true);
370        }
371        full_elements.get_or_insert_with(|| untransformed.clone());
372        let entries: Vec<(String, bool)> = untransformed
373            .iter()
374            .map(|(k, v)| (k.to_owned(), *v))
375            .collect();
376        for (key, intentionally_marked_as_dirty) in entries {
377            full_elements
378                .as_mut()
379                .expect("set above")
380                .set(&key, intentionally_marked_as_dirty);
381            if !intentionally_marked_as_dirty {
382                continue;
383            }
384            if let Some(node) = get_node_by_key(&key)
385                && !is_composing(&node)
386                && node.is_attached()
387            {
388                apply_transforms(editor, &node, &mut cache)?;
389            }
390        }
391        bump_infinite_transform_count();
392    }
393
394    let mut dirty = editor.0.dirty.borrow_mut();
395    if let Some(leaves) = full_leaves {
396        dirty.leaves = leaves;
397    }
398    if let Some(elements) = full_elements {
399        dirty.elements = elements;
400    }
401    Ok(())
402}
403
404/// `$parseSerializedNodeImpl`.
405fn parse_serialized_node_impl(
406    serialized_node: &Value,
407    registered_nodes: &HashMap<&'static str, NodeClass>,
408) -> Result<NodeRef, LexicalError> {
409    let Some(object) = serialized_node.as_object() else {
410        // `serializedNode.type` of a primitive is `undefined`; of `null` it
411        // throws a TypeError.
412        invariant!(
413            !serialized_node.is_null(),
414            "Cannot read properties of null (reading 'type')"
415        );
416        return Err(LexicalError::new(
417            "parseEditorState: type \"undefined\" + not found",
418        ));
419    };
420    let node_type = object.get("type");
421    let registered = node_type
422        .and_then(Value::as_str)
423        .and_then(|t| registered_nodes.get(t));
424    let Some(registered) = registered else {
425        let shown = match node_type {
426            None | Some(Value::Undefined) => "undefined".to_owned(),
427            Some(Value::String(s)) => s.clone(),
428            Some(other) => other.to_string(),
429        };
430        return Err(LexicalError::new(format!(
431            "parseEditorState: type \"{shown}\" + not found"
432        )));
433    };
434    let node = (registered.import_json)(object)?;
435    // A class's own `importJSON` calls `updateFromJSON`, which applies what
436    // the synthesized one does besides the class's own properties: the
437    // nested NodeState (`$updateStateFromJSON`), then the flat states the
438    // class declares (`$applyFlatStates`).
439    if !registered.imports_node_state() {
440        update_state_from_json(&node, object)?;
441        apply_flat_states(&node, object)?;
442    }
443    if let Some(Value::Array(children)) = object.get("children")
444        && node.is_element()
445    {
446        for child in children {
447            let child = parse_serialized_node_impl(child, registered_nodes)?;
448            node.append(&[child])?;
449        }
450    }
451    // `$slots` is truthy for any object (an array too, whose indices are its
452    // names) and any other truthy value, whose `for...in` finds nothing.
453    if let Some(slots) = object.get("$slots").filter(|v| is_truthy(v)) {
454        invariant!(
455            crate::slot::is_slot_host(&node),
456            "$parseSerializedNode: node {} has slots but is not a valid slot host; only ElementNodes and DecoratorNodes can host slots.",
457            node.get_type()
458        );
459        let entries: Vec<(String, Value)> = match slots {
460            Value::Object(o) => o.iter().map(|(k, v)| (k.to_owned(), v.clone())).collect(),
461            Value::Array(a) => a
462                .iter()
463                .enumerate()
464                .map(|(i, v)| (i.to_string(), v.clone()))
465                .collect(),
466            _ => Vec::new(),
467        };
468        for (name, value) in entries {
469            let slot_node = parse_serialized_node_impl(&value, registered_nodes)?;
470            crate::slot::set_slot(&node, &name, &slot_node)?;
471        }
472    }
473    Ok(node)
474}
475
476/// Whether a JSON value is truthy in JS.
477fn is_truthy(value: &Value) -> bool {
478    match value {
479        Value::Undefined | Value::Null => false,
480        Value::Bool(b) => *b,
481        Value::Number(n) => *n != 0.0 && !n.is_nan(),
482        Value::String(s) => !s.is_empty(),
483        Value::Array(_) | Value::Object(_) => true,
484    }
485}
486
487/// `$parseSerializedNode(serializedNode)`: a node, and its children, from
488/// its JSON, created in the active update with the active editor's node
489/// classes.
490pub fn parse_serialized_node(serialized_node: &Value) -> Result<NodeRef, LexicalError> {
491    let editor =
492        get_active_editor().ok_or_else(|| LexicalError::new("Unable to find an active editor."))?;
493    parse_serialized_node_impl(serialized_node, editor.registered_nodes())
494}
495
496/// `parseEditorState(serializedEditorState, editor)`. The nodes are created
497/// outside any update of the editor, so nothing is marked dirty (JS saves
498/// and restores the editor's dirty records instead).
499pub(crate) fn parse_editor_state(
500    serialized_editor_state: &Value,
501    editor: &Editor,
502    update_fn: Option<Box<dyn FnOnce() -> Result<(), LexicalError> + '_>>,
503) -> Result<EditorState, LexicalError> {
504    let editor_state = create_empty_editor_state();
505    let active = Active {
506        editor: None,
507        editor_state: Some(editor_state.clone()),
508        read_only: false,
509        registry: Some(editor.clone()),
510    };
511    with_active(active, || {
512        let serialized_node = serialized_editor_state.get("root");
513        invariant!(
514            serialized_node.is_some_and(|v| !v.is_undefined()),
515            "Cannot read properties of undefined (reading 'type')"
516        );
517        parse_serialized_node_impl(serialized_node.unwrap(), editor.registered_nodes())?;
518        if let Some(update_fn) = update_fn {
519            update_fn()?;
520        }
521        Ok(())
522    })?;
523    // Make the editor state immutable.
524    editor_state.0.read_only.set(true);
525    editor_state.0.parsed.set(true);
526    Ok(editor_state)
527}
528
529/// `getEditorStateTextContent(editorState)`.
530fn editor_state_text_content(editor_state: &EditorState) -> String {
531    editor_state.read(|| get_root().get_text_content())
532}
533
534/// `triggerListeners`'s bracket: listeners run with the editor marked as
535/// updating, so an update they start is queued.
536fn with_updating<R>(editor: &Editor, f: impl FnOnce() -> R) -> R {
537    struct Restore<'a>(&'a Editor, bool);
538    impl Drop for Restore<'_> {
539        fn drop(&mut self) {
540            self.0.0.updating.set(self.1);
541        }
542    }
543    let _restore = Restore(editor, editor.0.updating.replace(true));
544    f()
545}
546
547/// `$commitPendingUpdates(editor)`: announces a changed selection with
548/// `SELECTION_CHANGE_COMMAND` in the pending update, makes the pending
549/// state the editor's state, notifies the text content and update
550/// listeners, and runs the first update queued meanwhile.
551pub(crate) fn commit_pending_updates(editor: &Editor) -> Result<(), LexicalError> {
552    struct Restore(bool);
553    impl Drop for Restore {
554        fn drop(&mut self) {
555            IS_COMMITTING_PENDING_UPDATES.with(|c| c.set(self.0));
556        }
557    }
558    let _restore = Restore(IS_COMMITTING_PENDING_UPDATES.with(|c| c.replace(true)));
559    let notification_result = notify_pending_selection_change(editor)?;
560    commit_pending_updates_impl(editor)?;
561    if notification_result {
562        // Reported only after the pending edit is kept.
563        editor.on_warn(LexicalError::new(
564            "Selection change listeners are endlessly changing the selection.",
565        ))?;
566    }
567    Ok(())
568}
569
570/// `hasSelectionChanged(editor, selection)`: whether `selection` differs
571/// from the one last announced.
572fn has_selection_changed(editor: &Editor, selection: Option<&SelectionRef>) -> bool {
573    let previous = editor.0.last_notified_selection.borrow();
574    match selection {
575        None => previous.is_some(),
576        Some(selection) => previous.as_ref().is_none_or(|p| !selection.get().is(p)),
577    }
578}
579
580/// `$dispatchSelectionChangeCommand(editor, selection, force)`: announces
581/// `selection` with `SELECTION_CHANGE_COMMAND` when it differs from the one
582/// last announced, or always with `force`. Runs in the editor's pending
583/// update.
584pub(crate) fn dispatch_selection_change_command(
585    editor: &Editor,
586    selection: Option<&SelectionRef>,
587    force: bool,
588) -> Result<(), LexicalError> {
589    if !force && !has_selection_changed(editor, selection) {
590        return Ok(());
591    }
592    editor.dispatch_command(&crate::commands::SELECTION_CHANGE_COMMAND, ())?;
593    Ok(())
594}
595
596/// `$notifyPendingSelectionChange(editor)`: while the pending selection
597/// differs from the one last announced, dispatches `SELECTION_CHANGE_COMMAND`
598/// in the pending update (its listeners' edits join it), up to 100 times.
599/// A range selection, or none, is not announced by an editor without a
600/// connected root element. Returns true when the listeners hit the limit.
601fn notify_pending_selection_change(editor: &Editor) -> Result<bool, LexicalError> {
602    let id = Rc::as_ptr(&editor.0) as usize;
603    if !EDITORS_WITH_PENDING_SELECTION_CHANGE.with(|s| s.borrow_mut().insert(id)) {
604        return Ok(false);
605    }
606    struct Remove(usize);
607    impl Drop for Remove {
608        fn drop(&mut self) {
609            EDITORS_WITH_PENDING_SELECTION_CHANGE.with(|s| s.borrow_mut().remove(&self.0));
610        }
611    }
612    let _remove = Remove(id);
613    let mut count = 0;
614    while let Some(pending) = editor.pending() {
615        let selection = pending.selection();
616        if !has_selection_changed(editor, selection.as_ref()) {
617            return Ok(false);
618        }
619        let root_connected = editor
620            .get_root_element()
621            .is_some_and(|root| root.0.is_connected());
622        let skip_notification = selection.as_ref().is_none_or(SelectionRef::is_range)
623            && (editor.is_headless() || !root_connected);
624        if skip_notification || count == 100 {
625            // Skipped notifications are not replayed once the root
626            // reconnects, nor after stopping a listener loop.
627            *editor.0.last_notified_selection.borrow_mut() = selection.map(|s| s.get());
628            return Ok(!skip_notification);
629        }
630        // Extends the pending update, with its error handling; the caller
631        // owns the commit, so the listeners' edits and transforms join it.
632        let e = editor.clone();
633        begin_update_with(
634            editor,
635            move || {
636                e.dispatch_command(&crate::commands::SELECTION_CHANGE_COMMAND, ())
637                    .map(|_| ())
638            },
639            &UpdateOptions::default(),
640            true,
641        )?;
642        count += 1;
643    }
644    Ok(false)
645}
646
647/// Whether a commit ([`commit_pending_updates`]) is running on this thread
648/// (`isCommittingPendingUpdates`): the commands dispatched and the updates
649/// begun meanwhile are part of it, not a new action, so they don't reset
650/// the cascade budget.
651pub(crate) fn is_committing_pending_updates() -> bool {
652    IS_COMMITTING_PENDING_UPDATES.with(Cell::get)
653}
654
655/// The commit itself (`$commitPendingUpdatesImpl`).
656fn commit_pending_updates_impl(editor: &Editor) -> Result<(), LexicalError> {
657    let pending = editor.0.pending.borrow_mut().take();
658    let Some(pending) = pending else {
659        // Even without a pending state, flush the deferred callbacks a
660        // prior update added.
661        if !editor.0.updating.get() && !editor.0.deferred.borrow().is_empty() {
662            let deferred = std::mem::take(&mut *editor.0.deferred.borrow_mut());
663            trigger_deferred_update_callbacks(editor, deferred);
664        }
665        return Ok(());
666    };
667    let current = editor.get_editor_state();
668    let needs_update = editor.dirty_type() != DirtyType::None;
669    let previously_updating = editor.0.updating.get();
670    *editor.0.editor_state.borrow_mut() = pending.clone();
671    // The reconciler's model half, with a root element: which nodes it
672    // creates, updates and destroys, for the mutation listeners, the
673    // decorators, and the elements' text format and style.
674    let mutated_nodes =
675        if !editor.is_headless() && editor.get_root_element().is_some() && needs_update {
676            let mutated = with_active(
677                Active {
678                    editor: Some(editor.clone()),
679                    editor_state: Some(pending.clone()),
680                    read_only: false,
681                    registry: None,
682                },
683                || {
684                    with_updating(editor, || {
685                        let mutated = crate::reconciler::reconcile_root(&current, &pending, editor);
686                        (mutated, get_root().get_text_content())
687                    })
688                },
689            );
690            let (mutated, text) = mutated;
691            // The end of `$reconcileNode('root')`: the root caches its text
692            // content (`__cachedText`). A stale cache (a root not reconciled
693            // since it was cloned or made) is written through `getWritable()`,
694            // which marks the root dirty, as the update listeners then see;
695            // not in a committed state (`activeEditorStateReadOnly`), such as
696            // the one `setRootElement` reconciles.
697            let root = pending.0.node_map.borrow().get("root").cloned();
698            if let Some(root) = root.filter(|_| !pending.0.read_only.get()) {
699                let mut cache = editor.0.root_text_cache.borrow_mut();
700                let fresh = cache.as_ref().is_some_and(|(cached, cached_text)| {
701                    Rc::ptr_eq(cached, &root) && *cached_text == text
702                });
703                if !fresh {
704                    editor.0.dirty.borrow_mut().elements.set("root", true);
705                    *cache = Some((root, text));
706                }
707            }
708            Some(mutated)
709        } else {
710            None
711        };
712    pending.0.read_only.set(true);
713
714    let (dirty_elements, dirty_leaves, normalized_nodes) = {
715        let mut dirty = editor.0.dirty.borrow_mut();
716        let elements = dirty
717            .elements
718            .iter()
719            .map(|(k, v)| (k.to_owned(), *v))
720            .collect();
721        let leaves = dirty.leaves.iter().map(str::to_owned).collect();
722        let normalized = dirty.normalized.iter().map(str::to_owned).collect();
723        if needs_update {
724            *dirty = Default::default();
725        }
726        (elements, leaves, normalized)
727    };
728    // Reset even when nothing is dirty, so a no-op update's tags don't leak
729    // into the next one.
730    let tags: Vec<String> = std::mem::take(&mut *editor.0.tags.borrow_mut())
731        .iter()
732        .map(str::to_owned)
733        .collect();
734
735    // Listeners may start another update, which must not inherit them; an
736    // outer update still owns its callbacks when it forces an early commit.
737    let deferred = if previously_updating {
738        Vec::new()
739    } else {
740        std::mem::take(&mut *editor.0.deferred.borrow_mut())
741    };
742    crate::reconciler::garbage_collect_detached_decorators(editor, &pending);
743    let previously_dispatching = editor.0.dispatching_commit_listeners.replace(true);
744    // The mutation listeners run as the editor was updating before the
745    // commit (not, at the top level), so an update one starts begins at
746    // once, as in JS; the other listeners run as updating.
747    if let Some(mutated_nodes) = &mutated_nodes {
748        let leaves: &Vec<String> = &dirty_leaves;
749        trigger_mutation_listeners(editor, mutated_nodes, &tags, leaves, &current);
750    }
751    with_updating(editor, || {
752        // The decorators the reconciler and the GC changed.
753        let pending_decorators = editor.0.pending_decorators.borrow_mut().take();
754        if let Some(pending_decorators) = pending_decorators {
755            *editor.0.decorators.borrow_mut() = pending_decorators.clone();
756            editor.trigger_decorator_listeners(&pending_decorators);
757        }
758        if editor.has_text_content_listeners() {
759            let current_text = editor_state_text_content(&current);
760            let latest_text = editor_state_text_content(&pending);
761            if current_text != latest_text {
762                editor.trigger_text_content_listeners(&latest_text);
763            }
764        }
765        let payload = UpdateListenerPayload {
766            dirty_elements,
767            dirty_leaves,
768            normalized_nodes,
769            tags,
770            editor_state: pending.clone(),
771            prev_editor_state: current.clone(),
772            mutated_nodes: mutated_nodes.clone(),
773        };
774        editor.trigger_update_listeners(&payload);
775    });
776    editor
777        .0
778        .dispatching_commit_listeners
779        .set(previously_dispatching);
780    if !previously_updating {
781        trigger_deferred_update_callbacks(editor, deferred);
782    }
783    trigger_enqueued_updates(editor)
784}
785
786/// `triggerMutationListeners(editor, mutatedNodes, updateTags, dirtyLeaves,
787/// prevEditorState)`: each listener, for each class it listens to that the
788/// commit mutated.
789fn trigger_mutation_listeners(
790    editor: &Editor,
791    mutated_nodes: &crate::reconciler::MutatedNodes,
792    update_tags: &[String],
793    dirty_leaves: &[String],
794    prev_editor_state: &EditorState,
795) {
796    let payload = MutationListenerPayload {
797        dirty_leaves: dirty_leaves.to_vec(),
798        prev_editor_state: prev_editor_state.clone(),
799        update_tags: update_tags.to_vec(),
800    };
801    for (listener, node_type) in editor.mutation_listeners() {
802        if let Some((_, mutations)) = mutated_nodes.iter().find(|(t, _)| *t == node_type) {
803            listener(mutations, &payload);
804        }
805    }
806}
807
808/// `$triggerEnqueuedUpdates(editor)`: begins the next queued update, if
809/// any, unless listeners have been queueing updates endlessly.
810fn trigger_enqueued_updates(editor: &Editor) -> Result<(), LexicalError> {
811    if editor.0.updates.borrow().is_empty() {
812        editor.0.cascade_count.set(0);
813        return Ok(());
814    }
815    let count = editor
816        .0
817        .cascade_count
818        .replace(editor.0.cascade_count.get() + 1);
819    if count > 99 {
820        editor.0.updates.borrow_mut().clear();
821        editor.0.cascade_count.set(0);
822        // Reported through `onWarn` after breaking the cascade.
823        return editor.on_warn(LexicalError::new(format!(
824            "One or more update listeners are endlessly enqueueing more updates. May have encountered infinite recursion caused by update listeners that trigger additional updates without a stop condition. Editor namespace: {}",
825            editor.get_namespace()
826        )));
827    }
828    let queued = editor.0.updates.borrow_mut().pop_front();
829    match queued {
830        Some(queued) => begin_update(editor, queued.update_fn, &queued.options),
831        None => Ok(()),
832    }
833}
834
835/// `$processNestedUpdates(editor, initialSkipTransforms)`: runs the updates
836/// queued during this one as part of it.
837fn process_nested_updates(editor: &Editor, initial_skip: bool) -> Result<bool, LexicalError> {
838    let mut skip_transforms = initial_skip;
839    loop {
840        let queued = editor.0.updates.borrow_mut().pop_front();
841        let Some(queued) = queued else { break };
842        let pending = editor.pending();
843        if queued.options.skip_transforms {
844            skip_transforms = true;
845        }
846        if let Some(on_update) = &queued.options.on_update {
847            let on_update = on_update.clone();
848            editor
849                .0
850                .deferred
851                .borrow_mut()
852                .push(Box::new(move || on_update()));
853        }
854        if queued.options.discrete {
855            invariant!(
856                pending.is_some(),
857                "Unexpected empty pending editor state on discrete nested update"
858            );
859            pending.as_ref().expect("checked").0.flush_sync.set(true);
860        }
861        editor.add_tags(&queued.options.tags);
862        if pending.is_none() {
863            begin_update(editor, queued.update_fn, &queued.options)?;
864        } else {
865            (queued.update_fn)()?;
866        }
867    }
868    Ok(skip_transforms)
869}
870
871/// `$discardPendingUpdate(editor, queuedBefore)`: the editor goes back to
872/// its committed state; the updates the failed one queued are dropped.
873fn discard_pending_update(editor: &Editor, queued_before: &HashSet<u64>) {
874    let committed = editor.get_editor_state();
875    // A notification in the rejected update must not suppress a later
876    // retry or make up a selection change while restoring the committed
877    // state.
878    *editor.0.last_notified_selection.borrow_mut() = committed.selection().map(|s| s.get());
879    *editor.0.pending.borrow_mut() = Some(committed);
880    {
881        let mut dirty = editor.0.dirty.borrow_mut();
882        dirty.dirty_type = DirtyType::FullReconcile;
883        dirty.leaves = OrderedSet::new();
884        dirty.elements = OrderedMap::new();
885    }
886    editor
887        .0
888        .updates
889        .borrow_mut()
890        .retain(|u| queued_before.contains(&u.id));
891}
892
893/// `$beginUpdate(editor, updateFn, options)`.
894pub(crate) fn begin_update(
895    editor: &Editor,
896    update_fn: impl FnOnce() -> Result<(), LexicalError>,
897    options: &UpdateOptions,
898) -> Result<(), LexicalError> {
899    begin_update_with(editor, update_fn, options, false)
900}
901
902/// `$beginUpdate(editor, updateFn, options, skipCommit)`: with
903/// `skip_commit`, the update extends one that is about to commit, whose
904/// caller owns the commit.
905fn begin_update_with(
906    editor: &Editor,
907    update_fn: impl FnOnce() -> Result<(), LexicalError>,
908    options: &UpdateOptions,
909    skip_commit: bool,
910) -> Result<(), LexicalError> {
911    editor.add_tags(&options.tags);
912    if let Some(on_update) = &options.on_update {
913        let on_update = on_update.clone();
914        editor
915            .0
916            .deferred
917            .borrow_mut()
918            .push(Box::new(move || on_update()));
919    }
920    let mut skip_transforms = options.skip_transforms;
921    let current = editor.get_editor_state();
922    let mut was_cloned = false;
923    let pending = match editor.pending() {
924        Some(pending) if !pending.0.read_only.get() => pending,
925        other => {
926            let pending = clone_editor_state(other.as_ref().unwrap_or(&current));
927            *editor.0.pending.borrow_mut() = Some(pending.clone());
928            was_cloned = true;
929            pending
930        }
931    };
932    pending.0.flush_sync.set(options.discrete);
933    // The updates queued before this one (see discard_pending_update).
934    let queued_before: HashSet<u64> = editor.0.updates.borrow().iter().map(|u| u.id).collect();
935    let previous_active_state = ACTIVE.with(|a| a.borrow().editor_state.clone());
936    let previously_notified_selection = editor.0.last_notified_selection.borrow().clone();
937
938    struct Restore<'a>(&'a Editor, bool);
939    impl Drop for Restore<'_> {
940        fn drop(&mut self) {
941            self.0.0.updating.set(self.1);
942            INFINITE_TRANSFORM_COUNT.with(|c| c.set(0));
943        }
944    }
945    let restore = Restore(editor, editor.0.updating.replace(true));
946
947    let active = Active {
948        editor: Some(editor.clone()),
949        editor_state: Some(pending.clone()),
950        read_only: false,
951        registry: None,
952    };
953    let result = with_active(active, || {
954        let run = || -> Result<(), LexicalError> {
955            if was_cloned && let Some(selection) = current.selection() {
956                // A headless editor carries the selection over. So does one
957                // with a root element, where JS reads the DOM selection
958                // (`$internalCreateSelection`): the app's view keeps it, as in
959                // Swift.
960                *pending.0.selection.borrow_mut() = Some(selection.clone_selection());
961            }
962            update_fn()?;
963            skip_transforms = process_nested_updates(editor, skip_transforms)?;
964            crate::lexical_selection::apply_selection_transforms(&pending, editor)?;
965            if editor.dirty_type() != DirtyType::None {
966                if skip_transforms {
967                    normalize_all_dirty_text_nodes(editor)?;
968                } else {
969                    apply_all_transforms(editor)?;
970                }
971                process_nested_updates(editor, false)?;
972                garbage_collect_detached_nodes(&current, &pending, editor);
973            }
974            if let Some(selection) = pending.selection() {
975                // A range selection must not straddle a slot boundary.
976                if selection.is_range() && editor.0.slots_used.get() {
977                    crate::lexical_selection::clamp_range_selection_to_slot_frame(&selection)?;
978                }
979                if let Some(range) = selection.range() {
980                    let node_map = pending.0.node_map.borrow();
981                    invariant!(
982                        node_map.contains_key(&range.anchor.key)
983                            && node_map.contains_key(&range.focus.key),
984                        "updateEditor: selection has been lost because the previously selected nodes have been removed and selection wasn't moved to another node. Ensure selection changes after removing/replacing a selected node."
985                    );
986                } else if selection.with_node(|n| n.nodes.is_empty()) == Some(true) {
987                    *pending.0.selection.borrow_mut() = None;
988                }
989            }
990            Ok(())
991        };
992        match run() {
993            Ok(()) => Ok(()),
994            Err(error) => {
995                // An update nested in the running update whose pending state
996                // it shares leaves the error to that update.
997                if !was_cloned
998                    && previous_active_state
999                        .as_ref()
1000                        .is_some_and(|s| s.ptr_eq(&pending))
1001                {
1002                    return Err(error);
1003                }
1004                discard_pending_update(editor, &queued_before);
1005                // JS reports a failure of this commit to onError too; the
1006                // caller gets the update's error.
1007                let _ = commit_pending_updates(editor);
1008                Err(error)
1009            }
1010        }
1011    });
1012    drop(restore);
1013    result?;
1014
1015    if skip_commit {
1016        return Ok(());
1017    }
1018    let should_update = editor.dirty_type() != DirtyType::None
1019        || !editor.0.deferred.borrow().is_empty()
1020        || has_dirty_selection(
1021            pending.selection().as_ref(),
1022            editor.get_editor_state().selection().as_ref(),
1023        );
1024    if should_update {
1025        if pending.0.flush_sync.get() {
1026            pending.0.flush_sync.set(false);
1027            commit_pending_updates(editor)?;
1028        }
1029        // Otherwise the next read or discrete update commits it.
1030    } else {
1031        pending.0.flush_sync.set(false);
1032        if was_cloned {
1033            *editor.0.tags.borrow_mut() = OrderedSet::new();
1034            editor.0.deferred.borrow_mut().clear();
1035            *editor.0.pending.borrow_mut() = None;
1036            // A notification in the dropped update recorded a selection
1037            // that never commits, which would suppress the next
1038            // notification of it.
1039            *editor.0.last_notified_selection.borrow_mut() = previously_notified_selection;
1040        }
1041    }
1042    Ok(())
1043}
1044
1045/// `updateEditorSync(editor, updateFn, options)`: runs `f` in the editor's
1046/// running update when there are no options, or in a new update.
1047pub(crate) fn update_editor_sync(
1048    editor: &Editor,
1049    f: impl FnOnce() -> Result<(), LexicalError>,
1050    options: Option<&UpdateOptions>,
1051) -> Result<(), LexicalError> {
1052    let (in_update, read_only) = ACTIVE.with(|a| {
1053        let a = a.borrow();
1054        (
1055            a.editor.as_ref().is_some_and(|e| e.ptr_eq(editor)),
1056            a.read_only,
1057        )
1058    });
1059    match options {
1060        None if in_update && !read_only => f(),
1061        None => {
1062            if in_update {
1063                // An update started from a read of the same editor (a
1064                // command dispatched in `read`) runs as a fresh writable
1065                // update, with JS's development warning.
1066                crate::warnings::console_warn(
1067                    "updateEditorSync: an editor update (e.g. a command listener that mutates the editor) ran while a read-only context was on the stack. This most commonly happens when a command is dispatched from inside editor.read(). The update has been deferred to a fresh writable update so it still applies, but dispatching mutations from a read-only context is an anti-pattern — dispatch after editor.read() returns, or via queueMicrotask.",
1068                );
1069            }
1070            begin_update(editor, f, &UpdateOptions::default())
1071        }
1072        Some(options) => begin_update(editor, f, options),
1073    }
1074}
1075
1076/// `triggerCommandListeners(editor, type, payload, fromEditor)`: the
1077/// command's listeners from the highest priority down, and within each
1078/// priority those of the editor, then of its parent editors
1079/// (`getEditorsToPropagate`), each editor's in one update of it, until one
1080/// returns true. Every listener gets `from_editor`, the editor the command
1081/// was dispatched in. A parent editor that is updating is skipped, and the
1082/// command is dispatched again from it in an update queued after its own,
1083/// whose result isn't known (JS's legacy delegation).
1084pub(crate) fn trigger_command_listeners<P: 'static>(
1085    editor: &Editor,
1086    command: &LexicalCommand<P>,
1087    payload: &Rc<P>,
1088    from_editor: &Editor,
1089) -> Result<bool, LexicalError> {
1090    let _dispatch = CommandDispatchGuard::enter();
1091    let editors = get_editors_to_propagate(editor);
1092    let mut updating_parent_editor: Option<Editor> = None;
1093    // A command dispatched from outside an update starts a new action, in
1094    // each editor it reaches that isn't updating, unless the commit
1095    // dispatched it (the selection notification, a mutation listener).
1096    if !is_committing_pending_updates() {
1097        for e in &editors {
1098            if !e.0.updating.get() {
1099                e.0.cascade_count.set(0);
1100            }
1101        }
1102    }
1103    if command.id() == crate::commands::SELECTION_CHANGE_COMMAND.id() {
1104        let (in_update, read_only) = ACTIVE.with(|a| {
1105            let a = a.borrow();
1106            (
1107                a.editor.as_ref().is_some_and(|e| e.ptr_eq(editor)),
1108                a.read_only,
1109            )
1110        });
1111        if !in_update || read_only {
1112            let mut handled = false;
1113            update_editor_sync(
1114                editor,
1115                || {
1116                    handled = trigger_command_listeners(editor, command, payload, from_editor)?;
1117                    Ok(())
1118                },
1119                None,
1120            )?;
1121            return Ok(handled);
1122        }
1123        // Every dispatch counts, an application's too; recorded before the
1124        // listeners run, so their selection changes notify in turn.
1125        *editor.0.last_notified_selection.borrow_mut() =
1126            get_active_editor_state().selection().map(|s| s.get());
1127    }
1128    for priority in (0..=4).rev() {
1129        for (e, current_editor) in editors.iter().enumerate() {
1130            if e > 0 && current_editor.0.updating.get() {
1131                // An updating editor can't be updated synchronously without
1132                // an early commit that could collect nodes too early.
1133                updating_parent_editor = Some(current_editor.clone());
1134                break;
1135            }
1136            let listeners = current_editor.command_listeners(command, priority);
1137            if listeners.is_empty() {
1138                continue;
1139            }
1140            let mut handled = false;
1141            update_editor_sync(
1142                current_editor,
1143                || {
1144                    for listener in &listeners {
1145                        if listener(payload, from_editor)? {
1146                            handled = true;
1147                            return Ok(());
1148                        }
1149                    }
1150                    Ok(())
1151                },
1152                None,
1153            )?;
1154            if handled {
1155                return Ok(true);
1156            }
1157        }
1158    }
1159    if let Some(updating_parent_editor) = updating_parent_editor {
1160        let (command, payload, from_editor) =
1161            (command.clone(), payload.clone(), from_editor.clone());
1162        let parent = updating_parent_editor.clone();
1163        updating_parent_editor.update(
1164            move || {
1165                // An update of its own, so its result can't be known.
1166                trigger_command_listeners(&parent, &command, &payload, &from_editor).map(|_| ())
1167            },
1168            UpdateOptions::default(),
1169        )?;
1170    }
1171    Ok(false)
1172}