use crate::editor_state::{clone_editor_state, create_empty_editor_state};
use crate::error::invariant;
use crate::json::{self, Object, Value};
use crate::lexical_utils::{create_uid, set_node_key};
use crate::node::{LexicalNode, NodeKey, NodeRef};
use crate::node_state::{RequiredNodeStateConfig, SharedNodeState, create_shared_node_state};
use crate::nodes::{
artificial::ArtificialNode, line_break::LineBreakNode, paragraph::ParagraphNode,
root::RootNode, tab::TabNode, text::TextNode,
};
use crate::ordered::{OrderedMap, OrderedSet};
use crate::reconciler::Decorators;
use crate::selection_deletion::SelectionMovement;
use crate::structure::{
DeclaredNodeStructure, NodeStructureRegistration, get_declared_node_structure,
validate_node_structure,
};
use crate::updates::{
begin_update, commit_pending_updates, parse_editor_state, read_editor_state,
trigger_command_listeners, update_editor_sync,
};
use crate::{EditorState, LexicalError};
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
#[derive(Clone)]
pub struct NodeClass {
pub(crate) node_type: &'static str,
pub(crate) class_name: &'static str,
pub(crate) import_json: fn(&Object) -> Result<NodeRef, LexicalError>,
pub(crate) state_configs: fn() -> Vec<RequiredNodeStateConfig>,
#[cfg(feature = "html")]
pub(crate) import_dom: fn() -> Option<crate::lexical_dom::DomConversionMap>,
#[cfg_attr(not(feature = "extension"), allow(dead_code))]
pub(crate) is_inline_element: fn() -> bool,
pub(crate) declared_slots: fn() -> &'static [&'static str],
#[cfg_attr(not(feature = "extension"), allow(dead_code))]
pub(crate) is_text: fn() -> bool,
pub(crate) is_element_or_decorator: fn() -> bool,
node_structure: fn() -> DeclaredNodeStructure,
validate_node_structure: fn(),
pub(crate) super_types: fn() -> Vec<&'static str>,
pub(crate) replacement: Option<Rc<LexicalNodeReplacement>>,
new_node: Option<fn() -> Box<dyn LexicalNode>>,
}
fn new_node_of<T: LexicalNode + Default>() -> Box<dyn LexicalNode> {
Box::new(T::default())
}
pub type NodeReplace = Rc<dyn Fn(&NodeRef) -> Result<NodeRef, LexicalError>>;
#[derive(Clone)]
pub struct LexicalNodeReplacement {
pub replace: NodeClass,
pub with: NodeReplace,
pub with_klass: Option<NodeClass>,
}
impl From<LexicalNodeReplacement> for NodeClass {
fn from(replacement: LexicalNodeReplacement) -> Self {
let mut class = replacement.replace.clone();
class.replacement = Some(Rc::new(replacement));
class
}
}
fn is_element_or_decorator_of<T: LexicalNode + Default>() -> bool {
let node = T::default();
node.element().is_some() || node.is_decorator()
}
fn node_structure_of<T: LexicalNode + Default>() -> DeclaredNodeStructure {
get_declared_node_structure(&T::default())
}
fn validate_node_structure_of<T: LexicalNode + Default>() {
validate_node_structure(&T::default());
}
fn declared_slots_of<T: LexicalNode + Default>() -> &'static [&'static str] {
T::default().declared_slots()
}
#[cfg(feature = "html")]
fn import_dom_of<T: LexicalNode + Default>() -> Option<crate::lexical_dom::DomConversionMap> {
T::default().import_dom()
}
fn state_configs_of<T: LexicalNode + Default>() -> Vec<RequiredNodeStateConfig> {
T::default().state_configs()
}
fn is_text_of<T: LexicalNode + Default>() -> bool {
T::default().text().is_some()
}
fn super_types_of<T: LexicalNode + Default>() -> Vec<&'static str> {
T::default().super_types()
}
fn is_inline_element_of<T: LexicalNode + Default>() -> bool {
let node = T::default();
node.element().is_some() && node.is_inline()
}
fn import_default<T: LexicalNode + Default>(json: &Object) -> Result<NodeRef, LexicalError> {
let node_type = T::default().get_type();
let has_replacement = crate::updates::get_registry_editor().is_some_and(|editor| {
editor
.get_registered_node(node_type)
.is_some_and(|class| class.replacement.is_some())
});
let node = if has_replacement {
crate::lexical_utils::create::<T>()
} else {
set_node_key(Box::new(T::default()))
};
crate::node_state::update_state_from_json(&node, json)?;
crate::node_state::apply_flat_states(&node, json)?;
crate::lexical_utils::mutate(node.get_key(), |n| n.update_from_json(json));
Ok(node)
}
impl NodeClass {
pub fn of<T: LexicalNode + Default>() -> Self {
Self {
node_type: T::default().get_type(),
class_name: std::any::type_name::<T>()
.rsplit("::")
.next()
.unwrap_or_default(),
import_json: import_default::<T>,
state_configs: state_configs_of::<T>,
#[cfg(feature = "html")]
import_dom: import_dom_of::<T>,
is_inline_element: is_inline_element_of::<T>,
declared_slots: declared_slots_of::<T>,
is_text: is_text_of::<T>,
is_element_or_decorator: is_element_or_decorator_of::<T>,
node_structure: node_structure_of::<T>,
validate_node_structure: validate_node_structure_of::<T>,
super_types: super_types_of::<T>,
replacement: None,
new_node: Some(new_node_of::<T>),
}
}
pub fn with_import_json(
node_type: &'static str,
import_json: fn(&Object) -> Result<NodeRef, LexicalError>,
) -> Self {
Self {
node_type,
class_name: node_type,
import_json,
state_configs: Vec::new,
#[cfg(feature = "html")]
import_dom: || None,
is_inline_element: || false,
declared_slots: || &[],
is_text: || false,
is_element_or_decorator: || false,
node_structure: DeclaredNodeStructure::default,
validate_node_structure: || {},
super_types: Vec::new,
replacement: None,
new_node: None,
}
}
pub fn node_type(&self) -> &'static str {
self.node_type
}
pub(crate) fn imports_node_state(&self) -> bool {
self.new_node.is_some()
}
pub(crate) fn construct(&self) -> Option<NodeRef> {
self.new_node.map(|f| set_node_key(f()))
}
pub(crate) fn replace_with_klass(&self) -> Option<&'static str> {
self.replacement
.as_ref()
.and_then(|r| r.with_klass.as_ref())
.map(|k| k.node_type)
}
pub fn get_declared_node_structure(&self) -> DeclaredNodeStructure {
(self.node_structure)()
}
}
pub const COLLABORATION_TAG: &str = "collaboration";
pub const HISTORIC_TAG: &str = "historic";
pub const HISTORY_PUSH_TAG: &str = "history-push";
pub const HISTORY_MERGE_TAG: &str = "history-merge";
pub const PASTE_TAG: &str = "paste";
pub const CUT_TAG: &str = "cut";
pub const COMPOSITION_START_TAG: &str = "composition-start";
pub const COMPOSITION_END_TAG: &str = "composition-end";
pub const DEFER_COMPOSITION_MERGE_TAG: &str = "defer-composition-merge";
pub const SKIP_SELECTION_FOCUS_TAG: &str = "skip-selection-focus";
pub const SKIP_COLLAB_TAG: &str = "skip-collab";
pub const SKIP_SCROLL_INTO_VIEW_TAG: &str = "skip-scroll-into-view";
pub const SKIP_DOM_SELECTION_TAG: &str = "skip-dom-selection";
pub const FOCUS_TAG: &str = "focus";
pub type WarningHandler = Rc<dyn Fn(LexicalError) -> Result<(), LexicalError>>;
#[derive(Clone, Default)]
pub struct CreateEditorArgs {
pub nodes: Vec<NodeClass>,
pub namespace: String,
pub editor_state: Option<EditorState>,
pub editable: Option<bool>,
pub on_warn: Option<WarningHandler>,
pub parent_editor: Option<Editor>,
pub theme: Object,
#[cfg(feature = "html")]
pub html: crate::lexical_dom::HtmlConfig,
#[cfg(feature = "html")]
pub dom: Option<crate::lexical_dom::EditorDomRenderConfig>,
}
#[derive(Clone, Debug, Default)]
pub struct EditorConfig {
pub theme: Object,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditorReadMode {
ForceCommit,
Latest,
Pending,
}
#[derive(Clone, Default)]
pub struct UpdateOptions {
pub discrete: bool,
pub tags: Vec<String>,
pub skip_transforms: bool,
pub on_update: Option<Rc<dyn Fn()>>,
}
impl std::fmt::Debug for UpdateOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UpdateOptions")
.field("discrete", &self.discrete)
.field("tags", &self.tags)
.field("skip_transforms", &self.skip_transforms)
.field("on_update", &self.on_update.is_some())
.finish()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EditorFocusOptions {
#[default]
RootEnd,
RootStart,
}
#[derive(Clone, Debug)]
pub struct UpdateListenerPayload {
pub dirty_elements: Vec<(NodeKey, bool)>,
pub dirty_leaves: Vec<NodeKey>,
pub normalized_nodes: Vec<NodeKey>,
pub tags: Vec<String>,
pub editor_state: EditorState,
pub prev_editor_state: EditorState,
pub mutated_nodes: Option<MutatedNodes>,
}
pub type Transform = Rc<dyn Fn(&NodeRef) -> Result<(), LexicalError>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeMutation {
Created,
Updated,
Destroyed,
}
impl NodeMutation {
pub fn as_str(&self) -> &'static str {
match self {
NodeMutation::Created => "created",
NodeMutation::Updated => "updated",
NodeMutation::Destroyed => "destroyed",
}
}
}
pub type NodeMutations = Vec<(NodeKey, NodeMutation)>;
pub type MutatedNodes = Vec<(&'static str, NodeMutations)>;
#[derive(Clone, Debug)]
pub struct MutationListenerPayload {
pub dirty_leaves: Vec<NodeKey>,
pub prev_editor_state: EditorState,
pub update_tags: Vec<String>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct MutationListenerOptions {
pub skip_initialization: bool,
}
pub(crate) type MutationListener = Rc<dyn Fn(&NodeMutations, &MutationListenerPayload)>;
pub trait RootElement: Any {
#[cfg(feature = "a11y")]
fn live_region_host(self: Rc<Self>) -> Option<Rc<dyn crate::a11y::LiveRegionHost>> {
None
}
fn blur(&self) {}
fn focus(&self) {}
fn has_focus(&self) -> bool {
false
}
fn caret_from_point(&self, _x: f64, _y: f64) -> Option<crate::caret::PointCaret> {
None
}
#[cfg(feature = "selection")]
fn computed_style(&self, _key: &str) -> Option<crate::selection::ComputedStyle> {
None
}
fn is_connected(&self) -> bool {
true
}
}
type UpdateListenerFn = dyn Fn(&UpdateListenerPayload) -> Option<Unregister>;
type TextContentListenerFn = dyn Fn(&str) -> Option<Unregister>;
type DecoratorListenerFn = dyn Fn(&Decorators) -> Option<Unregister>;
#[derive(Clone)]
pub struct RootElementRef(pub Rc<dyn RootElement>);
impl PartialEq for RootElementRef {
fn eq(&self, other: &Self) -> bool {
std::ptr::addr_eq(Rc::as_ptr(&self.0), Rc::as_ptr(&other.0))
}
}
impl std::fmt::Debug for RootElementRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RootElementRef({:p})", Rc::as_ptr(&self.0) as *const ())
}
}
pub(crate) type RootListener =
Rc<dyn Fn(Option<&RootElementRef>, Option<&RootElementRef>) -> Option<Unregister>>;
type RootListenerEntry = (u64, RootListener, Rc<RefCell<Option<Unregister>>>);
pub type Unregister = Box<dyn FnOnce()>;
pub trait ListenerCleanup {
fn into_cleanup(self) -> Option<Unregister>;
}
impl ListenerCleanup for () {
fn into_cleanup(self) -> Option<Unregister> {
None
}
}
impl ListenerCleanup for Unregister {
fn into_cleanup(self) -> Option<Unregister> {
Some(self)
}
}
impl ListenerCleanup for Option<Unregister> {
fn into_cleanup(self) -> Option<Unregister> {
self
}
}
pub struct LexicalCommand<P> {
id: u64,
name: CommandName,
_payload: PhantomData<fn(&P)>,
}
#[derive(Clone)]
enum CommandName {
Static(&'static str),
Shared(Rc<str>),
}
impl<P> Clone for LexicalCommand<P> {
fn clone(&self) -> Self {
Self {
id: self.id,
name: self.name.clone(),
_payload: PhantomData,
}
}
}
impl<P> LexicalCommand<P> {
pub(crate) const fn constant(id: u64, name: &'static str) -> Self {
Self {
id,
name: CommandName::Static(name),
_payload: PhantomData,
}
}
pub fn name(&self) -> &str {
match &self.name {
CommandName::Static(name) => name,
CommandName::Shared(name) => name,
}
}
pub(crate) fn id(&self) -> u64 {
self.id
}
}
thread_local! {
static NEXT_COMMAND_ID: Cell<u64> = const { Cell::new(1) };
}
pub fn create_command<P>(name: &str) -> LexicalCommand<P> {
let id = NEXT_COMMAND_ID.with(|c| c.replace(c.get() + 1));
LexicalCommand {
id,
name: CommandName::Shared(name.into()),
_payload: PhantomData,
}
}
pub const COMMAND_PRIORITY_EDITOR: i8 = 0;
pub const COMMAND_PRIORITY_LOW: i8 = 1;
pub const COMMAND_PRIORITY_NORMAL: i8 = 2;
pub const COMMAND_PRIORITY_HIGH: i8 = 3;
pub const COMMAND_PRIORITY_CRITICAL: i8 = 4;
pub const COMMAND_PRIORITY_BEFORE_EDITOR: i8 = -8;
pub const COMMAND_PRIORITY_BEFORE_LOW: i8 = -7;
pub const COMMAND_PRIORITY_BEFORE_NORMAL: i8 = -6;
pub const COMMAND_PRIORITY_BEFORE_HIGH: i8 = -5;
pub const COMMAND_PRIORITY_BEFORE_CRITICAL: i8 = -4;
pub(crate) type CommandListener<P> = Rc<dyn Fn(&P, &Editor) -> Result<bool, LexicalError>>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum DirtyType {
#[default]
None,
HasDirtyNodes,
FullReconcile,
}
#[derive(Default)]
pub(crate) struct Dirty {
pub(crate) dirty_type: DirtyType,
pub(crate) elements: OrderedMap<bool>,
pub(crate) leaves: OrderedSet,
pub(crate) normalized: OrderedSet,
}
pub(crate) struct QueuedUpdate {
pub(crate) id: u64,
pub(crate) update_fn: Box<dyn FnOnce() -> Result<(), LexicalError>>,
pub(crate) options: UpdateOptions,
}
#[derive(Clone)]
pub struct Editor(pub(crate) Rc<EditorInner>);
impl PartialEq for Editor {
fn eq(&self, other: &Editor) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Editor {}
type Listeners<F> = RefCell<Vec<(u64, Rc<F>, Rc<RefCell<Option<Unregister>>>)>>;
type CommandListeners = [Vec<(u64, Rc<dyn Any>)>; 5];
pub(crate) struct EditorInner {
nodes: HashMap<&'static str, NodeClass>,
node_order: Vec<&'static str>,
shared_node_states: HashMap<&'static str, Rc<SharedNodeState>>,
pub(crate) editor_state: RefCell<EditorState>,
pub(crate) pending: RefCell<Option<EditorState>>,
pub(crate) dirty: RefCell<Dirty>,
pub(crate) tags: RefCell<OrderedSet>,
pub(crate) updating: Cell<bool>,
pub(crate) dispatching_commit_listeners: Cell<bool>,
pub(crate) updates: RefCell<VecDeque<QueuedUpdate>>,
pub(crate) cascade_count: Cell<u32>,
transforms: RefCell<HashMap<&'static str, Vec<(u64, Transform)>>>,
pub(crate) update_listeners: Listeners<UpdateListenerFn>,
text_content_listeners: Listeners<TextContentListenerFn>,
commands: RefCell<HashMap<u64, CommandListeners>>,
next_id: Cell<u64>,
selection_movement: RefCell<Option<Rc<dyn SelectionMovement>>>,
config: EditorConfig,
#[cfg(feature = "html")]
pub(crate) html_conversions: HashMap<String, Vec<crate::lexical_dom::DomImporter>>,
#[cfg(feature = "html")]
pub(crate) html_export: HashMap<&'static str, crate::lexical_dom::ExportOverride>,
#[cfg(feature = "html")]
pub(crate) dom: RefCell<crate::lexical_dom::EditorDomRenderConfig>,
namespace: String,
parent_editor: Option<Editor>,
key: String,
editable: Cell<bool>,
headless: Cell<bool>,
pub(crate) set_root_element_guard: RefCell<Option<SetRootElementGuard>>,
on_warn: WarningHandler,
pub(crate) slots_used: Cell<bool>,
root_element: RefCell<Option<RootElementRef>>,
pub(crate) node_structure: RefCell<Option<Rc<NodeStructureRegistration>>>,
mutation_listeners: RefCell<Vec<(u64, MutationListener, &'static str)>>,
pub(crate) editable_listeners: Listeners<dyn Fn(bool) -> Option<Unregister>>,
pub(crate) root_listeners: RefCell<Vec<RootListenerEntry>>,
pub(crate) deferred: RefCell<Vec<Box<dyn FnOnce()>>>,
pub(crate) composition_key: RefCell<Option<NodeKey>>,
pub(crate) composition_merge_held: RefCell<Option<NodeKey>>,
pub(crate) last_notified_selection: RefCell<Option<crate::lexical_selection::Selection>>,
pub(crate) input_state: RefCell<crate::events::InputState>,
pub(crate) key_down_shortcuts: RefCell<Option<crate::events::KeyDownShortcuts>>,
pub(crate) root_text_cache: RefCell<Option<(Rc<dyn LexicalNode>, String)>>,
pub(crate) key_to_dom_map: RefCell<crate::reconciler::KeyToDomMap>,
pub(crate) decorators: RefCell<Decorators>,
pub(crate) pending_decorators: RefCell<Option<Decorators>>,
decorator_listeners: Listeners<DecoratorListenerFn>,
#[cfg(feature = "extension")]
pub(crate) builder: RefCell<Option<Rc<dyn Any>>>,
}
pub(crate) type SetRootElementGuard =
Rc<dyn Fn(Option<&RootElementRef>) -> Result<(), LexicalError>>;
pub fn create_editor(args: CreateEditorArgs) -> Editor {
let parent_editor = args.parent_editor;
let namespace = if !args.namespace.is_empty() {
args.namespace
} else if let Some(parent) = &parent_editor {
parent.get_namespace().to_owned()
} else {
create_uid()
};
let core = [
NodeClass {
is_element_or_decorator: || true,
..NodeClass::with_import_json("root", RootNode::import_json)
},
NodeClass::of::<TextNode>(),
NodeClass::of::<LineBreakNode>(),
NodeClass::of::<TabNode>(),
NodeClass::of::<ParagraphNode>(),
NodeClass::of::<ArtificialNode>(),
];
let classes: Vec<NodeClass> = core.into_iter().chain(args.nodes).collect();
for class in &classes {
if let Some(replacement) = &class.replacement {
match &replacement.with_klass {
Some(with_klass) => assert!(
(with_klass.super_types)().contains(&class.node_type),
"{} doesn't extend the {}",
with_klass.class_name,
class.class_name
),
None => crate::warnings::console_warn(&format!(
"Override for {} specifies 'replace' without 'withKlass'. 'withKlass' will be required in a future version.",
class.class_name
)),
}
}
(class.validate_node_structure)();
}
let mut node_order: Vec<&'static str> = Vec::new();
for class in &classes {
if !node_order.contains(&class.node_type) {
node_order.push(class.node_type);
}
}
#[cfg(feature = "html")]
let html_conversions =
crate::lexical_dom::initialize_conversion_cache(&classes, &args.html.import);
let nodes: HashMap<&'static str, NodeClass> = classes
.into_iter()
.map(|class| (class.node_type, class))
.collect();
let headless = parent_editor.as_ref().is_some_and(|p| p.0.headless.get());
let on_warn = args.on_warn.unwrap_or_else(|| Rc::new(Err));
let shared_node_states = nodes
.iter()
.map(|(&node_type, class)| {
let shared = create_shared_node_state((class.state_configs)());
(node_type, Rc::new(shared))
})
.collect();
let editor = Editor(Rc::new(EditorInner {
nodes,
node_order,
shared_node_states,
editor_state: RefCell::new(create_empty_editor_state()),
pending: RefCell::new(None),
dirty: RefCell::new(Dirty::default()),
tags: RefCell::new(OrderedSet::new()),
updating: Cell::new(false),
dispatching_commit_listeners: Cell::new(false),
updates: RefCell::new(VecDeque::new()),
cascade_count: Cell::new(0),
transforms: RefCell::new(HashMap::new()),
update_listeners: RefCell::new(Vec::new()),
text_content_listeners: RefCell::new(Vec::new()),
commands: RefCell::new(HashMap::new()),
next_id: Cell::new(1),
selection_movement: RefCell::new(None),
config: EditorConfig { theme: args.theme },
#[cfg(feature = "html")]
html_conversions,
#[cfg(feature = "html")]
html_export: args.html.export.into_iter().collect(),
#[cfg(feature = "html")]
dom: RefCell::new(args.dom.unwrap_or_default()),
namespace,
parent_editor,
key: create_uid(),
editable: Cell::new(args.editable.unwrap_or(true)),
headless: Cell::new(headless),
set_root_element_guard: RefCell::new(None),
on_warn,
slots_used: Cell::new(false),
root_element: RefCell::new(None),
node_structure: RefCell::new(None),
mutation_listeners: RefCell::new(Vec::new()),
editable_listeners: RefCell::new(Vec::new()),
root_listeners: RefCell::new(Vec::new()),
deferred: RefCell::new(Vec::new()),
composition_key: RefCell::new(None),
composition_merge_held: RefCell::new(None),
last_notified_selection: RefCell::new(None),
input_state: RefCell::new(crate::events::InputState::default()),
key_down_shortcuts: RefCell::new(None),
root_text_cache: RefCell::new(None),
key_to_dom_map: RefCell::new(HashMap::new()),
decorators: RefCell::new(Decorators::default()),
pending_decorators: RefCell::new(None),
decorator_listeners: RefCell::new(Vec::new()),
#[cfg(feature = "extension")]
builder: RefCell::new(None),
}));
if let Some(initial_editor_state) = args.editor_state {
*editor.0.pending.borrow_mut() = Some(initial_editor_state);
editor.0.dirty.borrow_mut().dirty_type = DirtyType::FullReconcile;
}
let _unregister = crate::events::register_default_command_handlers(&editor);
editor
}
impl Editor {
pub fn config(&self) -> &EditorConfig {
&self.0.config
}
pub const VERSION: &'static str = "lexical-rust@0.53.0";
pub fn is_composing(&self) -> bool {
self.0.composition_key.borrow().is_some()
}
pub(crate) fn composition_key(&self) -> Option<NodeKey> {
self.0.composition_key.borrow().clone()
}
pub fn get_namespace(&self) -> &str {
&self.0.namespace
}
pub fn parent_editor(&self) -> Option<&Editor> {
self.0.parent_editor.as_ref()
}
pub fn get_key(&self) -> &str {
&self.0.key
}
pub fn blur(&self) {
if let Some(root) = self.get_root_element() {
root.0.blur();
}
}
pub fn focus(
&self,
callback: Option<Box<dyn FnOnce()>>,
options: EditorFocusOptions,
) -> Result<(), LexicalError> {
if self.get_root_element().is_none() {
return Ok(());
}
update_editor_sync(
self,
move || {
let selection = crate::get_selection();
let root = crate::get_root();
if let Some(selection) = selection {
if !selection.is_dirty() {
crate::set_selection(Some(selection.clone_selection()));
}
} else if root.get_children_size() != 0 {
if options == EditorFocusOptions::RootStart {
root.select_start()?;
} else {
root.select_end()?;
}
}
add_update_tag(FOCUS_TAG);
crate::on_update(move || {
if let Some(callback) = callback {
callback();
}
});
Ok(())
},
None,
)
}
pub fn is_headless(&self) -> bool {
self.0.headless.get()
}
pub(crate) fn set_headless(&self, guard: SetRootElementGuard) {
self.0.headless.set(true);
*self.0.set_root_element_guard.borrow_mut() = Some(guard);
}
pub(crate) fn on_warn(&self, warning: LexicalError) -> Result<(), LexicalError> {
(self.0.on_warn)(warning)
}
pub fn is_editable(&self) -> bool {
self.0.editable.get()
}
pub fn set_editable(&self, editable: bool) {
if self.0.editable.get() != editable {
self.0.editable.set(editable);
with_updating(self, true, || {
trigger_listeners(&self.0.editable_listeners, |listener| listener(editable));
});
}
}
pub fn register_editable_listener<R: ListenerCleanup>(
&self,
listener: impl Fn(bool) -> R + 'static,
) -> Unregister {
register_listener(
self,
|inner| &inner.editable_listeners,
Rc::new(move |editable| listener(editable).into_cleanup())
as Rc<dyn Fn(bool) -> Option<Unregister>>,
)
}
pub fn get_decorators(&self) -> Decorators {
self.0.decorators.borrow().clone()
}
pub fn register_decorator_listener<R: ListenerCleanup>(
&self,
listener: impl Fn(&Decorators) -> R + 'static,
) -> Unregister {
register_listener(
self,
|inner| &inner.decorator_listeners,
Rc::new(move |decorators: &Decorators| listener(decorators).into_cleanup())
as Rc<DecoratorListenerFn>,
)
}
pub(crate) fn trigger_decorator_listeners(&self, decorators: &Decorators) {
trigger_listeners(&self.0.decorator_listeners, |listener| listener(decorators));
}
pub fn get_root_element(&self) -> Option<RootElementRef> {
self.0.root_element.borrow().clone()
}
pub fn set_root_element(
&self,
next_root_element: Option<RootElementRef>,
) -> Result<(), LexicalError> {
let guard = self.0.set_root_element_guard.borrow().clone();
if let Some(guard) = guard {
guard(next_root_element.as_ref())?;
}
let prev_root_element = self.get_root_element();
if next_root_element == prev_root_element {
return Ok(());
}
let pending_editor_state = self.pending().unwrap_or_else(|| self.get_editor_state());
*self.0.root_element.borrow_mut() = next_root_element.clone();
*self.0.editor_state.borrow_mut() = create_empty_editor_state();
*self.0.pending.borrow_mut() = Some(pending_editor_state);
*self.0.composition_key.borrow_mut() = None;
*self.0.dirty.borrow_mut() = Dirty::default();
crate::reconciler::reset_key_to_dom_map(self, next_root_element.is_some());
if next_root_element.is_some() {
self.0.dirty.borrow_mut().dirty_type = DirtyType::FullReconcile;
}
self.add_tags(&[HISTORY_MERGE_TAG.to_owned()]);
let committed = commit_pending_updates(self);
let listeners: Vec<_> = self
.0
.root_listeners
.borrow()
.iter()
.map(|(_, l, cleanup)| (l.clone(), cleanup.clone()))
.collect();
with_updating(self, false, || {
for (listener, cleanup) in listeners {
trigger_root_listener(
&listener,
&cleanup,
next_root_element.as_ref(),
prev_root_element.as_ref(),
);
}
});
committed
}
pub fn register_root_listener(
&self,
listener: impl Fn(Option<&RootElementRef>, Option<&RootElementRef>) -> Option<Unregister>
+ 'static,
) -> Unregister {
let id = self.next_id();
let listener: RootListener = Rc::new(listener);
let root = self.get_root_element();
let cleanup = Rc::new(RefCell::new(listener(root.as_ref(), None)));
self.0
.root_listeners
.borrow_mut()
.push((id, listener.clone(), cleanup.clone()));
let weak = self.weak();
Box::new(move || {
let Some(inner) = weak.upgrade() else { return };
let root = inner.root_element.borrow().clone();
trigger_root_listener(&listener, &cleanup, None, root.as_ref());
inner
.root_listeners
.borrow_mut()
.retain(|(i, _, _)| *i != id);
let last = cleanup.borrow_mut().take();
if let Some(last) = last {
last();
}
})
}
pub fn register_mutation_listener(
&self,
node_type: &str,
listener: impl Fn(&NodeMutations, &MutationListenerPayload) + 'static,
options: MutationListenerOptions,
) -> Result<Unregister, LexicalError> {
let Some((&node_type, _)) = self.0.nodes.get_key_value(node_type) else {
return Err(LexicalError::new(format!(
"Node {node_type} has not been registered. Ensure node has been passed to createEditor."
)));
};
let node_type = self.resolve_registered_node_after_replacements(node_type)?;
let id = self.next_id();
let listener: MutationListener = Rc::new(listener);
self.0
.mutation_listeners
.borrow_mut()
.push((id, listener.clone(), node_type));
if !options.skip_initialization {
let prev_editor_state = self.get_editor_state();
let keys: NodeMutations = {
let node_map = prev_editor_state.0.node_map.borrow();
prev_editor_state
.keys_in_creation_order()
.into_iter()
.filter(|key| node_map[key].get_type() == node_type)
.map(|key| (key, NodeMutation::Created))
.collect()
};
if !keys.is_empty() {
listener(
&keys,
&MutationListenerPayload {
dirty_leaves: Vec::new(),
prev_editor_state,
update_tags: vec!["registerMutationListener".to_owned()],
},
);
}
}
let weak = self.weak();
Ok(Box::new(move || {
if let Some(inner) = weak.upgrade() {
inner
.mutation_listeners
.borrow_mut()
.retain(|(i, _, _)| *i != id);
}
}))
}
pub(crate) fn has_mutation_listeners(&self) -> bool {
!self.0.mutation_listeners.borrow().is_empty()
}
pub(crate) fn mutation_listeners(&self) -> Vec<(MutationListener, &'static str)> {
self.0
.mutation_listeners
.borrow()
.iter()
.map(|(_, l, t)| (l.clone(), *t))
.collect()
}
pub(crate) fn registered_nodes(&self) -> &HashMap<&'static str, NodeClass> {
&self.0.nodes
}
pub fn get_registered_node(&self, node_type: &str) -> Option<NodeClass> {
self.0.nodes.get(node_type).cloned()
}
pub fn resolve_registered_node_after_replacements(
&self,
node_type: &str,
) -> Result<&'static str, LexicalError> {
let Some((mut node_type, mut class)) = self.0.nodes.get_key_value(node_type) else {
return Err(LexicalError::new(format!(
"Node {node_type} has not been registered. Ensure node has been passed to createEditor."
)));
};
while let Some(next) = class.replace_with_klass() {
let Some((t, c)) = self.0.nodes.get_key_value(next) else {
return Err(LexicalError::new(format!(
"Node {next} has not been registered. Ensure node has been passed to createEditor."
)));
};
(node_type, class) = (t, c);
}
Ok(node_type)
}
pub fn has_node(&self, node_type: &str) -> bool {
self.0.nodes.contains_key(node_type)
}
pub fn has_nodes(&self, node_types: &[&str]) -> bool {
node_types.iter().all(|t| self.has_node(t))
}
pub(crate) fn registered_nodes_in_order(&self) -> Vec<NodeClass> {
self.0
.node_order
.iter()
.map(|node_type| self.0.nodes[node_type].clone())
.collect()
}
pub(crate) fn shared_node_state(&self, node_type: &str) -> Option<Rc<SharedNodeState>> {
self.0.shared_node_states.get(node_type).cloned()
}
pub(crate) fn ptr_eq(&self, other: &Editor) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
pub(crate) fn next_id(&self) -> u64 {
self.0.next_id.replace(self.0.next_id.get() + 1)
}
pub(crate) fn weak(&self) -> Weak<EditorInner> {
Rc::downgrade(&self.0)
}
pub fn set_selection_movement(&self, movement: Option<Rc<dyn SelectionMovement>>) {
*self.0.selection_movement.borrow_mut() = movement;
}
pub(crate) fn selection_movement(&self) -> Option<Rc<dyn SelectionMovement>> {
self.0.selection_movement.borrow().clone()
}
pub fn get_editor_state(&self) -> EditorState {
self.0.editor_state.borrow().clone()
}
pub(crate) fn pending(&self) -> Option<EditorState> {
self.0.pending.borrow().clone()
}
pub fn to_json(&self) -> Value {
let mut json = crate::json::Object::new();
json.insert(
"editorState",
self.get_editor_state()
.to_json(crate::serialized_export::is_compact_export()),
);
Value::Object(json)
}
pub fn parse_editor_state(&self, json: &str) -> Result<EditorState, LexicalError> {
let value = json::parse(json).map_err(|e| LexicalError::new(e.to_string()))?;
self.parse_editor_state_json(&value)
}
pub fn parse_editor_state_json(&self, json: &Value) -> Result<EditorState, LexicalError> {
parse_editor_state(json, self, None)
}
pub fn parse_editor_state_json_with(
&self,
json: &Value,
update_fn: impl FnOnce() -> Result<(), LexicalError>,
) -> Result<EditorState, LexicalError> {
parse_editor_state(json, self, Some(Box::new(update_fn)))
}
pub fn update(
&self,
update_fn: impl FnOnce() -> Result<(), LexicalError> + 'static,
options: UpdateOptions,
) -> Result<(), LexicalError> {
if self.0.updating.get() {
let id = self.next_id();
self.0.updates.borrow_mut().push_back(QueuedUpdate {
id,
update_fn: Box::new(update_fn),
options,
});
Ok(())
} else {
if !crate::updates::is_committing_pending_updates() {
self.0.cascade_count.set(0);
}
begin_update(self, update_fn, &options)
}
}
pub fn set_editor_state(
&self,
editor_state: &EditorState,
tag: Option<&str>,
) -> Result<(), LexicalError> {
let is_empty_editor_state = editor_state.is_empty();
let writable_editor_state = if editor_state.0.read_only.get() {
let writable = clone_editor_state(editor_state);
*writable.0.selection.borrow_mut() =
editor_state.selection().map(|s| s.clone_selection());
writable
} else {
editor_state.clone()
};
let tags: Vec<String> = tag.map(str::to_owned).into_iter().collect();
if let Some(pending) = self.pending()
&& !pending.is_empty()
{
self.add_tags(&tags);
commit_pending_updates(self)?;
}
*self.0.pending.borrow_mut() = Some(writable_editor_state.clone());
{
let mut dirty = self.0.dirty.borrow_mut();
dirty.dirty_type = DirtyType::FullReconcile;
dirty.elements.set("root", false);
}
*self.0.composition_key.borrow_mut() = None;
self.0
.slots_used
.set(self.0.slots_used.get() || editor_state.0.slots_used.get());
let parsed = editor_state.0.parsed.get();
let options = UpdateOptions {
discrete: true,
..UpdateOptions::default()
};
let editor = self.clone();
update_editor_sync(
self,
move || {
editor.add_tags(&tags);
invariant!(
!is_empty_editor_state,
"setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty."
);
if parsed {
let node_map = writable_editor_state.0.node_map.borrow();
let mut dirty = editor.0.dirty.borrow_mut();
for key in writable_editor_state.keys_in_creation_order() {
if node_map[&key].element().is_some() {
dirty.elements.set(&key, true);
} else {
dirty.leaves.add(&key);
}
}
}
Ok(())
},
(!self.0.updating.get()).then_some(&options),
)
}
pub fn read<R>(&self, f: impl FnOnce() -> R) -> Result<R, LexicalError> {
self.read_with_mode(EditorReadMode::ForceCommit, f)
}
pub fn read_with_mode<R>(
&self,
mode: EditorReadMode,
f: impl FnOnce() -> R,
) -> Result<R, LexicalError> {
if mode == EditorReadMode::ForceCommit {
if !self.0.dispatching_commit_listeners.get() {
commit_pending_updates(self)?;
} else if self.pending().is_some() {
crate::warnings::console_warn(
"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.",
);
}
}
let editor_state = match mode {
EditorReadMode::Pending => self.pending().unwrap_or_else(|| self.get_editor_state()),
_ => self.get_editor_state(),
};
Ok(read_editor_state(Some(self), &editor_state, f))
}
pub fn register_node_transform(
&self,
node_type: &'static str,
transform: impl Fn(&NodeRef) -> Result<(), LexicalError> + 'static,
) -> Unregister {
let transform: Transform = Rc::new(transform);
let mut types = vec![node_type];
if let Some(with_klass) = self
.0
.nodes
.get(node_type)
.and_then(NodeClass::replace_with_klass)
&& self.0.nodes.contains_key(with_klass)
{
types.push(with_klass);
}
let unregisters: Vec<Unregister> = types
.iter()
.map(|&t| {
let transform = transform.clone();
self.add_node_transform(t, move |node| transform(node))
})
.collect();
mark_nodes_with_types_as_dirty(self, &types);
Box::new(move || {
for unregister in unregisters {
unregister();
}
})
}
pub(crate) fn add_node_transform(
&self,
node_type: &'static str,
transform: impl Fn(&NodeRef) -> Result<(), LexicalError> + 'static,
) -> Unregister {
let id = self.next_id();
self.0
.transforms
.borrow_mut()
.entry(node_type)
.or_default()
.push((id, Rc::new(transform)));
let weak = self.weak();
Box::new(move || {
if let Some(inner) = weak.upgrade()
&& let Some(list) = inner.transforms.borrow_mut().get_mut(node_type)
{
list.retain(|(i, _)| *i != id);
}
})
}
pub(crate) fn transforms_of(&self, node_type: &str) -> Vec<Transform> {
self.0
.transforms
.borrow()
.get(node_type)
.map(|list| list.iter().map(|(_, t)| t.clone()).collect())
.unwrap_or_default()
}
pub fn register_update_listener<R: ListenerCleanup>(
&self,
listener: impl Fn(&UpdateListenerPayload) -> R + 'static,
) -> Unregister {
register_listener(
self,
|inner| &inner.update_listeners,
Rc::new(move |payload: &UpdateListenerPayload| listener(payload).into_cleanup())
as Rc<UpdateListenerFn>,
)
}
pub fn register_text_content_listener<R: ListenerCleanup>(
&self,
listener: impl Fn(&str) -> R + 'static,
) -> Unregister {
register_listener(
self,
|inner| &inner.text_content_listeners,
Rc::new(move |text: &str| listener(text).into_cleanup()) as Rc<TextContentListenerFn>,
)
}
pub(crate) fn trigger_update_listeners(&self, payload: &UpdateListenerPayload) {
trigger_listeners(&self.0.update_listeners, |listener| listener(payload));
}
pub(crate) fn has_text_content_listeners(&self) -> bool {
!self.0.text_content_listeners.borrow().is_empty()
}
pub(crate) fn trigger_text_content_listeners(&self, text: &str) {
trigger_listeners(&self.0.text_content_listeners, |listener| listener(text));
}
pub fn register_command<P: 'static>(
&self,
command: &LexicalCommand<P>,
listener: impl Fn(&P, &Editor) -> Result<bool, LexicalError> + 'static,
priority: i8,
) -> Unregister {
let normalized = priority & 7;
let before = normalized != priority;
let priority = usize::from(normalized.min(COMMAND_PRIORITY_CRITICAL) as u8);
let id = self.next_id();
let listener: CommandListener<P> = Rc::new(listener);
let command_id = command.id();
{
let mut commands = self.0.commands.borrow_mut();
let list = &mut commands.entry(command_id).or_default()[priority];
let entry = (id, Rc::new(listener) as Rc<dyn Any>);
if before {
list.insert(0, entry);
} else {
list.push(entry);
}
}
let weak = self.weak();
Box::new(move || {
if let Some(inner) = weak.upgrade() {
let mut commands = inner.commands.borrow_mut();
if let Some(lists) = commands.get_mut(&command_id) {
lists[priority].retain(|(i, _)| *i != id);
if lists.iter().all(Vec::is_empty) {
commands.remove(&command_id);
}
}
}
})
}
#[cfg(test)]
pub(crate) fn has_command<P>(&self, command: &LexicalCommand<P>) -> bool {
self.0.commands.borrow().contains_key(&command.id())
}
pub(crate) fn command_listeners<P: 'static>(
&self,
command: &LexicalCommand<P>,
priority: usize,
) -> Vec<CommandListener<P>> {
self.0
.commands
.borrow()
.get(&command.id())
.map(|lists| {
lists[priority]
.iter()
.filter_map(|(_, l)| l.downcast_ref::<CommandListener<P>>().cloned())
.collect()
})
.unwrap_or_default()
}
pub fn dispatch_command<P: 'static>(
&self,
command: &LexicalCommand<P>,
payload: P,
) -> Result<bool, LexicalError> {
trigger_command_listeners(self, command, &Rc::new(payload), self)
}
pub(crate) fn dirty_type(&self) -> DirtyType {
self.0.dirty.borrow().dirty_type
}
pub(crate) fn mark_dirty(&self, key: &str, is_element: bool) {
let mut dirty = self.0.dirty.borrow_mut();
if dirty.dirty_type == DirtyType::None {
dirty.dirty_type = DirtyType::HasDirtyNodes;
}
if is_element {
dirty.elements.set(key, true);
} else {
dirty.leaves.add(key);
}
}
pub(crate) fn add_tags(&self, tags: &[String]) {
let mut set = self.0.tags.borrow_mut();
for tag in tags {
set.add(tag);
}
}
}
pub fn has_update_tag(tag: &str) -> bool {
get_editor().0.tags.borrow().contains(tag)
}
pub fn add_update_tag(tag: &str) {
crate::updates::error_on_read_only();
get_editor().0.tags.borrow_mut().add(tag);
}
pub fn get_editor() -> Editor {
crate::updates::get_registry_editor().unwrap_or_else(|| {
panic!("Unable to find an active editor. This method can only be used synchronously during the callback of editor.update() or editor.read().")
})
}
fn with_updating<R>(editor: &Editor, updating: bool, f: impl FnOnce() -> R) -> R {
struct Restore<'a>(&'a Editor, bool);
impl Drop for Restore<'_> {
fn drop(&mut self) {
self.0.0.updating.set(self.1);
}
}
let _restore = Restore(editor, editor.0.updating.replace(updating));
f()
}
fn register_listener<F: ?Sized + 'static>(
editor: &Editor,
listeners: fn(&EditorInner) -> &Listeners<F>,
listener: Rc<F>,
) -> Unregister {
let id = editor.next_id();
listeners(&editor.0)
.borrow_mut()
.push((id, listener, Rc::default()));
let weak = editor.weak();
Box::new(move || {
let Some(inner) = weak.upgrade() else { return };
let removed = {
let mut list = listeners(&inner).borrow_mut();
list.iter()
.position(|(i, _, _)| *i == id)
.map(|at| list.remove(at))
};
let last = removed.and_then(|(_, _, cleanup)| cleanup.borrow_mut().take());
if let Some(last) = last {
last();
}
})
}
fn trigger_listeners<F: ?Sized>(listeners: &Listeners<F>, call: impl Fn(&F) -> Option<Unregister>) {
let snapshot: Vec<_> = listeners
.borrow()
.iter()
.map(|(id, l, cleanup)| (*id, l.clone(), cleanup.clone()))
.collect();
for (id, listener, cleanup) in snapshot {
let last = cleanup.borrow_mut().take();
if let Some(last) = last {
last();
}
let next = call(&listener);
if listeners.borrow().iter().any(|(i, _, _)| *i == id) {
*cleanup.borrow_mut() = next;
} else if let Some(next) = next {
next();
}
}
}
fn trigger_root_listener(
listener: &RootListener,
cleanup: &Rc<RefCell<Option<Unregister>>>,
next: Option<&RootElementRef>,
prev: Option<&RootElementRef>,
) {
let last = cleanup.borrow_mut().take();
if let Some(last) = last {
last();
}
let next_cleanup = listener(next, prev);
*cleanup.borrow_mut() = next_cleanup;
}
pub(crate) fn mark_nodes_with_types_as_dirty(editor: &Editor, types: &[&str]) {
let editor_state = editor.get_editor_state();
let keys: Vec<String> = {
let node_map = editor_state.0.node_map.borrow();
editor_state
.keys_in_creation_order()
.into_iter()
.filter(|key| types.contains(&node_map[key].get_type()))
.collect()
};
if keys.is_empty() {
return;
}
let options = UpdateOptions {
tags: if editor.pending().is_none() {
vec![HISTORY_MERGE_TAG.to_owned()]
} else {
Vec::new()
},
..UpdateOptions::default()
};
let _ = editor.update(
move || {
for key in &keys {
if let Some(node) = crate::get_node_by_key(key) {
node.mark_dirty();
}
}
Ok(())
},
options,
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{create_paragraph_node, create_text_node, get_root};
fn discrete() -> UpdateOptions {
UpdateOptions {
discrete: true,
..UpdateOptions::default()
}
}
#[test]
fn has_nodes_and_get_editor() {
let editor = create_editor(CreateEditorArgs::default());
assert!(editor.has_node("text") && editor.has_node("paragraph"));
assert!(!editor.has_node("heading"));
assert!(editor.has_nodes(&[]) && editor.has_nodes(&["text", "root"]));
assert!(!editor.has_nodes(&["text", "heading"]));
let same = Rc::new(Cell::new(false));
let (seen, active) = (same.clone(), editor.clone());
editor
.update(
move || {
seen.set(get_editor().ptr_eq(&active));
Ok(())
},
discrete(),
)
.unwrap();
assert!(same.get());
}
#[test]
fn create_editor_starts_with_the_given_state() {
let source = create_editor(CreateEditorArgs::default());
source
.update(
|| {
let paragraph = create_paragraph_node();
paragraph.append(&[create_text_node("hello")])?;
get_root().append(&[paragraph])
},
discrete(),
)
.unwrap();
let editor = create_editor(CreateEditorArgs {
editor_state: Some(source.get_editor_state()),
editable: Some(false),
..CreateEditorArgs::default()
});
assert!(!editor.is_editable());
assert_eq!(
editor.read(|| get_root().get_text_content()).unwrap(),
"hello"
);
}
#[test]
fn focus_without_a_root_element_does_nothing() {
let editor = create_editor(CreateEditorArgs::default());
let called = Rc::new(Cell::new(false));
let flag = called.clone();
editor
.focus(
Some(Box::new(move || flag.set(true))),
EditorFocusOptions::default(),
)
.unwrap();
assert!(!called.get());
assert!(editor.read(crate::get_selection).unwrap().is_none());
}
#[test]
fn on_warn_hears_an_endless_update_cascade() {
let warnings = Rc::new(RefCell::new(Vec::<String>::new()));
let heard = warnings.clone();
let editor = create_editor(CreateEditorArgs {
on_warn: Some(Rc::new(move |warning| {
heard.borrow_mut().push(warning.message().to_owned());
Ok(())
})),
..CreateEditorArgs::default()
});
let updates = Rc::new(Cell::new(0));
let (count, target) = (updates.clone(), editor.weak());
let _unregister = editor.register_update_listener(move |_| {
let Some(editor) = target.upgrade().map(Editor) else {
return;
};
if count.replace(count.get() + 1) < 1000 {
let _ = editor.update(|| get_root().append(&[create_paragraph_node()]), discrete());
}
});
editor
.update(|| get_root().append(&[create_paragraph_node()]), discrete())
.unwrap();
let warnings = warnings.borrow();
assert_eq!(warnings.len(), 1, "{warnings:?} after {}", updates.get());
assert!(warnings[0].starts_with("One or more update listeners are endlessly enqueueing"));
assert!(updates.get() < 1000);
}
}