lexical-ui 0.1.2

A Rust port of Lexical's model and headless packages, at parity with the JS implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
//! `LexicalUpdates.ts`: the active editor and editor state that `$`
//! functions read, the update cycle (`editor.update`, transforms, the
//! commit and its listeners), command dispatch, and `parseEditorState`.
//!
//! Without a root element the reconciler, mutation listeners and decorator
//! listeners never run, as in JS's headless editor; with one, the
//! reconciler's model half (`reconciler.rs`) does. Selection-change
//! notifications and the DOM selection never run here. Where JS commits a
//! non-discrete update in a microtask, Rust commits it at the next
//! [`Editor::read`] or discrete update, which JS also does when one comes
//! first.

use crate::editor::{
    DirtyType, LexicalCommand, MutationListenerPayload, NodeClass, Transform,
    UpdateListenerPayload, UpdateOptions,
};
use crate::editor_state::{clone_editor_state, create_empty_editor_state};
use crate::error::invariant;
use crate::gc::garbage_collect_detached_nodes;
use crate::json::Value;
use crate::lexical_selection::{SelectionRef, has_dirty_selection};
use crate::lexical_utils::{get_editors_to_propagate, get_node_by_key, get_root};
use crate::node::NodeRef;
use crate::node_state::{apply_flat_states, update_state_from_json};
use crate::nodes::element::is_root_or_shadow_root;
use crate::normalization::normalize_text_node;
use crate::ordered::{OrderedMap, OrderedSet};
use crate::{Editor, EditorState, LexicalError};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

/// JS's module-scope `activeEditor`, `activeEditorState` and
/// `isReadOnlyMode`, per thread.
#[derive(Clone, Default)]
struct Active {
    editor: Option<Editor>,
    editor_state: Option<EditorState>,
    read_only: bool,
    /// The editor whose node classes `$getEditor()` finds while
    /// `parseEditorState` runs, which JS makes the active editor and Rust
    /// doesn't (so nothing is marked dirty in it).
    registry: Option<Editor>,
}

thread_local! {
    static ACTIVE: RefCell<Active> = RefCell::new(Active::default());
    static INFINITE_TRANSFORM_COUNT: Cell<u32> = const { Cell::new(0) };
    /// `isCommittingPendingUpdates`: true for the whole of
    /// `$commitPendingUpdates`, so commands dispatched by the commit (the
    /// selection notification, mutation listeners) don't reset the update
    /// cascade budget.
    static IS_COMMITTING_PENDING_UPDATES: Cell<bool> = const { Cell::new(false) };
    /// `editorsWithPendingSelectionChange`, by the editors' addresses.
    static EDITORS_WITH_PENDING_SELECTION_CHANGE: RefCell<HashSet<usize>> =
        RefCell::new(HashSet::new());
    /// How many `triggerCommandListeners` calls are running, and the turn:
    /// a count of the outermost dispatches that returned. JS's microtasks
    /// run once the application's call returns; a dispatch is the port's
    /// nearest stand-in for that synchronous turn (`@lexical/mark`'s
    /// `forgetSoon`).
    static COMMAND_DISPATCH: Cell<(usize, u64)> = const { Cell::new((0, 0)) };
}

/// The turn of the running command dispatch, or `None` outside one: edits
/// recorded during a dispatch are those of the same synchronous turn until
/// the outermost dispatch returns (`@lexical/mark`'s `forgetSoon`).
#[cfg(all(feature = "mark", feature = "extension"))]
pub(crate) fn command_dispatch_turn() -> Option<u64> {
    let (depth, turn) = COMMAND_DISPATCH.with(Cell::get);
    (depth > 0).then_some(turn)
}

/// Counts a running dispatch until dropped.
struct CommandDispatchGuard;

impl CommandDispatchGuard {
    fn enter() -> Self {
        COMMAND_DISPATCH.with(|c| {
            let (depth, turn) = c.get();
            c.set((depth + 1, turn));
        });
        CommandDispatchGuard
    }
}

impl Drop for CommandDispatchGuard {
    fn drop(&mut self) {
        COMMAND_DISPATCH.with(|c| {
            let (depth, turn) = c.get();
            c.set(if depth == 1 {
                (0, turn + 1)
            } else {
                (depth - 1, turn)
            });
        });
    }
}

/// Runs `f` with `active` in place, restoring the previous one afterwards,
/// even when `f` panics.
fn with_active<R>(active: Active, f: impl FnOnce() -> R) -> R {
    struct Restore(Option<Active>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = self.0.take().expect("previous");
            ACTIVE.with(|a| *a.borrow_mut() = previous);
        }
    }
    let previous = ACTIVE.with(|a| std::mem::replace(&mut *a.borrow_mut(), active));
    let _restore = Restore(Some(previous));
    f()
}

/// `getActiveEditorState()`.
pub(crate) fn get_active_editor_state() -> EditorState {
    ACTIVE
        .with(|a| a.borrow().editor_state.clone())
        .unwrap_or_else(|| {
            panic!(
                "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()."
            )
        })
}

/// `INTERNAL_getActiveEditorState()`: the editor state of the update or
/// read that is running, if any.
#[cfg_attr(not(feature = "text"), allow(dead_code))]
pub(crate) fn internal_get_active_editor_state() -> Option<EditorState> {
    ACTIVE.with(|a| a.borrow().editor_state.clone())
}

