Skip to main content

plexus_ui_engine/keys/
mod.rs

1//! FRAME-36: **keys** — a component's shortcuts, the host's to handle.
2//!
3//! A component declares them (rhx: `keys(#{ "ctrl+k": "open", … })`, the
4//! tree's `keys`; a module: `bus.keys({ … })`); the host keeps one registry
5//! per page ([`Keys`], on the [`crate::bus::Bus`]) and listens on the window
6//! in the capture phase. A press that matches is the host's alone: the
7//! listener calls `preventDefault()`, `stopPropagation()` and
8//! `stopImmediatePropagation()` before anything else hears it, then runs
9//! what it names. A component's entries go when it leaves the bus (destroy,
10//! swap) — nothing outlives it.
11//!
12//! - A chord is `[ctrl+][alt+][shift+][meta+]key`, `key` the event's
13//!   `KeyboardEvent.key` lower-cased (`" "` is `space`); shift is said only
14//!   with a letter or a named key — a character shift makes (`?`) carries it.
15//!   A sequence is chords separated by a space, each within
16//!   [`SEQUENCE_MS`] of the one before.
17//! - An editable target (`input`, `textarea`, `select`, contenteditable) is
18//!   skipped unless the entry says `in_inputs` or its chord holds ctrl or
19//!   meta. FRAME-38: plain `enter` and `space` on an activatable target (a
20//!   button, a link, a `summary`, `[role=button]`) are skipped unless the
21//!   entry says `in_controls` — the press still clicks.
22//! - Two entries on one press both run, the last registered (the deeper,
23//!   mounted later) first; an entry that says `only` runs alone — the first
24//!   such in that order.
25//! - `?`, when nothing binds it and anything is registered, toggles the
26//!   overlay of every registered key, grouped by component; `escape` closes
27//!   it; an autorepeated `?` toggles nothing. FRAME-38: the overlay follows
28//!   the registry — redrawn on every change while open, closed when it
29//!   empties ([`Keys::on_change`]).
30//!
31//! Pure: the DOM's listener (`tree::dom`) turns a `KeyboardEvent` into a
32//! [`Press`] and asks [`Keys::press`]; the native tests ask it directly.
33
34use serde_json::{json, Value};
35use std::cell::{Cell, RefCell};
36use std::rc::{Rc, Weak};
37
38/// How long the next chord of a sequence may wait, in milliseconds.
39pub const SEQUENCE_MS: u64 = 800;
40
41/// The named keys a chord may end in (the compiler's list, `plexus_ui_compiler::keys::NAMED`).
42pub const NAMED: &[&str] = &[
43    "enter", "escape", "tab", "space", "backspace", "delete", "insert", "home", "end", "pageup", "pagedown", "arrowup", "arrowdown", "arrowleft", "arrowright",
44    "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
45];
46
47const MODS: [&str; 4] = ["ctrl", "alt", "shift", "meta"];
48
49/// EDITOR-13: the chords the browser keeps — no page ever hears them, so
50/// binding one is refused: `ctrl` or `meta` (with `shift` or not, never
51/// `alt`) and `t`, `w`, `n` or `tab`. The compiler's and the engine's lists,
52/// byte for byte.
53pub const RESERVED: &[&str] = &["t", "w", "n", "tab"];
54
55/// Why a chord (its modifiers held, its key) is the browser's, or none.
56pub fn reserved(held: [bool; 4], key: &str) -> Option<String> {
57    ((held[0] || held[3]) && !held[1] && RESERVED.contains(&key)).then(|| {
58        let mut chord = String::new();
59        for (i, m) in MODS.iter().enumerate() {
60            if held[i] {
61                chord.push_str(m);
62                chord.push('+');
63            }
64        }
65        chord.push_str(key);
66        format!("`{chord}` is the browser's — no page ever hears it (ctrl+t, ctrl+w, ctrl+n and ctrl+tab, with shift or meta, are kept by the browser); bind another chord")
67    })
68}
69
70/// One declared chord, canonical — the modifiers in the order ctrl, alt,
71/// shift, meta; or why it is not one. FRAME-38: a chord is lower case — an
72/// upper-case letter (`K`: shift+k, or k?) is refused. The compiler's twin,
73/// byte for byte.
74pub fn chord(text: &str) -> Result<String, String> {
75    if text.chars().any(char::is_uppercase) {
76        return Err(format!("`{text}`: a chord is lower case — write `{}` (a capital is `shift+` and the letter)", text.to_lowercase()));
77    }
78    let mut held = [false; 4];
79    let mut rest = text;
80    loop {
81        let Some(i) = MODS.iter().position(|m| rest.len() > m.len() + 1 && rest.get(..m.len()).is_some_and(|p| p.eq_ignore_ascii_case(m)) && rest.as_bytes()[m.len()] == b'+') else { break };
82        if held[i] {
83            return Err(format!("`{text}` says {} twice", MODS[i]));
84        }
85        held[i] = true;
86        rest = &rest[MODS[i].len() + 1..];
87    }
88    let key = rest.to_lowercase();
89    let one = key.chars().count() == 1;
90    if key.is_empty() || key.chars().any(char::is_whitespace) {
91        return Err(format!("`{text}` names no key"));
92    }
93    if !one && !NAMED.contains(&key.as_str()) {
94        return Err(format!("`{text}`: `{rest}` is no key — a chord is [ctrl+][alt+][shift+][meta+]key, the key one character or one of {}", NAMED.join(", ")));
95    }
96    if held[2] && one && !key.chars().all(char::is_alphabetic) {
97        return Err(format!("`{text}`: shift is in the character — write `{key}`"));
98    }
99    if let Some(why) = reserved(held, &key) {
100        return Err(why);
101    }
102    Ok(canonical(held, &key))
103}
104
105fn canonical(held: [bool; 4], key: &str) -> String {
106    let mut out = String::new();
107    for (i, m) in MODS.iter().enumerate() {
108        if held[i] {
109            out.push_str(m);
110            out.push('+');
111        }
112    }
113    out.push_str(key);
114    out
115}
116
117/// FRAME-38: `a` hides `b` — a chord (or sequence) bound alone that `b`
118/// begins with, so `b` could never be pressed.
119pub fn hides(a: &[String], b: &[String]) -> bool {
120    a.len() < b.len() && b.starts_with(a)
121}
122
123/// A declared sequence: its chords, canonical.
124pub fn sequence(text: &str) -> Result<Vec<String>, String> {
125    let chords: Vec<String> = text.split(' ').filter(|c| !c.is_empty()).map(chord).collect::<Result<_, _>>()?;
126    if chords.is_empty() {
127        return Err("a key is a chord, not empty".into());
128    }
129    Ok(chords)
130}
131
132/// The chord a `KeyboardEvent` is — its `key` and modifiers — or none for a
133/// modifier alone (or a dead key, or a composition's).
134pub fn event_chord(key: &str, ctrl: bool, alt: bool, shift: bool, meta: bool) -> Option<String> {
135    let key = if key == " " { "space".to_string() } else { key.to_lowercase() };
136    if key.is_empty() || ["control", "shift", "alt", "meta", "altgraph", "capslock", "dead", "unidentified", "process", "os", "fn"].contains(&key.as_str()) {
137        return None;
138    }
139    let one = key.chars().count() == 1;
140    // Shift is in a character it makes (`?`), said with a letter or a named key.
141    let shift = shift && (!one || key.chars().all(char::is_alphabetic));
142    Some(canonical([ctrl, alt, shift, meta], &key))
143}
144
145fn modded(chord: &str) -> bool {
146    chord.starts_with("ctrl+") || chord.contains("meta+")
147}
148
149/// One declaration: the sequence, what it runs (a fold's name, or a
150/// module's function's), its label, and its two switches.
151#[derive(Debug, Clone, PartialEq)]
152pub struct KeyDecl {
153    /// The sequence as written in the tree: canonical chords, one space.
154    pub chord: String,
155    pub seq: Vec<String>,
156    pub to: String,
157    pub label: Option<String>,
158    pub in_inputs: bool,
159    pub only: bool,
160    /// FRAME-38: heard as plain `enter` / `space` on a button or a link.
161    pub in_controls: bool,
162}
163
164impl KeyDecl {
165    /// `chord` read (and made canonical), or why it is no chord.
166    pub fn new(chord: &str, to: &str, label: Option<String>, in_inputs: bool, only: bool) -> Result<Self, String> {
167        let seq = sequence(chord)?;
168        Ok(Self { chord: seq.join(" "), seq, to: to.into(), label, in_inputs, only, in_controls: false })
169    }
170
171    /// FRAME-38: with `in_controls`.
172    pub fn controls(mut self, in_controls: bool) -> Self {
173        self.in_controls = in_controls;
174        self
175    }
176
177    /// Heard on this press's target.
178    fn heard(&self, p: &Press) -> bool {
179        if p.editable && !self.in_inputs() {
180            return false;
181        }
182        !(p.activatable && (p.chord == "enter" || p.chord == "space") && !self.in_controls)
183    }
184
185    /// What the overlay shows for it: its label, else what it runs.
186    pub fn shown(&self) -> String {
187        self.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| self.to.clone())
188    }
189
190    /// Heard in an editable target.
191    fn in_inputs(&self) -> bool {
192        self.in_inputs || modded(&self.seq[0])
193    }
194}
195
196/// What runs on a match: handed `{ key, chord, target }`.
197pub type KeyRun = Rc<dyn Fn(Value)>;
198
199/// One key press, as the window heard it.
200#[derive(Debug, Clone, PartialEq)]
201pub struct Press {
202    /// [`event_chord`]'s.
203    pub chord: String,
204    /// The event's own `key`.
205    pub key: String,
206    /// Its target is an input, a textarea, a select or contenteditable.
207    pub editable: bool,
208    /// FRAME-38: its target is a button, a link (`a[href]`), a `summary`
209    /// or `[role=button]` — `enter` and `space` click it.
210    pub activatable: bool,
211    /// FRAME-38: the key held down, autorepeating.
212    pub repeat: bool,
213    /// What a handler's `ev.target` is.
214    pub target: Value,
215    /// When, on the page's clock (ms).
216    pub at_ms: u64,
217}
218
219/// What [`Keys::press`] did with a press.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub enum Heard {
222    /// Nothing of the host's: the press goes on to the page and the browser.
223    Nothing,
224    /// It matched: these many entries ran.
225    Ran(usize),
226    /// The first chords of a sequence: held for the next.
227    Waiting,
228    /// The overlay opened (`true`) or closed.
229    Overlay(bool),
230    /// FRAME-38: the host's, and nothing changed (an autorepeated `?` on
231    /// the open overlay).
232    Kept,
233}
234
235impl Heard {
236    /// The host took it: the browser must not.
237    pub fn taken(self) -> bool {
238        self != Heard::Nothing
239    }
240}
241
242struct Entry {
243    id: u64,
244    member: u64,
245    component: String,
246    decl: KeyDecl,
247    run: KeyRun,
248}
249
250#[derive(Default)]
251struct Inner {
252    entries: RefCell<Vec<Entry>>,
253    /// The chords of a sequence under way, and when the last came.
254    pending: RefCell<(Vec<String>, u64)>,
255    overlay: Cell<bool>,
256    next: Cell<u64>,
257    /// FRAME-38: told after every change of the entries.
258    on_change: RefCell<Option<Rc<dyn Fn()>>>,
259}
260
261fn changed(inner: &Inner) {
262    let f = inner.on_change.borrow().clone();
263    if let Some(f) = f {
264        f();
265    }
266}
267
268/// The page's keys (a handle: clones are the same registry).
269#[derive(Clone, Default)]
270pub struct Keys(Rc<Inner>);
271
272/// The overlay's rows: per component (in the order they registered), each
273/// `(chord, what it shows)`.
274pub type KeyGroups = Vec<(String, Vec<(String, String)>)>;
275
276impl std::fmt::Debug for Keys {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        write!(f, "Keys({} entries)", self.0.entries.borrow().len())
279    }
280}
281
282/// Entries held: dropping it takes them out.
283pub struct KeysHeld {
284    keys: Weak<Inner>,
285    ids: Vec<u64>,
286}
287
288impl Drop for KeysHeld {
289    fn drop(&mut self) {
290        if let Some(inner) = self.keys.upgrade() {
291            inner.entries.borrow_mut().retain(|e| !self.ids.contains(&e.id));
292            if !self.ids.is_empty() {
293                changed(&inner);
294            }
295        }
296    }
297}
298
299impl Keys {
300    /// `decls` of `component` (bus member `member`), each with what it runs.
301    pub fn add(&self, member: u64, component: &str, decls: Vec<(KeyDecl, KeyRun)>) -> KeysHeld {
302        let mut ids = Vec::new();
303        {
304            let mut entries = self.0.entries.borrow_mut();
305            for (decl, run) in decls {
306                let id = self.0.next.get() + 1;
307                self.0.next.set(id);
308                ids.push(id);
309                entries.push(Entry { id, member, component: component.into(), decl, run });
310            }
311        }
312        if !ids.is_empty() {
313            changed(&self.0);
314        }
315        KeysHeld { keys: Rc::downgrade(&self.0), ids }
316    }
317
318    /// Every entry of `member` out (it left the bus).
319    pub fn remove_member(&self, member: u64) {
320        let gone = {
321            let mut entries = self.0.entries.borrow_mut();
322            let n = entries.len();
323            entries.retain(|e| e.member != member);
324            n != entries.len()
325        };
326        if gone {
327            changed(&self.0);
328        }
329    }
330
331    /// FRAME-38: `f` after every change of the entries (none borrowed
332    /// while it runs) — the host redraws an open overlay from it.
333    pub fn on_change(&self, f: Rc<dyn Fn()>) {
334        *self.0.on_change.borrow_mut() = Some(f);
335    }
336
337    /// FRAME-38: the overlay closed by the host (the registry emptied).
338    pub fn close_overlay(&self) {
339        self.0.overlay.set(false);
340    }
341
342    /// How many entries are registered.
343    pub fn len(&self) -> usize {
344        self.0.entries.borrow().len()
345    }
346
347    pub fn is_empty(&self) -> bool {
348        self.len() == 0
349    }
350
351    /// Whether the overlay is open.
352    pub fn overlay(&self) -> bool {
353        self.0.overlay.get()
354    }
355
356    /// Every registered key, grouped by component in the order they
357    /// registered (one group per component name; a chord once).
358    pub fn groups(&self) -> KeyGroups {
359        let mut out: KeyGroups = Vec::new();
360        for e in self.0.entries.borrow().iter() {
361            let at = match out.iter().position(|(c, _)| c == &e.component) {
362                Some(i) => i,
363                None => {
364                    out.push((e.component.clone(), Vec::new()));
365                    out.len() - 1
366                }
367            };
368            if !out[at].1.iter().any(|(c, _)| c == &e.decl.chord) {
369                out[at].1.push((e.decl.chord.clone(), e.decl.shown()));
370            }
371        }
372        out
373    }
374
375    /// A press: run what it matches (and say so), hold the first chords of
376    /// a sequence, or toggle the overlay. Nothing of the registry is
377    /// borrowed while an entry runs: it may unmount components, or bind more.
378    pub fn press(&self, p: &Press) -> Heard {
379        let inner = &self.0;
380        if inner.overlay.get() && p.chord == "?" && p.repeat {
381            return Heard::Kept;
382        }
383        if inner.overlay.get() && (p.chord == "escape" || p.chord == "?") {
384            inner.overlay.set(false);
385            return Heard::Overlay(false);
386        }
387        let mut seq = {
388            let pending = inner.pending.borrow();
389            if !pending.0.is_empty() && p.at_ms.saturating_sub(pending.1) <= SEQUENCE_MS {
390                pending.0.clone()
391            } else {
392                Vec::new()
393            }
394        };
395        seq.push(p.chord.clone());
396        loop {
397            // (id, run, only, chord) of every entry this sequence completes,
398            // the last registered first.
399            let (mut full, prefix) = {
400                let entries = inner.entries.borrow();
401                let heard = entries.iter().filter(|e| e.decl.heard(p));
402                let mut full = Vec::new();
403                let mut prefix = false;
404                for e in heard {
405                    if e.decl.seq == seq {
406                        full.push((e.id, e.run.clone(), e.decl.only, e.decl.chord.clone()));
407                    } else if e.decl.seq.len() > seq.len() && e.decl.seq.starts_with(&seq) {
408                        prefix = true;
409                    }
410                }
411                full.reverse();
412                (full, prefix)
413            };
414            if !full.is_empty() {
415                *inner.pending.borrow_mut() = (Vec::new(), 0);
416                let chosen: Vec<_> = match full.iter().position(|f| f.2) {
417                    Some(i) => vec![full.swap_remove(i)],
418                    None => full,
419                };
420                let mut ran = 0;
421                for (id, run, _, chord) in chosen {
422                    // One taken out by an earlier one hears nothing.
423                    if inner.entries.borrow().iter().any(|e| e.id == id) {
424                        run(json!({ "key": p.key, "chord": chord, "target": p.target }));
425                        ran += 1;
426                    }
427                }
428                return Heard::Ran(ran);
429            }
430            if prefix {
431                *inner.pending.borrow_mut() = (seq, p.at_ms);
432                return Heard::Waiting;
433            }
434            if seq.len() > 1 {
435                // A sequence that went nowhere: the press alone, afresh.
436                seq = vec![p.chord.clone()];
437                continue;
438            }
439            break;
440        }
441        *inner.pending.borrow_mut() = (Vec::new(), 0);
442        if p.chord == "?" && !p.editable && !p.repeat && !inner.entries.borrow().is_empty() {
443            inner.overlay.set(true);
444            return Heard::Overlay(true);
445        }
446        Heard::Nothing
447    }
448}
449
450#[cfg(test)]
451mod tests;