AI media harness for planning, generating, and editing locally
TypeScript
Let app shortcuts claim Ctrl+F, F3 and Alt+Left before the browser guard
Bittifa43d3d67ce8
diff --git a/src/App.test.tsx b/src/App.test.tsxindex 0bdbc8d..df84447 100644--- a/src/App.test.tsx+++ b/src/App.test.tsx@@ -1,11 +1,12 @@// @vitest-environment jsdomimport "@testing-library/jest-dom/vitest";-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import App from "./App";import { ProjectCard, relativeDate } from "./components/ProjectCard";import { chooseOption, comboValue, optionNames } from "./components/workspace/comboTestUtils";+import { installBrowserGuards } from "./lib/nativeShell";import { createProjectConfig, STORY_TRACK_ID } from "./lib/project";describe("how long ago a project was edited", () => {@@ -126,6 +127,29 @@ describe("project library controls", () => {expect(within(menu).getAllByRole("menuitem").map((item) => item.textContent)).toEqual(["Open", "Delete project…"]);});+ it("answers Ctrl+F and Alt+Left through the browser guard, which only blocks what the app left alone", async () => {+ const uninstall = installBrowserGuards();+ try {+ render(<App />);+ await screen.findByText("Northern Light — Brand Film");+ const search = screen.getByRole("searchbox", { name: "Search projects" });+ const find = new KeyboardEvent("keydown", { key: "f", ctrlKey: true, bubbles: true, cancelable: true });+ act(() => { document.body.dispatchEvent(find); });+ expect(document.activeElement).toBe(search);+ expect(find.defaultPrevented).toBe(true);+ fireEvent.click(screen.getByRole("button", { name: "Settings" }));+ const settings = screen.getByRole("main", { name: "Settings" });+ const back = new KeyboardEvent("keydown", { key: "ArrowLeft", altKey: true, bubbles: true, cancelable: true });+ act(() => { settings.dispatchEvent(back); });+ expect(screen.queryByRole("main", { name: "Settings" })).toBeNull();+ expect(back.defaultPrevented).toBe(true);+ // Nothing claims Alt+Left in the library: still no browser Back.+ const idle = new KeyboardEvent("keydown", { key: "ArrowLeft", altKey: true, bubbles: true, cancelable: true });+ document.body.dispatchEvent(idle);+ expect(idle.defaultPrevented).toBe(true);+ } finally { uninstall(); }+ });+it("opens the tile menu with a right-click and moves the selection with the arrow keys", async () => {// Opening a video project mounts the program monitor; jsdom plays nothing.vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => undefined);diff --git a/src/App.tsx b/src/App.tsxindex bb4a0ab..a07dbb1 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -16,7 +16,6 @@ import { UpdateInfoBar, UpdatePanel, updateNeedsAttention } from "./components/Uimport { CommandBar, CommandBarButton, CommandBarSeparator, InfoBadge, InfoBar, TextField } from "./components/ui";import { AppUpdater } from "./lib/updater";import { useShortcut } from "./lib/commands";-import { useGuardedShortcut } from "./lib/shellKeys";import { useRunningExportName } from "./lib/exportJob";import { reportGenerationJobs, revealInExplorer, type GuardJob } from "./lib/nativeShell";import { describeDiagnosticError, errorContext, writeDiagnostic } from "./lib/diagnostics";@@ -292,8 +291,8 @@ function App() {useShortcut("Ctrl+,", () => openSettings(), { enabled: !settingsOpen, allowInInput: true });useShortcut("Ctrl+N", () => { if (!busy) void chooseCreationFolder(); }, { enabled: inLibrary, allowInInput: true });useShortcut("Ctrl+O", () => { if (!busy) void openFromFolder(); }, { enabled: inLibrary, allowInInput: true });- useGuardedShortcut("Ctrl+F", () => { searchInput.current?.focus(); searchInput.current?.select(); }, { enabled: inLibrary, allowInInput: true });- useGuardedShortcut("Alt+ArrowLeft", closeSettings, { enabled: settingsOpen });+ useShortcut("Ctrl+F", () => { searchInput.current?.focus(); searchInput.current?.select(); }, { enabled: inLibrary, allowInInput: true });+ useShortcut("Alt+ArrowLeft", closeSettings, { enabled: settingsOpen });const queueFlyout = <WorkQueuePanel queue={workQueue} items={workItems} open={workQueueOpen} anchor={settingsOpen ? settingsQueueButton : queueButton} onClose={() => setWorkQueueOpen(false)} />;const cudaNotice = cudaDownload && !settingsOpen && !workQueueOpen && !projectToDelete && !newProjectOpendiff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex 391b5d0..2f62129 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -6,7 +6,6 @@ import { CHECKING_PROVIDERS, executeAgentCommands, type RuntimeStatus, type Slopimport { purgeTimelineThumbnails } from "../lib/timelineThumbnails";import { WorkQueue, projectQueueKey } from "../lib/workQueue";import { useShortcut } from "../lib/commands";-import { useGuardedShortcut } from "../lib/shellKeys";import { AgentDock } from "./workspace/AgentDock";import { ExportView } from "./workspace/ExportView";import { GeneratorView } from "./workspace/GeneratorView";@@ -175,7 +174,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =}, { enabled: idle, allowInInput: true });useShortcut("Ctrl+E", () => { if (imageProject) { if (!imageExportDisabled) void exportImage(); } else setView("export"); }, { enabled: idle, allowInInput: true });useShortcut("Ctrl+Shift+A", toggleAgent, { enabled: idle, allowInInput: true });- useGuardedShortcut("Alt+ArrowLeft", goBack, { enabled: idle });+ useShortcut("Alt+ArrowLeft", goBack, { enabled: idle });const viewIcon = (id: ShownView) => id === "timeline" ? <Film size={16} /> : id === "generator" ? <Sparkles size={16} /> : id === "references" ? <BookOpen size={16} /> : id === "export" ? <Download size={16} /> : <Image size={16} />;const shortcutOf = (index: number) => `Ctrl+${index + 1}`;diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 1c868a4..7d1ff7b 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -603,7 +603,9 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl<><main aria-hidden={editingLoraId ? true : undefined} className="settings-view" ref={page} tabIndex={-1} aria-label="Settings" onKeyDown={(event: KeyboardEvent<HTMLElement>) => {// The mounted editor must not receive shortcuts while Settings has focus.- event.stopPropagation();+ // Alt+Left is Settings' own Back (App binds it while Settings is open),+ // so that one press is let through to the dispatcher.+ if (!(event.altKey && event.key === "ArrowLeft")) event.stopPropagation();if (event.key !== "Escape" || event.defaultPrevented) return;back();}}>diff --git a/src/lib/commands.ts b/src/lib/commands.tsindex 4f45471..2e2b81c 100644--- a/src/lib/commands.ts+++ b/src/lib/commands.ts@@ -19,7 +19,8 @@scoped INSIDE that dialog, or that pass `allowInModal`, can fire.4. Of the handlers that remain, the one whose `scope` element is theinnermost ancestor of the focused element wins; unscoped handlers are- the outermost. Ties go to the most recently registered handler.+ the outermost, and `fallback` handlers come after all of them. Ties go+ to the most recently registered handler.5. A handler may return `false` to decline, and the next candidate runs.Combos are written the way Windows displays them: "Ctrl+Shift+Z", "F2",@@ -194,6 +195,10 @@ export interface ShortcutOptions {preventDefault?: boolean;/** Fire even while a modal dialog is open (unscoped handlers are otherwise muted). */allowInModal?: boolean;+ /** Last resort: runs only when no other handler took the key. The browser+ * guard (nativeShell.ts) uses it to cancel Ctrl+F / Alt+Left's browser+ * action without keeping them from app shortcuts. */+ fallback?: boolean;}/** Return `false` to decline; the next matching handler then runs. */@@ -241,7 +246,7 @@ function dispatch(event: KeyboardEvent) {if (scope === null) continue; // a scoped handler whose element is goneif (scope && !scope.contains(target)) continue;if (modal && !options.allowInModal && !(scope && modal.contains(scope))) continue;- candidates.push({ registration, rank: scope ? depth(scope) : 0 });+ candidates.push({ registration, rank: options.fallback ? -1 : scope ? depth(scope) : 0 });}candidates.sort((a, b) => b.rank - a.rank || b.registration.order - a.registration.order);for (const { registration } of candidates) {diff --git a/src/lib/nativeShell.test.ts b/src/lib/nativeShell.test.tsindex 4c91109..f3f13dc 100644--- a/src/lib/nativeShell.test.ts+++ b/src/lib/nativeShell.test.ts@@ -42,6 +42,7 @@ import {minimizeWindow, onMaximizedChange, pickFile, reportGenerationJobs, revealInExplorer, setTaskbarProgress,setWindowTheme, textTarget, toggleMaximizeWindow, type SystemAccent,} from "./nativeShell";+import { registerShortcut } from "./commands";/* Windows' default blue (#0078d4) and the ramp UISettings reports for it. */const BLUE: SystemAccent = {@@ -249,6 +250,68 @@ describe("browser guards", () => {document.removeEventListener("keydown", handler);});+ it("blocks the browser's find and history keys when nothing in the app claims them", () => {+ for (const init of [{ key: "f", ctrlKey: true }, { key: "F", ctrlKey: true, shiftKey: true }, { key: "F3" }, { key: "F3", shiftKey: true },+ { key: "ArrowLeft", altKey: true }, { key: "ArrowRight", altKey: true }]) {+ expect(key(init).defaultPrevented, JSON.stringify(init)).toBe(true);+ }+ // Also from inside a text field and while a dialog is open.+ document.body.innerHTML = `<div aria-modal="true"><input id="field" /></div>`;+ expect(key({ key: "f", ctrlKey: true }, document.getElementById("field")!).defaultPrevented).toBe(true);+ expect(key({ key: "ArrowLeft", altKey: true }, document.getElementById("field")!).defaultPrevented).toBe(true);+ });++ it("lets useShortcut handlers take Ctrl+F, F3 and Alt+Left", () => {+ const calls: string[] = [];+ const off = [+ registerShortcut("Ctrl+F", () => { calls.push("find"); }),+ registerShortcut("F3", () => { calls.push("next"); }),+ registerShortcut("Alt+ArrowLeft", () => { calls.push("back"); }),+ ];+ expect(key({ key: "f", ctrlKey: true }).defaultPrevented).toBe(true);+ expect(key({ key: "F3" }).defaultPrevented).toBe(true);+ expect(key({ key: "ArrowLeft", altKey: true }).defaultPrevented).toBe(true);+ expect(calls).toEqual(["find", "next", "back"]);+ off.forEach((unregister) => unregister());+ });++ it("still blocks the browser when an app handler declines the key", () => {+ const off = registerShortcut("Alt+ArrowLeft", () => false);+ expect(key({ key: "ArrowLeft", altKey: true }).defaultPrevented).toBe(true);+ off();+ });++ it("leaves a key another listener already handled alone", () => {+ const back = vi.fn();+ const off = registerShortcut("Alt+ArrowLeft", back);+ document.body.innerHTML = `<div id="menu"></div>`;+ const menu = document.getElementById("menu")!;+ menu.addEventListener("keydown", (event) => event.preventDefault());+ expect(key({ key: "ArrowLeft", altKey: true }, menu).defaultPrevented).toBe(true);+ expect(back).not.toHaveBeenCalled();+ off();+ });++ it("blocks the browser when a component stops the key before the dispatcher sees it", () => {+ const back = vi.fn();+ const off = registerShortcut("Alt+ArrowLeft", back);+ document.body.innerHTML = `<div id="island"></div>`;+ const island = document.getElementById("island")!;+ island.addEventListener("keydown", (event) => event.stopPropagation());+ expect(key({ key: "ArrowLeft", altKey: true }, island).defaultPrevented).toBe(true);+ expect(key({ key: "f", ctrlKey: true }, island).defaultPrevented).toBe(true);+ expect(key({ key: "k", ctrlKey: true }, island).defaultPrevented).toBe(false);+ expect(back).not.toHaveBeenCalled();+ off();+ });++ it("stops handling the claimable keys once uninstalled", () => {+ uninstall();+ expect(key({ key: "f", ctrlKey: true }).defaultPrevented).toBe(false);+ expect(key({ key: "ArrowLeft", altKey: true }).defaultPrevented).toBe(false);+ uninstall = installBrowserGuards();+ });+it("refuses a drop nothing accepted, and leaves drop targets and dropzones alone", () => {const drag = (target: Element, accept = false) => {const event = new Event("dragover", { bubbles: true, cancelable: true });diff --git a/src/lib/nativeShell.ts b/src/lib/nativeShell.tsindex ad36f55..d446873 100644--- a/src/lib/nativeShell.ts+++ b/src/lib/nativeShell.ts@@ -14,6 +14,7 @@* module against half a mock.*/+import { matchesCombo, registerShortcut } from "./commands";import type { ResolvedTheme, ThemeChoice } from "./theme";/** True inside the desktop app. Same test as `isTauri` in persistence.ts, kept@@ -396,6 +397,18 @@ export function isBrowserShortcut(event: KeyboardEvent): boolean {return false;}+/** Browser keys that are ALSO Slopus commands: find (Ctrl+F, F3 — the Edge+ * find bar) and history (Alt+Left / Alt+Right — Back to the library, out of+ * Settings). installBrowserGuards blocks the browser's action on them only+ * after the app has had its chance to handle them. */+export const APP_CLAIMABLE_KEYS: readonly string[] = [+ "Ctrl+F", "Ctrl+Shift+F", "F3", "Shift+F3", "Alt+ArrowLeft", "Alt+ArrowRight",+];++export function isAppClaimableKey(event: KeyboardEvent): boolean {+ return APP_CLAIMABLE_KEYS.some((combo) => matchesCombo(event, combo));+}+const EDITABLE_INPUT = /^(text|search|url|email|password|number|tel)$/i;const SELECTABLE_TEXT = ".compiled-prompt__text";@@ -425,8 +438,11 @@ export function textTarget(target: EventTarget | null): { editable: boolean; has/** Installs the page-wide guards once, for the lifetime of the window:** • browser shortcuts (F5, Ctrl+R, Ctrl+P, …) do nothing;- * • Ctrl+F only reaches the Edge find bar when no app handler took it —- * checked after every other listener has run, never before;+ * • the browser keys Slopus also uses (Ctrl+F, F3, Alt+Left/Right; see+ * APP_CLAIMABLE_KEYS) are left for the app first: the guard is a+ * `fallback` registration in the commands.ts dispatcher, so it only runs+ * — and only then cancels the find bar or history navigation — when no+ * useShortcut handler took the key;* • a file dropped where nothing accepts it is refused instead of the* webview navigating to it (drop targets that call preventDefault on* dragover, or sit inside [data-dropzone], are untouched);@@ -436,17 +452,33 @@ export function textTarget(target: EventTarget | null): { editable: boolean; has* Returns an uninstall, for tests. */export function installBrowserGuards(target: Window = window): () => void {const doc = target.document;+ /* Capture phase: keys that are only ever the browser's are cancelled before+ anything else sees them. The claimable ones are not touched here — a+ prevented default would make the dispatcher skip them (its rule 1), and+ app shortcuts on them could never fire. */const onKeyDownCapture = (event: KeyboardEvent) => {- if (isBrowserShortcut(event)) event.preventDefault();- };- /* Bubble phase on the window: every React and document handler has had its- turn, so one that claimed Ctrl+F has already called preventDefault. */- const onKeyDownLate = (event: KeyboardEvent) => {- if (event.defaultPrevented) return;- const ctrl = event.ctrlKey || event.metaKey;- const find = (ctrl && !event.altKey && event.key.toLowerCase() === "f") || event.key === "F3";- if (find) event.preventDefault();+ if (!isAppClaimableKey(event)) {+ if (isBrowserShortcut(event)) event.preventDefault();+ return;+ }+ /* A component that stops the press on its way up (Settings keeps keys+ from the editor mounted under it) keeps it from the dispatcher, and so+ from the fallback below too. Nothing in the app can claim it then, so+ stopping it also cancels the browser's action. */+ for (const method of ["stopPropagation", "stopImmediatePropagation"] as const) {+ const original = event[method];+ event[method] = function (this: KeyboardEvent) {+ event.preventDefault();+ original.call(this);+ };+ }};+ /* The claimable keys go through the dispatcher as its last resort. A+ handler that takes the key prevents its default itself; a component that+ handles it with its own listener (a menu, a field) does too, and then the+ dispatcher leaves the press alone. Only an unclaimed press reaches this+ one, whose whole job is the default preventDefault. */+ const unregisterFallback = registerShortcut(APP_CLAIMABLE_KEYS, () => undefined, { fallback: true, allowInInput: true, allowInModal: true });const inDropzone = (event: Event) => event.target instanceof Element && !!event.target.closest("[data-dropzone]");const onDragOver = (event: DragEvent) => {if (event.defaultPrevented || inDropzone(event)) return;@@ -469,13 +501,12 @@ export function installBrowserGuards(target: Window = window): () => void {.catch(() => undefined);};target.addEventListener("keydown", onKeyDownCapture, true);- target.addEventListener("keydown", onKeyDownLate);doc.addEventListener("dragover", onDragOver);doc.addEventListener("drop", onDrop);doc.addEventListener("contextmenu", onContextMenu);return () => {target.removeEventListener("keydown", onKeyDownCapture, true);- target.removeEventListener("keydown", onKeyDownLate);+ unregisterFallback();doc.removeEventListener("dragover", onDragOver);doc.removeEventListener("drop", onDrop);doc.removeEventListener("contextmenu", onContextMenu);diff --git a/src/lib/shellKeys.ts b/src/lib/shellKeys.tsdeleted file mode 100644index f04de4c..0000000--- a/src/lib/shellKeys.ts+++ /dev/null@@ -1,39 +0,0 @@-/* Shortcuts the browser guard gets to first.-- installBrowserGuards (nativeShell.ts) cancels a few keys before the page- sees them — Alt+Left (browser Back) in the capture phase, and Ctrl+F (the- Edge find bar) in a window listener registered at startup, ahead of the- commands.ts dispatcher. The dispatcher skips any press whose default is- already prevented, so useShortcut can never fire for those keys in the- desktop app. These two ARE Slopus commands (Back to the library, Search- projects), so they listen on the document instead: a document listener- runs before any window listener in the bubble phase, and it ignores the- guard's preventDefault, which only exists to stop the browser's own action.-- Same rules as useShortcut otherwise: nothing while an aria-modal dialog is- open, text fields left alone unless `allowInInput`. */--import { useEffect, useRef } from "react";-import { isTextEntry, matchesCombo } from "./commands";--export function useGuardedShortcut(- combo: string,- handler: (event: KeyboardEvent) => void,- options: { enabled?: boolean; allowInInput?: boolean } = {},-) {- const handlerRef = useRef(handler);- handlerRef.current = handler;- const { enabled = true, allowInInput = false } = options;- useEffect(() => {- if (!enabled) return;- const onKeyDown = (event: KeyboardEvent) => {- if (event.isComposing || !matchesCombo(event, combo)) return;- if (document.querySelector('[aria-modal="true"]')) return;- if (!allowInInput && isTextEntry(event.target)) return;- event.preventDefault();- handlerRef.current(event);- };- document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [combo, enabled, allowInInput]);-}