/// `internalGetActiveEditor()`: the editor whose update or read is running,
/// if any. Reading an editor state on its own ([`EditorState::read`],
/// parsing) has none.
pub(crate) fn get_active_editor() -> Option<Editor> {
    ACTIVE.with(|a| a.borrow().editor.clone())
}

/// `$getEditor()` for the node classes: the active editor, or the one
/// `parseEditorState` parses for.
pub(crate) fn get_registry_editor() -> Option<Editor> {
    ACTIVE.with(|a| {
        let a = a.borrow();
        a.editor.clone().or_else(|| a.registry.clone())
    })
}

/// `isCurrentlyReadOnlyMode()`.
pub(crate) fn is_currently_read_only_mode() -> bool {
    ACTIVE.with(|a| a.borrow().read_only)
}

/// `errorOnReadOnly()`.
pub(crate) fn error_on_read_only() {
    if is_currently_read_only_mode() {
        panic!("Cannot use method in read-only mode.");
    }
}

/// `$flushSyncAfterUpdate()`: the running update commits when it ends, as
/// a discrete one does, rather than at the next read or discrete update.
#[cfg_attr(not(feature = "rich-text"), allow(dead_code))]
pub(crate) fn flush_sync_after_update() {
    let editor_state = get_active_editor_state();
    error_on_read_only();
    editor_state.0.flush_sync.set(true);
}

/// `$onUpdate(updateFn)` (`LexicalUtils.ts`): runs `update_fn` once the
/// update that is running commits, after its listeners.
pub fn on_update(update_fn: impl FnOnce() + 'static) {
    error_on_read_only();
    let editor = get_active_editor().unwrap_or_else(|| {
        panic!("Unable to find an active editor. This method can only be used synchronously during the callback of editor.update() or editor.read().")
    });
    editor.0.deferred.borrow_mut().push(Box::new(update_fn));
}

/// `triggerDeferredUpdateCallbacks(editor, deferred)`.
fn trigger_deferred_update_callbacks(editor: &Editor, deferred: Vec<Box<dyn FnOnce()>>) {
    if !deferred.is_empty() {
        with_updating(editor, || {
            for callback in deferred {
                callback();
            }
        });
    }
}

/// `errorOnInfiniteTransforms()`.
pub(crate) fn error_on_infinite_transforms() {
    if INFINITE_TRANSFORM_COUNT.with(Cell::get) > 99 {
        panic!(
            "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."
        );
    }
}

fn bump_infinite_transform_count() {
    INFINITE_TRANSFORM_COUNT.with(|c| c.set(c.get() + 1));
}

/// `readEditorState(editor, editorState, callbackFn)`.
pub(crate) fn read_editor_state<R>(
    editor: Option<&Editor>,
    editor_state: &EditorState,
    f: impl FnOnce() -> R,
) -> R {
    with_active(
        Active {
            editor: editor.cloned(),
            editor_state: Some(editor_state.clone()),
            read_only: true,
            registry: None,
        },
        f,
    )
}

/// `$applyTransforms(editor, node, transformsCache)`.
fn apply_transforms(
    editor: &Editor,
    node: &NodeRef,
    cache: &mut HashMap<&'static str, Vec<Transform>>,
) -> Result<(), LexicalError> {
    // The class's own `$transform` (`getTransformSetFromKlass` walks the
    // class chain from the node's class up), then `ElementNode`'s.
    node.get_latest().transform(node)?;
    if !node.is_attached() {
        return Ok(());
    }
    if node.is_element() {
        normalize_shadow_root_children(node)?;
        if !node.is_attached() {
            return Ok(());
        }
    }
    let node_type = node.get_type();
    let transforms = cache
        .entry(node_type)
        .or_insert_with(|| editor.transforms_of(node_type))
        .clone();
    for transform in &transforms {
        transform(node)?;
        if !node.is_attached() {
            break;
        }
    }
    Ok(())
}

/// `$normalizeShadowRootChildren(node)` (`LexicalElementNode.ts`), the
/// `$transform` every `ElementNode` has: wraps each run of inline children
/// of a root or shadow root in the block the first one's
/// `createParentElementNode` makes, for documents parsed from outside.
/// Where `NodeStructureExtension` enforces declared structure, it wraps
/// these children itself (a root or shadow root holds blocks), after their
/// own repairs: an empty inline element it removes is then never wrapped,
/// which it would be here if this transform ran first.
fn normalize_shadow_root_children(node: &NodeRef) -> Result<(), LexicalError> {
    if !is_root_or_shadow_root(&*node.get_latest())
        || crate::structure::is_structure_enforced_on_active_editor()
    {
        return Ok(());
    }
    let mut block: Option<NodeRef> = None;
    for child in node.get_children() {
        block = if child.is_inline() {
            let block = match block {
                Some(block) => block,
                None => child.replace(&child.create_parent_element_node(), false)?,
            };
            block.append(&[child])?;
            Some(block)
        } else {
            None
        };
    }
    Ok(())
}

/// Whether a dirty leaf is normalized: attached, simple, mergeable text.
fn should_normalize(node: &NodeRef) -> bool {
    node.is_text() && node.is_attached() && node.is_simple_text() && !node.is_unmergeable()
}

