Spaces:
Paused

assistant / ui /web /src /lib /shortcuts.js
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
7.66 kB
// Shared keyboard-shortcut helpers for the Svelte UI.
/**
* The default "long conversation" threshold β€” the number of messages past
* which the destructive Alt+Delete clear asks for confirmation first. The
* LIVE threshold is a persisted user setting (Settings tab β†’
* "Confirm-clear threshold", surfaced via app.meta.clearConfirmMin); this
* constant is only the fallback when nothing has been configured.
*/
export const DEFAULT_CLEAR_CONFIRM_MIN = 8;
/**
* Bind an arbitrary key combo to a handler β€” the generic cousin of
* bindClearShortcut. `isMatch(e)` decides whether the KeyboardEvent is the
* combo; the handler only runs (and the event is preventDefault'ed) on a
* match.
*
* $effect(() => bindShortcut((e) => e.altKey && e.key === "t", onTranscribe));
*
* Returns the cleanup function β€” wire it from a Svelte 5 $effect so it
* pairs with the component's lifecycle (the effect runs once per mount;
* the cleanup is invoked on unmount / effect re-run).
*/
export function bindShortcut(isMatch, handler) {
function onKeydown(e) {
if (isMatch(e)) {
e.preventDefault();
handler(e);
}
}
window.addEventListener("keydown", onKeydown);
return () => window.removeEventListener("keydown", onKeydown);
}
/**
* Bind the app-wide "Clear" shortcut β€” Alt+Delete (or Alt+Backspace, for
* laptops without a dedicated Delete key) β€” to the given handler.
*
* Alt+Delete is deliberately chosen: it is not a Windows system combo, not
* a browser/WebView2 accelerator, and not a text-editing command β€” so it is
* safe to trigger even while the cursor sits in a text field (the STT
* transcript, the chat composer, a filename input). The handler receives
* the KeyboardEvent, whose `preventDefault()` has already been called for
* the matched combo.
*
* `options.confirm` β€” optional function evaluated at keypress time. It may
* return null (clear immediately) or a { message, ok, cancel } object to
* ask the user first via the themed in-app dialog; the handler only runs
* when the user confirms. All three strings are user-visible, so pass them
* through the i18n store (t(...)) at call time to stay in the current UI
* language.
*
* Returns the cleanup function that removes the listener β€” wire it up from
* a Svelte 5 effect so it pairs with the component's lifecycle:
*
* $effect(() => bindClearShortcut(clearChat, { confirm }));
*
* (The effect runs once per mount because the handler reference is stable;
* the returned cleanup is invoked on unmount / effect re-run.)
*/
export function bindClearShortcut(handler, { confirm } = {}) {
function onKeydown(e) {
if (e.altKey && (e.key === "Delete" || e.key === "Backspace")) {
e.preventDefault();
const ask = confirm ? confirm() : null;
if (ask) {
showConfirmDialog(ask).then((ok) => ok && handler(e));
} else {
handler(e);
}
}
}
window.addEventListener("keydown", onKeydown);
return () => window.removeEventListener("keydown", onKeydown);
}
// ---- themed in-app confirmation dialog (promise-based, no native prompt) ----
let confirmOpen = false;
let confirmStylesInjected = false;
/** Inject the dialog's styles once. They ride the app's CSS variables, so
* they inherit the current light/dark theme automatically. */
function ensureConfirmStyles() {
if (confirmStylesInjected || typeof document === "undefined") return;
confirmStylesInjected = true;
const style = document.createElement("style");
style.textContent = [
".lal-confirm-overlay{position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.45);",
"display:flex;align-items:center;justify-content:center;padding:16px}",
".lal-confirm-box{background:var(--bg-elev,#ffffff);border:1px solid var(--card-border,#e7e0d3);",
"border-radius:var(--radius,14px);padding:20px;max-width:400px;width:100%;",
"box-shadow:0 12px 40px rgba(0,0,0,.3)}",
".lal-confirm-msg{color:var(--text-strong,#3f332b);font-size:.9rem;line-height:1.55;",
"margin-bottom:18px;white-space:pre-wrap;overflow-wrap:anywhere}",
".lal-confirm-actions{display:flex;gap:8px;justify-content:flex-end}",
".lal-confirm-btn{border:1px solid var(--card-border,#e7e0d3);background:var(--btn-bg,#f7f2e9);",
"color:var(--text-strong,#3f332b);border-radius:10px;padding:8px 14px;font:inherit;",
"font-size:.85rem;font-weight:600;cursor:pointer;transition:filter .15s ease}",
".lal-confirm-btn:hover{filter:brightness(.97)}",
".lal-confirm-ok{background:var(--primary-600,#d97757);border-color:var(--primary-600,#d97757);color:#fff}",
".lal-confirm-ok:hover{filter:brightness(1.05)}",
].join("");
document.head.appendChild(style);
}
/**
* Promise-based confirmation dialog. Resolves `true` when the user clicks
* the OK button, `false` on Cancel / Escape / backdrop click. Only one
* dialog can be open at a time β€” a re-entrant call resolves `false`
* immediately. All labels come from the caller (bilingual via i18n).
*/
export function showConfirmDialog({ message, ok, cancel }) {
if (confirmOpen) return Promise.resolve(false);
confirmOpen = true;
return new Promise((resolve) => {
ensureConfirmStyles();
const prevFocus = document.activeElement;
const overlay = document.createElement("div");
overlay.className = "lal-confirm-overlay";
const box = document.createElement("div");
box.className = "lal-confirm-box";
box.setAttribute("role", "alertdialog");
box.setAttribute("aria-modal", "true");
const msg = document.createElement("div");
msg.className = "lal-confirm-msg";
msg.textContent = message;
const actions = document.createElement("div");
actions.className = "lal-confirm-actions";
const cancelBtn = document.createElement("button");
cancelBtn.type = "button";
cancelBtn.className = "lal-confirm-btn lal-confirm-cancel";
cancelBtn.textContent = cancel;
// Runtime-created controls still carry the app's styled data-tooltip
// (the Tooltip.svelte singleton binds [data-tooltip] dynamically) β€”
// keeps every interactive element on-brand and sweep-proof.
cancelBtn.setAttribute("data-tooltip", cancel);
const okBtn = document.createElement("button");
okBtn.type = "button";
okBtn.className = "lal-confirm-btn lal-confirm-ok";
okBtn.textContent = ok;
okBtn.setAttribute("data-tooltip", ok);
actions.append(cancelBtn, okBtn);
box.append(msg, actions);
overlay.append(box);
const close = (result) => {
overlay.remove();
document.removeEventListener("keydown", onKeydown, true);
confirmOpen = false;
if (prevFocus && typeof prevFocus.focus === "function") prevFocus.focus();
resolve(result);
};
okBtn.addEventListener("click", () => close(true));
cancelBtn.addEventListener("click", () => close(false));
// Clicking the dimmed backdrop = cancel.
overlay.addEventListener("mousedown", (e) => {
if (e.target === overlay) close(false);
});
function onKeydown(e) {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
close(false);
} else if (e.key === "Enter") {
// A focused button already fires its click on Enter β€” only handle
// Enter pressed outside the buttons, defaulting to the SAFE choice
// for a destructive action.
if (e.target === okBtn || e.target === cancelBtn) return;
e.preventDefault();
close(false);
}
}
document.addEventListener("keydown", onKeydown, true);
document.body.appendChild(overlay);
cancelBtn.focus();
});
}