plexus-ui-engine 0.2.2

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! FRAME-36: **keys** — a component's shortcuts, the host's to handle.
//!
//! A component declares them (rhx: `keys(#{ "ctrl+k": "open", … })`, the
//! tree's `keys`; a module: `bus.keys({ … })`); the host keeps one registry
//! per page ([`Keys`], on the [`crate::bus::Bus`]) and listens on the window
//! in the capture phase. A press that matches is the host's alone: the
//! listener calls `preventDefault()`, `stopPropagation()` and
//! `stopImmediatePropagation()` before anything else hears it, then runs
//! what it names. A component's entries go when it leaves the bus (destroy,
//! swap) — nothing outlives it.
//!
//! - A chord is `[ctrl+][alt+][shift+][meta+]key`, `key` the event's
//!   `KeyboardEvent.key` lower-cased (`" "` is `space`); shift is said only
//!   with a letter or a named key — a character shift makes (`?`) carries it.
//!   A sequence is chords separated by a space, each within
//!   [`SEQUENCE_MS`] of the one before.
//! - An editable target (`input`, `textarea`, `select`, contenteditable) is
//!   skipped unless the entry says `in_inputs` or its chord holds ctrl or
//!   meta. FRAME-38: plain `enter` and `space` on an activatable target (a
//!   button, a link, a `summary`, `[role=button]`) are skipped unless the
//!   entry says `in_controls` — the press still clicks.
//! - Two entries on one press both run, the last registered (the deeper,
//!   mounted later) first; an entry that says `only` runs alone — the first
//!   such in that order.
//! - `?`, when nothing binds it and anything is registered, toggles the
//!   overlay of every registered key, grouped by component; `escape` closes
//!   it; an autorepeated `?` toggles nothing. FRAME-38: the overlay follows
//!   the registry — redrawn on every change while open, closed when it
//!   empties ([`Keys::on_change`]).
//!
//! Pure: the DOM's listener (`tree::dom`) turns a `KeyboardEvent` into a
//! [`Press`] and asks [`Keys::press`]; the native tests ask it directly.

use serde_json::{json, Value};
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};

/// How long the next chord of a sequence may wait, in milliseconds.
pub const SEQUENCE_MS: u64 = 800;

/// The named keys a chord may end in (the compiler's list, `plexus_ui_compiler::keys::NAMED`).
pub const NAMED: &[&str] = &[
    "enter", "escape", "tab", "space", "backspace", "delete", "insert", "home", "end", "pageup", "pagedown", "arrowup", "arrowdown", "arrowleft", "arrowright",
    "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
];

const MODS: [&str; 4] = ["ctrl", "alt", "shift", "meta"];

/// EDITOR-13: the chords the browser keeps — no page ever hears them, so
/// binding one is refused: `ctrl` or `meta` (with `shift` or not, never
/// `alt`) and `t`, `w`, `n` or `tab`. The compiler's and the engine's lists,
/// byte for byte.
pub const RESERVED: &[&str] = &["t", "w", "n", "tab"];

/// Why a chord (its modifiers held, its key) is the browser's, or none.
pub fn reserved(held: [bool; 4], key: &str) -> Option<String> {
    ((held[0] || held[3]) && !held[1] && RESERVED.contains(&key)).then(|| {
        let mut chord = String::new();
        for (i, m) in MODS.iter().enumerate() {
            if held[i] {
                chord.push_str(m);
                chord.push('+');
            }
        }
        chord.push_str(key);
        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")
    })
}