/// `$normalizeAllDirtyTextNodes(editorState, editor)`. Iterates the dirty
/// leaves as JS's `for...of` does, seeing those added meanwhile.
fn normalize_all_dirty_text_nodes(editor: &Editor) -> Result<(), LexicalError> {
    let mut i = 0;
    loop {
        let key = editor
            .0
            .dirty
            .borrow()
            .leaves
            .key_at(&mut i)
            .map(str::to_owned);
        let Some(key) = key else { break };
        if let Some(node) = get_node_by_key(&key)
            && should_normalize(&node)
        {
            normalize_text_node(&node)?;
        }
        i += 1;
    }
    Ok(())
}

/// `$applyAllTransforms(editorState, editor)`: transforms dirty leaves
/// first, repeating while they dirty more leaves, then the elements marked
/// dirty themselves, the root last, and again from the leaves while
/// anything new is dirty.
///
/// JS swaps the editor's dirty sets for fresh ones to see what each round
/// dirties, and accumulates the full record in the sets it started with;
/// in the first round the full record is the editor's own set, which is
/// why `full_*` is `None` until the editor's set is first swapped out.
fn apply_all_transforms(editor: &Editor) -> Result<(), LexicalError> {
    let mut cache = HashMap::new();
    // `$isNodeValidForTransform`: nodes being composed aren't transformed.
    let composition_key = crate::lexical_utils::get_composition_key();
    let is_composing = |node: &NodeRef| composition_key.as_deref() == Some(node.get_key());
    let mut full_leaves: Option<OrderedSet> = None;
    let mut full_elements: Option<OrderedMap<bool>> = None;

    loop {
        let (leaves_len, elements_len) = {
            let dirty = editor.0.dirty.borrow();
            (dirty.leaves.len(), dirty.elements.len())
        };
        if leaves_len == 0 && elements_len == 0 {
            break;
        }
        if leaves_len > 0 {
            let untransformed = std::mem::take(&mut editor.0.dirty.borrow_mut().leaves);
            let keys: Vec<String> = untransformed.iter().map(str::to_owned).collect();
            full_leaves.get_or_insert(untransformed);
            for key in &keys {
                if let Some(node) = get_node_by_key(key) {
                    if should_normalize(&node) {
                        normalize_text_node(&node)?;
                    }
                    if !is_composing(&node) && node.is_attached() {
                        apply_transforms(editor, &node, &mut cache)?;
                    }
                }
                full_leaves.as_mut().expect("set above").add(key);
            }
            // Leaf transforms come before element transforms.
            if !editor.0.dirty.borrow().leaves.is_empty() {
                bump_infinite_transform_count();
                continue;
            }
        }

        let (previous_leaves, mut untransformed) = {
            let mut dirty = editor.0.dirty.borrow_mut();
            (
                std::mem::take(&mut dirty.leaves),
                std::mem::take(&mut dirty.elements),
            )
        };
        full_leaves.get_or_insert(previous_leaves);
        // The root is always considered intentionally dirty if any attached
        // node is dirty, and moving it last applies its transforms last.
        if untransformed.delete("root").is_some() {
            untransformed.set("root", true);
        }
        full_elements.get_or_insert_with(|| untransformed.clone());
        let entries: Vec<(String, bool)> = untransformed
            .iter()
            .map(|(k, v)| (k.to_owned(), *v))
            .collect();
        for (key, intentionally_marked_as_dirty) in entries {
            full_elements
                .as_mut()
                .expect("set above")
                .set(&key, intentionally_marked_as_dirty);
            if !intentionally_marked_as_dirty {
                continue;
            }
            if let Some(node) = get_node_by_key(&key)
                && !is_composing(&node)
                && node.is_attached()
            {
                apply_transforms(editor, &node, &mut cache)?;
            }
        }
        bump_infinite_transform_count();
    }

    let mut dirty = editor.0.dirty.borrow_mut();
    if let Some(leaves) = full_leaves {
        dirty.leaves = leaves;
    }
    if let Some(elements) = full_elements {
        dirty.elements = elements;
    }
    Ok(())
}

