nsh-js 0.8.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
452
453
454
455
456
457
458
459
460
461
462
463
464
//! `nsh/keymap`: app-level keyboard shortcuts.
//!
//! `keymap.bind("mod+k", handler)` parses the keystroke natively
//! (`nsh_core::keymap`), keeps the handler and sends the surface's whole
//! table to the platform (`Prop::Keymap` on the root). The platform
//! decides on the spot whether a key fires a binding and consumes it, then
//! reports the binding's id with the root's `KeyCommand` event, which runs
//! the handler here: the main thread never waits for JS.
//!
//! A binding made while a component renders (or an effect runs) is undone
//! with it; one made by a module's top-level code is undone when hot
//! module replacement runs that module again (`hot::undo_on_rerun`).

use std::{
    cell::{Cell, RefCell},
    sync::Arc,
};

use nsh_core::{
    EventKind, NodeId, Op, Prop, ROOT_ID,
    keymap::{KeyBinding, Keystroke, OverFocused, When, apple_keys},
};
use rquickjs::qjs;

use crate::{
    modules::{Export, Item, Ts},
    web::js::{self, Args, Ctx, R, Raw, UNDEFINED, V, closure, native, type_error},
};

struct Binding {
    id: u32,
    /// The keystroke as the app wrote it (what the handler gets).
    text: String,
    keystroke: Keystroke,
    options: Options,
    /// The window it fires in (`None`: every window).
    window: Option<NodeId>,
    handler: V,
}

/// How a binding fires: `keymap.bind`'s options.
#[derive(Clone, Copy, Default)]
struct Options {
    when: When,
    repeat: bool,
    pass_through: bool,
    for_focus: bool,
    /// What it takes from the focused control (`overFocused`).
    over_focused: OverFocused,
    /// Where it fires; `None`: the current window, or every window in the
    /// app root.
    scope: Option<Scope>,
}

/// `keymap.bind`'s `scope`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// Every window.
    App,
    /// The window the binding is made in.
    Window,
}

/// A context's bindings, oldest first.
#[derive(Default)]
pub(crate) struct Keymap {
    bindings: RefCell<Vec<Binding>>,
    next: Cell<u32>,
}

impl Keymap {
    /// Frees the handlers (the state is unregistered).
    pub(crate) fn free_all(&self) {
        self.bindings.borrow_mut().clear();
    }
}

fn keymap<'a>(cx: Ctx) -> &'a Keymap {
    // SAFETY: a projection of the state's field, by shared reference.
    unsafe { &(*crate::state::state(cx)).keymap }
}

fn os(cx: Ctx) -> nsh_core::platform::Os {
    // SAFETY: the state's renderer, by shared reference.
    unsafe { &(*crate::state::state(cx)).dom }.os()
}

/// Whether shortcuts follow Apple's conventions here (`mod` is Command):
/// the app's OS, or for a browser the platform it runs on.
fn apple(cx: Ctx) -> bool {
    apple_keys(os(cx), crate::env::current(cx).apple_keyboard)
}

/// The `keymap` object.
fn make(cx: Ctx) -> Raw {
    let made = (|| -> R<V> {
        let obj = js::new_object(cx)?;
        let bind = js::function(cx, c"bind", bind, 3)?;
        js::define(cx, obj.raw(), "bind", bind, true)?;
        let label = js::function(cx, c"label", label, 1)?;
        js::define(cx, obj.raw(), "label", label, true)?;
        Ok(obj)
    })();
    made.map_or(qjs::JS_EXCEPTION, V::take)
}