/// One declared chord, canonical — the modifiers in the order ctrl, alt,
/// shift, meta; or why it is not one. FRAME-38: a chord is lower case — an
/// upper-case letter (`K`: shift+k, or k?) is refused. The compiler's twin,
/// byte for byte.
pub fn chord(text: &str) -> Result<String, String> {
    if text.chars().any(char::is_uppercase) {
        return Err(format!("`{text}`: a chord is lower case — write `{}` (a capital is `shift+` and the letter)", text.to_lowercase()));
    }
    let mut held = [false; 4];
    let mut rest = text;
    loop {
        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 };
        if held[i] {
            return Err(format!("`{text}` says {} twice", MODS[i]));
        }
        held[i] = true;
        rest = &rest[MODS[i].len() + 1..];
    }
    let key = rest.to_lowercase();
    let one = key.chars().count() == 1;
    if key.is_empty() || key.chars().any(char::is_whitespace) {
        return Err(format!("`{text}` names no key"));
    }
    if !one && !NAMED.contains(&key.as_str()) {
        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(", ")));
    }
    if held[2] && one && !key.chars().all(char::is_alphabetic) {
        return Err(format!("`{text}`: shift is in the character — write `{key}`"));
    }
    if let Some(why) = reserved(held, &key) {
        return Err(why);
    }
    Ok(canonical(held, &key))
}

fn canonical(held: [bool; 4], key: &str) -> String {
    let mut out = String::new();
    for (i, m) in MODS.iter().enumerate() {
        if held[i] {
            out.push_str(m);
            out.push('+');
        }
    }
    out.push_str(key);
    out
}

/// FRAME-38: `a` hides `b` — a chord (or sequence) bound alone that `b`
/// begins with, so `b` could never be pressed.
pub fn hides(a: &[String], b: &[String]) -> bool {
    a.len() < b.len() && b.starts_with(a)
}

/// A declared sequence: its chords, canonical.
pub fn sequence(text: &str) -> Result<Vec<String>, String> {
    let chords: Vec<String> = text.split(' ').filter(|c| !c.is_empty()).map(chord).collect::<Result<_, _>>()?;
    if chords.is_empty() {
        return Err("a key is a chord, not empty".into());
    }
    Ok(chords)
}

/// The chord a `KeyboardEvent` is — its `key` and modifiers — or none for a
/// modifier alone (or a dead key, or a composition's).
pub fn event_chord(key: &str, ctrl: bool, alt: bool, shift: bool, meta: bool) -> Option<String> {
    let key = if key == " " { "space".to_string() } else { key.to_lowercase() };
    if key.is_empty() || ["control", "shift", "alt", "meta", "altgraph", "capslock", "dead", "unidentified", "process", "os", "fn"].contains(&key.as_str()) {
        return None;
    }
    let one = key.chars().count() == 1;
    // Shift is in a character it makes (`?`), said with a letter or a named key.
    let shift = shift && (!one || key.chars().all(char::is_alphabetic));
    Some(canonical([ctrl, alt, shift, meta], &key))
}

fn modded(chord: &str) -> bool {
    chord.starts_with("ctrl+") || chord.contains("meta+")
}

/// One declaration: the sequence, what it runs (a fold's name, or a
/// module's function's), its label, and its two switches.
#[derive(Debug, Clone, PartialEq)]
pub struct KeyDecl {
    /// The sequence as written in the tree: canonical chords, one space.
    pub chord: String,
    pub seq: Vec<String>,
    pub to: String,
    pub label: Option<String>,
    pub in_inputs: bool,
    pub only: bool,
    /// FRAME-38: heard as plain `enter` / `space` on a button or a link.
    pub in_controls: bool,
}

impl KeyDecl {
    /// `chord` read (and made canonical), or why it is no chord.
    pub fn new(chord: &str, to: &str, label: Option<String>, in_inputs: bool, only: bool) -> Result<Self, String> {
        let seq = sequence(chord)?;
        Ok(Self { chord: seq.join(" "), seq, to: to.into(), label, in_inputs, only, in_controls: false })
    }

    /// FRAME-38: with `in_controls`.
    pub fn controls(mut self, in_controls: bool) -> Self {
        self.in_controls = in_controls;
        self
    }

    /// Heard on this press's target.
    fn heard(&self, p: &Press) -> bool {
        if p.editable && !self.in_inputs() {
            return false;
        }
        !(p.activatable && (p.chord == "enter" || p.chord == "space") && !self.in_controls)
    }

    /// What the overlay shows for it: its label, else what it runs.
    pub fn shown(&self) -> String {
        self.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| self.to.clone())
    }

    /// Heard in an editable target.
    fn in_inputs(&self) -> bool {
        self.in_inputs || modded(&self.seq[0])
    }
}