/// `$parseSerializedNodeImpl`.
fn parse_serialized_node_impl(
    serialized_node: &Value,
    registered_nodes: &HashMap<&'static str, NodeClass>,
) -> Result<NodeRef, LexicalError> {
    let Some(object) = serialized_node.as_object() else {
        // `serializedNode.type` of a primitive is `undefined`; of `null` it
        // throws a TypeError.
        invariant!(
            !serialized_node.is_null(),
            "Cannot read properties of null (reading 'type')"
        );
        return Err(LexicalError::new(
            "parseEditorState: type \"undefined\" + not found",
        ));
    };
    let node_type = object.get("type");
    let registered = node_type
        .and_then(Value::as_str)
        .and_then(|t| registered_nodes.get(t));
    let Some(registered) = registered else {
        let shown = match node_type {
            None | Some(Value::Undefined) => "undefined".to_owned(),
            Some(Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
        };
        return Err(LexicalError::new(format!(
            "parseEditorState: type \"{shown}\" + not found"
        )));
    };
    let node = (registered.import_json)(object)?;
    // A class's own `importJSON` calls `updateFromJSON`, which applies what
    // the synthesized one does besides the class's own properties: the
    // nested NodeState (`$updateStateFromJSON`), then the flat states the
    // class declares (`$applyFlatStates`).
    if !registered.imports_node_state() {
        update_state_from_json(&node, object)?;
        apply_flat_states(&node, object)?;
    }
    if let Some(Value::Array(children)) = object.get("children")
        && node.is_element()
    {
        for child in children {
            let child = parse_serialized_node_impl(child, registered_nodes)?;
            node.append(&[child])?;
        }
    }
    // `$slots` is truthy for any object (an array too, whose indices are its
    // names) and any other truthy value, whose `for...in` finds nothing.
    if let Some(slots) = object.get("$slots").filter(|v| is_truthy(v)) {
        invariant!(
            crate::slot::is_slot_host(&node),
            "$parseSerializedNode: node {} has slots but is not a valid slot host; only ElementNodes and DecoratorNodes can host slots.",
            node.get_type()
        );
        let entries: Vec<(String, Value)> = match slots {
            Value::Object(o) => o.iter().map(|(k, v)| (k.to_owned(), v.clone())).collect(),
            Value::Array(a) => a
                .iter()
                .enumerate()
                .map(|(i, v)| (i.to_string(), v.clone()))
                .collect(),
            _ => Vec::new(),
        };
        for (name, value) in entries {
            let slot_node = parse_serialized_node_impl(&value, registered_nodes)?;
            crate::slot::set_slot(&node, &name, &slot_node)?;
        }
    }
    Ok(node)
}

/// Whether a JSON value is truthy in JS.
fn is_truthy(value: &Value) -> bool {
    match value {
        Value::Undefined | Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(n) => *n != 0.0 && !n.is_nan(),
        Value::String(s) => !s.is_empty(),
        Value::Array(_) | Value::Object(_) => true,
    }
}

/// `$parseSerializedNode(serializedNode)`: a node, and its children, from
/// its JSON, created in the active update with the active editor's node
/// classes.
pub fn parse_serialized_node(serialized_node: &Value) -> Result<NodeRef, LexicalError> {
    let editor =
        get_active_editor().ok_or_else(|| LexicalError::new("Unable to find an active editor."))?;
    parse_serialized_node_impl(serialized_node, editor.registered_nodes())
}

/// `parseEditorState(serializedEditorState, editor)`. The nodes are created
/// outside any update of the editor, so nothing is marked dirty (JS saves
/// and restores the editor's dirty records instead).
pub(crate) fn parse_editor_state(
    serialized_editor_state: &Value,
    editor: &Editor,
    update_fn: Option<Box<dyn FnOnce() -> Result<(), LexicalError> + '_>>,
) -> Result<EditorState, LexicalError> {
    let editor_state = create_empty_editor_state();
    let active = Active {
        editor: None,
        editor_state: Some(editor_state.clone()),
        read_only: false,
        registry: Some(editor.clone()),
    };
    with_active(active, || {
        let serialized_node = serialized_editor_state.get("root");
        invariant!(
            serialized_node.is_some_and(|v| !v.is_undefined()),
            "Cannot read properties of undefined (reading 'type')"
        );
        parse_serialized_node_impl(serialized_node.unwrap(), editor.registered_nodes())?;
        if let Some(update_fn) = update_fn {
            update_fn()?;
        }
        Ok(())
    })?;
    // Make the editor state immutable.
    editor_state.0.read_only.set(true);
    editor_state.0.parsed.set(true);
    Ok(editor_state)
}

/// `getEditorStateTextContent(editorState)`.
fn editor_state_text_content(editor_state: &EditorState) -> String {
    editor_state.read(|| get_root().get_text_content())
}

/// `triggerListeners`'s bracket: listeners run with the editor marked as
/// updating, so an update they start is queued.
fn with_updating<R>(editor: &Editor, f: impl FnOnce() -> R) -> R {
    struct Restore<'a>(&'a Editor, bool);
    impl Drop for Restore<'_> {
        fn drop(&mut self) {
            self.0.0.updating.set(self.1);
        }
    }
    let _restore = Restore(editor, editor.0.updating.replace(true));
    f()
}

/// `$commitPendingUpdates(editor)`: announces a changed selection with
/// `SELECTION_CHANGE_COMMAND` in the pending update, makes the pending
/// state the editor's state, notifies the text content and update
/// listeners, and runs the first update queued meanwhile.
pub(crate) fn commit_pending_updates(editor: &Editor) -> Result<(), LexicalError> {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            IS_COMMITTING_PENDING_UPDATES.with(|c| c.set(self.0));
        }
    }
    let _restore = Restore(IS_COMMITTING_PENDING_UPDATES.with(|c| c.replace(true)));
    let notification_result = notify_pending_selection_change(editor)?;
    commit_pending_updates_impl(editor)?;
    if notification_result {
        // Reported only after the pending edit is kept.
        editor.on_warn(LexicalError::new(
            "Selection change listeners are endlessly changing the selection.",
        ))?;
    }
    Ok(())
}

/// `hasSelectionChanged(editor, selection)`: whether `selection` differs
/// from the one last announced.
fn has_selection_changed(editor: &Editor, selection: Option<&SelectionRef>) -> bool {
    let previous = editor.0.last_notified_selection.borrow();
    match selection {
        None => previous.is_some(),
        Some(selection) => previous.as_ref().is_none_or(|p| !selection.get().is(p)),
    }
}

