use super::named_signals::named_signals_config;
use super::signals::effect;
use crate::extension_core::{
ExtensionBuildState, ExtensionRegisterState, LexicalExtension, define_extension,
};
use crate::{
CLICK_COMMAND, COMMAND_PRIORITY_CRITICAL, Editor, NodeRef, create_paragraph_node, get_root,
};
use std::rc::Rc;
pub fn default_should_insert_after(node: &NodeRef) -> bool {
node.is_decorator() || crate::lexical_utils::is_shadow_root_node(node)
}
#[derive(Clone)]
pub struct ShouldInsertAfter(pub Rc<dyn Fn(&NodeRef) -> bool>);
impl PartialEq for ShouldInsertAfter {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
named_signals_config! {
pub struct ClickAfterLastBlockConfig;
pub struct ClickAfterLastBlockConfigOverrides;
pub struct ClickAfterLastBlockOutput {
disabled: bool,
should_insert_after: ShouldInsertAfter,
}
}
pub type ClickAfterLastBlockExtensionType =
LexicalExtension<ClickAfterLastBlockConfig, ClickAfterLastBlockOutput, ()>;
fn make() -> Rc<ClickAfterLastBlockExtensionType> {
define_extension(LexicalExtension {
build: Some(Rc::new(
|_: &Editor, config: &ClickAfterLastBlockConfig, _: &ExtensionBuildState<()>| {
Ok(ClickAfterLastBlockOutput::of(config))
},
)),
register: Some(Rc::new(
|editor: &Editor,
_: &ClickAfterLastBlockConfig,
state: &ExtensionRegisterState<(), ClickAfterLastBlockOutput>| {
let output = state
.get_output()
.expect("ClickAfterLastBlockExtension has a build");
let editor = editor.weak();
Ok(effect(move || {
if output.disabled.value() {
return None;
}
let editor = editor.upgrade().map(Editor)?;
let should_insert_after = output.should_insert_after.clone();
Some(editor.register_command(
&CLICK_COMMAND,
move |event, editor| {
if !editor.is_editable() || event.target_key.as_deref() != Some("root")
{
return Ok(false);
}
let Some(last_child) = get_root().get_last_child() else {
return Ok(false);
};
if !(should_insert_after.peek().0)(&last_child) {
return Ok(false);
}
event.prevent_default();
let paragraph = create_paragraph_node();
last_child.insert_after(¶graph, true)?;
paragraph.select(None, None)?;
Ok(true)
},
COMMAND_PRIORITY_CRITICAL,
))
}))
},
)),
..LexicalExtension::new(
"@lexical/ClickAfterLastBlock",
ClickAfterLastBlockConfig {
disabled: false,
should_insert_after: ShouldInsertAfter(Rc::new(default_should_insert_after)),
},
)
})
}
thread_local! {
static CLICK_AFTER_LAST_BLOCK_EXTENSION: Rc<ClickAfterLastBlockExtensionType> = make();
}
pub fn click_after_last_block_extension() -> Rc<ClickAfterLastBlockExtensionType> {
CLICK_AFTER_LAST_BLOCK_EXTENSION.with(Rc::clone)
}