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,
text: String,
keystroke: Keystroke,
options: Options,
window: Option<NodeId>,
handler: V,
}
#[derive(Clone, Copy, Default)]
struct Options {
when: When,
repeat: bool,
pass_through: bool,
for_focus: bool,
over_focused: OverFocused,
scope: Option<Scope>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Scope {
App,
Window,
}
#[derive(Default)]
pub(crate) struct Keymap {
bindings: RefCell<Vec<Binding>>,
next: Cell<u32>,
}
impl Keymap {
pub(crate) fn free_all(&self) {
self.bindings.borrow_mut().clear();
}
}
fn keymap<'a>(cx: Ctx) -> &'a Keymap {
unsafe { &(*crate::state::state(cx)).keymap }
}
fn os(cx: Ctx) -> nsh_core::platform::Os {
unsafe { &(*crate::state::state(cx)).dom }.os()
}
fn apple(cx: Ctx) -> bool {
apple_keys(os(cx), crate::env::current(cx).apple_keyboard)
}
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)
}
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")?;
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! {
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! {
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,
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));
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)
}
}
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(());
}
drop(gone);
if empty {
crate::dom::set_handler(cx, ROOT_ID, EventKind::KeyCommand, UNDEFINED)
.map_err(|_| js::Throw)?;
}
send(cx)
}
pub(crate) fn undo_with_owner(cx: Ctx, unbind: &V) {
if crate::reactive::has_owner(cx) {
let mut f = unbind.raw();
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());
}
}
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)
}
unsafe extern "C" fn on_key_command(
cx: Ctx,
_this: Raw,
argc: std::ffi::c_int,
argv: *mut Raw,
) -> Raw {
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()));
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)
}
pub(crate) const EXPORTS: &[Item] = &[(
"keymap",
Export::Value(make),
Ts::value(
"The app's keyboard shortcuts: `keymap.bind(\"mod+k\", openSearch)`.",
"Keymap",
),
)];
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;
}
"#;