/// `$dispatchSelectionChangeCommand(editor, selection, force)`: announces
/// `selection` with `SELECTION_CHANGE_COMMAND` when it differs from the one
/// last announced, or always with `force`. Runs in the editor's pending
/// update.
pub(crate) fn dispatch_selection_change_command(
    editor: &Editor,
    selection: Option<&SelectionRef>,
    force: bool,
) -> Result<(), LexicalError> {
    if !force && !has_selection_changed(editor, selection) {
        return Ok(());
    }
    editor.dispatch_command(&crate::commands::SELECTION_CHANGE_COMMAND, ())?;
    Ok(())
}

/// `$notifyPendingSelectionChange(editor)`: while the pending selection
/// differs from the one last announced, dispatches `SELECTION_CHANGE_COMMAND`
/// in the pending update (its listeners' edits join it), up to 100 times.
/// A range selection, or none, is not announced by an editor without a
/// connected root element. Returns true when the listeners hit the limit.
fn notify_pending_selection_change(editor: &Editor) -> Result<bool, LexicalError> {
    let id = Rc::as_ptr(&editor.0) as usize;
    if !EDITORS_WITH_PENDING_SELECTION_CHANGE.with(|s| s.borrow_mut().insert(id)) {
        return Ok(false);
    }
    struct Remove(usize);
    impl Drop for Remove {
        fn drop(&mut self) {
            EDITORS_WITH_PENDING_SELECTION_CHANGE.with(|s| s.borrow_mut().remove(&self.0));
        }
    }
    let _remove = Remove(id);
    let mut count = 0;
    while let Some(pending) = editor.pending() {
        let selection = pending.selection();
        if !has_selection_changed(editor, selection.as_ref()) {
            return Ok(false);
        }
        let root_connected = editor
            .get_root_element()
            .is_some_and(|root| root.0.is_connected());
        let skip_notification = selection.as_ref().is_none_or(SelectionRef::is_range)
            && (editor.is_headless() || !root_connected);
        if skip_notification || count == 100 {
            // Skipped notifications are not replayed once the root
            // reconnects, nor after stopping a listener loop.
            *editor.0.last_notified_selection.borrow_mut() = selection.map(|s| s.get());
            return Ok(!skip_notification);
        }
        // Extends the pending update, with its error handling; the caller
        // owns the commit, so the listeners' edits and transforms join it.
        let e = editor.clone();
        begin_update_with(
            editor,
            move || {
                e.dispatch_command(&crate::commands::SELECTION_CHANGE_COMMAND, ())
                    .map(|_| ())
            },
            &UpdateOptions::default(),
            true,
        )?;
        count += 1;
    }
    Ok(false)
}

/// Whether a commit ([`commit_pending_updates`]) is running on this thread
/// (`isCommittingPendingUpdates`): the commands dispatched and the updates
/// begun meanwhile are part of it, not a new action, so they don't reset
/// the cascade budget.
pub(crate) fn is_committing_pending_updates() -> bool {
    IS_COMMITTING_PENDING_UPDATES.with(Cell::get)
}

