1use 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#[derive(Clone, Default)]
36struct Active {
37 editor: Option<Editor>,
38 editor_state: Option<EditorState>,
39 read_only: bool,
40 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 static IS_COMMITTING_PENDING_UPDATES: Cell<bool> = const { Cell::new(false) };
54 static EDITORS_WITH_PENDING_SELECTION_CHANGE: RefCell<HashSet<usize>> =
56 RefCell::new(HashSet::new());
57 static COMMAND_DISPATCH: Cell<(usize, u64)> = const { Cell::new((0, 0)) };
63}
64
65#[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
74struct 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
100fn 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
115pub(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#[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
133pub(crate) fn get_active_editor() -> Option<Editor> {
137 ACTIVE.with(|a| a.borrow().editor.clone())
138}
139
140pub(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
149pub(crate) fn is_currently_read_only_mode() -> bool {
151 ACTIVE.with(|a| a.borrow().read_only)
152}
153
154pub(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#[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
170pub 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
180fn 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
191pub(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
204pub(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
221fn apply_transforms(
223 editor: &Editor,
224 node: &NodeRef,
225 cache: &mut HashMap<&'static str, Vec<Transform>>,
226) -> Result<(), LexicalError> {
227 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
253fn 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
283fn should_normalize(node: &NodeRef) -> bool {
285 node.is_text() && node.is_attached() && node.is_simple_text() && !node.is_unmergeable()
286}
287
288fn 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
311fn apply_all_transforms(editor: &Editor) -> Result<(), LexicalError> {
321 let mut cache = HashMap::new();
322 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 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 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
404fn 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 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 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 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
476fn 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
487pub 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
496pub(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 editor_state.0.read_only.set(true);
525 editor_state.0.parsed.set(true);
526 Ok(editor_state)
527}
528
529fn editor_state_text_content(editor_state: &EditorState) -> String {
531 editor_state.read(|| get_root().get_text_content())
532}
533
534fn 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
547pub(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 editor.on_warn(LexicalError::new(
564 "Selection change listeners are endlessly changing the selection.",
565 ))?;
566 }
567 Ok(())
568}
569
570fn 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
580pub(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
596fn 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 *editor.0.last_notified_selection.borrow_mut() = selection.map(|s| s.get());
628 return Ok(!skip_notification);
629 }
630 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
647pub(crate) fn is_committing_pending_updates() -> bool {
652 IS_COMMITTING_PENDING_UPDATES.with(Cell::get)
653}
654
655fn commit_pending_updates_impl(editor: &Editor) -> Result<(), LexicalError> {
657 let pending = editor.0.pending.borrow_mut().take();
658 let Some(pending) = pending else {
659 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 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(¤t, &pending, editor);
686 (mutated, get_root().get_text_content())
687 })
688 },
689 );
690 let (mutated, text) = mutated;
691 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 let tags: Vec<String> = std::mem::take(&mut *editor.0.tags.borrow_mut())
731 .iter()
732 .map(str::to_owned)
733 .collect();
734
735 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 if let Some(mutated_nodes) = &mutated_nodes {
748 let leaves: &Vec<String> = &dirty_leaves;
749 trigger_mutation_listeners(editor, mutated_nodes, &tags, leaves, ¤t);
750 }
751 with_updating(editor, || {
752 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(¤t);
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
786fn 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
808fn 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 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
835fn 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
871fn discard_pending_update(editor: &Editor, queued_before: &HashSet<u64>) {
874 let committed = editor.get_editor_state();
875 *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
893pub(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
902fn 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(¤t));
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 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 *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(¤t, &pending, editor);
973 }
974 if let Some(selection) = pending.selection() {
975 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 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 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 } 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 *editor.0.last_notified_selection.borrow_mut() = previously_notified_selection;
1040 }
1041 }
1042 Ok(())
1043}
1044
1045pub(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 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
1076pub(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 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 *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 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 trigger_command_listeners(&parent, &command, &payload, &from_editor).map(|_| ())
1167 },
1168 UpdateOptions::default(),
1169 )?;
1170 }
1171 Ok(false)
1172}