/// What runs on a match: handed `{ key, chord, target }`.
pub type KeyRun = Rc<dyn Fn(Value)>;

/// One key press, as the window heard it.
#[derive(Debug, Clone, PartialEq)]
pub struct Press {
    /// [`event_chord`]'s.
    pub chord: String,
    /// The event's own `key`.
    pub key: String,
    /// Its target is an input, a textarea, a select or contenteditable.
    pub editable: bool,
    /// FRAME-38: its target is a button, a link (`a[href]`), a `summary`
    /// or `[role=button]` — `enter` and `space` click it.
    pub activatable: bool,
    /// FRAME-38: the key held down, autorepeating.
    pub repeat: bool,
    /// What a handler's `ev.target` is.
    pub target: Value,
    /// When, on the page's clock (ms).
    pub at_ms: u64,
}

/// What [`Keys::press`] did with a press.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Heard {
    /// Nothing of the host's: the press goes on to the page and the browser.
    Nothing,
    /// It matched: these many entries ran.
    Ran(usize),
    /// The first chords of a sequence: held for the next.
    Waiting,
    /// The overlay opened (`true`) or closed.
    Overlay(bool),
    /// FRAME-38: the host's, and nothing changed (an autorepeated `?` on
    /// the open overlay).
    Kept,
}

impl Heard {
    /// The host took it: the browser must not.
    pub fn taken(self) -> bool {
        self != Heard::Nothing
    }
}

struct Entry {
    id: u64,
    member: u64,
    component: String,
    decl: KeyDecl,
    run: KeyRun,
}

#[derive(Default)]
struct Inner {
    entries: RefCell<Vec<Entry>>,
    /// The chords of a sequence under way, and when the last came.
    pending: RefCell<(Vec<String>, u64)>,
    overlay: Cell<bool>,
    next: Cell<u64>,
    /// FRAME-38: told after every change of the entries.
    on_change: RefCell<Option<Rc<dyn Fn()>>>,
}

fn changed(inner: &Inner) {
    let f = inner.on_change.borrow().clone();
    if let Some(f) = f {
        f();
    }
}

/// The page's keys (a handle: clones are the same registry).
#[derive(Clone, Default)]
pub struct Keys(Rc<Inner>);

/// The overlay's rows: per component (in the order they registered), each
/// `(chord, what it shows)`.
pub type KeyGroups = Vec<(String, Vec<(String, String)>)>;

impl std::fmt::Debug for Keys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Keys({} entries)", self.0.entries.borrow().len())
    }
}

/// Entries held: dropping it takes them out.
pub struct KeysHeld {
    keys: Weak<Inner>,
    ids: Vec<u64>,
}

impl Drop for KeysHeld {
    fn drop(&mut self) {
        if let Some(inner) = self.keys.upgrade() {
            inner.entries.borrow_mut().retain(|e| !self.ids.contains(&e.id));
            if !self.ids.is_empty() {
                changed(&inner);
            }
        }
    }
}

impl Keys {
    /// `decls` of `component` (bus member `member`), each with what it runs.
    pub fn add(&self, member: u64, component: &str, decls: Vec<(KeyDecl, KeyRun)>) -> KeysHeld {
        let mut ids = Vec::new();
        {
            let mut entries = self.0.entries.borrow_mut();
            for (decl, run) in decls {
                let id = self.0.next.get() + 1;
                self.0.next.set(id);
                ids.push(id);
                entries.push(Entry { id, member, component: component.into(), decl, run });
            }
        }
        if !ids.is_empty() {
            changed(&self.0);
        }
        KeysHeld { keys: Rc::downgrade(&self.0), ids }
    }

    /// Every entry of `member` out (it left the bus).
    pub fn remove_member(&self, member: u64) {
        let gone = {
            let mut entries = self.0.entries.borrow_mut();
            let n = entries.len();
            entries.retain(|e| e.member != member);
            n != entries.len()
        };
        if gone {
            changed(&self.0);
        }
    }