/// The commit itself (`$commitPendingUpdatesImpl`).
fn commit_pending_updates_impl(editor: &Editor) -> Result<(), LexicalError> {
    let pending = editor.0.pending.borrow_mut().take();
    let Some(pending) = pending else {
        // Even without a pending state, flush the deferred callbacks a
        // prior update added.
        if !editor.0.updating.get() && !editor.0.deferred.borrow().is_empty() {
            let deferred = std::mem::take(&mut *editor.0.deferred.borrow_mut());
            trigger_deferred_update_callbacks(editor, deferred);
        }
        return Ok(());
    };
    let current = editor.get_editor_state();
    let needs_update = editor.dirty_type() != DirtyType::None;
    let previously_updating = editor.0.updating.get();
    *editor.0.editor_state.borrow_mut() = pending.clone();
    // The reconciler's model half, with a root element: which nodes it
    // creates, updates and destroys, for the mutation listeners, the
    // decorators, and the elements' text format and style.
    let mutated_nodes =
        if !editor.is_headless() && editor.get_root_element().is_some() && needs_update {
            let mutated = with_active(
                Active {
                    editor: Some(editor.clone()),
                    editor_state: Some(pending.clone()),
                    read_only: false,
                    registry: None,
                },
                || {
                    with_updating(editor, || {
                        let mutated = crate::reconciler::reconcile_root(&current, &pending, editor);
                        (mutated, get_root().get_text_content())
                    })
                },
            );
            let (mutated, text) = mutated;
            // The end of `$reconcileNode('root')`: the root caches its text
            // content (`__cachedText`). A stale cache (a root not reconciled
            // since it was cloned or made) is written through `getWritable()`,
            // which marks the root dirty, as the update listeners then see;
            // not in a committed state (`activeEditorStateReadOnly`), such as
            // the one `setRootElement` reconciles.
            let root = pending.0.node_map.borrow().get("root").cloned();
            if let Some(root) = root.filter(|_| !pending.0.read_only.get()) {
                let mut cache = editor.0.root_text_cache.borrow_mut();
                let fresh = cache.as_ref().is_some_and(|(cached, cached_text)| {
                    Rc::ptr_eq(cached, &root) && *cached_text == text
                });
                if !fresh {
                    editor.0.dirty.borrow_mut().elements.set("root", true);
                    *cache = Some((root, text));
                }
            }
            Some(mutated)
        } else {
            None
        };
    pending.0.read_only.set(true);

    let (dirty_elements, dirty_leaves, normalized_nodes) = {
        let mut dirty = editor.0.dirty.borrow_mut();
        let elements = dirty
            .elements
            .iter()
            .map(|(k, v)| (k.to_owned(), *v))
            .collect();
        let leaves = dirty.leaves.iter().map(str::to_owned).collect();
        let normalized = dirty.normalized.iter().map(str::to_owned).collect();
        if needs_update {
            *dirty = Default::default();
        }
        (elements, leaves, normalized)
    };
    // Reset even when nothing is dirty, so a no-op update's tags don't leak
    // into the next one.
    let tags: Vec<String> = std::mem::take(&mut *editor.0.tags.borrow_mut())
        .iter()
        .map(str::to_owned)
        .collect();

    // Listeners may start another update, which must not inherit them; an
    // outer update still owns its callbacks when it forces an early commit.
    let deferred = if previously_updating {
        Vec::new()
    } else {
        std::mem::take(&mut *editor.0.deferred.borrow_mut())
    };
    crate::reconciler::garbage_collect_detached_decorators(editor, &pending);
    let previously_dispatching = editor.0.dispatching_commit_listeners.replace(true);
    // The mutation listeners run as the editor was updating before the
    // commit (not, at the top level), so an update one starts begins at
    // once, as in JS; the other listeners run as updating.
    if let Some(mutated_nodes) = &mutated_nodes {
        let leaves: &Vec<String> = &dirty_leaves;
        trigger_mutation_listeners(editor, mutated_nodes, &tags, leaves, &current);
    }
    with_updating(editor, || {
        // The decorators the reconciler and the GC changed.
        let pending_decorators = editor.0.pending_decorators.borrow_mut().take();
        if let Some(pending_decorators) = pending_decorators {
            *editor.0.decorators.borrow_mut() = pending_decorators.clone();
            editor.trigger_decorator_listeners(&pending_decorators);
        }
        if editor.has_text_content_listeners() {
            let current_text = editor_state_text_content(&current);
            let latest_text = editor_state_text_content(&pending);
            if current_text != latest_text {
                editor.trigger_text_content_listeners(&latest_text);
            }
        }
        let payload = UpdateListenerPayload {
            dirty_elements,
            dirty_leaves,
            normalized_nodes,
            tags,
            editor_state: pending.clone(),
            prev_editor_state: current.clone(),
            mutated_nodes: mutated_nodes.clone(),
        };
        editor.trigger_update_listeners(&payload);
    });
    editor
        .0
        .dispatching_commit_listeners
        .set(previously_dispatching);
    if !previously_updating {
        trigger_deferred_update_callbacks(editor, deferred);
    }
    trigger_enqueued_updates(editor)
}

/// `triggerMutationListeners(editor, mutatedNodes, updateTags, dirtyLeaves,
/// prevEditorState)`: each listener, for each class it listens to that the
/// commit mutated.
fn trigger_mutation_listeners(
    editor: &Editor,
    mutated_nodes: &crate::reconciler::MutatedNodes,
    update_tags: &[String],
    dirty_leaves: &[String],
    prev_editor_state: &EditorState,
) {
    let payload = MutationListenerPayload {
        dirty_leaves: dirty_leaves.to_vec(),
        prev_editor_state: prev_editor_state.clone(),
        update_tags: update_tags.to_vec(),
    };
    for (listener, node_type) in editor.mutation_listeners() {
        if let Some((_, mutations)) = mutated_nodes.iter().find(|(t, _)| *t == node_type) {
            listener(mutations, &payload);
        }
    }
}

/// `$triggerEnqueuedUpdates(editor)`: begins the next queued update, if
/// any, unless listeners have been queueing updates endlessly.
fn trigger_enqueued_updates(editor: &Editor) -> Result<(), LexicalError> {
    if editor.0.updates.borrow().is_empty() {
        editor.0.cascade_count.set(0);
        return Ok(());
    }
    let count = editor
        .0
        .cascade_count
        .replace(editor.0.cascade_count.get() + 1);
    if count > 99 {
        editor.0.updates.borrow_mut().clear();
        editor.0.cascade_count.set(0);
        // Reported through `onWarn` after breaking the cascade.
        return editor.on_warn(LexicalError::new(format!(
            "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: {}",
            editor.get_namespace()
        )));
    }
    let queued = editor.0.updates.borrow_mut().pop_front();
    match queued {
        Some(queued) => begin_update(editor, queued.update_fn, &queued.options),
        None => Ok(()),
    }
}

/// `$processNestedUpdates(editor, initialSkipTransforms)`: runs the updates
/// queued during this one as part of it.
fn process_nested_updates(editor: &Editor, initial_skip: bool) -> Result<bool, LexicalError> {
    let mut skip_transforms = initial_skip;
    loop {
        let queued = editor.0.updates.borrow_mut().pop_front();
        let Some(queued) = queued else { break };
        let pending = editor.pending();
        if queued.options.skip_transforms {
            skip_transforms = true;
        }
        if let Some(on_update) = &queued.options.on_update {
            let on_update = on_update.clone();
            editor
                .0
                .deferred
                .borrow_mut()
                .push(Box::new(move || on_update()));
        }
        if queued.options.discrete {
            invariant!(
                pending.is_some(),
                "Unexpected empty pending editor state on discrete nested update"
            );
            pending.as_ref().expect("checked").0.flush_sync.set(true);
        }
        editor.add_tags(&queued.options.tags);
        if pending.is_none() {
            begin_update(editor, queued.update_fn, &queued.options)?;
        } else {
            (queued.update_fn)()?;
        }
    }
    Ok(skip_transforms)
}

