1use crate::editor_state::{clone_editor_state, create_empty_editor_state};
5use crate::error::invariant;
6use crate::json::{self, Object, Value};
7use crate::lexical_utils::{create_uid, set_node_key};
8use crate::node::{LexicalNode, NodeKey, NodeRef};
9use crate::node_state::{RequiredNodeStateConfig, SharedNodeState, create_shared_node_state};
10use crate::nodes::{
11 artificial::ArtificialNode, line_break::LineBreakNode, paragraph::ParagraphNode,
12 root::RootNode, tab::TabNode, text::TextNode,
13};
14use crate::ordered::{OrderedMap, OrderedSet};
15use crate::reconciler::Decorators;
16use crate::selection_deletion::SelectionMovement;
17use crate::structure::{
18 DeclaredNodeStructure, NodeStructureRegistration, get_declared_node_structure,
19 validate_node_structure,
20};
21use crate::updates::{
22 begin_update, commit_pending_updates, parse_editor_state, read_editor_state,
23 trigger_command_listeners, update_editor_sync,
24};
25use crate::{EditorState, LexicalError};
26use std::any::Any;
27use std::cell::{Cell, RefCell};
28use std::collections::{HashMap, VecDeque};
29use std::marker::PhantomData;
30use std::rc::{Rc, Weak};
31
32#[derive(Clone)]
37pub struct NodeClass {
38 pub(crate) node_type: &'static str,
39 pub(crate) class_name: &'static str,
43 pub(crate) import_json: fn(&Object) -> Result<NodeRef, LexicalError>,
44 pub(crate) state_configs: fn() -> Vec<RequiredNodeStateConfig>,
46 #[cfg(feature = "html")]
48 pub(crate) import_dom: fn() -> Option<crate::lexical_dom::DomConversionMap>,
49 #[cfg_attr(not(feature = "extension"), allow(dead_code))]
55 pub(crate) is_inline_element: fn() -> bool,
56 pub(crate) declared_slots: fn() -> &'static [&'static str],
58 #[cfg_attr(not(feature = "extension"), allow(dead_code))]
61 pub(crate) is_text: fn() -> bool,
62 pub(crate) is_element_or_decorator: fn() -> bool,
65 node_structure: fn() -> DeclaredNodeStructure,
67 validate_node_structure: fn(),
69 pub(crate) super_types: fn() -> Vec<&'static str>,
72 pub(crate) replacement: Option<Rc<LexicalNodeReplacement>>,
74 new_node: Option<fn() -> Box<dyn LexicalNode>>,
77}
78
79fn new_node_of<T: LexicalNode + Default>() -> Box<dyn LexicalNode> {
80 Box::new(T::default())
81}
82
83pub type NodeReplace = Rc<dyn Fn(&NodeRef) -> Result<NodeRef, LexicalError>>;
87
88#[derive(Clone)]
95pub struct LexicalNodeReplacement {
96 pub replace: NodeClass,
97 pub with: NodeReplace,
98 pub with_klass: Option<NodeClass>,
99}
100
101impl From<LexicalNodeReplacement> for NodeClass {
102 fn from(replacement: LexicalNodeReplacement) -> Self {
103 let mut class = replacement.replace.clone();
104 class.replacement = Some(Rc::new(replacement));
105 class
106 }
107}
108
109fn is_element_or_decorator_of<T: LexicalNode + Default>() -> bool {
110 let node = T::default();
111 node.element().is_some() || node.is_decorator()
112}
113
114fn node_structure_of<T: LexicalNode + Default>() -> DeclaredNodeStructure {
115 get_declared_node_structure(&T::default())
116}
117
118fn validate_node_structure_of<T: LexicalNode + Default>() {
119 validate_node_structure(&T::default());
120}
121
122fn declared_slots_of<T: LexicalNode + Default>() -> &'static [&'static str] {
123 T::default().declared_slots()
124}
125
126#[cfg(feature = "html")]
127fn import_dom_of<T: LexicalNode + Default>() -> Option<crate::lexical_dom::DomConversionMap> {
128 T::default().import_dom()
129}
130
131fn state_configs_of<T: LexicalNode + Default>() -> Vec<RequiredNodeStateConfig> {
132 T::default().state_configs()
133}
134
135fn is_text_of<T: LexicalNode + Default>() -> bool {
136 T::default().text().is_some()
137}
138
139fn super_types_of<T: LexicalNode + Default>() -> Vec<&'static str> {
140 T::default().super_types()
141}
142
143fn is_inline_element_of<T: LexicalNode + Default>() -> bool {
144 let node = T::default();
145 node.element().is_some() && node.is_inline()
146}
147
148fn import_default<T: LexicalNode + Default>(json: &Object) -> Result<NodeRef, LexicalError> {
151 let node_type = T::default().get_type();
152 let has_replacement = crate::updates::get_registry_editor().is_some_and(|editor| {
153 editor
154 .get_registered_node(node_type)
155 .is_some_and(|class| class.replacement.is_some())
156 });
157 let node = if has_replacement {
158 crate::lexical_utils::create::<T>()
159 } else {
160 set_node_key(Box::new(T::default()))
161 };
162 crate::node_state::update_state_from_json(&node, json)?;
166 crate::node_state::apply_flat_states(&node, json)?;
167 crate::lexical_utils::mutate(node.get_key(), |n| n.update_from_json(json));
168 Ok(node)
169}
170
171impl NodeClass {
172 pub fn of<T: LexicalNode + Default>() -> Self {
175 Self {
176 node_type: T::default().get_type(),
177 class_name: std::any::type_name::<T>()
178 .rsplit("::")
179 .next()
180 .unwrap_or_default(),
181 import_json: import_default::<T>,
182 state_configs: state_configs_of::<T>,
183 #[cfg(feature = "html")]
184 import_dom: import_dom_of::<T>,
185 is_inline_element: is_inline_element_of::<T>,
186 declared_slots: declared_slots_of::<T>,
187 is_text: is_text_of::<T>,
188 is_element_or_decorator: is_element_or_decorator_of::<T>,
189 node_structure: node_structure_of::<T>,
190 validate_node_structure: validate_node_structure_of::<T>,
191 super_types: super_types_of::<T>,
192 replacement: None,
193 new_node: Some(new_node_of::<T>),
194 }
195 }
196
197 pub fn with_import_json(
200 node_type: &'static str,
201 import_json: fn(&Object) -> Result<NodeRef, LexicalError>,
202 ) -> Self {
203 Self {
204 node_type,
205 class_name: node_type,
206 import_json,
207 state_configs: Vec::new,
208 #[cfg(feature = "html")]
209 import_dom: || None,
210 is_inline_element: || false,
211 declared_slots: || &[],
212 is_text: || false,
213 is_element_or_decorator: || false,
214 node_structure: DeclaredNodeStructure::default,
215 validate_node_structure: || {},
216 super_types: Vec::new,
217 replacement: None,
218 new_node: None,
219 }
220 }
221
222 pub fn node_type(&self) -> &'static str {
223 self.node_type
224 }
225
226 pub(crate) fn imports_node_state(&self) -> bool {
230 self.new_node.is_some()
231 }
232
233 pub(crate) fn construct(&self) -> Option<NodeRef> {
235 self.new_node.map(|f| set_node_key(f()))
236 }
237
238 pub(crate) fn replace_with_klass(&self) -> Option<&'static str> {
240 self.replacement
241 .as_ref()
242 .and_then(|r| r.with_klass.as_ref())
243 .map(|k| k.node_type)
244 }
245
246 pub fn get_declared_node_structure(&self) -> DeclaredNodeStructure {
250 (self.node_structure)()
251 }
252}
253
254pub const COLLABORATION_TAG: &str = "collaboration";
257
258pub const HISTORIC_TAG: &str = "historic";
261
262pub const HISTORY_PUSH_TAG: &str = "history-push";
265
266pub const HISTORY_MERGE_TAG: &str = "history-merge";
269
270pub const PASTE_TAG: &str = "paste";
272
273pub const CUT_TAG: &str = "cut";
275
276pub const COMPOSITION_START_TAG: &str = "composition-start";
279
280pub const COMPOSITION_END_TAG: &str = "composition-end";
283
284pub const DEFER_COMPOSITION_MERGE_TAG: &str = "defer-composition-merge";
287
288pub const SKIP_SELECTION_FOCUS_TAG: &str = "skip-selection-focus";
291
292pub const SKIP_COLLAB_TAG: &str = "skip-collab";
295
296pub const SKIP_SCROLL_INTO_VIEW_TAG: &str = "skip-scroll-into-view";
299
300pub const SKIP_DOM_SELECTION_TAG: &str = "skip-dom-selection";
303
304pub const FOCUS_TAG: &str = "focus";
307
308pub type WarningHandler = Rc<dyn Fn(LexicalError) -> Result<(), LexicalError>>;
312
313#[derive(Clone, Default)]
322pub struct CreateEditorArgs {
323 pub nodes: Vec<NodeClass>,
324 pub namespace: String,
325 pub editor_state: Option<EditorState>,
328 pub editable: Option<bool>,
330 pub on_warn: Option<WarningHandler>,
334 pub parent_editor: Option<Editor>,
337 pub theme: Object,
341 #[cfg(feature = "html")]
343 pub html: crate::lexical_dom::HtmlConfig,
344 #[cfg(feature = "html")]
346 pub dom: Option<crate::lexical_dom::EditorDomRenderConfig>,
347}
348
349#[derive(Clone, Debug, Default)]
351pub struct EditorConfig {
352 pub theme: Object,
354}
355
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358pub enum EditorReadMode {
359 ForceCommit,
361 Latest,
363 Pending,
365}
366
367#[derive(Clone, Default)]
369pub struct UpdateOptions {
370 pub discrete: bool,
372 pub tags: Vec<String>,
374 pub skip_transforms: bool,
375 pub on_update: Option<Rc<dyn Fn()>>,
378}
379
380impl std::fmt::Debug for UpdateOptions {
381 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382 f.debug_struct("UpdateOptions")
383 .field("discrete", &self.discrete)
384 .field("tags", &self.tags)
385 .field("skip_transforms", &self.skip_transforms)
386 .field("on_update", &self.on_update.is_some())
387 .finish()
388 }
389}
390
391#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
393pub enum EditorFocusOptions {
394 #[default]
396 RootEnd,
397 RootStart,
399}
400
401#[derive(Clone, Debug)]
405pub struct UpdateListenerPayload {
406 pub dirty_elements: Vec<(NodeKey, bool)>,
407 pub dirty_leaves: Vec<NodeKey>,
408 pub normalized_nodes: Vec<NodeKey>,
409 pub tags: Vec<String>,
410 pub editor_state: EditorState,
411 pub prev_editor_state: EditorState,
412 pub mutated_nodes: Option<MutatedNodes>,
416}
417
418pub type Transform = Rc<dyn Fn(&NodeRef) -> Result<(), LexicalError>>;
420
421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub enum NodeMutation {
424 Created,
426 Updated,
428 Destroyed,
430}
431
432impl NodeMutation {
433 pub fn as_str(&self) -> &'static str {
435 match self {
436 NodeMutation::Created => "created",
437 NodeMutation::Updated => "updated",
438 NodeMutation::Destroyed => "destroyed",
439 }
440 }
441}
442
443pub type NodeMutations = Vec<(NodeKey, NodeMutation)>;
446
447pub type MutatedNodes = Vec<(&'static str, NodeMutations)>;
451
452#[derive(Clone, Debug)]
455pub struct MutationListenerPayload {
456 pub dirty_leaves: Vec<NodeKey>,
457 pub prev_editor_state: EditorState,
458 pub update_tags: Vec<String>,
459}
460
461#[derive(Clone, Copy, Debug, Default)]
463pub struct MutationListenerOptions {
464 pub skip_initialization: bool,
467}
468
469pub(crate) type MutationListener = Rc<dyn Fn(&NodeMutations, &MutationListenerPayload)>;
471
472pub trait RootElement: Any {
478 #[cfg(feature = "a11y")]
483 fn live_region_host(self: Rc<Self>) -> Option<Rc<dyn crate::a11y::LiveRegionHost>> {
484 None
485 }
486
487 fn blur(&self) {}
491
492 fn focus(&self) {}
497
498 fn has_focus(&self) -> bool {
502 false
503 }
504
505 fn caret_from_point(&self, _x: f64, _y: f64) -> Option<crate::caret::PointCaret> {
512 None
513 }
514
515 #[cfg(feature = "selection")]
522 fn computed_style(&self, _key: &str) -> Option<crate::selection::ComputedStyle> {
523 None
524 }
525
526 fn is_connected(&self) -> bool {
531 true
532 }
533}
534
535type UpdateListenerFn = dyn Fn(&UpdateListenerPayload) -> Option<Unregister>;
537type TextContentListenerFn = dyn Fn(&str) -> Option<Unregister>;
539type DecoratorListenerFn = dyn Fn(&Decorators) -> Option<Unregister>;
541
542#[derive(Clone)]
544pub struct RootElementRef(pub Rc<dyn RootElement>);
545
546impl PartialEq for RootElementRef {
547 fn eq(&self, other: &Self) -> bool {
548 std::ptr::addr_eq(Rc::as_ptr(&self.0), Rc::as_ptr(&other.0))
549 }
550}
551
552impl std::fmt::Debug for RootElementRef {
553 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
554 write!(f, "RootElementRef({:p})", Rc::as_ptr(&self.0) as *const ())
555 }
556}
557
558pub(crate) type RootListener =
562 Rc<dyn Fn(Option<&RootElementRef>, Option<&RootElementRef>) -> Option<Unregister>>;
563
564type RootListenerEntry = (u64, RootListener, Rc<RefCell<Option<Unregister>>>);
567
568pub type Unregister = Box<dyn FnOnce()>;
571
572pub trait ListenerCleanup {
578 fn into_cleanup(self) -> Option<Unregister>;
580}
581
582impl ListenerCleanup for () {
583 fn into_cleanup(self) -> Option<Unregister> {
584 None
585 }
586}
587
588impl ListenerCleanup for Unregister {
589 fn into_cleanup(self) -> Option<Unregister> {
590 Some(self)
591 }
592}
593
594impl ListenerCleanup for Option<Unregister> {
595 fn into_cleanup(self) -> Option<Unregister> {
596 self
597 }
598}
599
600pub struct LexicalCommand<P> {
603 id: u64,
604 name: CommandName,
605 _payload: PhantomData<fn(&P)>,
606}
607
608#[derive(Clone)]
611enum CommandName {
612 Static(&'static str),
613 Shared(Rc<str>),
614}
615
616impl<P> Clone for LexicalCommand<P> {
617 fn clone(&self) -> Self {
618 Self {
619 id: self.id,
620 name: self.name.clone(),
621 _payload: PhantomData,
622 }
623 }
624}
625
626impl<P> LexicalCommand<P> {
627 pub(crate) const fn constant(id: u64, name: &'static str) -> Self {
630 Self {
631 id,
632 name: CommandName::Static(name),
633 _payload: PhantomData,
634 }
635 }
636
637 pub fn name(&self) -> &str {
638 match &self.name {
639 CommandName::Static(name) => name,
640 CommandName::Shared(name) => name,
641 }
642 }
643 pub(crate) fn id(&self) -> u64 {
644 self.id
645 }
646}
647
648thread_local! {
649 static NEXT_COMMAND_ID: Cell<u64> = const { Cell::new(1) };
650}
651
652pub fn create_command<P>(name: &str) -> LexicalCommand<P> {
654 let id = NEXT_COMMAND_ID.with(|c| c.replace(c.get() + 1));
655 LexicalCommand {
656 id,
657 name: CommandName::Shared(name.into()),
658 _payload: PhantomData,
659 }
660}
661
662pub const COMMAND_PRIORITY_EDITOR: i8 = 0;
665pub const COMMAND_PRIORITY_LOW: i8 = 1;
667pub const COMMAND_PRIORITY_NORMAL: i8 = 2;
669pub const COMMAND_PRIORITY_HIGH: i8 = 3;
671pub const COMMAND_PRIORITY_CRITICAL: i8 = 4;
673pub const COMMAND_PRIORITY_BEFORE_EDITOR: i8 = -8;
676pub const COMMAND_PRIORITY_BEFORE_LOW: i8 = -7;
678pub const COMMAND_PRIORITY_BEFORE_NORMAL: i8 = -6;
681pub const COMMAND_PRIORITY_BEFORE_HIGH: i8 = -5;
684pub const COMMAND_PRIORITY_BEFORE_CRITICAL: i8 = -4;
687
688pub(crate) type CommandListener<P> = Rc<dyn Fn(&P, &Editor) -> Result<bool, LexicalError>>;
691
692#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
694pub(crate) enum DirtyType {
695 #[default]
696 None,
697 HasDirtyNodes,
698 FullReconcile,
699}
700
701#[derive(Default)]
704pub(crate) struct Dirty {
705 pub(crate) dirty_type: DirtyType,
706 pub(crate) elements: OrderedMap<bool>,
707 pub(crate) leaves: OrderedSet,
708 pub(crate) normalized: OrderedSet,
709}
710
711pub(crate) struct QueuedUpdate {
713 pub(crate) id: u64,
714 pub(crate) update_fn: Box<dyn FnOnce() -> Result<(), LexicalError>>,
715 pub(crate) options: UpdateOptions,
716}
717
718#[derive(Clone)]
722pub struct Editor(pub(crate) Rc<EditorInner>);
723
724impl PartialEq for Editor {
726 fn eq(&self, other: &Editor) -> bool {
727 Rc::ptr_eq(&self.0, &other.0)
728 }
729}
730
731impl Eq for Editor {}
732
733type Listeners<F> = RefCell<Vec<(u64, Rc<F>, Rc<RefCell<Option<Unregister>>>)>>;
736type CommandListeners = [Vec<(u64, Rc<dyn Any>)>; 5];
739
740pub(crate) struct EditorInner {
741 nodes: HashMap<&'static str, NodeClass>,
742 node_order: Vec<&'static str>,
745 shared_node_states: HashMap<&'static str, Rc<SharedNodeState>>,
747 pub(crate) editor_state: RefCell<EditorState>,
748 pub(crate) pending: RefCell<Option<EditorState>>,
749 pub(crate) dirty: RefCell<Dirty>,
750 pub(crate) tags: RefCell<OrderedSet>,
751 pub(crate) updating: Cell<bool>,
752 pub(crate) dispatching_commit_listeners: Cell<bool>,
753 pub(crate) updates: RefCell<VecDeque<QueuedUpdate>>,
754 pub(crate) cascade_count: Cell<u32>,
755 transforms: RefCell<HashMap<&'static str, Vec<(u64, Transform)>>>,
756 pub(crate) update_listeners: Listeners<UpdateListenerFn>,
757 text_content_listeners: Listeners<TextContentListenerFn>,
758 commands: RefCell<HashMap<u64, CommandListeners>>,
759 next_id: Cell<u64>,
760 selection_movement: RefCell<Option<Rc<dyn SelectionMovement>>>,
762 config: EditorConfig,
764 #[cfg(feature = "html")]
767 pub(crate) html_conversions: HashMap<String, Vec<crate::lexical_dom::DomImporter>>,
768 #[cfg(feature = "html")]
770 pub(crate) html_export: HashMap<&'static str, crate::lexical_dom::ExportOverride>,
771 #[cfg(feature = "html")]
774 pub(crate) dom: RefCell<crate::lexical_dom::EditorDomRenderConfig>,
775 namespace: String,
777 parent_editor: Option<Editor>,
779 key: String,
781 editable: Cell<bool>,
783 headless: Cell<bool>,
786 pub(crate) set_root_element_guard: RefCell<Option<SetRootElementGuard>>,
789 on_warn: WarningHandler,
791 pub(crate) slots_used: Cell<bool>,
794 root_element: RefCell<Option<RootElementRef>>,
796 pub(crate) node_structure: RefCell<Option<Rc<NodeStructureRegistration>>>,
799 mutation_listeners: RefCell<Vec<(u64, MutationListener, &'static str)>>,
802 pub(crate) editable_listeners: Listeners<dyn Fn(bool) -> Option<Unregister>>,
804 pub(crate) root_listeners: RefCell<Vec<RootListenerEntry>>,
806 pub(crate) deferred: RefCell<Vec<Box<dyn FnOnce()>>>,
808 pub(crate) composition_key: RefCell<Option<NodeKey>>,
810 pub(crate) composition_merge_held: RefCell<Option<NodeKey>>,
813 pub(crate) last_notified_selection: RefCell<Option<crate::lexical_selection::Selection>>,
817 pub(crate) input_state: RefCell<crate::events::InputState>,
819 pub(crate) key_down_shortcuts: RefCell<Option<crate::events::KeyDownShortcuts>>,
821 pub(crate) root_text_cache: RefCell<Option<(Rc<dyn LexicalNode>, String)>>,
825 pub(crate) key_to_dom_map: RefCell<crate::reconciler::KeyToDomMap>,
827 pub(crate) decorators: RefCell<Decorators>,
829 pub(crate) pending_decorators: RefCell<Option<Decorators>>,
831 decorator_listeners: Listeners<DecoratorListenerFn>,
833 #[cfg(feature = "extension")]
836 pub(crate) builder: RefCell<Option<Rc<dyn Any>>>,
837}
838
839pub(crate) type SetRootElementGuard =
842 Rc<dyn Fn(Option<&RootElementRef>) -> Result<(), LexicalError>>;
843
844pub fn create_editor(args: CreateEditorArgs) -> Editor {
854 let parent_editor = args.parent_editor;
855 let namespace = if !args.namespace.is_empty() {
858 args.namespace
859 } else if let Some(parent) = &parent_editor {
860 parent.get_namespace().to_owned()
861 } else {
862 create_uid()
863 };
864 let core = [
865 NodeClass {
867 is_element_or_decorator: || true,
868 ..NodeClass::with_import_json("root", RootNode::import_json)
869 },
870 NodeClass::of::<TextNode>(),
871 NodeClass::of::<LineBreakNode>(),
872 NodeClass::of::<TabNode>(),
873 NodeClass::of::<ParagraphNode>(),
874 NodeClass::of::<ArtificialNode>(),
875 ];
876 let classes: Vec<NodeClass> = core.into_iter().chain(args.nodes).collect();
877 for class in &classes {
880 if let Some(replacement) = &class.replacement {
881 match &replacement.with_klass {
882 Some(with_klass) => assert!(
883 (with_klass.super_types)().contains(&class.node_type),
885 "{} doesn't extend the {}",
886 with_klass.class_name,
887 class.class_name
888 ),
889 None => crate::warnings::console_warn(&format!(
890 "Override for {} specifies 'replace' without 'withKlass'. 'withKlass' will be required in a future version.",
891 class.class_name
892 )),
893 }
894 }
895 (class.validate_node_structure)();
896 }
897 let mut node_order: Vec<&'static str> = Vec::new();
898 for class in &classes {
899 if !node_order.contains(&class.node_type) {
900 node_order.push(class.node_type);
901 }
902 }
903 #[cfg(feature = "html")]
904 let html_conversions =
905 crate::lexical_dom::initialize_conversion_cache(&classes, &args.html.import);
906 let nodes: HashMap<&'static str, NodeClass> = classes
907 .into_iter()
908 .map(|class| (class.node_type, class))
909 .collect();
910 let headless = parent_editor.as_ref().is_some_and(|p| p.0.headless.get());
911 let on_warn = args.on_warn.unwrap_or_else(|| Rc::new(Err));
912 let shared_node_states = nodes
913 .iter()
914 .map(|(&node_type, class)| {
915 let shared = create_shared_node_state((class.state_configs)());
916 (node_type, Rc::new(shared))
917 })
918 .collect();
919 let editor = Editor(Rc::new(EditorInner {
920 nodes,
921 node_order,
922 shared_node_states,
923 editor_state: RefCell::new(create_empty_editor_state()),
924 pending: RefCell::new(None),
925 dirty: RefCell::new(Dirty::default()),
926 tags: RefCell::new(OrderedSet::new()),
927 updating: Cell::new(false),
928 dispatching_commit_listeners: Cell::new(false),
929 updates: RefCell::new(VecDeque::new()),
930 cascade_count: Cell::new(0),
931 transforms: RefCell::new(HashMap::new()),
932 update_listeners: RefCell::new(Vec::new()),
933 text_content_listeners: RefCell::new(Vec::new()),
934 commands: RefCell::new(HashMap::new()),
935 next_id: Cell::new(1),
936 selection_movement: RefCell::new(None),
937 config: EditorConfig { theme: args.theme },
938 #[cfg(feature = "html")]
939 html_conversions,
940 #[cfg(feature = "html")]
941 html_export: args.html.export.into_iter().collect(),
942 #[cfg(feature = "html")]
943 dom: RefCell::new(args.dom.unwrap_or_default()),
944 namespace,
945 parent_editor,
946 key: create_uid(),
947 editable: Cell::new(args.editable.unwrap_or(true)),
948 headless: Cell::new(headless),
949 set_root_element_guard: RefCell::new(None),
950 on_warn,
951 slots_used: Cell::new(false),
952 root_element: RefCell::new(None),
953 node_structure: RefCell::new(None),
954 mutation_listeners: RefCell::new(Vec::new()),
955 editable_listeners: RefCell::new(Vec::new()),
956 root_listeners: RefCell::new(Vec::new()),
957 deferred: RefCell::new(Vec::new()),
958 composition_key: RefCell::new(None),
959 composition_merge_held: RefCell::new(None),
960 last_notified_selection: RefCell::new(None),
961 input_state: RefCell::new(crate::events::InputState::default()),
962 key_down_shortcuts: RefCell::new(None),
963 root_text_cache: RefCell::new(None),
964 key_to_dom_map: RefCell::new(HashMap::new()),
965 decorators: RefCell::new(Decorators::default()),
966 pending_decorators: RefCell::new(None),
967 decorator_listeners: RefCell::new(Vec::new()),
968 #[cfg(feature = "extension")]
969 builder: RefCell::new(None),
970 }));
971 if let Some(initial_editor_state) = args.editor_state {
972 *editor.0.pending.borrow_mut() = Some(initial_editor_state);
973 editor.0.dirty.borrow_mut().dirty_type = DirtyType::FullReconcile;
974 }
975 let _unregister = crate::events::register_default_command_handlers(&editor);
976 editor
977}
978
979impl Editor {
980 pub fn config(&self) -> &EditorConfig {
982 &self.0.config
983 }
984
985 pub const VERSION: &'static str = "lexical-rust@0.53.0";
989
990 pub fn is_composing(&self) -> bool {
993 self.0.composition_key.borrow().is_some()
994 }
995
996 pub(crate) fn composition_key(&self) -> Option<NodeKey> {
998 self.0.composition_key.borrow().clone()
999 }
1000
1001 pub fn get_namespace(&self) -> &str {
1003 &self.0.namespace
1004 }
1005
1006 pub fn parent_editor(&self) -> Option<&Editor> {
1009 self.0.parent_editor.as_ref()
1010 }
1011
1012 pub fn get_key(&self) -> &str {
1015 &self.0.key
1016 }
1017
1018 pub fn blur(&self) {
1021 if let Some(root) = self.get_root_element() {
1022 root.0.blur();
1023 }
1024 }
1025
1026 pub fn focus(
1034 &self,
1035 callback: Option<Box<dyn FnOnce()>>,
1036 options: EditorFocusOptions,
1037 ) -> Result<(), LexicalError> {
1038 if self.get_root_element().is_none() {
1039 return Ok(());
1040 }
1041 update_editor_sync(
1042 self,
1043 move || {
1044 let selection = crate::get_selection();
1045 let root = crate::get_root();
1046 if let Some(selection) = selection {
1047 if !selection.is_dirty() {
1050 crate::set_selection(Some(selection.clone_selection()));
1051 }
1052 } else if root.get_children_size() != 0 {
1053 if options == EditorFocusOptions::RootStart {
1054 root.select_start()?;
1055 } else {
1056 root.select_end()?;
1057 }
1058 }
1059 add_update_tag(FOCUS_TAG);
1060 crate::on_update(move || {
1061 if let Some(callback) = callback {
1062 callback();
1063 }
1064 });
1065 Ok(())
1066 },
1067 None,
1068 )
1069 }
1070
1071 pub fn is_headless(&self) -> bool {
1075 self.0.headless.get()
1076 }
1077
1078 pub(crate) fn set_headless(&self, guard: SetRootElementGuard) {
1079 self.0.headless.set(true);
1080 *self.0.set_root_element_guard.borrow_mut() = Some(guard);
1081 }
1082
1083 pub(crate) fn on_warn(&self, warning: LexicalError) -> Result<(), LexicalError> {
1085 (self.0.on_warn)(warning)
1086 }
1087
1088 pub fn is_editable(&self) -> bool {
1090 self.0.editable.get()
1091 }
1092
1093 pub fn set_editable(&self, editable: bool) {
1096 if self.0.editable.get() != editable {
1097 self.0.editable.set(editable);
1098 with_updating(self, true, || {
1099 trigger_listeners(&self.0.editable_listeners, |listener| listener(editable));
1100 });
1101 }
1102 }
1103
1104 pub fn register_editable_listener<R: ListenerCleanup>(
1107 &self,
1108 listener: impl Fn(bool) -> R + 'static,
1109 ) -> Unregister {
1110 register_listener(
1111 self,
1112 |inner| &inner.editable_listeners,
1113 Rc::new(move |editable| listener(editable).into_cleanup())
1114 as Rc<dyn Fn(bool) -> Option<Unregister>>,
1115 )
1116 }
1117
1118 pub fn get_decorators(&self) -> Decorators {
1122 self.0.decorators.borrow().clone()
1123 }
1124
1125 pub fn register_decorator_listener<R: ListenerCleanup>(
1129 &self,
1130 listener: impl Fn(&Decorators) -> R + 'static,
1131 ) -> Unregister {
1132 register_listener(
1133 self,
1134 |inner| &inner.decorator_listeners,
1135 Rc::new(move |decorators: &Decorators| listener(decorators).into_cleanup())
1136 as Rc<DecoratorListenerFn>,
1137 )
1138 }
1139
1140 pub(crate) fn trigger_decorator_listeners(&self, decorators: &Decorators) {
1142 trigger_listeners(&self.0.decorator_listeners, |listener| listener(decorators));
1143 }
1144
1145 pub fn get_root_element(&self) -> Option<RootElementRef> {
1147 self.0.root_element.borrow().clone()
1148 }
1149
1150 pub fn set_root_element(
1157 &self,
1158 next_root_element: Option<RootElementRef>,
1159 ) -> Result<(), LexicalError> {
1160 let guard = self.0.set_root_element_guard.borrow().clone();
1161 if let Some(guard) = guard {
1162 guard(next_root_element.as_ref())?;
1163 }
1164 let prev_root_element = self.get_root_element();
1165 if next_root_element == prev_root_element {
1166 return Ok(());
1167 }
1168 let pending_editor_state = self.pending().unwrap_or_else(|| self.get_editor_state());
1169 *self.0.root_element.borrow_mut() = next_root_element.clone();
1170 *self.0.editor_state.borrow_mut() = create_empty_editor_state();
1172 *self.0.pending.borrow_mut() = Some(pending_editor_state);
1173 *self.0.composition_key.borrow_mut() = None;
1174 *self.0.dirty.borrow_mut() = Dirty::default();
1175 crate::reconciler::reset_key_to_dom_map(self, next_root_element.is_some());
1176 if next_root_element.is_some() {
1177 self.0.dirty.borrow_mut().dirty_type = DirtyType::FullReconcile;
1178 }
1179 self.add_tags(&[HISTORY_MERGE_TAG.to_owned()]);
1180 let committed = commit_pending_updates(self);
1181 let listeners: Vec<_> = self
1183 .0
1184 .root_listeners
1185 .borrow()
1186 .iter()
1187 .map(|(_, l, cleanup)| (l.clone(), cleanup.clone()))
1188 .collect();
1189 with_updating(self, false, || {
1190 for (listener, cleanup) in listeners {
1191 trigger_root_listener(
1192 &listener,
1193 &cleanup,
1194 next_root_element.as_ref(),
1195 prev_root_element.as_ref(),
1196 );
1197 }
1198 });
1199 committed
1200 }
1201
1202 pub fn register_root_listener(
1207 &self,
1208 listener: impl Fn(Option<&RootElementRef>, Option<&RootElementRef>) -> Option<Unregister>
1209 + 'static,
1210 ) -> Unregister {
1211 let id = self.next_id();
1212 let listener: RootListener = Rc::new(listener);
1213 let root = self.get_root_element();
1214 let cleanup = Rc::new(RefCell::new(listener(root.as_ref(), None)));
1215 self.0
1216 .root_listeners
1217 .borrow_mut()
1218 .push((id, listener.clone(), cleanup.clone()));
1219 let weak = self.weak();
1220 Box::new(move || {
1221 let Some(inner) = weak.upgrade() else { return };
1222 let root = inner.root_element.borrow().clone();
1223 trigger_root_listener(&listener, &cleanup, None, root.as_ref());
1224 inner
1225 .root_listeners
1226 .borrow_mut()
1227 .retain(|(i, _, _)| *i != id);
1228 let last = cleanup.borrow_mut().take();
1229 if let Some(last) = last {
1230 last();
1231 }
1232 })
1233 }
1234
1235 pub fn register_mutation_listener(
1242 &self,
1243 node_type: &str,
1244 listener: impl Fn(&NodeMutations, &MutationListenerPayload) + 'static,
1245 options: MutationListenerOptions,
1246 ) -> Result<Unregister, LexicalError> {
1247 let Some((&node_type, _)) = self.0.nodes.get_key_value(node_type) else {
1248 return Err(LexicalError::new(format!(
1249 "Node {node_type} has not been registered. Ensure node has been passed to createEditor."
1250 )));
1251 };
1252 let node_type = self.resolve_registered_node_after_replacements(node_type)?;
1255 let id = self.next_id();
1256 let listener: MutationListener = Rc::new(listener);
1257 self.0
1258 .mutation_listeners
1259 .borrow_mut()
1260 .push((id, listener.clone(), node_type));
1261 if !options.skip_initialization {
1262 let prev_editor_state = self.get_editor_state();
1264 let keys: NodeMutations = {
1265 let node_map = prev_editor_state.0.node_map.borrow();
1266 prev_editor_state
1267 .keys_in_creation_order()
1268 .into_iter()
1269 .filter(|key| node_map[key].get_type() == node_type)
1270 .map(|key| (key, NodeMutation::Created))
1271 .collect()
1272 };
1273 if !keys.is_empty() {
1274 listener(
1275 &keys,
1276 &MutationListenerPayload {
1277 dirty_leaves: Vec::new(),
1278 prev_editor_state,
1279 update_tags: vec!["registerMutationListener".to_owned()],
1280 },
1281 );
1282 }
1283 }
1284 let weak = self.weak();
1285 Ok(Box::new(move || {
1286 if let Some(inner) = weak.upgrade() {
1287 inner
1288 .mutation_listeners
1289 .borrow_mut()
1290 .retain(|(i, _, _)| *i != id);
1291 }
1292 }))
1293 }
1294
1295 pub(crate) fn has_mutation_listeners(&self) -> bool {
1297 !self.0.mutation_listeners.borrow().is_empty()
1298 }
1299
1300 pub(crate) fn mutation_listeners(&self) -> Vec<(MutationListener, &'static str)> {
1301 self.0
1302 .mutation_listeners
1303 .borrow()
1304 .iter()
1305 .map(|(_, l, t)| (l.clone(), *t))
1306 .collect()
1307 }
1308
1309 pub(crate) fn registered_nodes(&self) -> &HashMap<&'static str, NodeClass> {
1310 &self.0.nodes
1311 }
1312
1313 pub fn get_registered_node(&self, node_type: &str) -> Option<NodeClass> {
1316 self.0.nodes.get(node_type).cloned()
1317 }
1318
1319 pub fn resolve_registered_node_after_replacements(
1324 &self,
1325 node_type: &str,
1326 ) -> Result<&'static str, LexicalError> {
1327 let Some((mut node_type, mut class)) = self.0.nodes.get_key_value(node_type) else {
1328 return Err(LexicalError::new(format!(
1329 "Node {node_type} has not been registered. Ensure node has been passed to createEditor."
1330 )));
1331 };
1332 while let Some(next) = class.replace_with_klass() {
1333 let Some((t, c)) = self.0.nodes.get_key_value(next) else {
1334 return Err(LexicalError::new(format!(
1335 "Node {next} has not been registered. Ensure node has been passed to createEditor."
1336 )));
1337 };
1338 (node_type, class) = (t, c);
1339 }
1340 Ok(node_type)
1341 }
1342
1343 pub fn has_node(&self, node_type: &str) -> bool {
1345 self.0.nodes.contains_key(node_type)
1346 }
1347
1348 pub fn has_nodes(&self, node_types: &[&str]) -> bool {
1351 node_types.iter().all(|t| self.has_node(t))
1352 }
1353
1354 pub(crate) fn registered_nodes_in_order(&self) -> Vec<NodeClass> {
1356 self.0
1357 .node_order
1358 .iter()
1359 .map(|node_type| self.0.nodes[node_type].clone())
1360 .collect()
1361 }
1362
1363 pub(crate) fn shared_node_state(&self, node_type: &str) -> Option<Rc<SharedNodeState>> {
1365 self.0.shared_node_states.get(node_type).cloned()
1366 }
1367
1368 pub(crate) fn ptr_eq(&self, other: &Editor) -> bool {
1369 Rc::ptr_eq(&self.0, &other.0)
1370 }
1371
1372 pub(crate) fn next_id(&self) -> u64 {
1373 self.0.next_id.replace(self.0.next_id.get() + 1)
1374 }
1375
1376 pub(crate) fn weak(&self) -> Weak<EditorInner> {
1377 Rc::downgrade(&self.0)
1378 }
1379
1380 pub fn set_selection_movement(&self, movement: Option<Rc<dyn SelectionMovement>>) {
1386 *self.0.selection_movement.borrow_mut() = movement;
1387 }
1388
1389 pub(crate) fn selection_movement(&self) -> Option<Rc<dyn SelectionMovement>> {
1392 self.0.selection_movement.borrow().clone()
1393 }
1394
1395 pub fn get_editor_state(&self) -> EditorState {
1397 self.0.editor_state.borrow().clone()
1398 }
1399
1400 pub(crate) fn pending(&self) -> Option<EditorState> {
1401 self.0.pending.borrow().clone()
1402 }
1403
1404 pub fn to_json(&self) -> Value {
1409 let mut json = crate::json::Object::new();
1410 json.insert(
1411 "editorState",
1412 self.get_editor_state()
1413 .to_json(crate::serialized_export::is_compact_export()),
1414 );
1415 Value::Object(json)
1416 }
1417
1418 pub fn parse_editor_state(&self, json: &str) -> Result<EditorState, LexicalError> {
1420 let value = json::parse(json).map_err(|e| LexicalError::new(e.to_string()))?;
1421 self.parse_editor_state_json(&value)
1422 }
1423
1424 pub fn parse_editor_state_json(&self, json: &Value) -> Result<EditorState, LexicalError> {
1426 parse_editor_state(json, self, None)
1427 }
1428
1429 pub fn parse_editor_state_json_with(
1434 &self,
1435 json: &Value,
1436 update_fn: impl FnOnce() -> Result<(), LexicalError>,
1437 ) -> Result<EditorState, LexicalError> {
1438 parse_editor_state(json, self, Some(Box::new(update_fn)))
1439 }
1440
1441 pub fn update(
1450 &self,
1451 update_fn: impl FnOnce() -> Result<(), LexicalError> + 'static,
1452 options: UpdateOptions,
1453 ) -> Result<(), LexicalError> {
1454 if self.0.updating.get() {
1455 let id = self.next_id();
1456 self.0.updates.borrow_mut().push_back(QueuedUpdate {
1457 id,
1458 update_fn: Box::new(update_fn),
1459 options,
1460 });
1461 Ok(())
1462 } else {
1463 if !crate::updates::is_committing_pending_updates() {
1469 self.0.cascade_count.set(0);
1470 }
1471 begin_update(self, update_fn, &options)
1472 }
1473 }
1474
1475 pub fn set_editor_state(
1482 &self,
1483 editor_state: &EditorState,
1484 tag: Option<&str>,
1485 ) -> Result<(), LexicalError> {
1486 let is_empty_editor_state = editor_state.is_empty();
1487 let writable_editor_state = if editor_state.0.read_only.get() {
1489 let writable = clone_editor_state(editor_state);
1490 *writable.0.selection.borrow_mut() =
1491 editor_state.selection().map(|s| s.clone_selection());
1492 writable
1493 } else {
1494 editor_state.clone()
1495 };
1496 let tags: Vec<String> = tag.map(str::to_owned).into_iter().collect();
1497 if let Some(pending) = self.pending()
1498 && !pending.is_empty()
1499 {
1500 self.add_tags(&tags);
1501 commit_pending_updates(self)?;
1502 }
1503 *self.0.pending.borrow_mut() = Some(writable_editor_state.clone());
1504 {
1505 let mut dirty = self.0.dirty.borrow_mut();
1506 dirty.dirty_type = DirtyType::FullReconcile;
1507 dirty.elements.set("root", false);
1508 }
1509 *self.0.composition_key.borrow_mut() = None;
1510 self.0
1511 .slots_used
1512 .set(self.0.slots_used.get() || editor_state.0.slots_used.get());
1513 let parsed = editor_state.0.parsed.get();
1514 let options = UpdateOptions {
1515 discrete: true,
1516 ..UpdateOptions::default()
1517 };
1518 let editor = self.clone();
1519 update_editor_sync(
1520 self,
1521 move || {
1522 editor.add_tags(&tags);
1523 invariant!(
1524 !is_empty_editor_state,
1525 "setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty."
1526 );
1527 if parsed {
1528 let node_map = writable_editor_state.0.node_map.borrow();
1531 let mut dirty = editor.0.dirty.borrow_mut();
1532 for key in writable_editor_state.keys_in_creation_order() {
1533 if node_map[&key].element().is_some() {
1534 dirty.elements.set(&key, true);
1535 } else {
1536 dirty.leaves.add(&key);
1537 }
1538 }
1539 }
1540 Ok(())
1541 },
1542 (!self.0.updating.get()).then_some(&options),
1543 )
1544 }
1545
1546 pub fn read<R>(&self, f: impl FnOnce() -> R) -> Result<R, LexicalError> {
1550 self.read_with_mode(EditorReadMode::ForceCommit, f)
1551 }
1552
1553 pub fn read_with_mode<R>(
1559 &self,
1560 mode: EditorReadMode,
1561 f: impl FnOnce() -> R,
1562 ) -> Result<R, LexicalError> {
1563 if mode == EditorReadMode::ForceCommit {
1564 if !self.0.dispatching_commit_listeners.get() {
1565 commit_pending_updates(self)?;
1566 } else if self.pending().is_some() {
1567 crate::warnings::console_warn(
1568 "editor.read() was called while the editor was notifying listeners of a commit, and a listener had started another update. That update was not committed early, so that listeners observe commits in order, and the read observed the state being committed. Inside listeners, read with editor.getEditorState().read(fn, {editor}) or editor.read('latest', fn) instead.",
1569 );
1570 }
1571 }
1572 let editor_state = match mode {
1573 EditorReadMode::Pending => self.pending().unwrap_or_else(|| self.get_editor_state()),
1574 _ => self.get_editor_state(),
1575 };
1576 Ok(read_editor_state(Some(self), &editor_state, f))
1577 }
1578
1579 pub fn register_node_transform(
1584 &self,
1585 node_type: &'static str,
1586 transform: impl Fn(&NodeRef) -> Result<(), LexicalError> + 'static,
1587 ) -> Unregister {
1588 let transform: Transform = Rc::new(transform);
1589 let mut types = vec![node_type];
1590 if let Some(with_klass) = self
1591 .0
1592 .nodes
1593 .get(node_type)
1594 .and_then(NodeClass::replace_with_klass)
1595 && self.0.nodes.contains_key(with_klass)
1596 {
1597 types.push(with_klass);
1598 }
1599 let unregisters: Vec<Unregister> = types
1600 .iter()
1601 .map(|&t| {
1602 let transform = transform.clone();
1603 self.add_node_transform(t, move |node| transform(node))
1604 })
1605 .collect();
1606 mark_nodes_with_types_as_dirty(self, &types);
1607 Box::new(move || {
1608 for unregister in unregisters {
1609 unregister();
1610 }
1611 })
1612 }
1613
1614 pub(crate) fn add_node_transform(
1620 &self,
1621 node_type: &'static str,
1622 transform: impl Fn(&NodeRef) -> Result<(), LexicalError> + 'static,
1623 ) -> Unregister {
1624 let id = self.next_id();
1625 self.0
1626 .transforms
1627 .borrow_mut()
1628 .entry(node_type)
1629 .or_default()
1630 .push((id, Rc::new(transform)));
1631 let weak = self.weak();
1632 Box::new(move || {
1633 if let Some(inner) = weak.upgrade()
1634 && let Some(list) = inner.transforms.borrow_mut().get_mut(node_type)
1635 {
1636 list.retain(|(i, _)| *i != id);
1637 }
1638 })
1639 }
1640
1641 pub(crate) fn transforms_of(&self, node_type: &str) -> Vec<Transform> {
1642 self.0
1643 .transforms
1644 .borrow()
1645 .get(node_type)
1646 .map(|list| list.iter().map(|(_, t)| t.clone()).collect())
1647 .unwrap_or_default()
1648 }
1649
1650 pub fn register_update_listener<R: ListenerCleanup>(
1652 &self,
1653 listener: impl Fn(&UpdateListenerPayload) -> R + 'static,
1654 ) -> Unregister {
1655 register_listener(
1656 self,
1657 |inner| &inner.update_listeners,
1658 Rc::new(move |payload: &UpdateListenerPayload| listener(payload).into_cleanup())
1659 as Rc<UpdateListenerFn>,
1660 )
1661 }
1662
1663 pub fn register_text_content_listener<R: ListenerCleanup>(
1665 &self,
1666 listener: impl Fn(&str) -> R + 'static,
1667 ) -> Unregister {
1668 register_listener(
1669 self,
1670 |inner| &inner.text_content_listeners,
1671 Rc::new(move |text: &str| listener(text).into_cleanup()) as Rc<TextContentListenerFn>,
1672 )
1673 }
1674
1675 pub(crate) fn trigger_update_listeners(&self, payload: &UpdateListenerPayload) {
1677 trigger_listeners(&self.0.update_listeners, |listener| listener(payload));
1678 }
1679
1680 pub(crate) fn has_text_content_listeners(&self) -> bool {
1682 !self.0.text_content_listeners.borrow().is_empty()
1683 }
1684
1685 pub(crate) fn trigger_text_content_listeners(&self, text: &str) {
1687 trigger_listeners(&self.0.text_content_listeners, |listener| listener(text));
1688 }
1689
1690 pub fn register_command<P: 'static>(
1696 &self,
1697 command: &LexicalCommand<P>,
1698 listener: impl Fn(&P, &Editor) -> Result<bool, LexicalError> + 'static,
1699 priority: i8,
1700 ) -> Unregister {
1701 let normalized = priority & 7;
1702 let before = normalized != priority;
1703 let priority = usize::from(normalized.min(COMMAND_PRIORITY_CRITICAL) as u8);
1704 let id = self.next_id();
1705 let listener: CommandListener<P> = Rc::new(listener);
1706 let command_id = command.id();
1707 {
1708 let mut commands = self.0.commands.borrow_mut();
1709 let list = &mut commands.entry(command_id).or_default()[priority];
1710 let entry = (id, Rc::new(listener) as Rc<dyn Any>);
1711 if before {
1712 list.insert(0, entry);
1713 } else {
1714 list.push(entry);
1715 }
1716 }
1717 let weak = self.weak();
1718 Box::new(move || {
1719 if let Some(inner) = weak.upgrade() {
1720 let mut commands = inner.commands.borrow_mut();
1721 if let Some(lists) = commands.get_mut(&command_id) {
1722 lists[priority].retain(|(i, _)| *i != id);
1723 if lists.iter().all(Vec::is_empty) {
1725 commands.remove(&command_id);
1726 }
1727 }
1728 }
1729 })
1730 }
1731
1732 #[cfg(test)]
1734 pub(crate) fn has_command<P>(&self, command: &LexicalCommand<P>) -> bool {
1735 self.0.commands.borrow().contains_key(&command.id())
1736 }
1737
1738 pub(crate) fn command_listeners<P: 'static>(
1739 &self,
1740 command: &LexicalCommand<P>,
1741 priority: usize,
1742 ) -> Vec<CommandListener<P>> {
1743 self.0
1744 .commands
1745 .borrow()
1746 .get(&command.id())
1747 .map(|lists| {
1748 lists[priority]
1749 .iter()
1750 .filter_map(|(_, l)| l.downcast_ref::<CommandListener<P>>().cloned())
1751 .collect()
1752 })
1753 .unwrap_or_default()
1754 }
1755
1756 pub fn dispatch_command<P: 'static>(
1760 &self,
1761 command: &LexicalCommand<P>,
1762 payload: P,
1763 ) -> Result<bool, LexicalError> {
1764 trigger_command_listeners(self, command, &Rc::new(payload), self)
1765 }
1766
1767 pub(crate) fn dirty_type(&self) -> DirtyType {
1770 self.0.dirty.borrow().dirty_type
1771 }
1772
1773 pub(crate) fn mark_dirty(&self, key: &str, is_element: bool) {
1776 let mut dirty = self.0.dirty.borrow_mut();
1777 if dirty.dirty_type == DirtyType::None {
1779 dirty.dirty_type = DirtyType::HasDirtyNodes;
1780 }
1781 if is_element {
1782 dirty.elements.set(key, true);
1783 } else {
1784 dirty.leaves.add(key);
1785 }
1786 }
1787
1788 pub(crate) fn add_tags(&self, tags: &[String]) {
1789 let mut set = self.0.tags.borrow_mut();
1790 for tag in tags {
1791 set.add(tag);
1792 }
1793 }
1794}
1795
1796pub fn has_update_tag(tag: &str) -> bool {
1800 get_editor().0.tags.borrow().contains(tag)
1801}
1802
1803pub fn add_update_tag(tag: &str) {
1808 crate::updates::error_on_read_only();
1809 get_editor().0.tags.borrow_mut().add(tag);
1810}
1811
1812pub fn get_editor() -> Editor {
1816 crate::updates::get_registry_editor().unwrap_or_else(|| {
1817 panic!("Unable to find an active editor. This method can only be used synchronously during the callback of editor.update() or editor.read().")
1818 })
1819}
1820
1821fn with_updating<R>(editor: &Editor, updating: bool, f: impl FnOnce() -> R) -> R {
1824 struct Restore<'a>(&'a Editor, bool);
1825 impl Drop for Restore<'_> {
1826 fn drop(&mut self) {
1827 self.0.0.updating.set(self.1);
1828 }
1829 }
1830 let _restore = Restore(editor, editor.0.updating.replace(updating));
1831 f()
1832}
1833
1834fn register_listener<F: ?Sized + 'static>(
1837 editor: &Editor,
1838 listeners: fn(&EditorInner) -> &Listeners<F>,
1839 listener: Rc<F>,
1840) -> Unregister {
1841 let id = editor.next_id();
1842 listeners(&editor.0)
1843 .borrow_mut()
1844 .push((id, listener, Rc::default()));
1845 let weak = editor.weak();
1846 Box::new(move || {
1847 let Some(inner) = weak.upgrade() else { return };
1848 let removed = {
1849 let mut list = listeners(&inner).borrow_mut();
1850 list.iter()
1851 .position(|(i, _, _)| *i == id)
1852 .map(|at| list.remove(at))
1853 };
1854 let last = removed.and_then(|(_, _, cleanup)| cleanup.borrow_mut().take());
1855 if let Some(last) = last {
1856 last();
1857 }
1858 })
1859}
1860
1861fn trigger_listeners<F: ?Sized>(listeners: &Listeners<F>, call: impl Fn(&F) -> Option<Unregister>) {
1866 let snapshot: Vec<_> = listeners
1867 .borrow()
1868 .iter()
1869 .map(|(id, l, cleanup)| (*id, l.clone(), cleanup.clone()))
1870 .collect();
1871 for (id, listener, cleanup) in snapshot {
1872 let last = cleanup.borrow_mut().take();
1873 if let Some(last) = last {
1874 last();
1875 }
1876 let next = call(&listener);
1877 if listeners.borrow().iter().any(|(i, _, _)| *i == id) {
1878 *cleanup.borrow_mut() = next;
1879 } else if let Some(next) = next {
1880 next();
1881 }
1882 }
1883}
1884
1885fn trigger_root_listener(
1888 listener: &RootListener,
1889 cleanup: &Rc<RefCell<Option<Unregister>>>,
1890 next: Option<&RootElementRef>,
1891 prev: Option<&RootElementRef>,
1892) {
1893 let last = cleanup.borrow_mut().take();
1894 if let Some(last) = last {
1895 last();
1896 }
1897 let next_cleanup = listener(next, prev);
1898 *cleanup.borrow_mut() = next_cleanup;
1899}
1900
1901pub(crate) fn mark_nodes_with_types_as_dirty(editor: &Editor, types: &[&str]) {
1905 let editor_state = editor.get_editor_state();
1906 let keys: Vec<String> = {
1907 let node_map = editor_state.0.node_map.borrow();
1908 editor_state
1909 .keys_in_creation_order()
1910 .into_iter()
1911 .filter(|key| types.contains(&node_map[key].get_type()))
1912 .collect()
1913 };
1914 if keys.is_empty() {
1915 return;
1916 }
1917 let options = UpdateOptions {
1918 tags: if editor.pending().is_none() {
1919 vec![HISTORY_MERGE_TAG.to_owned()]
1920 } else {
1921 Vec::new()
1922 },
1923 ..UpdateOptions::default()
1924 };
1925 let _ = editor.update(
1927 move || {
1928 for key in &keys {
1929 if let Some(node) = crate::get_node_by_key(key) {
1930 node.mark_dirty();
1931 }
1932 }
1933 Ok(())
1934 },
1935 options,
1936 );
1937}
1938
1939#[cfg(test)]
1940mod tests {
1941 use super::*;
1942 use crate::{create_paragraph_node, create_text_node, get_root};
1943
1944 fn discrete() -> UpdateOptions {
1945 UpdateOptions {
1946 discrete: true,
1947 ..UpdateOptions::default()
1948 }
1949 }
1950
1951 #[test]
1952 fn has_nodes_and_get_editor() {
1953 let editor = create_editor(CreateEditorArgs::default());
1954 assert!(editor.has_node("text") && editor.has_node("paragraph"));
1955 assert!(!editor.has_node("heading"));
1956 assert!(editor.has_nodes(&[]) && editor.has_nodes(&["text", "root"]));
1957 assert!(!editor.has_nodes(&["text", "heading"]));
1958 let same = Rc::new(Cell::new(false));
1959 let (seen, active) = (same.clone(), editor.clone());
1960 editor
1961 .update(
1962 move || {
1963 seen.set(get_editor().ptr_eq(&active));
1964 Ok(())
1965 },
1966 discrete(),
1967 )
1968 .unwrap();
1969 assert!(same.get());
1970 }
1971
1972 #[test]
1973 fn create_editor_starts_with_the_given_state() {
1974 let source = create_editor(CreateEditorArgs::default());
1975 source
1976 .update(
1977 || {
1978 let paragraph = create_paragraph_node();
1979 paragraph.append(&[create_text_node("hello")])?;
1980 get_root().append(&[paragraph])
1981 },
1982 discrete(),
1983 )
1984 .unwrap();
1985 let editor = create_editor(CreateEditorArgs {
1986 editor_state: Some(source.get_editor_state()),
1987 editable: Some(false),
1988 ..CreateEditorArgs::default()
1989 });
1990 assert!(!editor.is_editable());
1991 assert_eq!(
1992 editor.read(|| get_root().get_text_content()).unwrap(),
1993 "hello"
1994 );
1995 }
1996
1997 #[test]
1998 fn focus_without_a_root_element_does_nothing() {
1999 let editor = create_editor(CreateEditorArgs::default());
2000 let called = Rc::new(Cell::new(false));
2001 let flag = called.clone();
2002 editor
2003 .focus(
2004 Some(Box::new(move || flag.set(true))),
2005 EditorFocusOptions::default(),
2006 )
2007 .unwrap();
2008 assert!(!called.get());
2009 assert!(editor.read(crate::get_selection).unwrap().is_none());
2010 }
2011
2012 #[test]
2013 fn on_warn_hears_an_endless_update_cascade() {
2014 let warnings = Rc::new(RefCell::new(Vec::<String>::new()));
2015 let heard = warnings.clone();
2016 let editor = create_editor(CreateEditorArgs {
2017 on_warn: Some(Rc::new(move |warning| {
2018 heard.borrow_mut().push(warning.message().to_owned());
2019 Ok(())
2020 })),
2021 ..CreateEditorArgs::default()
2022 });
2023 let updates = Rc::new(Cell::new(0));
2024 let (count, target) = (updates.clone(), editor.weak());
2025 let _unregister = editor.register_update_listener(move |_| {
2026 let Some(editor) = target.upgrade().map(Editor) else {
2027 return;
2028 };
2029 if count.replace(count.get() + 1) < 1000 {
2030 let _ = editor.update(|| get_root().append(&[create_paragraph_node()]), discrete());
2031 }
2032 });
2033 editor
2034 .update(|| get_root().append(&[create_paragraph_node()]), discrete())
2035 .unwrap();
2036 let warnings = warnings.borrow();
2037 assert_eq!(warnings.len(), 1, "{warnings:?} after {}", updates.get());
2038 assert!(warnings[0].starts_with("One or more update listeners are endlessly enqueueing"));
2039 assert!(updates.get() < 1000);
2040 }
2041}