/// The options: `when` (`undefined`, `"always"` or `"notEditing"`),
/// `repeat`, `passThrough`, `forFocus`, `overFocused` (a boolean or
/// `"pointer"`) and `scope` (`"app"` or `"window"`).
fn parse_options(cx: Ctx, options: Raw) -> R<Options> {
    if js::is_nullish(options) {
        return Ok(Options::default());
    }
    if !js::is_object(options) {
        return Err(type_error(cx, "keymap.bind: options must be an object"));
    }
    let repeat = js::to_bool(cx, js::get(cx, options, "repeat")?.raw());
    let pass_through = js::to_bool(cx, js::get(cx, options, "passThrough")?.raw());
    let for_focus = js::to_bool(cx, js::get(cx, options, "forFocus")?.raw());
    let over = js::get(cx, options, "overFocused")?;
    // SAFETY: an inline tag check.
    let over_focused = if !unsafe { qjs::JS_IsString(over.raw()) } {
        if js::to_bool(cx, over.raw()) {
            OverFocused::Always
        } else {
            OverFocused::Never
        }
    } else {
        match js::to_string(cx, over.raw())?.as_str() {
            "pointer" => OverFocused::Pointer,
            other => {
                return Err(type_error(
                    cx,
                    &format!(
                        "keymap.bind: overFocused must be a boolean or \"pointer\", not {other:?}"
                    ),
                ));
            }
        }
    };
    let scope = js::get(cx, options, "scope")?;
    let scope = if scope.is_undefined() {
        None
    } else {
        Some(match js::to_string(cx, scope.raw())?.as_str() {
            "app" => Scope::App,
            "window" => Scope::Window,
            other => {
                return Err(type_error(
                    cx,
                    &format!("keymap.bind: scope must be \"app\" or \"window\", not {other:?}"),
                ));
            }
        })
    };
    let value = js::get(cx, options, "when")?;
    if value.is_undefined() {
        return Ok(Options {
            when: When::Auto,
            repeat,
            pass_through,
            for_focus,
            over_focused,
            scope,
        });
    }
    let when = match js::to_string(cx, value.raw())?.as_str() {
        "always" => When::Always,
        "notEditing" => When::NotEditing,
        other => {
            return Err(type_error(
                cx,
                &format!("keymap.bind: when must be \"always\" or \"notEditing\", not {other:?}"),
            ));
        }
    };
    Ok(Options {
        when,
        repeat,
        pass_through,
        for_focus,
        over_focused,
        scope,
    })
}

native! {
    /// `label(keystroke)`: the keystroke as hints show it here (`⇧⌘L`,
    /// `Ctrl+Shift+L`).
    fn label(cx, _this, args) {
        let text = js::to_string(cx, args.get(0))?;
        let keystroke = Keystroke::parse_with(&text, apple(cx))
            .map_err(|e| type_error(cx, &format!("keymap.label: {e}")))?;
        let ctrl = crate::env::current(cx).ctrl_for_command;
        js::string(cx, &keystroke.pressed(ctrl).label(os(cx), apple(cx)))
    }
}

native! {
    /// `bind(keystroke, handler, options?)` or `bind({ keystroke: handler },
    /// options?)`: returns a function that removes the bindings.
    fn bind(cx, _this, args) {
        let first = args.get(0);
        let (pairs, options) = if js::is_object(first) && !js::is_function(cx, first) {
            (js::record(cx, first)?, args.get(1))
        } else {
            let text = match js::opt_string(cx, first)? {
                Some(text) if !js::is_nullish(first) => text,
                _ => {
                    return Err(type_error(
                        cx,
                        "keymap.bind: expected a keystroke (\"mod+k\") or an object of keystrokes and handlers",
                    ));
                }
            };
            (vec![(text, V::dup(cx, args.get(1)))], args.get(2))
        };
        let options = parse_options(cx, options)?;
        let current = crate::window::current_node(cx);
        let window = match options.scope {
            Some(Scope::App) => None,
            // The app root is not a window: an explicit window scope there
            // is a mistake, not an app-wide binding.
            Some(Scope::Window) => match current {
                Some(id) => Some(id),
                None => {
                    return Err(type_error(
                        cx,
                        "keymap.bind: scope \"window\" needs a window: bind it in a component inside <Window>, or use scope \"app\"",
                    ));
                }
            },
            None => current,
        };
        let (os, apple) = (os(cx), apple(cx));
        // Every binding is checked before any is made.
        let mut parsed = Vec::with_capacity(pairs.len());
        for (text, handler) in pairs {
            let keystroke = Keystroke::parse_with(&text, apple)
                .map_err(|e| type_error(cx, &format!("keymap.bind: {e}")))?;
            if let Some(why) = keystroke.reserved(os) {
                return Err(type_error(
                    cx,
                    &format!("keymap.bind: {text:?} cannot be bound: {why}"),
                ));
            }
            if !js::is_function(cx, handler.raw()) {
                return Err(type_error(
                    cx,
                    &format!("keymap.bind: the handler of {text:?} is not a function"),
                ));
            }
            parsed.push((text, keystroke, handler));
        }
        let k = keymap(cx);
        let first_id = k.next.get() + 1;
        let count = parsed.len() as u32;
        k.next.set(first_id + count);
        let was_empty = k.bindings.borrow().is_empty();
        k.bindings.borrow_mut().extend(parsed.into_iter().enumerate().map(
            |(i, (text, keystroke, handler))| Binding {
                id: first_id + i as u32,
                text,
                keystroke,
                options,
                window,
                handler,
            },
        ));
        if was_empty && count > 0 {
            let on = js::function(cx, c"onKeyCommand", on_key_command, 1)?;
            crate::dom::set_handler(cx, ROOT_ID, EventKind::KeyCommand, on.raw())
                .map_err(|_| js::Throw)?;
        }
        send(cx)?;
        let unbind = closure(cx, Vec::new(), move |cx, _, _| {
            unbind(cx, first_id..first_id + count)?;
            Ok(V::undefined())
        })?;
        undo_with_owner(cx, &unbind);
        Ok(unbind)
    }
}