/// `$discardPendingUpdate(editor, queuedBefore)`: the editor goes back to
/// its committed state; the updates the failed one queued are dropped.
fn discard_pending_update(editor: &Editor, queued_before: &HashSet<u64>) {
    let committed = editor.get_editor_state();
    // A notification in the rejected update must not suppress a later
    // retry or make up a selection change while restoring the committed
    // state.
    *editor.0.last_notified_selection.borrow_mut() = committed.selection().map(|s| s.get());
    *editor.0.pending.borrow_mut() = Some(committed);
    {
        let mut dirty = editor.0.dirty.borrow_mut();
        dirty.dirty_type = DirtyType::FullReconcile;
        dirty.leaves = OrderedSet::new();
        dirty.elements = OrderedMap::new();
    }
    editor
        .0
        .updates
        .borrow_mut()
        .retain(|u| queued_before.contains(&u.id));
}

/// `$beginUpdate(editor, updateFn, options)`.
pub(crate) fn begin_update(
    editor: &Editor,
    update_fn: impl FnOnce() -> Result<(), LexicalError>,
    options: &UpdateOptions,
) -> Result<(), LexicalError> {
    begin_update_with(editor, update_fn, options, false)
}

/// `$beginUpdate(editor, updateFn, options, skipCommit)`: with
/// `skip_commit`, the update extends one that is about to commit, whose
/// caller owns the commit.
fn begin_update_with(
    editor: &Editor,
    update_fn: impl FnOnce() -> Result<(), LexicalError>,
    options: &UpdateOptions,
    skip_commit: bool,
) -> Result<(), LexicalError> {
    editor.add_tags(&options.tags);
    if let Some(on_update) = &options.on_update {
        let on_update = on_update.clone();
        editor
            .0
            .deferred
            .borrow_mut()
            .push(Box::new(move || on_update()));
    }
    let mut skip_transforms = options.skip_transforms;
    let current = editor.get_editor_state();
    let mut was_cloned = false;
    let pending = match editor.pending() {
        Some(pending) if !pending.0.read_only.get() => pending,
        other => {
            let pending = clone_editor_state(other.as_ref().unwrap_or(&current));
            *editor.0.pending.borrow_mut() = Some(pending.clone());
            was_cloned = true;
            pending
        }
    };
    pending.0.flush_sync.set(options.discrete);
    // The updates queued before this one (see discard_pending_update).
    let queued_before: HashSet<u64> = editor.0.updates.borrow().iter().map(|u| u.id).collect();
    let previous_active_state = ACTIVE.with(|a| a.borrow().editor_state.clone());
    let previously_notified_selection = editor.0.last_notified_selection.borrow().clone();

    struct Restore<'a>(&'a Editor, bool);
    impl Drop for Restore<'_> {
        fn drop(&mut self) {
            self.0.0.updating.set(self.1);
            INFINITE_TRANSFORM_COUNT.with(|c| c.set(0));
        }
    }
    let restore = Restore(editor, editor.0.updating.replace(true));

    let active = Active {
        editor: Some(editor.clone()),
        editor_state: Some(pending.clone()),
        read_only: false,
        registry: None,
    };
    let result = with_active(active, || {
        let run = || -> Result<(), LexicalError> {
            if was_cloned && let Some(selection) = current.selection() {
                // A headless editor carries the selection over. So does one
                // with a root element, where JS reads the DOM selection
                // (`$internalCreateSelection`): the app's view keeps it, as in
                // Swift.
                *pending.0.selection.borrow_mut() = Some(selection.clone_selection());
            }
            update_fn()?;
            skip_transforms = process_nested_updates(editor, skip_transforms)?;
            crate::lexical_selection::apply_selection_transforms(&pending, editor)?;
            if editor.dirty_type() != DirtyType::None {
                if skip_transforms {
                    normalize_all_dirty_text_nodes(editor)?;
                } else {
                    apply_all_transforms(editor)?;
                }
                process_nested_updates(editor, false)?;
                garbage_collect_detached_nodes(&current, &pending, editor);
            }
            if let Some(selection) = pending.selection() {
                // A range selection must not straddle a slot boundary.
                if selection.is_range() && editor.0.slots_used.get() {
                    crate::lexical_selection::clamp_range_selection_to_slot_frame(&selection)?;
                }
                if let Some(range) = selection.range() {
                    let node_map = pending.0.node_map.borrow();
                    invariant!(
                        node_map.contains_key(&range.anchor.key)
                            && node_map.contains_key(&range.focus.key),
                        "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."
                    );
                } else if selection.with_node(|n| n.nodes.is_empty()) == Some(true) {
                    *pending.0.selection.borrow_mut() = None;
                }
            }
            Ok(())
        };
        match run() {
            Ok(()) => Ok(()),
            Err(error) => {
                // An update nested in the running update whose pending state
                // it shares leaves the error to that update.
                if !was_cloned
                    && previous_active_state
                        .as_ref()
                        .is_some_and(|s| s.ptr_eq(&pending))
                {
                    return Err(error);
                }
                discard_pending_update(editor, &queued_before);
                // JS reports a failure of this commit to onError too; the
                // caller gets the update's error.
                let _ = commit_pending_updates(editor);
                Err(error)
            }
        }
    });
    drop(restore);
    result?;

    if skip_commit {
        return Ok(());
    }
    let should_update = editor.dirty_type() != DirtyType::None
        || !editor.0.deferred.borrow().is_empty()
        || has_dirty_selection(
            pending.selection().as_ref(),
            editor.get_editor_state().selection().as_ref(),
        );
    if should_update {
        if pending.0.flush_sync.get() {
            pending.0.flush_sync.set(false);
            commit_pending_updates(editor)?;
        }
        // Otherwise the next read or discrete update commits it.
    } else {
        pending.0.flush_sync.set(false);
        if was_cloned {
            *editor.0.tags.borrow_mut() = OrderedSet::new();
            editor.0.deferred.borrow_mut().clear();
            *editor.0.pending.borrow_mut() = None;
            // A notification in the dropped update recorded a selection
            // that never commits, which would suppress the next
            // notification of it.
            *editor.0.last_notified_selection.borrow_mut() = previously_notified_selection;
        }
    }
    Ok(())
}

