Skip to main content

lexical_ui/
keyboard_shortcuts.rs

1//! `LexicalKeyboardShortcuts.ts`: shortcuts as data (a key, its modifiers
2//! and a command), the platform's primary and secondary modifier masks, and
3//! shortcut tables compiled for look-up by key and code.
4
5use crate::environment::is_apple;
6use crate::error::invariant;
7use crate::events::KeyboardEvent;
8use crate::lexical_selection::SelectionRef;
9use crate::lexical_utils::{
10    ControlOrOther, KeyboardEventModifierMask, KeyboardEventModifiers, ModifierExpectation,
11};
12use crate::{Editor, LexicalCommand, LexicalError, utf16};
13use std::collections::HashMap;
14use std::rc::Rc;
15
16/// `KeyboardShortcutMatch` (`@experimental`): which keyboard events a
17/// shortcut matches, an `event.key` value (case-insensitive) and a
18/// [`KeyboardEventModifierMask`], with the semantics of
19/// [`is_exact_shortcut_match`](crate::is_exact_shortcut_match), including
20/// the `event.code` fallback for non-Latin layouts.
21pub trait KeyboardShortcutMatch {
22    /// `key`: the `KeyboardEvent.key` to match, case-insensitive.
23    fn key(&self) -> &str;
24    /// `modifiers`: the expected state of the modifier keys (none pressed
25    /// by default).
26    fn modifiers(&self) -> KeyboardEventModifierMask;
27    /// `unshiftedKey`: the key without Shift, for display.
28    fn unshifted_key(&self) -> Option<&str> {
29        None
30    }
31}
32
33/// A shortcut's `$disabled(selection, editor)`.
34pub type ShortcutDisabledFn =
35    Rc<dyn Fn(Option<&SelectionRef>, &Editor) -> Result<bool, LexicalError>>;
36
37/// A shortcut's `$dispatch(command, event, $next, editor)`.
38pub type ShortcutDispatchFn = Rc<
39    dyn Fn(
40        &LexicalCommand<Rc<KeyboardEvent>>,
41        &Rc<KeyboardEvent>,
42        &dyn Fn() -> Result<bool, LexicalError>,
43        &Editor,
44    ) -> Result<bool, LexicalError>,
45>;
46
47/// `KeyboardShortcut` (`@experimental`): a shortcut as data, the key and
48/// modifiers to match and the command to dispatch with the matched event.
49/// `@lexical/extension`'s `KeyboardShortcutsExtension`
50/// ([`keyboard_shortcuts_extension`](crate::extension::keyboard_shortcuts_extension),
51/// the `extension` feature) dispatches a table of them.
52#[derive(Clone)]
53pub struct KeyboardShortcut {
54    pub key: String,
55    pub modifiers: KeyboardEventModifierMask,
56    pub unshifted_key: Option<String>,
57    /// `command`: dispatched with the matched event as its payload.
58    pub command: LexicalCommand<Rc<KeyboardEvent>>,
59    /// `description`, for menus and help.
60    pub description: Option<String>,
61    /// `$disabled`: skip the shortcut when it returns `true`.
62    pub disabled: Option<ShortcutDisabledFn>,
63    /// `$dispatch`: replaces dispatching `command`; its `$next` dispatches
64    /// it.
65    pub dispatch: Option<ShortcutDispatchFn>,
66    /// `bubbleFromNestedEditors`.
67    pub bubble_from_nested_editors: bool,
68}
69
70impl KeyboardShortcut {
71    /// A shortcut of `key` with no modifiers that dispatches `command`.
72    pub fn new(key: &str, command: LexicalCommand<Rc<KeyboardEvent>>) -> Self {
73        Self {
74            key: key.to_owned(),
75            modifiers: KeyboardEventModifierMask::default(),
76            unshifted_key: None,
77            command,
78            description: None,
79            disabled: None,
80            dispatch: None,
81            bubble_from_nested_editors: false,
82        }
83    }
84}
85
86impl KeyboardShortcutMatch for KeyboardShortcut {
87    fn key(&self) -> &str {
88        &self.key
89    }
90    fn modifiers(&self) -> KeyboardEventModifierMask {
91        self.modifiers
92    }
93    fn unshifted_key(&self) -> Option<&str> {
94        self.unshifted_key.as_deref()
95    }
96}
97
98/// `CONTROL_OR_META`: the primary shortcut modifier, ⌘ (`metaKey`) on Apple
99/// platforms and Ctrl elsewhere, for the platform [`is_apple`] names.
100pub fn control_or_meta() -> KeyboardEventModifierMask {
101    let apple = is_apple();
102    KeyboardEventModifierMask {
103        ctrl_key: (!apple).into(),
104        meta_key: apple.into(),
105        control_or_other: Some(ControlOrOther::MetaKey),
106        ..KeyboardEventModifierMask::default()
107    }
108}
109
110/// `CONTROL_OR_ALT`: the secondary shortcut modifier, ⌥ (`altKey`) on Apple
111/// platforms and Ctrl elsewhere, for word-level editing and block formats.
112pub fn control_or_alt() -> KeyboardEventModifierMask {
113    let apple = is_apple();
114    KeyboardEventModifierMask {
115        alt_key: apple.into(),
116        ctrl_key: (!apple).into(),
117        control_or_other: Some(ControlOrOther::AltKey),
118        ..KeyboardEventModifierMask::default()
119    }
120}
121
122/// `MODIFIER_BITS`, in JS's order.
123fn modifier_bits(mask: &KeyboardEventModifierMask) -> [(ModifierExpectation, u8); 4] {
124    [
125        (mask.alt_key, 1),
126        (mask.ctrl_key, 2),
127        (mask.meta_key, 4),
128        (mask.shift_key, 8),
129    ]
130}
131
132/// `getEventModifierBits(event)`.
133fn get_event_modifier_bits(event: &impl KeyboardEventModifiers) -> u8 {
134    u8::from(event.alt_key())
135        | (u8::from(event.ctrl_key()) << 1)
136        | (u8::from(event.meta_key()) << 2)
137        | (u8::from(event.shift_key()) << 3)
138}
139
140/// `getMaskModifierBits(mask)`: the modifier bitmasks that satisfy the mask,
141/// each `'any'` expanded into both states.
142fn get_mask_modifier_bits(mask: &KeyboardEventModifierMask) -> Vec<u8> {
143    let mut combos = vec![0];
144    for (expected, bit) in modifier_bits(mask) {
145        match expected {
146            ModifierExpectation::Any => {
147                let with: Vec<u8> = combos.iter().map(|bits| bits | bit).collect();
148                combos.extend(with);
149            }
150            ModifierExpectation::Pressed => {
151                for bits in &mut combos {
152                    *bits |= bit;
153                }
154            }
155            ModifierExpectation::Released => {}
156        }
157    }
158    combos
159}
160
161/// Whether `key` is one ASCII character (one UTF-16 code unit up to 127).
162fn is_ascii_key(key: &str) -> bool {
163    utf16::len(key) == 1 && key.encode_utf16().next().is_some_and(|c| c <= 127)
164}
165
166/// `CompiledKeyboardShortcuts` (`@experimental @internal`): a shortcut
167/// table indexed by the event's modifier bits and `key` (and, for
168/// non-Latin layouts, its `code`), so a look-up costs the same however
169/// many shortcuts it holds.
170pub struct CompiledKeyboardShortcuts<S> {
171    /// `${modifierBits}:${key.toLowerCase()}`: shortcuts in insertion order.
172    by_key: HashMap<String, Vec<Rc<S>>>,
173    /// `${modifierBits}:${code}` (`Digit1`, `KeyB`), used only when
174    /// `event.key` is not a single ASCII character.
175    by_code: HashMap<String, Vec<Rc<S>>>,
176}
177
178impl<S> Default for CompiledKeyboardShortcuts<S> {
179    fn default() -> Self {
180        Self {
181            by_key: HashMap::new(),
182            by_code: HashMap::new(),
183        }
184    }
185}
186
187impl<S: KeyboardShortcutMatch> CompiledKeyboardShortcuts<S> {
188    pub fn new() -> Self {
189        Self::default()
190    }
191
192    /// `add(shortcut)`.
193    pub fn add(&mut self, shortcut: S) -> Result<&mut Self, LexicalError> {
194        let key = shortcut.key().to_owned();
195        invariant!(
196            !key.is_empty(),
197            "KeyboardShortcutMatch: key must be non-empty"
198        );
199        let modifiers = shortcut.modifiers();
200        let shortcut = Rc::new(shortcut);
201        let lower_key = key.to_lowercase();
202        let single = utf16::len(&key) == 1;
203        for bits in get_mask_modifier_bits(&modifiers) {
204            self.by_key
205                .entry(format!("{bits}:{lower_key}"))
206                .or_default()
207                .push(shortcut.clone());
208            if single {
209                if key.bytes().any(|b| b.is_ascii_digit()) {
210                    self.by_code
211                        .entry(format!("{bits}:Digit{key}"))
212                        .or_default()
213                        .push(shortcut.clone());
214                } else if lower_key.bytes().any(|b| b.is_ascii_lowercase()) {
215                    self.by_code
216                        .entry(format!("{bits}:Key{}", lower_key.to_uppercase()))
217                        .or_default()
218                        .push(shortcut.clone());
219                }
220            }
221        }
222        Ok(self)
223    }
224
225    /// `matches(event)`: every shortcut matching the event, in insertion
226    /// order, the matches by `key` before those by the `code` fallback.
227    pub fn matches(&self, event: &impl KeyboardEventModifiers) -> Vec<Rc<S>> {
228        let key = event.key();
229        if key.is_empty() {
230            return Vec::new();
231        }
232        let bits = get_event_modifier_bits(event);
233        let mut matches = self
234            .by_key
235            .get(&format!("{bits}:{}", key.to_lowercase()))
236            .cloned()
237            .unwrap_or_default();
238        // The code fallback only applies when event.key is not a single
239        // ASCII character, otherwise it would break remapped layouts
240        // (Dvorak, etc.).
241        if !self.by_code.is_empty()
242            && !is_ascii_key(key)
243            && let Some(by_code) = self.by_code.get(&format!("{bits}:{}", event.code()))
244        {
245            matches.extend(by_code.iter().cloned());
246        }
247        matches
248    }
249
250    /// `match(event)`: the first shortcut matching the event.
251    pub fn r#match(&self, event: &impl KeyboardEventModifiers) -> Option<Rc<S>> {
252        self.matches(event).into_iter().next()
253    }
254}
255
256/// `compileKeyboardShortcuts(shortcuts)` (`@experimental @internal`).
257pub fn compile_keyboard_shortcuts<S: KeyboardShortcutMatch>(
258    shortcuts: impl IntoIterator<Item = S>,
259) -> Result<CompiledKeyboardShortcuts<S>, LexicalError> {
260    let mut compiled = CompiledKeyboardShortcuts::new();
261    for shortcut in shortcuts {
262        compiled.add(shortcut)?;
263    }
264    Ok(compiled)
265}