/// Removes the bindings with ids in `ids` (once: later calls find none).
fn unbind(cx: Ctx, ids: std::ops::Range<u32>) -> R<()> {
    let k = keymap(cx);
    let (gone, empty) = {
        let mut bindings = k.bindings.borrow_mut();
        let gone: Vec<Binding> = bindings.extract_if(.., |b| ids.contains(&b.id)).collect();
        (gone, bindings.is_empty())
    };
    if gone.is_empty() {
        return Ok(());
    }
    // The handlers are freed with no borrow held.
    drop(gone);
    if empty {
        crate::dom::set_handler(cx, ROOT_ID, EventKind::KeyCommand, UNDEFINED)
            .map_err(|_| js::Throw)?;
    }
    send(cx)
}

/// The function undoing a binding runs when the current owner (a
/// component, an effect) goes, or, at a module's top level, when hot
/// module replacement runs the module again.
pub(crate) fn undo_with_owner(cx: Ctx, unbind: &V) {
    if crate::reactive::has_owner(cx) {
        let mut f = unbind.raw();
        // SAFETY: one borrowed argument; the result is a new reference.
        let r = unsafe { crate::reactive::on_cleanup(cx, UNDEFINED, 1, &mut f) };
        drop(V::own(cx, r));
    } else {
        crate::hot::undo_on_rerun(cx, unbind.clone_ref());
    }
}

/// Sends the table to the platform.
fn send(cx: Ctx) -> R<()> {
    let table = keymap(cx)
        .bindings
        .borrow()
        .iter()
        .map(|b| {
            let binding = KeyBinding::new(b.id, b.keystroke, b.options.when, b.options.repeat)
                .passing_through(b.options.pass_through)
                .focus_keys(b.options.for_focus)
                .over_focused(b.options.over_focused);
            match b.window {
                Some(window) => binding.in_window(window),
                None => binding,
            }
        })
        .collect();
    let op = Op::SetProp {
        id: ROOT_ID,
        prop: Prop::Keymap(Arc::new(nsh_core::keymap::Keymap::new(table))),
    };
    crate::dom::push_op(cx, op).map_err(|_| js::Throw)
}

/// The root's `onKeyCommand(id)`: runs the binding's handler with
/// `{ keystroke }` (as written; one object, as every event).
unsafe extern "C" fn on_key_command(
    cx: Ctx,
    _this: Raw,
    argc: std::ffi::c_int,
    argv: *mut Raw,
) -> Raw {
    // SAFETY: QuickJS passes `argc` live arguments.
    let args = unsafe { Args::new(argc, argv) };
    let run = || -> R<V> {
        let id = js::to_number(cx, args.get(0))? as u32;
        let found = keymap(cx)
            .bindings
            .borrow()
            .iter()
            .find(|b| b.id == id)
            .map(|b| (b.handler.clone_ref(), b.text.clone()));
        // A binding removed since the platform matched it.
        let Some((handler, text)) = found else {
            return Ok(V::undefined());
        };
        let event = js::new_object(cx)?;
        js::define(cx, event.raw(), "keystroke", js::string(cx, &text)?, true)?;
        js::call(cx, handler.raw(), UNDEFINED, &[event.raw()])
    };
    run().map_or(qjs::JS_EXCEPTION, V::take)
}

/// `nsh/keymap`'s exports.
pub(crate) const EXPORTS: &[Item] = &[(
    "keymap",
    Export::Value(make),
    Ts::value(
        "The app's keyboard shortcuts: `keymap.bind(\"mod+k\", openSearch)`.",
        "Keymap",
    ),
)];