/// `updateEditorSync(editor, updateFn, options)`: runs `f` in the editor's
/// running update when there are no options, or in a new update.
pub(crate) fn update_editor_sync(
    editor: &Editor,
    f: impl FnOnce() -> Result<(), LexicalError>,
    options: Option<&UpdateOptions>,
) -> Result<(), LexicalError> {
    let (in_update, read_only) = ACTIVE.with(|a| {
        let a = a.borrow();
        (
            a.editor.as_ref().is_some_and(|e| e.ptr_eq(editor)),
            a.read_only,
        )
    });
    match options {
        None if in_update && !read_only => f(),
        None => {
            if in_update {
                // An update started from a read of the same editor (a
                // command dispatched in `read`) runs as a fresh writable
                // update, with JS's development warning.
                crate::warnings::console_warn(
                    "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.",
                );
            }
            begin_update(editor, f, &UpdateOptions::default())
        }
        Some(options) => begin_update(editor, f, options),
    }
}

/// `triggerCommandListeners(editor, type, payload, fromEditor)`: the
/// command's listeners from the highest priority down, and within each
/// priority those of the editor, then of its parent editors
/// (`getEditorsToPropagate`), each editor's in one update of it, until one
/// returns true. Every listener gets `from_editor`, the editor the command
/// was dispatched in. A parent editor that is updating is skipped, and the
/// command is dispatched again from it in an update queued after its own,
/// whose result isn't known (JS's legacy delegation).
pub(crate) fn trigger_command_listeners<P: 'static>(
    editor: &Editor,
    command: &LexicalCommand<P>,
    payload: &Rc<P>,
    from_editor: &Editor,
) -> Result<bool, LexicalError> {
    let _dispatch = CommandDispatchGuard::enter();
    let editors = get_editors_to_propagate(editor);
    let mut updating_parent_editor: Option<Editor> = None;
    // A command dispatched from outside an update starts a new action, in
    // each editor it reaches that isn't updating, unless the commit
    // dispatched it (the selection notification, a mutation listener).
    if !is_committing_pending_updates() {
        for e in &editors {
            if !e.0.updating.get() {
                e.0.cascade_count.set(0);
            }
        }
    }
    if command.id() == crate::commands::SELECTION_CHANGE_COMMAND.id() {
        let (in_update, read_only) = ACTIVE.with(|a| {
            let a = a.borrow();
            (
                a.editor.as_ref().is_some_and(|e| e.ptr_eq(editor)),
                a.read_only,
            )
        });
        if !in_update || read_only {
            let mut handled = false;
            update_editor_sync(
                editor,
                || {
                    handled = trigger_command_listeners(editor, command, payload, from_editor)?;
                    Ok(())
                },
                None,
            )?;
            return Ok(handled);
        }
        // Every dispatch counts, an application's too; recorded before the
        // listeners run, so their selection changes notify in turn.
        *editor.0.last_notified_selection.borrow_mut() =
            get_active_editor_state().selection().map(|s| s.get());
    }
    for priority in (0..=4).rev() {
        for (e, current_editor) in editors.iter().enumerate() {
            if e > 0 && current_editor.0.updating.get() {
                // An updating editor can't be updated synchronously without
                // an early commit that could collect nodes too early.
                updating_parent_editor = Some(current_editor.clone());
                break;
            }
            let listeners = current_editor.command_listeners(command, priority);
            if listeners.is_empty() {
                continue;
            }
            let mut handled = false;
            update_editor_sync(
                current_editor,
                || {
                    for listener in &listeners {
                        if listener(payload, from_editor)? {
                            handled = true;
                            return Ok(());
                        }
                    }
                    Ok(())
                },
                None,
            )?;
            if handled {
                return Ok(true);
            }
        }
    }
    if let Some(updating_parent_editor) = updating_parent_editor {
        let (command, payload, from_editor) =
            (command.clone(), payload.clone(), from_editor.clone());
        let parent = updating_parent_editor.clone();
        updating_parent_editor.update(
            move || {
                // An update of its own, so its result can't be known.
                trigger_command_listeners(&parent, &command, &payload, &from_editor).map(|_| ())
            },
            UpdateOptions::default(),
        )?;
    }
    Ok(false)
}