Skip to main content

lexical_ui/
editor.rs

1//! `LexicalEditor.ts`: creating an editor, its registered nodes, and the
2//! registration of transforms, listeners and commands.
3
4use 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/// A node class an editor registers: its type and how it imports JSON (the
33/// static `importJSON`). As an editor's registration (`RegisteredNode`) it
34/// also holds the class's node replacement, if any: what
35/// [`LexicalNodeReplacement`] makes of the class.
36#[derive(Clone)]
37pub struct NodeClass {
38    pub(crate) node_type: &'static str,
39    /// `klass.name`, which messages name a class by: the Rust type's name
40    /// (the node type for a class made with
41    /// [`NodeClass::with_import_json`]).
42    pub(crate) class_name: &'static str,
43    pub(crate) import_json: fn(&Object) -> Result<NodeRef, LexicalError>,
44    /// The `stateConfigs` of the class's `$config`.
45    pub(crate) state_configs: fn() -> Vec<RequiredNodeStateConfig>,
46    /// The class's own static `importDOM` (`None` when it inherits one).
47    #[cfg(feature = "html")]
48    pub(crate) import_dom: fn() -> Option<crate::lexical_dom::DomConversionMap>,
49    /// Whether the class is an `ElementNode` with an `isInline` of its own
50    /// (`klass.prototype.isInline !== ElementNode.prototype.isInline`,
51    /// which `NormalizeInlineElementsExtension` asks). A trait method can't
52    /// tell an override, so this asks a fresh node whether it is an inline
53    /// element; every ported class answers the same for all its nodes.
54    #[cfg_attr(not(feature = "extension"), allow(dead_code))]
55    pub(crate) is_inline_element: fn() -> bool,
56    /// The `slots` of the class's `$config()` (`getDeclaredSlots`).
57    pub(crate) declared_slots: fn() -> &'static [&'static str],
58    /// Whether the class is `TextNode` or a subclass of it
59    /// (`klass.prototype instanceof TextNode`).
60    #[cfg_attr(not(feature = "extension"), allow(dead_code))]
61    pub(crate) is_text: fn() -> bool,
62    /// Whether the class is `ElementNode` or `DecoratorNode`, or a subclass
63    /// of either, whose nodes `INTERNAL_registerNodeStructure` marks dirty.
64    pub(crate) is_element_or_decorator: fn() -> bool,
65    /// `getDeclaredNodeStructure(klass)`.
66    node_structure: fn() -> DeclaredNodeStructure,
67    /// `validateNodeStructure(klass)`, which panics on a bad declaration.
68    validate_node_structure: fn(),
69    /// The types of the classes the class extends, nearest first
70    /// ([`LexicalNode::super_types`]), which stand for `instanceof`.
71    pub(crate) super_types: fn() -> Vec<&'static str>,
72    /// `replace` and `replaceWithKlass`: the class's node replacement.
73    pub(crate) replacement: Option<Rc<LexicalNodeReplacement>>,
74    /// `new klass()`, which `$create` calls; `None` for a class made with
75    /// [`NodeClass::with_import_json`].
76    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
83/// A node replacement's `with`: given a new node of the replaced class
84/// (with a key, in the active editor state), the node to use instead, which
85/// must have a key of its own.
86pub type NodeReplace = Rc<dyn Fn(&NodeRef) -> Result<NodeRef, LexicalError>>;
87
88/// `LexicalNodeReplacement`: an entry of [`CreateEditorArgs::nodes`] (as a
89/// [`NodeClass`], through `From`) that makes `$create` and the `$create*`
90/// functions of the `replace` class give what `with` makes of their node.
91/// `with_klass`, the class `with` makes (which must extend `replace` and be
92/// registered too), lets transforms and mutation listeners registered for
93/// `replace` reach its nodes.
94#[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
148/// The `importJSON` of a class: `$create(klass).updateFromJSON(json)`, so
149/// with the editor's replacement of the class.
150fn 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    // `updateFromJSON`: the nested NodeState (`$updateStateFromJSON`), then
163    // `$applyJSONSetters`, which applies the flat states before the class's
164    // own properties.
165    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    /// The class of `T`, which imports a node as `T::default()` with the
173    /// JSON applied.
174    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    /// A class with its own `importJSON`, which declares no NodeState and
198    /// is not an inline element.
199    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    /// Whether the class's `importJSON` is the synthesized one
227    /// ([`NodeClass::of`]), which applies the NodeState in the JSON, rather
228    /// than one of its own ([`NodeClass::with_import_json`]).
229    pub(crate) fn imports_node_state(&self) -> bool {
230        self.new_node.is_some()
231    }
232
233    /// `new klass()`, with a key in the active editor state.
234    pub(crate) fn construct(&self) -> Option<NodeRef> {
235        self.new_node.map(|f| set_node_key(f()))
236    }
237
238    /// `replaceWithKlass`: the type of the class the replacement makes.
239    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    /// `getDeclaredNodeStructure(klass)` (`@experimental node-structure`):
247    /// the structure the class declares. A class made with
248    /// [`with_import_json`](Self::with_import_json) declares none.
249    pub fn get_declared_node_structure(&self) -> DeclaredNodeStructure {
250        (self.node_structure)()
251    }
252}
253
254/// `COLLABORATION_TAG` (`LexicalUpdateTags.ts`): the update applies changes
255/// that came from another replica.
256pub const COLLABORATION_TAG: &str = "collaboration";
257
258/// `HISTORIC_TAG` (`LexicalUpdateTags.ts`): the update applies a state from
259/// the undo or redo stack.
260pub const HISTORIC_TAG: &str = "historic";
261
262/// `HISTORY_PUSH_TAG` (`LexicalUpdateTags.ts`): the update starts a new
263/// history entry.
264pub const HISTORY_PUSH_TAG: &str = "history-push";
265
266/// `HISTORY_MERGE_TAG` (`LexicalUpdateTags.ts`): the update joins the
267/// previous history entry.
268pub const HISTORY_MERGE_TAG: &str = "history-merge";
269
270/// `PASTE_TAG` (`LexicalUpdateTags.ts`): the update is a paste.
271pub const PASTE_TAG: &str = "paste";
272
273/// `CUT_TAG` (`LexicalUpdateTags.ts`): the update is a cut.
274pub const CUT_TAG: &str = "cut";
275
276/// `COMPOSITION_START_TAG` (`LexicalUpdateTags.ts`): the update starts an
277/// input method composition.
278pub const COMPOSITION_START_TAG: &str = "composition-start";
279
280/// `COMPOSITION_END_TAG` (`LexicalUpdateTags.ts`): the update ends an input
281/// method composition.
282pub const COMPOSITION_END_TAG: &str = "composition-end";
283
284/// `DEFER_COMPOSITION_MERGE_TAG` (`LexicalUpdateTags.ts`): the update must
285/// not merge text into or out of the node being composed.
286pub const DEFER_COMPOSITION_MERGE_TAG: &str = "defer-composition-merge";
287
288/// `SKIP_SELECTION_FOCUS_TAG` (`LexicalUpdateTags.ts`): the update must
289/// not move the focus to the editor.
290pub const SKIP_SELECTION_FOCUS_TAG: &str = "skip-selection-focus";
291
292/// `SKIP_COLLAB_TAG` (`LexicalUpdateTags.ts`): the update must not be sent
293/// to other replicas.
294pub const SKIP_COLLAB_TAG: &str = "skip-collab";
295
296/// `SKIP_SCROLL_INTO_VIEW_TAG` (`LexicalUpdateTags.ts`): the update must
297/// not scroll the selection into view.
298pub const SKIP_SCROLL_INTO_VIEW_TAG: &str = "skip-scroll-into-view";
299
300/// `SKIP_DOM_SELECTION_TAG` (`LexicalUpdateTags.ts`): the update must not
301/// change the platform's selection.
302pub const SKIP_DOM_SELECTION_TAG: &str = "skip-dom-selection";
303
304/// `FOCUS_TAG` (`LexicalUpdateTags.ts`): the update is
305/// [`Editor::focus`]'s.
306pub const FOCUS_TAG: &str = "focus";
307
308/// `ErrorHandler` as `onWarn` takes it: it gets a warning the editor has
309/// recovered from, and what it returns is what the call that warned
310/// returns (JS's default throws in development, as the vectors record).
311pub type WarningHandler = Rc<dyn Fn(LexicalError) -> Result<(), LexicalError>>;
312
313/// `CreateEditorArgs`: the node classes (and [`LexicalNodeReplacement`]s,
314/// as `NodeClass`es) to register besides the core ones, the editor's
315/// `namespace` (when empty, its parent editor's, or a random one,
316/// `createUID()`), the initial state, whether it is editable, the theme,
317/// the parent editor, `onWarn`, and (with the `html` feature) the HTML
318/// import and export overrides and the render config. JS's `onError` has
319/// no counterpart: an update's error is returned from
320/// [`Editor::update`].
321#[derive(Clone, Default)]
322pub struct CreateEditorArgs {
323    pub nodes: Vec<NodeClass>,
324    pub namespace: String,
325    /// `editorState`: the state the editor starts with, committed by its
326    /// first read or update.
327    pub editor_state: Option<EditorState>,
328    /// `editable`; `None` is JS's `undefined`, editable.
329    pub editable: Option<bool>,
330    /// `onWarn`: what hears of recoverable conditions (an update cascade
331    /// cut short); by default the warning is returned as an error, as JS's
332    /// default throws in development.
333    pub on_warn: Option<WarningHandler>,
334    /// `parentEditor`: the editor this one is nested in, which commands
335    /// dispatched in this one reach after its own listeners.
336    pub parent_editor: Option<Editor>,
337    /// `theme`: class names by node kind (`EditorThemeClasses`), as JSON:
338    /// a string or an array of strings, or (for `text`) an object of them
339    /// by format.
340    pub theme: Object,
341    /// `html`: export overrides by node type and extra import conversions.
342    #[cfg(feature = "html")]
343    pub html: crate::lexical_dom::HtmlConfig,
344    /// `dom`: the render config; `None` for the default.
345    #[cfg(feature = "html")]
346    pub dom: Option<crate::lexical_dom::EditorDomRenderConfig>,
347}
348
349/// `EditorConfig` (`editor._config`): what `createDOM` reads.
350#[derive(Clone, Debug, Default)]
351pub struct EditorConfig {
352    /// `theme`.
353    pub theme: Object,
354}
355
356/// `EditorReadMode`: which state [`Editor::read_with_mode`] reads.
357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358pub enum EditorReadMode {
359    /// `'force-commit'`: commit the pending update, then read.
360    ForceCommit,
361    /// `'latest'`: the committed state, without committing.
362    Latest,
363    /// `'pending'`: the pending state, or the committed one without one.
364    Pending,
365}
366
367/// `EditorUpdateOptions`. `event` comes with its users.
368#[derive(Clone, Default)]
369pub struct UpdateOptions {
370    /// Commit at the end of the update instead of at the next read.
371    pub discrete: bool,
372    /// Update tags (`tag`).
373    pub tags: Vec<String>,
374    pub skip_transforms: bool,
375    /// `onUpdate`: runs once the update commits, after its listeners and
376    /// before the callbacks of `$onUpdate` ([`on_update`](crate::on_update)).
377    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/// `EditorFocusOptions`.
392#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
393pub enum EditorFocusOptions {
394    /// `defaultSelection: 'rootEnd'` (the default, as `undefined` is).
395    #[default]
396    RootEnd,
397    /// `defaultSelection: 'rootStart'`.
398    RootStart,
399}
400
401/// What an update listener receives (`UpdateListenerPayload`). The dirty
402/// nodes are in the order they were marked; each dirty element says whether
403/// it was marked itself (`true`) or only because a descendant was.
404#[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    /// `mutatedNodes`: what the reconciler did to the nodes, by node type,
413    /// when it ran (the editor has a root element and something was
414    /// dirty), or `None`. Empty unless a mutation listener is registered.
415    pub mutated_nodes: Option<MutatedNodes>,
416}
417
418/// A node transform (`Transform<T>`).
419pub type Transform = Rc<dyn Fn(&NodeRef) -> Result<(), LexicalError>>;
420
421/// `NodeMutation`: what the reconciler did with a node in a commit.
422#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub enum NodeMutation {
424    /// `'created'`.
425    Created,
426    /// `'updated'`.
427    Updated,
428    /// `'destroyed'`.
429    Destroyed,
430}
431
432impl NodeMutation {
433    /// The mutation as JS names it.
434    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
443/// The nodes of one class a commit mutated, in the order the reconciler
444/// reached them (JS's `Map<NodeKey, NodeMutation>`).
445pub type NodeMutations = Vec<(NodeKey, NodeMutation)>;
446
447/// `MutatedNodes`: the nodes a commit mutated by node type, in the order
448/// the reconciler first reached one of the type (JS keys its `Map` by
449/// class).
450pub type MutatedNodes = Vec<(&'static str, NodeMutations)>;
451
452/// A mutation listener's second argument (`MutationListener`'s
453/// `{dirtyLeaves, prevEditorState, updateTags}`).
454#[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/// `MutationListenerOptions`.
462#[derive(Clone, Copy, Debug, Default)]
463pub struct MutationListenerOptions {
464    /// `skipInitialization`: don't call the listener at once with the
465    /// class's existing nodes as created (false by default, as in JS).
466    pub skip_initialization: bool,
467}
468
469/// A mutation listener.
470pub(crate) type MutationListener = Rc<dyn Fn(&NodeMutations, &MutationListenerPayload)>;
471
472/// The editor's root element: what JS's `HTMLElement` root is to an app
473/// without a DOM, the view that shows the document. Setting one
474/// ([`Editor::set_root_element`]) runs the reconciler's model half, so
475/// mutation listeners hear from the editor. Root elements compare by
476/// identity, as JS's elements do.
477pub trait RootElement: Any {
478    /// JS appends `@lexical/a11y`'s live region to `owner`, or to the root
479    /// element's `ownerDocument.body`: this is where a root element puts it,
480    /// or `None` (the default) for a root without one, where announcements
481    /// are dropped.
482    #[cfg(feature = "a11y")]
483    fn live_region_host(self: Rc<Self>) -> Option<Rc<dyn crate::a11y::LiveRegionHost>> {
484        None
485    }
486
487    /// Gives up the focus and clears the platform's selection, as
488    /// [`Editor::blur`] (`editor.blur()`) does to a DOM root. Does nothing
489    /// by default.
490    fn blur(&self) {}
491
492    /// Takes the focus, as `rootElement.focus()` does. Does nothing by
493    /// default. ([`Editor::focus`] doesn't call it: JS's moves the focus by
494    /// setting the DOM selection, which the app's view does when it draws
495    /// the selection of an update tagged [`FOCUS_TAG`].)
496    fn focus(&self) {}
497
498    /// Whether the root (or a view in it) has the focus, as
499    /// `rootElement.contains(document.activeElement)` says of a DOM root.
500    /// `false` by default.
501    fn has_focus(&self) -> bool {
502        false
503    }
504
505    /// The caret at a point in the root's coordinates, as
506    /// `caretFromPoint(x, y, rootElement)` from `@lexical/clipboard`
507    /// hit-tests the DOM, which drop and drag handlers ask for the
508    /// position of a `MouseEvent` (`clientX`, `clientY`). It is read
509    /// inside an update. `None` (the default) when no caret resolves
510    /// there.
511    fn caret_from_point(&self, _x: f64, _y: f64) -> Option<crate::caret::PointCaret> {
512        None
513    }
514
515    /// The computed style of the element rendered for the node `key`, as
516    /// `getComputedStyle(editor.getElementByKey(key))`, which
517    /// `@lexical/selection`'s `$getComputedStyleForElement` reads for the
518    /// text direction and writing mode the arrow keys follow. It is read
519    /// inside an update. `None` (the default) for a node with no element,
520    /// as a JS editor that renders nothing has none.
521    #[cfg(feature = "selection")]
522    fn computed_style(&self, _key: &str) -> Option<crate::selection::ComputedStyle> {
523        None
524    }
525
526    /// Whether the root is attached, as a DOM element's `isConnected` says
527    /// (for a view: whether it is in a window). The commit announces a
528    /// range selection (or none) with `SELECTION_CHANGE_COMMAND` only while
529    /// the root is connected. `true` by default.
530    fn is_connected(&self) -> bool {
531        true
532    }
533}
534
535/// A stored update listener, which may return a clean-up.
536type UpdateListenerFn = dyn Fn(&UpdateListenerPayload) -> Option<Unregister>;
537/// A stored text content listener, which may return a clean-up.
538type TextContentListenerFn = dyn Fn(&str) -> Option<Unregister>;
539/// A stored decorator listener, which may return a clean-up.
540type DecoratorListenerFn = dyn Fn(&Decorators) -> Option<Unregister>;
541
542/// A root element, compared by identity.
543#[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
558/// A root listener (`RootListener`): the next and the previous root
559/// element; what it returns runs before its next call and when it is
560/// unregistered.
561pub(crate) type RootListener =
562    Rc<dyn Fn(Option<&RootElementRef>, Option<&RootElementRef>) -> Option<Unregister>>;
563
564/// A registered root listener: its id, the listener, and what its last call
565/// returned.
566type RootListenerEntry = (u64, RootListener, Rc<RefCell<Option<Unregister>>>);
567
568/// Calling it removes what was registered, as the function JS's `register*`
569/// methods return. Dropping it without calling it keeps the registration.
570pub type Unregister = Box<dyn FnOnce()>;
571
572/// What an update, text content, decorator or editable listener returns:
573/// nothing (`()`), or a clean-up function (an [`Unregister`], or an
574/// `Option` of one), which runs before the listener's next call, or when
575/// it is unregistered. JS takes a returned function as the clean-up and
576/// ignores any other value (`triggerListeners`).
577pub trait ListenerCleanup {
578    /// The clean-up, if there is one.
579    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
600/// A command (`createCommand`), compared by identity: two commands made
601/// with the same name are different commands.
602pub struct LexicalCommand<P> {
603    id: u64,
604    name: CommandName,
605    _payload: PhantomData<fn(&P)>,
606}
607
608/// A command's name: shared when [`create_command`] makes it, static for
609/// the core's own commands (`commands`), which are constants.
610#[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    /// One of the core's own commands, with an id [`create_command`] never
628    /// gives (they count up from 1).
629    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
652/// `createCommand(type)`.
653pub 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
662/// `COMMAND_PRIORITY_EDITOR`: a listener added to the end of the editor
663/// priority queue (after critical, high, normal, low).
664pub const COMMAND_PRIORITY_EDITOR: i8 = 0;
665/// `COMMAND_PRIORITY_LOW`: the end of the low priority queue.
666pub const COMMAND_PRIORITY_LOW: i8 = 1;
667/// `COMMAND_PRIORITY_NORMAL`: the end of the normal priority queue.
668pub const COMMAND_PRIORITY_NORMAL: i8 = 2;
669/// `COMMAND_PRIORITY_HIGH`: the end of the high priority queue.
670pub const COMMAND_PRIORITY_HIGH: i8 = 3;
671/// `COMMAND_PRIORITY_CRITICAL`: the end of the critical priority queue.
672pub const COMMAND_PRIORITY_CRITICAL: i8 = 4;
673/// `COMMAND_PRIORITY_BEFORE_EDITOR`: the beginning of the editor priority
674/// queue.
675pub const COMMAND_PRIORITY_BEFORE_EDITOR: i8 = -8;
676/// `COMMAND_PRIORITY_BEFORE_LOW`: the beginning of the low priority queue.
677pub const COMMAND_PRIORITY_BEFORE_LOW: i8 = -7;
678/// `COMMAND_PRIORITY_BEFORE_NORMAL`: the beginning of the normal priority
679/// queue.
680pub const COMMAND_PRIORITY_BEFORE_NORMAL: i8 = -6;
681/// `COMMAND_PRIORITY_BEFORE_HIGH`: the beginning of the high priority
682/// queue.
683pub const COMMAND_PRIORITY_BEFORE_HIGH: i8 = -5;
684/// `COMMAND_PRIORITY_BEFORE_CRITICAL`: the beginning of the critical
685/// priority queue.
686pub const COMMAND_PRIORITY_BEFORE_CRITICAL: i8 = -4;
687
688/// A command listener: it returns whether it handled the command, which
689/// stops the ones after it.
690pub(crate) type CommandListener<P> = Rc<dyn Fn(&P, &Editor) -> Result<bool, LexicalError>>;
691
692/// `NO_DIRTY_NODES`, `HAS_DIRTY_NODES`, `FULL_RECONCILE`.
693#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
694pub(crate) enum DirtyType {
695    #[default]
696    None,
697    HasDirtyNodes,
698    FullReconcile,
699}
700
701/// The editor's record of what an update changed: `_dirtyType`,
702/// `_dirtyElements`, `_dirtyLeaves` and `_normalizedNodes`.
703#[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
711/// An update queued while the editor was updating (`_updates`).
712pub(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/// A Lexical editor. A handle; cloning it shares the same editor. Without a
719/// DOM it is what JS calls a headless editor. It is neither `Send` nor
720/// `Sync`.
721#[derive(Clone)]
722pub struct Editor(pub(crate) Rc<EditorInner>);
723
724/// Editors compare by identity, as JS compares them with `===`.
725impl 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
733/// A listener map (`ListenerMap`): each listener with its id and what its
734/// last call returned.
735type Listeners<F> = RefCell<Vec<(u64, Rc<F>, Rc<RefCell<Option<Unregister>>>)>>;
736/// A command's listeners by priority, each a `CommandListener<P>` of the
737/// command's payload type.
738type CommandListeners = [Vec<(u64, Rc<dyn Any>)>; 5];
739
740pub(crate) struct EditorInner {
741    nodes: HashMap<&'static str, NodeClass>,
742    /// The types of `nodes` in the order JS's `_nodes` map holds them: the
743    /// core nodes, then `args.nodes`, each type where it first came.
744    node_order: Vec<&'static str>,
745    /// Each registered node's `sharedNodeState`.
746    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    /// Stands in for the DOM's `Selection.modify` (no JS field).
761    selection_movement: RefCell<Option<Rc<dyn SelectionMovement>>>,
762    /// `_config`.
763    config: EditorConfig,
764    /// `_htmlConversions`: the import conversions by lower-case DOM node
765    /// name, in registration order.
766    #[cfg(feature = "html")]
767    pub(crate) html_conversions: HashMap<String, Vec<crate::lexical_dom::DomImporter>>,
768    /// The `exportDOM` overrides of `html.export`, by node type.
769    #[cfg(feature = "html")]
770    pub(crate) html_export: HashMap<&'static str, crate::lexical_dom::ExportOverride>,
771    /// `_config.dom`, which `DOMRenderExtension` replaces when its overrides
772    /// change (here, not in [`EditorConfig`], which nodes borrow).
773    #[cfg(feature = "html")]
774    pub(crate) dom: RefCell<crate::lexical_dom::EditorDomRenderConfig>,
775    /// `_config.namespace`.
776    namespace: String,
777    /// `_parentEditor`.
778    parent_editor: Option<Editor>,
779    /// `_key`.
780    key: String,
781    /// `_editable`.
782    editable: Cell<bool>,
783    /// `_headless`: the editor never reconciles (`@lexical/headless`, or a
784    /// headless parent editor).
785    headless: Cell<bool>,
786    /// What `@lexical/headless` puts before `setRootElement` (where JS
787    /// replaces the method on the instance): it refuses a root.
788    pub(crate) set_root_element_guard: RefCell<Option<SetRootElementGuard>>,
789    /// `_onWarn`.
790    on_warn: WarningHandler,
791    /// `_slotsUsed`: whether a slot was ever set in this editor, or in a
792    /// state it was given. Latched for the editor's lifetime.
793    pub(crate) slots_used: Cell<bool>,
794    /// `_rootElement`.
795    root_element: RefCell<Option<RootElementRef>>,
796    /// `INTERNAL_registerNodeStructure`'s registration (JS keeps it in a
797    /// module-level `WeakMap` by editor).
798    pub(crate) node_structure: RefCell<Option<Rc<NodeStructureRegistration>>>,
799    /// `_listeners.mutation`: each listener with its class, in the order
800    /// they were registered.
801    mutation_listeners: RefCell<Vec<(u64, MutationListener, &'static str)>>,
802    /// `_listeners.editable`.
803    pub(crate) editable_listeners: Listeners<dyn Fn(bool) -> Option<Unregister>>,
804    /// `_listeners.root`, each with what its last call returned.
805    pub(crate) root_listeners: RefCell<Vec<RootListenerEntry>>,
806    /// `_deferred`: the `$onUpdate` callbacks of the pending update.
807    pub(crate) deferred: RefCell<Vec<Box<dyn FnOnce()>>>,
808    /// `_compositionKey`: the node an input method is composing in.
809    pub(crate) composition_key: RefCell<Option<NodeKey>>,
810    /// `_compositionMergeHeld`: the composed node a merge was held back
811    /// for (`DEFER_COMPOSITION_MERGE_TAG`).
812    pub(crate) composition_merge_held: RefCell<Option<NodeKey>>,
813    /// `_lastNotifiedSelection`: the selection `SELECTION_CHANGE_COMMAND`
814    /// last announced (a clone), which the commit compares the pending
815    /// selection with.
816    pub(crate) last_notified_selection: RefCell<Option<crate::lexical_selection::Selection>>,
817    /// `_inputState`, the part the model reads.
818    pub(crate) input_state: RefCell<crate::events::InputState>,
819    /// `_keyDownShortcuts`: the compiled key-down bindings.
820    pub(crate) key_down_shortcuts: RefCell<Option<crate::events::KeyDownShortcuts>>,
821    /// `RootNode.__cachedText`: the root the reconciler last cached its
822    /// text content on, and that text. JS keeps it on the root node, which
823    /// a clone resets; here the cache names the root by identity.
824    pub(crate) root_text_cache: RefCell<Option<(Rc<dyn LexicalNode>, String)>>,
825    /// `_keyToDOMMap`: what the reconciler keeps of each node it rendered.
826    pub(crate) key_to_dom_map: RefCell<crate::reconciler::KeyToDomMap>,
827    /// `_decorators`.
828    pub(crate) decorators: RefCell<Decorators>,
829    /// `_pendingDecorators`.
830    pub(crate) pending_decorators: RefCell<Option<Decorators>>,
831    /// `_listeners.decorator`.
832    decorator_listeners: Listeners<DecoratorListenerFn>,
833    /// The `LexicalBuilder` that built the editor (JS's
834    /// `editor[builderSymbol]`).
835    #[cfg(feature = "extension")]
836    pub(crate) builder: RefCell<Option<Rc<dyn Any>>>,
837}
838
839/// What refuses a root element in [`Editor::set_root_element`], before it
840/// changes anything.
841pub(crate) type SetRootElementGuard =
842    Rc<dyn Fn(Option<&RootElementRef>) -> Result<(), LexicalError>>;
843
844/// `createEditor(config)`: registers the core nodes (root, text, line
845/// break, tab, paragraph, artificial) and `args.nodes`, in `args.namespace`,
846/// or the parent editor's when that is empty. (JS's `createEditor()` with
847/// no config at all takes the active editor as the parent; Rust always
848/// takes a config, as Swift does.)
849///
850/// A node replacement whose `with_klass` doesn't extend the class it
851/// replaces panics, as JS's development build throws; one without
852/// `with_klass` warns ([`with_warning_handler`](crate::with_warning_handler)).
853pub fn create_editor(args: CreateEditorArgs) -> Editor {
854    let parent_editor = args.parent_editor;
855    // `config.namespace || (parentEditor !== null ?
856    // parentEditor._config.namespace : createUID())`.
857    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        // The root is an `ElementNode`.
866        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    // `validateNodeStructure(klass)`, which JS runs in development, as the
878    // vectors were recorded.
879    for class in &classes {
880        if let Some(replacement) = &class.replacement {
881            match &replacement.with_klass {
882                Some(with_klass) => assert!(
883                    // `replaceWithKlass.prototype instanceof klass`.
884                    (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    /// `editor._config`.
981    pub fn config(&self) -> &EditorConfig {
982        &self.0.config
983    }
984
985    /// `LexicalEditor.version`: the port's own, as Swift's is
986    /// `lexical-swift@<upstream>`, for the upstream release in
987    /// [`UPSTREAM_VERSION`](crate::UPSTREAM_VERSION).
988    pub const VERSION: &'static str = "lexical-rust@0.53.0";
989
990    /// `isComposing()`: whether an input method is composing
991    /// (`_compositionKey` is set).
992    pub fn is_composing(&self) -> bool {
993        self.0.composition_key.borrow().is_some()
994    }
995
996    /// `_compositionKey`.
997    pub(crate) fn composition_key(&self) -> Option<NodeKey> {
998        self.0.composition_key.borrow().clone()
999    }
1000
1001    /// `_config.namespace`: the namespace the editor was created with.
1002    pub fn get_namespace(&self) -> &str {
1003        &self.0.namespace
1004    }
1005
1006    /// `_parentEditor`: the editor this one is nested in
1007    /// ([`CreateEditorArgs::parent_editor`]), if any.
1008    pub fn parent_editor(&self) -> Option<&Editor> {
1009        self.0.parent_editor.as_ref()
1010    }
1011
1012    /// `getKey()`: the editor's own random key (`createUID()`), which a
1013    /// drag from it is marked with (`$writeDragSourceToDataTransfer`).
1014    pub fn get_key(&self) -> &str {
1015        &self.0.key
1016    }
1017
1018    /// `blur()`: the root element gives up the focus and its selection
1019    /// ([`RootElement::blur`]).
1020    pub fn blur(&self) {
1021        if let Some(root) = self.get_root_element() {
1022            root.0.blur();
1023        }
1024    }
1025
1026    /// `focus(callbackFn, options)`: with a root element, an update (tagged
1027    /// [`FOCUS_TAG`]) that marks the selection dirty, so the view applies
1028    /// it again, or selects the end (or, with
1029    /// [`EditorFocusOptions::RootStart`], the start) of the root when there
1030    /// is none; `callback` runs once it commits. Without a root element it
1031    /// does nothing. (JS also turns `autocapitalize` off on the DOM root
1032    /// around the update, which only iOS's keyboard reads.)
1033    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                    // Marking the selection dirty will force the selection
1048                    // back to it.
1049                    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    /// `_headless`: whether the editor never reconciles, as
1072    /// [`create_headless_editor`](crate::create_headless_editor) makes it
1073    /// (and a nested editor of a headless one is).
1074    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    /// `_onWarn(error)`: what the call that warned returns.
1084    pub(crate) fn on_warn(&self, warning: LexicalError) -> Result<(), LexicalError> {
1085        (self.0.on_warn)(warning)
1086    }
1087
1088    /// `isEditable()`.
1089    pub fn is_editable(&self) -> bool {
1090        self.0.editable.get()
1091    }
1092
1093    /// `setEditable(editable)`: when that changes the editor's mode, the
1094    /// editable listeners hear of it.
1095    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    /// `registerEditableListener(listener)`: `listener` hears each change of
1105    /// [`is_editable`](Self::is_editable).
1106    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    /// `getDecorators()`: what each decorator decorated to
1119    /// ([`LexicalNode::decorate`]), as the reconciler last collected it.
1120    /// It is empty until the editor has a root element.
1121    pub fn get_decorators(&self) -> Decorators {
1122        self.0.decorators.borrow().clone()
1123    }
1124
1125    /// `registerDecoratorListener(listener)`: `listener` hears each commit
1126    /// that changed [`get_decorators`](Self::get_decorators), with the new
1127    /// decorators.
1128    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    /// `triggerListeners('decorator', ...)`'s loop.
1141    pub(crate) fn trigger_decorator_listeners(&self, decorators: &Decorators) {
1142        trigger_listeners(&self.0.decorator_listeners, |listener| listener(decorators));
1143    }
1144
1145    /// `getRootElement()`.
1146    pub fn get_root_element(&self) -> Option<RootElementRef> {
1147        self.0.root_element.borrow().clone()
1148    }
1149
1150    /// `setRootElement(nextRootElement)`, its model half: the editor is
1151    /// reset (its state is empty again) and the pending state, or the
1152    /// current one, is committed with `history-merge`, the queued updates
1153    /// and tags kept. With a root, every node is reconciled, so mutation
1154    /// listeners hear of each as created; then the root listeners run.
1155    /// Styling and events are the app's view's job.
1156    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        // `resetEditor(this, prev, next, pendingEditorState, {preserveUpdateQueue: true})`.
1171        *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        // `triggerListeners('root', this, false, next, prev)`.
1182        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    /// `registerRootListener(listener)`: `listener` is called at once with
1203    /// the root element (and `None`), then with the next and previous root
1204    /// each time it changes, and with `None` and the root when it is
1205    /// unregistered. What it returns runs before its next call.
1206    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    /// `registerMutationListener(klass, listener, options)`, by the node
1236    /// type: after each commit that the reconciler ran in (the editor has a
1237    /// root element), `listener` gets the class's nodes it created,
1238    /// updated or destroyed. Unless `skip_initialization`, it is called at
1239    /// once with the class's nodes in the editor's state as created. Fails
1240    /// for a type the editor doesn't register.
1241    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        // `resolveRegisteredNodeAfterReplacements`: a replaced class's
1253        // listener hears of the class that replaces it.
1254        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            // `initializeMutationListener(listener, klass)`.
1263            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    /// The node types mutation listeners listen to.
1296    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    /// `editor._nodes.get(type)`: the class the editor registers under the
1314    /// type.
1315    pub fn get_registered_node(&self, node_type: &str) -> Option<NodeClass> {
1316        self.0.nodes.get(node_type).cloned()
1317    }
1318
1319    /// `resolveRegisteredNodeAfterReplacements(registeredNode)`, by type:
1320    /// the type of the class a registered class's replacements end at
1321    /// (following `withKlass`). Fails for a `withKlass` that isn't
1322    /// registered.
1323    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    /// `hasNode(klass)`, by the node type: whether the editor registers it.
1344    pub fn has_node(&self, node_type: &str) -> bool {
1345        self.0.nodes.contains_key(node_type)
1346    }
1347
1348    /// `hasNodes(klasses)`, by the node types: whether the editor registers
1349    /// all of them.
1350    pub fn has_nodes(&self, node_types: &[&str]) -> bool {
1351        node_types.iter().all(|t| self.has_node(t))
1352    }
1353
1354    /// The registered node classes in the order JS's `_nodes` holds them.
1355    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    /// The `sharedNodeState` of a registered node type.
1364    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    /// Sets what stands in for the DOM's `Selection.modify` in this editor:
1381    /// where a caret lands when `modify`, `deleteCharacter`, `deleteWord` or
1382    /// `deleteLine` move it within text, which only text layout knows.
1383    /// Without one (the default) the editor behaves as JS does with no root
1384    /// element: those moves fail with `window object not found`.
1385    pub fn set_selection_movement(&self, movement: Option<Rc<dyn SelectionMovement>>) {
1386        *self.0.selection_movement.borrow_mut() = movement;
1387    }
1388
1389    /// The movement [`set_selection_movement`](Self::set_selection_movement)
1390    /// set.
1391    pub(crate) fn selection_movement(&self) -> Option<Rc<dyn SelectionMovement>> {
1392        self.0.selection_movement.borrow().clone()
1393    }
1394
1395    /// `getEditorState()`: the committed state.
1396    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    /// `toJSON()`: `{editorState}`, this editor's committed state in the
1405    /// form the export around it is writing
1406    /// ([`is_compact_export`](crate::is_compact_export)), which is how a
1407    /// nested editor stays in the form of the document containing it.
1408    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    /// `parseEditorState(json)` from the JSON text.
1419    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    /// `parseEditorState(serializedEditorState)` from parsed JSON.
1425    pub fn parse_editor_state_json(&self, json: &Value) -> Result<EditorState, LexicalError> {
1426        parse_editor_state(json, self, None)
1427    }
1428
1429    /// `parseEditorState(serializedEditorState, updateFn)`: runs `update_fn`
1430    /// on the parsed state before it is made read-only, as an update of
1431    /// that state (`$getRoot()` is its root); nothing it changes is marked
1432    /// dirty in this editor, nor in an update running here.
1433    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    /// `update(updateFn, options)`. Inside another update of this editor (or
1442    /// a listener of its commit) the update is queued and runs after it, as
1443    /// in JS, which is why `update_fn` is `'static`.
1444    ///
1445    /// A non-discrete update is committed by the next [`read`](Self::read)
1446    /// or discrete update, where JS commits it in a microtask. An update
1447    /// that fails is discarded, the editor keeps its previous state, and the
1448    /// error is returned (JS reports it to `onError`).
1449    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            // `scheduleCascadeReset`: JS resets the cascade budget in a
1464            // macrotask, once control returns to the event loop. An update
1465            // begun outside any update or commit of this editor is the
1466            // host's next turn, so separate actions don't accumulate
1467            // toward the limit; a runaway cascade continues from commits.
1468            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    /// `setEditorState(editorState, {tag})`: makes `editor_state` the
1476    /// editor's state, through an update, so a state from
1477    /// [`parse_editor_state`](Self::parse_editor_state) has its text
1478    /// normalized and its transforms run, as in JS. The editor keeps its
1479    /// state and this returns the error when the update fails, such as for
1480    /// a state with nothing but the root (an invariant in JS's DEV build).
1481    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        // A writable state, so transforms can run on it.
1488        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                    // Every node is dirty, so normalization and transforms
1529                    // run on a state that arrived from outside.
1530                    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    /// `read(callbackFn)`: commits any pending update, then runs `f` with
1547    /// the editor's state active, read-only. Fails when committing runs a
1548    /// queued update that fails.
1549    pub fn read<R>(&self, f: impl FnOnce() -> R) -> Result<R, LexicalError> {
1550        self.read_with_mode(EditorReadMode::ForceCommit, f)
1551    }
1552
1553    /// `read(mode, callbackFn)`: [`read`](Self::read) for
1554    /// `EditorReadMode::ForceCommit`; `Latest` reads the committed state
1555    /// without committing first, and `Pending` the state of the update in
1556    /// progress or queued (the committed one without one), without
1557    /// committing it.
1558    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    /// `registerNodeTransform(klass, listener)`, by the node type. Nodes of
1580    /// that type already in the editor are marked dirty, so the transform
1581    /// runs on them with the next update. A class replaced by a
1582    /// `with_klass` ([`LexicalNodeReplacement`]) gets it on that class too.
1583    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    /// `registeredNode.transforms.add(transform)`: what
1615    /// [`register_node_transform`](Self::register_node_transform) does
1616    /// before marking the type's nodes dirty, for callers that add to a
1617    /// class's transforms directly, as `NormalizeInlineElementsExtension`
1618    /// does.
1619    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    /// `registerUpdateListener(listener)`.
1651    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    /// `registerTextContentListener(listener)`.
1664    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    /// `triggerListeners('update', ...)`'s loop.
1676    pub(crate) fn trigger_update_listeners(&self, payload: &UpdateListenerPayload) {
1677        trigger_listeners(&self.0.update_listeners, |listener| listener(payload));
1678    }
1679
1680    /// Whether a text content listener is registered.
1681    pub(crate) fn has_text_content_listeners(&self) -> bool {
1682        !self.0.text_content_listeners.borrow().is_empty()
1683    }
1684
1685    /// `triggerListeners('textcontent', ...)`'s loop.
1686    pub(crate) fn trigger_text_content_listeners(&self, text: &str) {
1687        trigger_listeners(&self.0.text_content_listeners, |listener| listener(text));
1688    }
1689
1690    /// `registerCommand(command, listener, priority)`, `priority` being one
1691    /// of the `COMMAND_PRIORITY_*` constants: 0 to 4 add the listener to the
1692    /// end of that priority's queue, and the `COMMAND_PRIORITY_BEFORE_*`
1693    /// ones (-8 to -4) to its beginning (`normalizePriority`'s `priority &
1694    /// 7`).
1695    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                    // The command leaves the map with its last listener.
1724                    if lists.iter().all(Vec::is_empty) {
1725                        commands.remove(&command_id);
1726                    }
1727                }
1728            }
1729        })
1730    }
1731
1732    /// `editor._commands.has(command)`.
1733    #[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    /// `dispatchCommand(command, payload)`: runs the command's listeners, by
1757    /// priority (within each, this editor's, then its parent editors'),
1758    /// until one handles it, and returns whether one did.
1759    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    // The dirty records.
1768
1769    pub(crate) fn dirty_type(&self) -> DirtyType {
1770        self.0.dirty.borrow().dirty_type
1771    }
1772
1773    /// Marks a node dirty: an element as intentionally dirty, any other node
1774    /// as a dirty leaf.
1775    pub(crate) fn mark_dirty(&self, key: &str, is_element: bool) {
1776        let mut dirty = self.0.dirty.borrow_mut();
1777        // Don't downgrade a full reconcile.
1778        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
1796/// `$hasUpdateTag(tag)`: whether the running update has the tag (one of
1797/// its options' tags, or one [`add_update_tag`] added). Panics outside an
1798/// update or a read of an editor, as JS's `getActiveEditor()` throws.
1799pub fn has_update_tag(tag: &str) -> bool {
1800    get_editor().0.tags.borrow().contains(tag)
1801}
1802
1803/// `$addUpdateTag(tag)`: adds a tag to the running update, which update and
1804/// mutation listeners and [`has_update_tag`] see. Panics in a read, or
1805/// outside an update, as JS's `errorOnReadOnly` and `getActiveEditor()`
1806/// throw.
1807pub fn add_update_tag(tag: &str) {
1808    crate::updates::error_on_read_only();
1809    get_editor().0.tags.borrow_mut().add(tag);
1810}
1811
1812/// `$getEditor()`: the editor of the running update or read (or the one
1813/// `parseEditorState` parses for). Panics outside them, as JS's
1814/// `getActiveEditor()` throws.
1815pub 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
1821/// Runs `f` with the editor's `_updating` set to `updating`, as
1822/// `triggerListeners` does with `isCurrentlyEnqueuingUpdates`.
1823fn 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
1834/// `registerListener(listenerMap, listener)`: `unregisterListener` removes
1835/// the listener and runs what its last call returned.
1836fn 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
1861/// `triggerListeners(type, ...)`'s loop over the listeners registered when
1862/// it starts: each one's last clean-up runs, then the listener; what it
1863/// returns is kept for its next call, or runs at once if the listener was
1864/// unregistered meanwhile.
1865fn 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
1885/// `triggerListener(listenerMap, listener, args)` of a root listener: what
1886/// it returned last runs, then it runs, and what it returns is kept.
1887fn 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
1901/// `markNodesWithTypesAsDirty(editor, types)`: an update that marks every
1902/// node of those types in the committed state dirty, in the order JS's
1903/// node map holds them.
1904pub(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    // Marking existing nodes dirty can't fail.
1926    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}