use super::{
DateNow, HistoryState, HistoryStateChange, create_empty_history_state, register_history_with,
system_date_now,
};
use crate::extension::get_peer_dependency_from_editor;
use crate::extension::signals::{ReadonlySignal, Signal, batch, effect, signal};
use crate::extension_core::{
ExtensionBuildState, ExtensionConfigBase, ExtensionInitState, ExtensionRegisterState,
InitialEditorConfig, LexicalExtension, config_extension, define_extension,
};
use crate::{Editor, LexicalError};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
pub struct HistoryStateRef(pub SharedHistoryState);
impl PartialEq for HistoryStateRef {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
pub type SharedHistoryState = Rc<RefCell<HistoryState>>;
#[derive(Clone)]
pub struct CreateInitialHistoryState(pub Rc<dyn Fn(&Editor) -> SharedHistoryState>);
impl PartialEq for CreateInitialHistoryState {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone)]
pub struct HistoryNow(pub DateNow);
impl PartialEq for HistoryNow {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone)]
pub struct HistoryConfig {
pub delay: f64,
pub create_initial_history_state: CreateInitialHistoryState,
pub disabled: bool,
pub max_depth: Option<usize>,
pub now: HistoryNow,
}
#[derive(Clone, Default)]
pub struct HistoryConfigOverrides {
pub delay: Option<f64>,
pub create_initial_history_state: Option<CreateInitialHistoryState>,
pub disabled: Option<bool>,
pub max_depth: Option<Option<usize>>,
pub now: Option<HistoryNow>,
}
impl ExtensionConfigBase for HistoryConfig {
type Partial = HistoryConfigOverrides;
fn shallow_merge(&self, o: &HistoryConfigOverrides) -> Self {
HistoryConfig {
delay: o.delay.unwrap_or(self.delay),
create_initial_history_state: o
.create_initial_history_state
.clone()
.unwrap_or_else(|| self.create_initial_history_state.clone()),
disabled: o.disabled.unwrap_or(self.disabled),
max_depth: o.max_depth.unwrap_or(self.max_depth),
now: o.now.clone().unwrap_or_else(|| self.now.clone()),
}
}
}
#[derive(Clone)]
pub struct HistoryExtensionInit {
pub can_redo: Signal<bool>,
pub can_undo: Signal<bool>,
}
#[derive(Clone)]
pub struct HistoryExtensionOutput {
pub can_redo: ReadonlySignal<bool>,
pub can_undo: ReadonlySignal<bool>,
pub delay: Signal<f64>,
pub disabled: Signal<bool>,
pub history_state: Signal<HistoryStateRef>,
pub max_depth: Signal<Option<usize>>,
pub now: Signal<HistoryNow>,
}
pub type HistoryExtensionType =
LexicalExtension<HistoryConfig, HistoryExtensionOutput, HistoryExtensionInit>;
fn make_history_extension() -> Rc<HistoryExtensionType> {
define_extension(LexicalExtension {
build: Some(Rc::new(
|editor: &Editor,
config: &HistoryConfig,
state: &ExtensionBuildState<HistoryExtensionInit>| {
let history_state = (config.create_initial_history_state.0)(editor);
let init = state.get_init_result()?;
Ok(HistoryExtensionOutput {
delay: signal(config.delay),
disabled: signal(config.disabled),
history_state: signal(HistoryStateRef(history_state)),
max_depth: signal(config.max_depth),
now: signal(config.now.clone()),
can_redo: init.can_redo.as_readonly(),
can_undo: init.can_undo.as_readonly(),
})
},
)),
init: Some(Rc::new(
|_: &mut InitialEditorConfig, _: &HistoryConfig, _: &ExtensionInitState| {
Ok(HistoryExtensionInit {
can_redo: signal(false),
can_undo: signal(false),
})
},
)),
register:
Some(
Rc::new(
|editor: &Editor,
_config: &HistoryConfig,
state: &ExtensionRegisterState<
HistoryExtensionInit,
HistoryExtensionOutput,
>| {
let init = state.get_init_result()?;
let stores = state.get_output().expect("HistoryExtension has a build");
let sync_from_history_state = {
let (can_undo, can_redo) =
(init.can_undo.clone(), init.can_redo.clone());
move |history_state: Option<&HistoryState>| {
batch(|| {
can_undo.set_value(
history_state.is_some_and(|h| !h.undo_stack.is_empty()),
);
can_redo.set_value(
history_state.is_some_and(|h| !h.redo_stack.is_empty()),
);
});
}
};
let editor = editor.weak();
Ok(effect(move || {
if stores.disabled.value() {
sync_from_history_state(None);
return None;
}
let history_state = stores.history_state.value();
let editor = editor.upgrade().map(Editor)?;
let delay = stores.delay.clone();
let now = stores.now.clone();
let max_depth = stores.max_depth.clone();
let sync = sync_from_history_state.clone();
Some(register_history_with(
&editor,
&history_state.0,
Rc::new(move || delay.peek()),
Some(Rc::new(move || (now.peek().0)())),
Some(Rc::new(move |h: &HistoryState| sync(Some(h)))
as HistoryStateChange),
Rc::new(move || max_depth.peek()),
))
}))
},
),
),
..LexicalExtension::new(
"@lexical/history/History",
HistoryConfig {
create_initial_history_state: CreateInitialHistoryState(Rc::new(|_| {
create_empty_history_state()
})),
delay: 300.0,
disabled: false,
max_depth: None,
now: HistoryNow(Rc::new(system_date_now)),
},
)
})
}
fn get_history_peer(
editor: Option<&Editor>,
) -> Result<
Option<
crate::LexicalExtensionDependency<
HistoryConfig,
HistoryExtensionOutput,
HistoryExtensionInit,
>,
>,
LexicalError,
> {
match editor {
None => Ok(None),
Some(editor) => get_peer_dependency_from_editor(editor, "@lexical/history/History"),
}
}
#[derive(Clone, Default)]
pub struct SharedHistoryConfig {
pub disabled: bool,
pub parent_editor: Option<Editor>,
}
#[derive(Clone, Default)]
pub struct SharedHistoryConfigOverrides {
pub disabled: Option<bool>,
pub parent_editor: Option<Option<Editor>>,
}
impl ExtensionConfigBase for SharedHistoryConfig {
type Partial = SharedHistoryConfigOverrides;
fn shallow_merge(&self, o: &SharedHistoryConfigOverrides) -> Self {
SharedHistoryConfig {
disabled: o.disabled.unwrap_or(self.disabled),
parent_editor: o
.parent_editor
.clone()
.unwrap_or_else(|| self.parent_editor.clone()),
}
}
}
#[derive(Clone)]
pub struct SharedHistoryOutput {
pub disabled: Signal<bool>,
pub parent_editor: Signal<Option<Editor>>,
}
pub type SharedHistoryExtensionType =
LexicalExtension<SharedHistoryConfig, SharedHistoryOutput, ()>;
fn make_shared_history_extension() -> Rc<SharedHistoryExtensionType> {
define_extension(LexicalExtension {
build: Some(Rc::new(
|editor: &Editor, config: &SharedHistoryConfig, _: &ExtensionBuildState<()>| {
Ok(SharedHistoryOutput {
disabled: signal(config.disabled),
parent_editor: signal(
config
.parent_editor
.clone()
.or_else(|| editor.parent_editor().cloned()),
),
})
},
)),
dependencies: vec![config_extension(
&history_extension(),
[HistoryConfigOverrides {
disabled: Some(true),
..HistoryConfigOverrides::default()
}],
)],
register: Some(Rc::new(
|editor: &Editor,
_config: &SharedHistoryConfig,
state: &ExtensionRegisterState<(), SharedHistoryOutput>| {
let stores = state
.get_output()
.expect("SharedHistoryExtension has a build");
let output = state
.get_dependency(&history_extension())?
.output
.expect("HistoryExtension has a build");
let _ = editor;
Ok(effect(move || {
if stores.disabled.value() {
return None;
}
let parent_editor = stores.parent_editor.value();
let Ok(Some(parent_peer)) = get_history_peer(parent_editor.as_ref()) else {
return None;
};
let parent_output = parent_peer.output?;
batch(|| {
output.delay.set_value(parent_output.delay.value());
output
.history_state
.set_value(parent_output.history_state.value());
output.now.set_value(parent_output.now.value());
output.max_depth.set_value(parent_output.max_depth.value());
output.disabled.set_value(parent_output.disabled.value());
});
None
}))
},
)),
..LexicalExtension::new(
"@lexical/history/SharedHistory",
SharedHistoryConfig::default(),
)
})
}
thread_local! {
static HISTORY_EXTENSION: Rc<HistoryExtensionType> = make_history_extension();
static SHARED_HISTORY_EXTENSION: Rc<SharedHistoryExtensionType> =
make_shared_history_extension();
}
pub fn history_extension() -> Rc<HistoryExtensionType> {
HISTORY_EXTENSION.with(Rc::clone)
}
pub fn shared_history_extension() -> Rc<SharedHistoryExtensionType> {
SHARED_HISTORY_EXTENSION.with(Rc::clone)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extension::{build_editor_from_extensions, get_extension_dependency_from_editor};
use crate::{UNDO_COMMAND, UpdateOptions, create_paragraph_node, create_text_node, get_root};
fn type_text(editor: &Editor, text: &'static str) {
editor
.update(
move || {
let root = get_root();
root.clear()?;
let paragraph = create_paragraph_node();
paragraph.append(&[create_text_node(text)])?;
root.append(&[paragraph])
},
UpdateOptions {
discrete: true,
..UpdateOptions::default()
},
)
.unwrap();
}
#[test]
fn shared_history_uses_the_parent_history() {
let parent = build_editor_from_extensions(vec![config_extension(
&history_extension(),
[HistoryConfigOverrides {
delay: Some(0.0),
..HistoryConfigOverrides::default()
}],
)])
.unwrap();
let child = build_editor_from_extensions(vec![config_extension(
&shared_history_extension(),
[SharedHistoryConfigOverrides {
parent_editor: Some(Some(parent.editor().clone())),
..SharedHistoryConfigOverrides::default()
}],
)])
.unwrap();
let parent_output =
get_extension_dependency_from_editor(parent.editor(), &history_extension())
.unwrap()
.output
.unwrap();
let child_output =
get_extension_dependency_from_editor(child.editor(), &history_extension())
.unwrap()
.output
.unwrap();
assert!(child_output.history_state.peek() == parent_output.history_state.peek());
assert!(!child_output.disabled.peek());
parent.editor().read(|| ()).unwrap();
child.editor().read(|| ()).unwrap();
type_text(child.editor(), "child");
assert_eq!(
parent_output
.history_state
.peek()
.0
.borrow()
.undo_stack
.len(),
1
);
assert!(child_output.can_undo.peek());
assert!(child.editor().dispatch_command(&UNDO_COMMAND, ()).unwrap());
let text = child
.editor()
.read(|| get_root().get_text_content())
.unwrap();
assert_eq!(text, "");
parent_output.disabled.set_value(true);
assert!(child_output.disabled.peek());
child.dispose();
parent.dispose();
}
}