lexical_ui/
keyboard_shortcuts.rs1use 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
16pub trait KeyboardShortcutMatch {
22 fn key(&self) -> &str;
24 fn modifiers(&self) -> KeyboardEventModifierMask;
27 fn unshifted_key(&self) -> Option<&str> {
29 None
30 }
31}
32
33pub type ShortcutDisabledFn =
35 Rc<dyn Fn(Option<&SelectionRef>, &Editor) -> Result<bool, LexicalError>>;
36
37pub 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#[derive(Clone)]
53pub struct KeyboardShortcut {
54 pub key: String,
55 pub modifiers: KeyboardEventModifierMask,
56 pub unshifted_key: Option<String>,
57 pub command: LexicalCommand<Rc<KeyboardEvent>>,
59 pub description: Option<String>,
61 pub disabled: Option<ShortcutDisabledFn>,
63 pub dispatch: Option<ShortcutDispatchFn>,
66 pub bubble_from_nested_editors: bool,
68}
69
70impl KeyboardShortcut {
71 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
98pub 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
110pub 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
122fn 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
132fn 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
140fn 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
161fn is_ascii_key(key: &str) -> bool {
163 utf16::len(key) == 1 && key.encode_utf16().next().is_some_and(|c| c <= 127)
164}
165
166pub struct CompiledKeyboardShortcuts<S> {
171 by_key: HashMap<String, Vec<Rc<S>>>,
173 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 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 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 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 pub fn r#match(&self, event: &impl KeyboardEventModifiers) -> Option<Rc<S>> {
252 self.matches(event).into_iter().next()
253 }
254}
255
256pub 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}