/// `nsh/keymap`'s types.
pub(crate) const TYPES: &str = r#"export interface KeyBindingOptions {
  /** When the binding fires while a text input (or a web view) has the
   * keyboard focus. By default it does unless the input uses the keystroke
   * itself: keys that type, move the caret or delete, and select all, cut,
   * copy, paste, undo, redo. `"always"`: in text inputs too.
   * `"notEditing"`: never while one has the focus. */
  when?: "always" | "notEditing";
  /** Fire again on the auto-repeats of a held key (default false: once until
   * the key is released). */
  repeat?: boolean;
  /** Let the key go on after the handler runs, as if nothing were bound
   * (default false: the platform consumes the key). A binding of `"tab"`
   * that closes a popup lets the focus move on as Tab moves it. */
  passThrough?: boolean;
  /** The keys of the view that has the keyboard focus (default false). A
   * plain Return or Space (Shift allowed) presses the focused control
   * (`onPress`), and other bindings of those keys give way to it; a
   * `forFocus` binding takes them first. Bind it while your view has the
   * focus (`onFocus`) and remove it as the focus leaves (`onBlur`): a tile
   * whose Space flips its switch and whose Return opens it. */
  forFocus?: boolean;
  /** What the binding takes from the control with the keyboard focus
   * (default false: a focused component's own binding of the keystroke and
   * its press win over the app's).
   *
   * `true`: come before the bindings of the views, to take a key a focused
   * component binds itself, as a query editor's mod+enter over the editor's
   * insert-line-below: bind it while that view has the focus (`onFocus`)
   * and remove it as the focus leaves (`onBlur`), so the component keeps
   * the key elsewhere.
   *
   * `"pointer"`: take Return and Space from a control that a pointer gave
   * the keyboard focus. A press can focus the control it lands on (on
   * Windows, as native buttons do), and a popup a press used gives the
   * focus back to its trigger (except on macOS and iOS, where a press
   * leaves the focus where it was): with this, the binding fires instead
   * of pressing that control again. A control the keyboard focused (Tab,
   * the arrows) still takes them, and text inputs keep their keys as
   * `when` says. A media player's Space plays and pauses after a click on
   * Mute: `keymap.bind("space", toggle, { when: "notEditing", overFocused:
   * "pointer" })`. */
  overFocused?: boolean | "pointer";
  /** Where the binding fires. By default it fires in the window it is bound
   * in (a component inside `<Window>`), and in every window when it is bound
   * in the app root. `"app"`: every window, even when bound inside one.
   * `"window"`: only the window it is bound in; binding it in the app root
   * is an error. */
  scope?: "app" | "window";
}

/** The app's keyboard shortcuts: on the desktops, the web, and iOS and
 * Android with a hardware keyboard. A keystroke is modifiers and a key joined by
 * `+`, in any case (lowercase is the recommended style; a capital letter is
 * the same key, not Shift): `"mod+k"`, `"ctrl+shift+p"`, `"alt+enter"`, `"escape"`,
 * `"f5"`, `"mod+plus"`. Modifiers: `mod` (`cmdorctrl`): Command on Apple
 * platforms (and in a browser on one), Control elsewhere, for the app's own shortcuts; `cmd`
 * (`command`, `meta`, `super`, `win`), `ctrl` (`control`), `alt` (`option`,
 * `opt`), `shift`. Keys: the character a key types on the US layout without
 * Shift (`k`, `1`, `/`, `[`; `"shift+/"` for `?`), `plus` (`=`), `minus`
 * (`-`), `space`, `enter`, `escape`, `tab`, `backspace`, `delete`, `insert`,
 * `up`, `down`, `left`, `right`, `home`, `end`, `pageup`, `pagedown`, `f1` to
 * `f24`; they match on any keyboard layout, and menu shortcuts
 * (`nsh/desktop`) take the same. The platform consumes a key that fires a
 * binding, unless the binding passes it through (`passThrough`); when several bindings have its keystroke, the newest that may
 * fire runs. */
export interface Keymap {
  /** Runs `handler` when `keystroke` is pressed (it gets `{ keystroke }`,
   * the keystroke as written, in its case); returns a function that removes the binding. A binding made while a component renders is removed
   * with the component. Throws on an invalid keystroke, or one the platform
   * keeps (Command+Q, Command+H, Command+M, Control+Command+F on Apple
   * platforms; Control+Q, Alt+F4, F11 elsewhere). */
  bind(keystroke: string, handler: (e: { keystroke: string }) => void, options?: KeyBindingOptions): () => void;
  /** Binds each keystroke of `bindings` to its handler, which gets
   * `{ keystroke }` as written; returns a function that removes them all. */
  bind(bindings: Record<string, (e: { keystroke: string }) => void>, options?: KeyBindingOptions): () => void;
  /** `keystroke` as menus and hints show it where the app runs: `"⇧⌘L"` on
   * Apple platforms (and in a browser on one), `"Ctrl+Shift+L"` elsewhere,
   * for `"mod+shift+l"`; `"⌃⇧L"` in a macOS terminal that cannot report
   * Command, where Ctrl stands in for it. Throws on an invalid keystroke. */
  label(keystroke: string): string;
}
"#;