rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! What a web view's page and rustimal tell each other: which shortcuts the page hands
//! back, and the script that does it.

use super::*;

/// rustimal's shortcuts that work the same while a web app has the keyboard: switching
/// between the apps and the terminal, and everything about panes. The app gets every
/// other key. Where the two want the same one (Alt+arrows, Ctrl+Shift+arrows,
/// Ctrl+Shift+Z), rustimal gets it; rebinding the action in Settings gives it back.
pub(in crate::app) const FORWARDED: &[Action] = &[
    Action::Embed,
    Action::Code,
    Action::Chat,
    Action::Review,
    Action::Git,
    Action::FocusLeft,
    Action::FocusRight,
    Action::FocusUp,
    Action::FocusDown,
    Action::ResizeLeft,
    Action::ResizeRight,
    Action::ResizeUp,
    Action::ResizeDown,
    Action::SplitLeft,
    Action::SplitRight,
    Action::SplitUp,
    Action::SplitDown,
    Action::ClosePane,
    Action::Zoom,
];

/// The chords a page should hand back, as `chord -> action id`. A key without Ctrl or
/// Alt is never taken, so that typing in the page always works.
pub(in crate::app) fn forwarded_chords(keymap: &Keymap) -> BTreeMap<String, &'static str> {
    let is_function_key = |c: &Chord| c.key.len() > 1 && c.key.starts_with('f');
    FORWARDED
        .iter()
        .flat_map(|&a| keymap.chords(a).into_iter().map(move |c| (c, a)))
        .filter(|(c, _)| c.ctrl || c.alt || is_function_key(c))
        .map(|(c, a)| (c.to_config(), a.id()))
        .collect()
}

/// The action a forwarded message asks for. Only the forwarded ones are accepted.
pub(super) fn forwarded_action(message: &str) -> Option<Action> {
    Action::from_id(message.strip_prefix("key:")?).filter(|a| FORWARDED.contains(a))
}

/// Runs in the page: passes rustimal's shortcuts back, and says when the page is clicked,
/// so rustimal knows which pane has the focus.
pub(super) fn bridge_script(keymap: &Keymap, kind: WebKind) -> String {
    let chords = serde_json::to_string(&forwarded_chords(keymap)).unwrap_or_else(|_| "{}".into());
    let own = match kind {
        WebKind::T3 => PAIRING_WATCH,
        WebKind::Code => HIDE_CHAT_ONCE,
    };
    format!(
        r#"(() => {{
    const chords = {chords};
    const named = {{ ArrowLeft: "left", ArrowRight: "right", ArrowUp: "up", ArrowDown: "down", " ": "space" }};
    addEventListener("keydown", (e) => {{
        const key = named[e.key] || e.key.toLowerCase();
        const chord = (e.ctrlKey ? "ctrl+" : "") + (e.altKey ? "alt+" : "") + (e.shiftKey ? "shift+" : "") + key;
        if (!Object.hasOwn(chords, chord)) return;
        e.preventDefault();
        e.stopImmediatePropagation();
        window.ipc.postMessage("key:" + chords[chord]);
    }}, true);
    addEventListener("pointerdown", () => window.ipc.postMessage("focus"), true);{own}
}})();"#
    )
}