    /// FRAME-38: `f` after every change of the entries (none borrowed
    /// while it runs) — the host redraws an open overlay from it.
    pub fn on_change(&self, f: Rc<dyn Fn()>) {
        *self.0.on_change.borrow_mut() = Some(f);
    }

    /// FRAME-38: the overlay closed by the host (the registry emptied).
    pub fn close_overlay(&self) {
        self.0.overlay.set(false);
    }

    /// How many entries are registered.
    pub fn len(&self) -> usize {
        self.0.entries.borrow().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether the overlay is open.
    pub fn overlay(&self) -> bool {
        self.0.overlay.get()
    }

    /// Every registered key, grouped by component in the order they
    /// registered (one group per component name; a chord once).
    pub fn groups(&self) -> KeyGroups {
        let mut out: KeyGroups = Vec::new();
        for e in self.0.entries.borrow().iter() {
            let at = match out.iter().position(|(c, _)| c == &e.component) {
                Some(i) => i,
                None => {
                    out.push((e.component.clone(), Vec::new()));
                    out.len() - 1
                }
            };
            if !out[at].1.iter().any(|(c, _)| c == &e.decl.chord) {
                out[at].1.push((e.decl.chord.clone(), e.decl.shown()));
            }
        }
        out
    }

    /// A press: run what it matches (and say so), hold the first chords of
    /// a sequence, or toggle the overlay. Nothing of the registry is
    /// borrowed while an entry runs: it may unmount components, or bind more.
    pub fn press(&self, p: &Press) -> Heard {
        let inner = &self.0;
        if inner.overlay.get() && p.chord == "?" && p.repeat {
            return Heard::Kept;
        }
        if inner.overlay.get() && (p.chord == "escape" || p.chord == "?") {
            inner.overlay.set(false);
            return Heard::Overlay(false);
        }
        let mut seq = {
            let pending = inner.pending.borrow();
            if !pending.0.is_empty() && p.at_ms.saturating_sub(pending.1) <= SEQUENCE_MS {
                pending.0.clone()
            } else {
                Vec::new()
            }
        };
        seq.push(p.chord.clone());
        loop {
            // (id, run, only, chord) of every entry this sequence completes,
            // the last registered first.
            let (mut full, prefix) = {
                let entries = inner.entries.borrow();
                let heard = entries.iter().filter(|e| e.decl.heard(p));
                let mut full = Vec::new();
                let mut prefix = false;
                for e in heard {
                    if e.decl.seq == seq {
                        full.push((e.id, e.run.clone(), e.decl.only, e.decl.chord.clone()));
                    } else if e.decl.seq.len() > seq.len() && e.decl.seq.starts_with(&seq) {
                        prefix = true;
                    }
                }
                full.reverse();
                (full, prefix)
            };
            if !full.is_empty() {
                *inner.pending.borrow_mut() = (Vec::new(), 0);
                let chosen: Vec<_> = match full.iter().position(|f| f.2) {
                    Some(i) => vec![full.swap_remove(i)],
                    None => full,
                };
                let mut ran = 0;
                for (id, run, _, chord) in chosen {
                    // One taken out by an earlier one hears nothing.
                    if inner.entries.borrow().iter().any(|e| e.id == id) {
                        run(json!({ "key": p.key, "chord": chord, "target": p.target }));
                        ran += 1;
                    }
                }
                return Heard::Ran(ran);
            }
            if prefix {
                *inner.pending.borrow_mut() = (seq, p.at_ms);
                return Heard::Waiting;
            }
            if seq.len() > 1 {
                // A sequence that went nowhere: the press alone, afresh.
                seq = vec![p.chord.clone()];
                continue;
            }
            break;
        }
        *inner.pending.borrow_mut() = (Vec::new(), 0);
        if p.chord == "?" && !p.editable && !p.repeat && !inner.entries.borrow().is_empty() {
            inner.overlay.set(true);
            return Heard::Overlay(true);
        }
        Heard::Nothing
    }
}

#[cfg(test)]
mod tests;