Skip to main content

lexical_ui/code/
code_extension.rs

1//! `CodeExtension.ts`: what `CodeExtension` registers.
2
3use super::code_node::{exit_code_node_on_enter, is_code_node};
4use crate::{COMMAND_PRIORITY_LOW, Editor, KEY_ENTER_COMMAND, Unregister, get_selection};
5
6/// `CodeExtension`'s `register(editor)`, without the extension: a
7/// `KEY_ENTER_COMMAND` handler that leaves a code block after two line
8/// breaks at its end (`$exitCodeNodeOnEnter`), and a transform that clears
9/// the format of a tab in a code block. Returns what unregisters them.
10pub fn register_code(editor: &Editor) -> Unregister {
11    let unregister_enter = editor.register_command(
12        &KEY_ENTER_COMMAND,
13        |event, _| match get_selection().filter(|s| s.is_range()) {
14            Some(selection) if exit_code_node_on_enter(&selection)?.is_some() => {
15                if let Some(event) = event {
16                    event.prevent_default();
17                }
18                Ok(true)
19            }
20            _ => Ok(false),
21        },
22        COMMAND_PRIORITY_LOW,
23    );
24    let unregister_tab = editor.register_node_transform("tab", |node| {
25        if node.text_data().get_format() != 0.0
26            && node.get_parent().is_some_and(|p| is_code_node(&p))
27        {
28            node.set_format(0.0);
29        }
30        Ok(())
31    });
32    Box::new(move || {
33        unregister_enter();
34        unregister_tab();
35    })
36}
37
38#[cfg(feature = "extension")]
39pub use extension::*;
40
41#[cfg(feature = "extension")]
42mod extension {
43    use super::super::code_indentation::register_code_indentation;
44    use super::super::code_nodes;
45    use super::register_code;
46    use crate::extension::named_signals_config;
47    use crate::extension::signals::effect;
48    use crate::extension_core::{
49        ExtensionBuildState, ExtensionRegisterState, LexicalExtension, define_extension,
50    };
51    use crate::{Editor, Unregister};
52    use std::rc::Rc;
53
54    /// `CodeExtension`.
55    pub type CodeExtensionType = LexicalExtension;
56
57    fn make_code_extension() -> Rc<CodeExtensionType> {
58        define_extension(LexicalExtension {
59            // `CoreImportExtension` and `DOMImportExtension` with
60            // `CodeImportRules` and the VS Code paste overlay: the HTML
61            // import, with `html`.
62            #[cfg(feature = "html")]
63            dependencies: crate::html::import::package_import_dependencies(
64                crate::code::code_import_rules(),
65                vec![crate::code::install_vscode_code_paste_overlay()],
66            ),
67            nodes: code_nodes(),
68            register: Some(Rc::new(
69                |editor: &Editor, _: &(), _: &ExtensionRegisterState<(), ()>| {
70                    Ok(register_code(editor) as Unregister)
71                },
72            )),
73            ..LexicalExtension::new("@lexical/code", ())
74        })
75    }
76
77    named_signals_config! {
78        /// `CodeIndentConfig`.
79        pub struct CodeIndentConfig;
80        /// `Partial<CodeIndentConfig>`.
81        pub struct CodeIndentConfigOverrides;
82        /// `namedSignals(CodeIndentConfig)`: `CodeIndentExtension`'s output.
83        pub struct CodeIndentOutput {
84            /// `disabled`: the indent commands aren't registered.
85            disabled: bool,
86            /// `tabSize`: how many leading spaces of a line outdenting
87            /// removes as one level; `None` (the default) removes only
88            /// tabs.
89            tab_size: Option<usize>,
90            /// `escapeWithArrows`: the arrow keys leave a code block with
91            /// nothing around it.
92            escape_with_arrows: bool,
93        }
94    }
95
96    /// `CodeIndentExtension`.
97    pub type CodeIndentExtensionType = LexicalExtension<CodeIndentConfig, CodeIndentOutput, ()>;
98
99    fn make_code_indent_extension() -> Rc<CodeIndentExtensionType> {
100        define_extension(LexicalExtension {
101            build: Some(Rc::new(
102                |_: &Editor, config: &CodeIndentConfig, _: &ExtensionBuildState<()>| {
103                    Ok(CodeIndentOutput::of(config))
104                },
105            )),
106            dependencies: vec![code_extension().into()],
107            register: Some(Rc::new(
108                |editor: &Editor,
109                 _: &CodeIndentConfig,
110                 state: &ExtensionRegisterState<(), CodeIndentOutput>| {
111                    let stores = state.get_output().expect("CodeIndentExtension has a build");
112                    let editor = editor.weak();
113                    Ok(effect(move || {
114                        if stores.disabled.value() {
115                            return None;
116                        }
117                        let tab_size = stores.tab_size.value();
118                        let escape_with_arrows = stores.escape_with_arrows.value();
119                        let editor = editor.upgrade().map(Editor)?;
120                        Some(register_code_indentation(
121                            &editor,
122                            tab_size,
123                            escape_with_arrows,
124                        ))
125                    }))
126                },
127            )),
128            ..LexicalExtension::new(
129                "@lexical/code-indent",
130                CodeIndentConfig {
131                    disabled: false,
132                    tab_size: None,
133                    escape_with_arrows: false,
134                },
135            )
136        })
137    }
138
139    thread_local! {
140        static CODE_EXTENSION: Rc<CodeExtensionType> = make_code_extension();
141        static CODE_INDENT_EXTENSION: Rc<CodeIndentExtensionType> = make_code_indent_extension();
142    }
143
144    /// `CodeExtension`: `CodeNode` and `CodeHighlightNode`, and
145    /// [`register_code`]. In an editor built with it, Enter
146    /// (`INSERT_PARAGRAPH_COMMAND`) in a code block always adds a line; JS
147    /// exits the block on `KEY_ENTER_COMMAND` instead.
148    pub fn code_extension() -> Rc<CodeExtensionType> {
149        CODE_EXTENSION.with(Rc::clone)
150    }
151
152    /// `CodeIndentExtension`: [`code_extension`] and
153    /// [`register_code_indentation`] with its `tab_size`, unless `disabled`.
154    pub fn code_indent_extension() -> Rc<CodeIndentExtensionType> {
155        CODE_INDENT_EXTENSION.with(Rc::clone)
156    }
157}