Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add title bar, native shell helpers and Mica-aware theme boot

Bittie85f84ff8868
diff --git a/index.html b/index.html
index e4667a7..7328cd7 100644
--- a/index.html
+++ b/index.html
@@ -2,11 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <link rel="icon" type="image/png" href="/marketing/icon.png" />
- <meta name="theme-color" content="#080a0f" />
- <meta name="description" content="Slopus — an agentic video creation workspace." />
- <title>Slopus - 0.1.1</title>
+ <title>Slopus</title>
<!-- Parser-blocking on purpose: it paints the saved theme's ground before
anything reaches the screen, so a light-theme user never sees the dark
window flash through. Must stay a classic same-origin script — the
diff --git a/package-lock.json b/package-lock.json
index d9e6941..ca1fc97 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,7 @@
"version": "0.1.1",
"dependencies": {
"@tauri-apps/api": "^2.8.0",
+ "@tauri-apps/plugin-dialog": "^2.7.3",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.11.0",
"lucide-react": "^0.468.0",
@@ -1560,6 +1561,15 @@
"node": ">= 10"
}
},
+ "node_modules/@tauri-apps/plugin-dialog": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.3.tgz",
+ "integrity": "sha512-CRgE+7TP4tvq9MjBU6f04NLTFIqVMLKHk3hAqlhil00ngK9ACTrXPH3oHpKMProxILodd3YjBoKbMwSI4IEcfA==",
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@tauri-apps/api": "^2.11.0"
+ }
+ },
"node_modules/@tauri-apps/plugin-process": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.3.1.tgz",
diff --git a/package.json b/package.json
index 340773a..83d2440 100644
--- a/package.json
+++ b/package.json
@@ -15,6 +15,7 @@
},
"dependencies": {
"@tauri-apps/api": "^2.8.0",
+ "@tauri-apps/plugin-dialog": "^2.7.3",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.11.0",
"lucide-react": "^0.468.0",
diff --git a/public/theme-boot.js b/public/theme-boot.js
index f395ef5..3181589 100644
--- a/public/theme-boot.js
+++ b/public/theme-boot.js
@@ -14,6 +14,12 @@
* and deliberately duplicates the storage key and the two --bg values, because
* nothing here may depend on the bundle having loaded. theme.test.ts pins both
* copies against tokens.css so they cannot drift apart in silence.
+ *
+ * On Windows 11 the window is transparent with Mica behind it. Rust announces
+ * that through `window.__SLOPUS_BACKDROP__` (an initialization script, which
+ * runs before this file); it becomes <html data-backdrop="mica"> here, before
+ * the first paint, and the ground is left transparent so the backdrop shows.
+ * src/styles/window.css does the rest.
*/
(function () {
var GROUND = { dark: "#080a0f", light: "#eef1f6" };
@@ -30,6 +36,8 @@
}
var root = document.documentElement;
+ var mica = window.__SLOPUS_BACKDROP__ === "mica";
+ if (mica) root.setAttribute("data-backdrop", "mica");
if (choice === "system") root.removeAttribute("data-theme");
else root.setAttribute("data-theme", choice);
@@ -40,5 +48,5 @@
? "light"
: "dark";
}
- root.style.backgroundColor = GROUND[resolved];
+ root.style.backgroundColor = mica ? "transparent" : GROUND[resolved];
})();
diff --git a/src/components/TitleBar.test.tsx b/src/components/TitleBar.test.tsx
new file mode 100644
index 0000000..3b554d4
--- /dev/null
+++ b/src/components/TitleBar.test.tsx
@@ -0,0 +1,110 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const appWindow = vi.hoisted(() => ({
+ minimize: vi.fn(async () => undefined),
+ toggleMaximize: vi.fn(async () => undefined),
+ close: vi.fn(async () => undefined),
+ isMaximized: vi.fn(async () => false),
+ resized: [] as Array<() => void>,
+ focus: [] as Array<(event: { payload: boolean }) => void>,
+ onResized: vi.fn(async (handler: () => void) => {
+ appWindow.resized.push(handler);
+ return () => undefined;
+ }),
+ onFocusChanged: vi.fn(async (handler: (event: { payload: boolean }) => void) => {
+ appWindow.focus.push(handler);
+ return () => undefined;
+ }),
+}));
+vi.mock("@tauri-apps/api/window", () => ({ getCurrentWindow: () => appWindow }));
+
+import { TitleBar } from "./TitleBar";
+
+const flush = () => act(() => new Promise((resolve) => setTimeout(resolve, 0)));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ appWindow.resized = [];
+ appWindow.focus = [];
+ appWindow.isMaximized.mockResolvedValue(false);
+});
+afterEach(() => {
+ cleanup();
+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
+});
+
+it("lays out the slots in caption order and defaults the title to Slopus", () => {
+ render(
+ <TitleBar
+ leading={<button type="button">Back</button>}
+ secondary="Teaser folder"
+ actions={<button type="button">Save</button>}
+ >
+ <input aria-label="Search" />
+ </TitleBar>,
+ );
+ const bar = screen.getByRole("banner");
+ const order = [...bar.querySelectorAll("button, input, .titlebar__title, .titlebar__secondary")]
+ .map((element) => element.getAttribute("aria-label") ?? element.textContent);
+ expect(order).toEqual(["Back", "Slopus", "Teaser folder", "Search", "Save", "Minimize", "Maximize", "Close"]);
+});
+
+it("is one deep drag region, which Tauri's script stops at every control", () => {
+ render(<TitleBar title="Product teaser" />);
+ const bar = screen.getByRole("banner");
+ expect(bar).toHaveAttribute("data-tauri-drag-region", "deep");
+ /* The drag script treats a <button> without the attribute as a blocker, so
+ none of the caption buttons may carry it. */
+ for (const button of screen.getAllByRole("button")) expect(button).not.toHaveAttribute("data-tauri-drag-region");
+});
+
+it("draws the Windows caption glyphs and keeps them out of the tab order", () => {
+ render(<TitleBar />);
+ const minimize = screen.getByRole("button", { name: "Minimize" });
+ expect(minimize).toHaveAttribute("tabindex", "-1");
+ expect(minimize.textContent).toBe("\uE921");
+ expect(screen.getByRole("button", { name: "Close" }).textContent).toBe("\uE8BB");
+});
+
+it("can drop or replace the app icon", () => {
+ const { container, rerender } = render(<TitleBar />);
+ expect(container.querySelector(".titlebar__icon img")).not.toBeNull();
+ rerender(<TitleBar icon={false} />);
+ expect(container.querySelector(".titlebar__icon")).toBeNull();
+ rerender(<TitleBar icon={<svg data-testid="custom" />} />);
+ expect(screen.getByTestId("custom")).toBeInTheDocument();
+});
+
+it("does nothing outside Tauri", async () => {
+ render(<TitleBar />);
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ await flush();
+ expect(appWindow.close).not.toHaveBeenCalled();
+});
+
+it("drives the native window and follows its maximized and focus state", async () => {
+ Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
+ render(<TitleBar />);
+ await flush();
+
+ fireEvent.click(screen.getByRole("button", { name: "Minimize" }));
+ fireEvent.click(screen.getByRole("button", { name: "Maximize" }));
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ await flush();
+ expect(appWindow.minimize).toHaveBeenCalledOnce();
+ expect(appWindow.toggleMaximize).toHaveBeenCalledOnce();
+ expect(appWindow.close).toHaveBeenCalledOnce();
+
+ appWindow.isMaximized.mockResolvedValue(true);
+ await act(async () => { appWindow.resized.forEach((handler) => handler()); });
+ await flush();
+ const restore = screen.getByRole("button", { name: "Restore" });
+ expect(restore.textContent).toBe("\uE923");
+ expect(screen.getByRole("banner")).toHaveAttribute("data-maximized", "true");
+
+ await act(async () => { appWindow.focus.forEach((handler) => handler({ payload: false })); });
+ expect(screen.getByRole("banner")).toHaveClass("titlebar--inactive");
+});
diff --git a/src/components/TitleBar.tsx b/src/components/TitleBar.tsx
new file mode 100644
index 0000000..a24dc91
--- /dev/null
+++ b/src/components/TitleBar.tsx
@@ -0,0 +1,110 @@
+import { useEffect, useState, type ReactNode } from "react";
+import icon from "../../marketing/icon.png";
+import {
+ closeWindow, minimizeWindow, onMaximizedChange, onWindowFocusChange, toggleMaximizeWindow,
+} from "../lib/nativeShell";
+
+/* The window's title bar. The window is frameless (tauri.conf.json
+ `decorations: false`), so this row IS the caption: it drags the window,
+ double-clicking it maximizes and restores (Tauri's drag script does both),
+ and it carries the three caption buttons at the right edge.
+
+ Screens own what goes in it:
+
+ [leading] [icon title secondary] [children ········] [actions] [– □ ×]
+
+ The whole bar is a drag region "deep", so any plain text or empty space in
+ any slot drags the window; Tauri's drag script stops at the first button,
+ link, input, [tabindex] or interactive role on the way up, so the controls a
+ screen puts in a slot keep working without opting out. Something clickable
+ that is none of those needs `data-tauri-drag-region="false"`. */
+
+export interface TitleBarProps {
+ /** The window's caption, 12px. Defaults to "Slopus". */
+ title?: ReactNode;
+ /** Quieter text after the title, e.g. the open project's folder. */
+ secondary?: ReactNode;
+ /** Replaces the 16px app icon; `false` leaves it out. */
+ icon?: ReactNode | false;
+ /** Before the icon, e.g. a Back button. */
+ leading?: ReactNode;
+ /** The flexible middle, e.g. a search box or tabs. Fills the free width. */
+ children?: ReactNode;
+ /** Right-aligned, just before the caption buttons, e.g. Save. */
+ actions?: ReactNode;
+ className?: string;
+}
+
+/* Segoe Fluent Icons (Windows 11), with Segoe MDL2 Assets (Windows 10) at the
+ same code points, which is what Windows' own caption buttons draw. */
+const GLYPH = {
+ minimize: "",
+ maximize: "",
+ restore: "",
+ close: "",
+} as const;
+
+/** Follows the native maximized state. False outside Tauri. */
+export function useWindowMaximized(): boolean {
+ const [maximized, setMaximized] = useState(false);
+ useEffect(() => onMaximizedChange(setMaximized), []);
+ return maximized;
+}
+
+function useWindowFocused(): boolean {
+ const [focused, setFocused] = useState(true);
+ useEffect(() => onWindowFocusChange(setFocused), []);
+ return focused;
+}
+
+export function TitleBar({
+ title = "Slopus",
+ secondary,
+ icon: customIcon,
+ leading,
+ children,
+ actions,
+ className,
+}: TitleBarProps) {
+ const maximized = useWindowMaximized();
+ const focused = useWindowFocused();
+ const classes = ["titlebar", focused ? "" : "titlebar--inactive", className ?? ""].filter(Boolean).join(" ");
+ const run = (action: () => Promise<void>) => () => { void action().catch(() => undefined); };
+
+ return (
+ <header className={classes} data-tauri-drag-region="deep" data-maximized={maximized || undefined}>
+ {leading && <div className="titlebar__leading">{leading}</div>}
+ <div className="titlebar__identity">
+ {customIcon !== false && (
+ <span className="titlebar__icon" aria-hidden="true">
+ {customIcon ?? <img src={icon} alt="" draggable={false} />}
+ </span>
+ )}
+ <span className="titlebar__title">{title}</span>
+ {secondary && <span className="titlebar__secondary">{secondary}</span>}
+ </div>
+ <div className="titlebar__middle">{children}</div>
+ {actions && <div className="titlebar__actions">{actions}</div>}
+ {/* Not tab stops, like Windows' own: the keyboard reaches them through
+ Alt+Space, Win+Up/Down and Alt+F4. */}
+ <div className="titlebar__captions" role="group" aria-label="Window controls">
+ <button type="button" className="titlebar__caption" tabIndex={-1} aria-label="Minimize" title="Minimize" onClick={run(minimizeWindow)}>
+ <span aria-hidden="true">{GLYPH.minimize}</span>
+ </button>
+ <button
+ type="button"
+ className="titlebar__caption titlebar__caption--maximize"
+ tabIndex={-1}
+ aria-label={maximized ? "Restore" : "Maximize"}
+ title={maximized ? "Restore Down" : "Maximize"}
+ onClick={run(toggleMaximizeWindow)}
+ >
+ <span aria-hidden="true">{maximized ? GLYPH.restore : GLYPH.maximize}</span>
+ </button>
+ <button type="button" className="titlebar__caption titlebar__caption--close" tabIndex={-1} aria-label="Close" title="Close" onClick={run(closeWindow)}>
+ <span aria-hidden="true">{GLYPH.close}</span>
+ </button>
+ </div>
+ </header>
+ );
+}
diff --git a/src/lib/nativeShell.test.ts b/src/lib/nativeShell.test.ts
new file mode 100644
index 0000000..4c91109
--- /dev/null
+++ b/src/lib/nativeShell.test.ts
@@ -0,0 +1,303 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const appWindow = vi.hoisted(() => ({
+ minimize: vi.fn(async () => undefined),
+ toggleMaximize: vi.fn(async () => undefined),
+ close: vi.fn(async () => undefined),
+ isMaximized: vi.fn(async () => false),
+ setTheme: vi.fn(async () => undefined),
+ setProgressBar: vi.fn(async () => undefined),
+ resized: [] as Array<() => void>,
+ onResized: vi.fn(async (handler: () => void) => {
+ appWindow.resized.push(handler);
+ return () => { appWindow.resized = appWindow.resized.filter((entry) => entry !== handler); };
+ }),
+ onFocusChanged: vi.fn(async () => () => undefined),
+}));
+
+vi.mock("@tauri-apps/api/window", () => ({
+ getCurrentWindow: () => appWindow,
+ ProgressBarStatus: { None: "none", Normal: "normal", Indeterminate: "indeterminate", Paused: "paused", Error: "error" },
+}));
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => null) }));
+const listeners = vi.hoisted(() => new Map<string, (event: { payload: unknown }) => void>());
+vi.mock("@tauri-apps/api/event", () => ({
+ listen: vi.fn(async (name: string, handler: (event: { payload: unknown }) => void) => {
+ listeners.set(name, handler);
+ return () => listeners.delete(name);
+ }),
+}));
+vi.mock("@tauri-apps/plugin-dialog", () => ({
+ ask: vi.fn(async () => true),
+ message: vi.fn(async () => "Ok"),
+}));
+
+import { invoke } from "@tauri-apps/api/core";
+import { ask, message } from "@tauri-apps/plugin-dialog";
+import {
+ accentStylesheet, accentTokens, ACCENT_STYLE_ID, applySystemAccent, askNative, closeWindow, contrast,
+ followSystemAccent, inkOn, installBrowserGuards, isBrowserShortcut, isWindowMaximized, messageNative,
+ minimizeWindow, onMaximizedChange, pickFile, reportGenerationJobs, revealInExplorer, setTaskbarProgress,
+ setWindowTheme, textTarget, toggleMaximizeWindow, type SystemAccent,
+} from "./nativeShell";
+
+/* Windows' default blue (#0078d4) and the ramp UISettings reports for it. */
+const BLUE: SystemAccent = {
+ accent: "#0078d4",
+ light1: "#429ce3", light2: "#76b9ed", light3: "#99ebff",
+ dark1: "#005a9e", dark2: "#004275", dark3: "#002642",
+};
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+const setTauri = (on: boolean) => {
+ if (on) Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
+ else delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listeners.clear();
+ appWindow.resized = [];
+ document.getElementById(ACCENT_STYLE_ID)?.remove();
+});
+afterEach(() => setTauri(false));
+
+describe("outside Tauri", () => {
+ it("every helper is a no-op with the safe answer", async () => {
+ await minimizeWindow();
+ await toggleMaximizeWindow();
+ await closeWindow();
+ await setWindowTheme("light");
+ await setTaskbarProgress(0.5);
+ await revealInExplorer("C:\\file.mp4");
+ await reportGenerationJobs([{ title: "Shot", running: true }]);
+ await messageNative({ message: "Hi" });
+ expect(await isWindowMaximized()).toBe(false);
+ expect(await askNative({ message: "Delete?" })).toBe(false);
+ expect(await pickFile()).toBeNull();
+ const stop = onMaximizedChange(() => undefined);
+ stop();
+ followSystemAccent()();
+ await flush();
+ expect(invoke).not.toHaveBeenCalled();
+ expect(ask).not.toHaveBeenCalled();
+ expect(appWindow.minimize).not.toHaveBeenCalled();
+ });
+});
+
+describe("inside Tauri", () => {
+ beforeEach(() => setTauri(true));
+
+ it("drives the window", async () => {
+ await minimizeWindow();
+ await toggleMaximizeWindow();
+ await closeWindow();
+ expect(appWindow.minimize).toHaveBeenCalledOnce();
+ expect(appWindow.toggleMaximize).toHaveBeenCalledOnce();
+ expect(appWindow.close).toHaveBeenCalledOnce();
+ });
+
+ it("hands the theme to the native window, and system back to the OS", async () => {
+ await setWindowTheme("light");
+ await setWindowTheme("system");
+ expect(appWindow.setTheme).toHaveBeenNthCalledWith(1, "light");
+ expect(appWindow.setTheme).toHaveBeenNthCalledWith(2, null);
+ });
+
+ it("reports the maximized state now and on every change, once per change", async () => {
+ const seen: boolean[] = [];
+ const stop = onMaximizedChange((maximized) => seen.push(maximized));
+
+ await vi.waitFor(() => expect(appWindow.resized).toHaveLength(1));
+ expect(seen).toEqual([false]);
+ appWindow.isMaximized.mockResolvedValue(true);
+ appWindow.resized.forEach((handler) => handler());
+ await flush();
+ appWindow.resized.forEach((handler) => handler());
+ await flush();
+ expect(seen).toEqual([false, true]);
+ stop();
+ await flush();
+ expect(appWindow.resized).toHaveLength(0);
+ appWindow.isMaximized.mockResolvedValue(false);
+ });
+
+ it("asks and tells through the dialog plugin", async () => {
+ expect(await askNative({ title: "Delete project", message: "Delete it?", okLabel: "Delete", cancelLabel: "Keep" })).toBe(true);
+ expect(ask).toHaveBeenCalledWith("Delete it?", { title: "Delete project", kind: "warning", okLabel: "Delete", cancelLabel: "Keep" });
+ await messageNative({ message: "Done", okLabel: "Got it" });
+ expect(message).toHaveBeenCalledWith("Done", { title: undefined, kind: "info", buttons: { ok: "Got it" } });
+ });
+
+ it("calls the Rust commands with the names and arguments they declare", async () => {
+ await revealInExplorer("C:\\out\\film.mp4");
+ expect(invoke).toHaveBeenCalledWith("reveal_in_explorer", { path: "C:\\out\\film.mp4" });
+ vi.mocked(invoke).mockResolvedValueOnce("C:\\in\\a.png");
+ const filters = [{ name: "Images", extensions: ["png"] }];
+ expect(await pickFile({ title: "Pick", filters })).toBe("C:\\in\\a.png");
+ expect(invoke).toHaveBeenCalledWith("pick_file", { title: "Pick", filters });
+ await reportGenerationJobs([{ title: "Opening", running: true }]);
+ expect(invoke).toHaveBeenCalledWith("set_generation_active", { active: true, jobs: [{ title: "Opening", running: true }] });
+ await reportGenerationJobs([]);
+ expect(invoke).toHaveBeenLastCalledWith("set_generation_active", { active: false, jobs: [] });
+ });
+
+ it("puts progress on the taskbar button as a percentage, and clears it", async () => {
+ await setTaskbarProgress(0.426);
+ expect(appWindow.setProgressBar).toHaveBeenLastCalledWith({ status: "normal", progress: 43 });
+ await setTaskbarProgress(2, "error");
+ expect(appWindow.setProgressBar).toHaveBeenLastCalledWith({ status: "error", progress: 100 });
+ await setTaskbarProgress(null);
+ expect(appWindow.setProgressBar).toHaveBeenLastCalledWith({ status: "none" });
+ });
+
+ it("follows the accent: reads it once, then applies every change", async () => {
+ vi.mocked(invoke).mockResolvedValueOnce(BLUE);
+ const seen: Array<SystemAccent | null> = [];
+ const stop = followSystemAccent((accent) => seen.push(accent));
+ await flush();
+ expect(invoke).toHaveBeenCalledWith("system_accent_colors");
+ expect(document.getElementById(ACCENT_STYLE_ID)?.textContent).toContain("--accent: #76b9ed");
+ const green = { ...BLUE, light2: "#8ee39a", dark1: "#107c10" };
+ listeners.get("system-accent-changed")!({ payload: green });
+ expect(document.getElementById(ACCENT_STYLE_ID)?.textContent).toContain("--accent: #8ee39a");
+ expect(seen).toHaveLength(2);
+ stop();
+ await flush();
+ expect(listeners.size).toBe(0);
+ });
+});
+
+describe("accent tokens", () => {
+ it("fills with AccentLight2 in dark and AccentDark1 in light, as WinUI does", () => {
+ expect(accentTokens(BLUE, "dark")["--button-primary-bg"]).toBe("#76b9ed");
+ expect(accentTokens(BLUE, "light")["--button-primary-bg"]).toBe("#005a9e");
+ expect(accentTokens(BLUE, "dark")["--accent-bright"]).toBe("#99ebff");
+ expect(accentTokens(BLUE, "light")["--accent-bright"]).toBe("#004275");
+ });
+
+ it("puts black ink on a pale fill and white ink on a deep one, whichever reads better", () => {
+ expect(inkOn("#76b9ed")).toBe("#000000");
+ expect(inkOn("#005a9e")).toBe("#ffffff");
+ expect(accentTokens(BLUE, "dark")["--on-accent"]).toBe("#000000");
+ expect(accentTokens(BLUE, "light")["--on-accent"]).toBe("#ffffff");
+ /* And it is legible, not merely the better of two bad options, for the
+ default accent in both themes. */
+ expect(contrast("#76b9ed", "#000000")).toBeGreaterThan(4.5);
+ expect(contrast("#005a9e", "#ffffff")).toBeGreaterThan(4.5);
+ /* A mid-yellow accent must still get black. */
+ expect(inkOn("#ffb900")).toBe("#000000");
+ });
+
+ it("mirrors the three theme blocks of tokens.css so a theme switch needs no JavaScript", () => {
+ const css = accentStylesheet(BLUE);
+ expect(css).toContain(":root:root {");
+ expect(css).toContain('@media (prefers-color-scheme: light) {\n:root:root:not([data-theme="dark"]) {');
+ expect(css).toContain(':root:root[data-theme="light"] {');
+ });
+
+ it("removes itself for null or a malformed payload, putting the palette's blue back", () => {
+ applySystemAccent(BLUE);
+ expect(document.getElementById(ACCENT_STYLE_ID)).not.toBeNull();
+ expect(document.documentElement.hasAttribute("data-system-accent")).toBe(true);
+ applySystemAccent({ ...BLUE, light2: "blue" });
+ expect(document.getElementById(ACCENT_STYLE_ID)).toBeNull();
+ applySystemAccent(BLUE);
+ applySystemAccent(null);
+ expect(document.getElementById(ACCENT_STYLE_ID)).toBeNull();
+ expect(document.documentElement.hasAttribute("data-system-accent")).toBe(false);
+ });
+});
+
+describe("browser guards", () => {
+ let uninstall: () => void;
+ beforeEach(() => { uninstall = installBrowserGuards(); });
+ afterEach(() => { uninstall(); document.body.innerHTML = ""; });
+
+ const key = (init: KeyboardEventInit, target: EventTarget = document.body) => {
+ const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init });
+ target.dispatchEvent(event);
+ return event;
+ };
+
+ it("knows which keys belong to a browser tab", () => {
+ for (const init of [{ key: "F5" }, { key: "r", ctrlKey: true }, { key: "R", ctrlKey: true, shiftKey: true },
+ { key: "p", ctrlKey: true }, { key: "u", ctrlKey: true }, { key: "j", ctrlKey: true }, { key: "g", ctrlKey: true },
+ { key: "ArrowLeft", altKey: true }, { key: "ArrowRight", altKey: true }]) {
+ expect(isBrowserShortcut(new KeyboardEvent("keydown", init)), JSON.stringify(init)).toBe(true);
+ }
+ for (const init of [{ key: "k", ctrlKey: true }, { key: "c", ctrlKey: true }, { key: "a", ctrlKey: true },
+ { key: "ArrowLeft" }, { key: "r" }]) {
+ expect(isBrowserShortcut(new KeyboardEvent("keydown", init)), JSON.stringify(init)).toBe(false);
+ }
+ });
+
+ it("swallows reload and print but leaves ordinary shortcuts alone", () => {
+ expect(key({ key: "F5" }).defaultPrevented).toBe(true);
+ expect(key({ key: "r", ctrlKey: true }).defaultPrevented).toBe(true);
+ expect(key({ key: "k", ctrlKey: true }).defaultPrevented).toBe(false);
+ });
+
+ it("lets an app handler see Ctrl+F untouched, and only then stops the find bar", () => {
+ let seenPrevented: boolean | null = null;
+ const handler = (event: KeyboardEvent) => { seenPrevented = event.defaultPrevented; };
+ document.addEventListener("keydown", handler);
+ expect(key({ key: "f", ctrlKey: true }).defaultPrevented).toBe(true);
+ expect(seenPrevented).toBe(false);
+ document.removeEventListener("keydown", handler);
+ });
+
+ 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 });
+ if (accept) target.addEventListener("dragover", (e) => e.preventDefault(), { once: true });
+ target.dispatchEvent(event);
+ return event;
+ };
+ document.body.innerHTML = `<div id="plain"></div><div data-dropzone><span id="zone"></span></div>`;
+ expect(drag(document.getElementById("plain")!).defaultPrevented).toBe(true);
+ expect(drag(document.getElementById("zone")!).defaultPrevented).toBe(false);
+ const drop = new Event("drop", { bubbles: true, cancelable: true });
+ document.getElementById("plain")!.dispatchEvent(drop);
+ expect(drop.defaultPrevented).toBe(true);
+ });
+
+ it("replaces the browser's right-click menu, asking Rust for a text menu only over text", async () => {
+ setTauri(true);
+ document.body.innerHTML = `<input id="field" value="hello" /><input id="locked" readonly value="x" /><div id="plain">x</div><input id="box" type="checkbox" />`;
+ const right = (id: string) => {
+ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
+ document.getElementById(id)!.dispatchEvent(event);
+ return event;
+ };
+ expect(right("plain").defaultPrevented).toBe(true);
+ expect(right("box").defaultPrevented).toBe(true);
+ await flush();
+ expect(invoke).not.toHaveBeenCalled();
+ expect(right("field").defaultPrevented).toBe(true);
+ await flush();
+ expect(invoke).toHaveBeenCalledWith("show_text_context_menu", { request: { editable: true, hasSelection: false } });
+ right("locked");
+ await flush();
+ expect(invoke).toHaveBeenLastCalledWith("show_text_context_menu", { request: { editable: false, hasSelection: false } });
+ });
+
+ it("stays out of the way of a menu the app shows itself", async () => {
+ setTauri(true);
+ document.body.innerHTML = `<input id="field" />`;
+ const field = document.getElementById("field")!;
+ field.addEventListener("contextmenu", (event) => event.preventDefault(), { once: true });
+ field.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
+ await flush();
+ expect(invoke).not.toHaveBeenCalled();
+ });
+
+ it("reads a selection in a field", () => {
+ document.body.innerHTML = `<textarea id="text">hello world</textarea>`;
+ const text = document.getElementById("text") as HTMLTextAreaElement;
+ text.setSelectionRange(0, 5);
+ expect(textTarget(text)).toEqual({ editable: true, hasSelection: true });
+ });
+});
diff --git a/src/lib/nativeShell.ts b/src/lib/nativeShell.ts
new file mode 100644
index 0000000..ad36f55
--- /dev/null
+++ b/src/lib/nativeShell.ts
@@ -0,0 +1,483 @@
+/* The page's half of the native shell (src-tauri/src/native_shell.rs).
+ *
+ * Everything that makes the Slopus window behave like a Windows app rather
+ * than a web page: the caption buttons' window calls, native message boxes,
+ * Explorer and the Open dialog, the taskbar progress bar, the Windows accent
+ * colour, and the guards that switch off what a browser tab would do with a
+ * key press, a dropped file or a right click.
+ *
+ * Every helper here is safe to call anywhere. Outside Tauri — the Vite dev
+ * server in a browser, and the jsdom test runner — each one is a no-op that
+ * resolves to the "nothing happened" answer (false, null, undefined). The
+ * Tauri modules are imported lazily, and only once `inTauri()` is true, so a
+ * test that mocks `@tauri-apps/api/core` alone never evaluates the window
+ * module against half a mock.
+ */
+
+import type { ResolvedTheme, ThemeChoice } from "./theme";
+
+/** True inside the desktop app. Same test as `isTauri` in persistence.ts, kept
+ * local so this file (which theme.ts reaches for) pulls in nothing else. */
+export const inTauri = (): boolean =>
+ typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
+
+/* Each module is imported once and the promise kept: a burst of callers at
+ startup (the title bar asks for the maximized state while it subscribes to
+ resizes) then shares one load instead of racing several. */
+let coreModule: Promise<typeof import("@tauri-apps/api/core")> | undefined;
+let windowModule: Promise<typeof import("@tauri-apps/api/window")> | undefined;
+const core = () => (coreModule ??= import("@tauri-apps/api/core"));
+const windowApi = () => (windowModule ??= import("@tauri-apps/api/window"));
+const currentWindow = async () => (await windowApi()).getCurrentWindow();
+
+/* ── Window controls ─────────────────────────────────────────────────────── */
+
+export async function minimizeWindow(): Promise<void> {
+ if (!inTauri()) return;
+ await (await currentWindow()).minimize();
+}
+
+export async function toggleMaximizeWindow(): Promise<void> {
+ if (!inTauri()) return;
+ await (await currentWindow()).toggleMaximize();
+}
+
+/** Asks the window to close. It goes through the same CloseRequested path as
+ * Alt+F4, so the exit guard still asks while something is generating. */
+export async function closeWindow(): Promise<void> {
+ if (!inTauri()) return;
+ await (await currentWindow()).close();
+}
+
+export async function isWindowMaximized(): Promise<boolean> {
+ if (!inTauri()) return false;
+ try {
+ return await (await currentWindow()).isMaximized();
+ } catch {
+ return false;
+ }
+}
+
+/** Calls back with the maximized state now and whenever it changes (any
+ * resize — caption button, double-click, Win+Up, Aero Snap — is checked).
+ * Returns an unsubscribe that is safe to call before the listener exists. */
+export function onMaximizedChange(callback: (maximized: boolean) => void): () => void {
+ if (!inTauri()) return () => {};
+ let disposed = false;
+ let last: boolean | undefined;
+ let checking = false;
+ let again = false;
+ /* A drag-resize fires dozens of events a second; one isMaximized() round
+ trip at a time is plenty, with one more queued behind it. */
+ const check = async () => {
+ if (checking) { again = true; return; }
+ checking = true;
+ try {
+ do {
+ again = false;
+ const maximized = await isWindowMaximized();
+ if (!disposed && maximized !== last) {
+ last = maximized;
+ callback(maximized);
+ }
+ } while (again && !disposed);
+ } finally {
+ checking = false;
+ }
+ };
+ void check();
+ const stop = currentWindow()
+ .then((appWindow) => appWindow.onResized(() => { void check(); }))
+ .catch(() => undefined);
+ return () => {
+ disposed = true;
+ void stop.then((unlisten) => unlisten?.());
+ };
+}
+
+/** Calls back when the window gains or loses focus, so a title bar can dim
+ * its caption the way every Windows app does when it is not the active one.
+ * Returns an unsubscribe. */
+export function onWindowFocusChange(callback: (focused: boolean) => void): () => void {
+ if (!inTauri()) return () => {};
+ let disposed = false;
+ const stop = currentWindow()
+ .then((appWindow) => appWindow.onFocusChanged(({ payload }) => { if (!disposed) callback(payload); }))
+ .catch(() => undefined);
+ return () => {
+ disposed = true;
+ void stop.then((unlisten) => unlisten?.());
+ };
+}
+
+/** Keeps the native window's theme — the Mica tint, the context menus, the
+ * message boxes — on the page's choice. "system" hands it back to the OS. */
+export async function setWindowTheme(choice: ThemeChoice): Promise<void> {
+ if (!inTauri()) return;
+ try {
+ await (await currentWindow()).setTheme(choice === "system" ? null : choice);
+ } catch {
+ /* An old capability file without set-theme costs the tint, not the app. */
+ }
+}
+
+/* ── Message boxes ───────────────────────────────────────────────────────── */
+
+export type NativeDialogKind = "info" | "warning" | "error";
+
+export interface AskNativeOptions {
+ title?: string;
+ message: string;
+ kind?: NativeDialogKind;
+ /** The confirming button, e.g. "Delete". Windows default: "OK". */
+ okLabel?: string;
+ /** The declining button, e.g. "Keep". Windows default: "Cancel". */
+ cancelLabel?: string;
+}
+
+/** A native yes/no question. Resolves true for the OK button; Esc, the
+ * cancel button and the box's own close button all resolve false — and so
+ * does every call outside Tauri, because the safe answer to "delete this?"
+ * when nobody can be asked is no. */
+export async function askNative(options: AskNativeOptions): Promise<boolean> {
+ if (!inTauri()) return false;
+ const { ask } = await import("@tauri-apps/plugin-dialog");
+ return ask(options.message, {
+ title: options.title,
+ kind: options.kind ?? "warning",
+ okLabel: options.okLabel,
+ cancelLabel: options.cancelLabel,
+ });
+}
+
+export interface MessageNativeOptions {
+ title?: string;
+ message: string;
+ kind?: NativeDialogKind;
+ okLabel?: string;
+}
+
+/** A native message box with one button. */
+export async function messageNative(options: MessageNativeOptions): Promise<void> {
+ if (!inTauri()) return;
+ const { message } = await import("@tauri-apps/plugin-dialog");
+ await message(options.message, {
+ title: options.title,
+ kind: options.kind ?? "info",
+ buttons: options.okLabel ? { ok: options.okLabel } : "Ok",
+ });
+}
+
+/* ── Files ────────────────────────────────────────────────────────────────── */
+
+/** Opens File Explorer with the file selected. Rejects with Rust's message
+ * when the path does not exist. */
+export async function revealInExplorer(path: string): Promise<void> {
+ if (!inTauri()) return;
+ const { invoke } = await core();
+ await invoke("reveal_in_explorer", { path });
+}
+
+export interface FileFilter {
+ name: string;
+ /** Without the dot: ["png", "jpg"]. */
+ extensions: string[];
+}
+
+/** The system Open dialog for one file. Null when cancelled. */
+export async function pickFile(options: { title?: string; filters?: FileFilter[] } = {}): Promise<string | null> {
+ if (!inTauri()) return null;
+ const { invoke } = await core();
+ return (await invoke<string | null>("pick_file", { title: options.title, filters: options.filters })) ?? null;
+}
+
+/* ── Taskbar ──────────────────────────────────────────────────────────────── */
+
+export type TaskbarProgressState = "normal" | "indeterminate" | "paused" | "error";
+
+/** The progress bar on the taskbar button. `fraction` is 0…1; null clears the
+ * bar (and so does any call with nothing to show). */
+export async function setTaskbarProgress(
+ fraction: number | null,
+ state: TaskbarProgressState = "normal",
+): Promise<void> {
+ if (!inTauri()) return;
+ const { getCurrentWindow, ProgressBarStatus } = await windowApi();
+ const status = {
+ normal: ProgressBarStatus.Normal,
+ indeterminate: ProgressBarStatus.Indeterminate,
+ paused: ProgressBarStatus.Paused,
+ error: ProgressBarStatus.Error,
+ }[state];
+ if (fraction === null && state !== "indeterminate") {
+ await getCurrentWindow().setProgressBar({ status: ProgressBarStatus.None });
+ return;
+ }
+ const progress = Math.round(Math.min(1, Math.max(0, Number.isFinite(fraction) ? (fraction as number) : 0)) * 100);
+ await getCurrentWindow().setProgressBar({ status, progress });
+}
+
+/* ── Exit guard ───────────────────────────────────────────────────────────── */
+
+export interface GuardJob {
+ title: string;
+ /** Rendering right now, rather than waiting in the queue. */
+ running: boolean;
+}
+
+/** Tells Rust what would be lost if the window closed now. The native exit
+ * question (window.rs) names these jobs; an empty list lets the window close
+ * without asking. */
+export async function reportGenerationJobs(jobs: GuardJob[]): Promise<void> {
+ if (!inTauri()) return;
+ const { invoke } = await core();
+ await invoke("set_generation_active", {
+ active: jobs.length > 0,
+ jobs: jobs.map(({ title, running }) => ({ title, running })),
+ });
+}
+
+/* ── Accent colour ────────────────────────────────────────────────────────── */
+
+/** The Windows accent palette, `#rrggbb` each (native_shell.rs AccentColors). */
+export interface SystemAccent {
+ accent: string;
+ light1: string;
+ light2: string;
+ light3: string;
+ dark1: string;
+ dark2: string;
+ dark3: string;
+}
+
+const ACCENT_EVENT = "system-accent-changed";
+export const ACCENT_STYLE_ID = "system-accent";
+
+type Rgb = [number, number, number];
+
+function parseHex(hex: string): Rgb | null {
+ const match = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
+ if (!match) return null;
+ const value = parseInt(match[1], 16);
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
+}
+
+const channel = (value: number) => {
+ const c = value / 255;
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+};
+const luminance = ([r, g, b]: Rgb) => 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
+
+/** WCAG contrast ratio of two `#rrggbb` colours. */
+export function contrast(a: string, b: string): number {
+ const [x, y] = [parseHex(a), parseHex(b)];
+ if (!x || !y) return 1;
+ const [hi, lo] = [luminance(x), luminance(y)].sort((p, q) => q - p);
+ return (hi + 0.05) / (lo + 0.05);
+}
+
+/** Black or white, whichever reads better on `fill`. Windows does the same:
+ * black on the pale dark-theme fill, white on the deep light-theme one. */
+export function inkOn(fill: string): "#000000" | "#ffffff" {
+ return contrast(fill, "#000000") >= contrast(fill, "#ffffff") ? "#000000" : "#ffffff";
+}
+
+const alpha = (hex: string, opacity: number) => {
+ const rgb = parseHex(hex) ?? [0, 0, 0];
+ return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${opacity})`;
+};
+
+/** The accent tokens tokens.css defines, derived the way WinUI derives its
+ * accent brushes: AccentLight2 fills in the dark theme and AccentDark1 in
+ * the light one; accent TEXT is one step further from the ground (Light3 /
+ * Dark2); hover and pressed are the fill at 90 % and 80 %. */
+export function accentTokens(accent: SystemAccent, theme: ResolvedTheme): Record<string, string> {
+ const dark = theme === "dark";
+ const fill = dark ? accent.light2 : accent.dark1;
+ const text = dark ? accent.light3 : accent.dark2;
+ const ink = inkOn(fill);
+ return {
+ "--accent": fill,
+ "--accent-bright": text,
+ "--accent-fill": fill,
+ "--accent-dark": fill,
+ "--accent-soft": alpha(fill, dark ? 0.15 : 0.1),
+ "--accent-soft-strong": alpha(fill, dark ? 0.22 : 0.16),
+ "--accent-on-soft": text,
+ "--accent-line": alpha(text, dark ? 0.28 : 0.3),
+ "--accent-line-strong": alpha(text, dark ? 0.55 : 0.6),
+ "--accent-ring": alpha(fill, dark ? 0.1 : 0.14),
+ "--button-primary-bg": fill,
+ "--button-primary-hover": `color-mix(in srgb, ${fill} 90%, transparent)`,
+ "--button-primary-active": `color-mix(in srgb, ${fill} 80%, transparent)`,
+ "--on-accent": ink,
+ "--on-accent-dim": alpha(ink, 0.35),
+ };
+}
+
+const block = (selector: string, tokens: Record<string, string>) =>
+ `${selector} {\n${Object.entries(tokens).map(([name, value]) => ` ${name}: ${value};`).join("\n")}\n}`;
+
+/** The stylesheet text for one accent. It mirrors the three blocks of
+ * tokens.css — dark on :root, light twice (the OS media query guarded by
+ * :not([data-theme="dark"]), and the explicit attribute) — so a theme switch
+ * repaints through CSS alone. `:root:root` outranks tokens.css's own
+ * selectors by one class, whatever order the two sheets end up in. */
+export function accentStylesheet(accent: SystemAccent): string {
+ const dark = accentTokens(accent, "dark");
+ const light = accentTokens(accent, "light");
+ return [
+ block(":root:root", dark),
+ `@media (prefers-color-scheme: light) {\n${block(':root:root:not([data-theme="dark"])', light)}\n}`,
+ block(':root:root[data-theme="light"]', light),
+ ].join("\n");
+}
+
+const isAccent = (value: unknown): value is SystemAccent =>
+ !!value && typeof value === "object"
+ && (["accent", "light1", "light2", "light3", "dark1", "dark2", "dark3"] as const)
+ .every((key) => typeof (value as Record<string, unknown>)[key] === "string"
+ && parseHex((value as Record<string, string>)[key]) !== null);
+
+/** Paints the accent, or with null (or anything malformed) removes it, which
+ * puts the palette's own blue from tokens.css back. */
+export function applySystemAccent(accent: SystemAccent | null): void {
+ if (typeof document === "undefined") return;
+ const existing = document.getElementById(ACCENT_STYLE_ID);
+ if (!isAccent(accent)) {
+ existing?.remove();
+ document.documentElement.removeAttribute("data-system-accent");
+ return;
+ }
+ const style = existing ?? Object.assign(document.createElement("style"), { id: ACCENT_STYLE_ID });
+ style.textContent = accentStylesheet(accent);
+ /* Last in <head>, so it also follows every stylesheet Vite injects. */
+ document.head.appendChild(style);
+ document.documentElement.setAttribute("data-system-accent", "");
+}
+
+/** Reads the Windows accent once, then follows it. `onChange` is optional:
+ * the tokens are applied either way. Returns an unsubscribe. */
+export function followSystemAccent(onChange?: (accent: SystemAccent | null) => void): () => void {
+ if (!inTauri()) return () => {};
+ let disposed = false;
+ const apply = (accent: SystemAccent | null) => {
+ if (disposed) return;
+ applySystemAccent(accent);
+ onChange?.(accent);
+ };
+ /* Listen first, then ask: a change landing between the two is then seen
+ by the listener rather than lost. */
+ const stop = import("@tauri-apps/api/event")
+ .then(({ listen }) => listen<SystemAccent>(ACCENT_EVENT, (event) => apply(event.payload)))
+ .catch(() => undefined);
+ void stop
+ .then(async () => (await core()).invoke<SystemAccent | null>("system_accent_colors"))
+ .then((accent) => apply(accent ?? null))
+ .catch(() => undefined);
+ return () => {
+ disposed = true;
+ void stop.then((unlisten) => unlisten?.());
+ };
+}
+
+/* ── Browser guards ───────────────────────────────────────────────────────── */
+
+/** Keys that do something to a BROWSER TAB — reload, print, view source,
+ * downloads, find-next, history — and nothing in Slopus. WebView2's own
+ * accelerators are switched off in release builds (native_shell.rs); this is
+ * the fallback for debug builds and older runtimes. */
+export function isBrowserShortcut(event: KeyboardEvent): boolean {
+ const key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
+ const ctrl = event.ctrlKey || event.metaKey;
+ if (key === "F5" || key === "BrowserRefresh" || key === "BrowserBack" || key === "BrowserForward") return true;
+ if (event.altKey && !ctrl && (key === "ArrowLeft" || key === "ArrowRight")) return true;
+ if (ctrl && !event.altKey && ["r", "p", "u", "j", "g"].includes(key)) return true;
+ return false;
+}
+
+const EDITABLE_INPUT = /^(text|search|url|email|password|number|tel)$/i;
+const SELECTABLE_TEXT = ".compiled-prompt__text";
+
+/** What the text context menu needs to know about a right-clicked element, or
+ * null when it is not text. */
+export function textTarget(target: EventTarget | null): { editable: boolean; hasSelection: boolean } | null {
+ if (!(target instanceof Element)) return null;
+ const field = target.closest("input, textarea");
+ if (field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) {
+ if (field instanceof HTMLInputElement && !EDITABLE_INPUT.test(field.type || "text")) return null;
+ let hasSelection = false;
+ try {
+ hasSelection = field.selectionStart !== null && field.selectionStart !== field.selectionEnd;
+ } catch {
+ /* type=number/email throw on selectionStart in some engines. */
+ }
+ return { editable: !field.readOnly && !field.disabled, hasSelection };
+ }
+ const selection = typeof window.getSelection === "function" ? window.getSelection() : null;
+ const hasSelection = !!selection && !selection.isCollapsed && selection.toString().length > 0;
+ const editableHost = target.closest("[contenteditable]:not([contenteditable='false'])");
+ if (editableHost) return { editable: true, hasSelection };
+ if (target.closest(SELECTABLE_TEXT) || hasSelection) return { editable: false, hasSelection };
+ return null;
+}
+
+/** 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;
+ * • 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);
+ * • right-click: a menu the app shows itself wins; over text a native
+ * Cut/Copy/Paste/Select all menu replaces Edge's; elsewhere nothing.
+ *
+ * Returns an uninstall, for tests. */
+export function installBrowserGuards(target: Window = window): () => void {
+ const doc = target.document;
+ 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();
+ };
+ const inDropzone = (event: Event) => event.target instanceof Element && !!event.target.closest("[data-dropzone]");
+ const onDragOver = (event: DragEvent) => {
+ if (event.defaultPrevented || inDropzone(event)) return;
+ /* Cancelling dragover is what stops the webview treating the page as a
+ place to open files; dropEffect "none" keeps the no-entry cursor. */
+ event.preventDefault();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "none";
+ };
+ const onDrop = (event: DragEvent) => {
+ if (event.defaultPrevented || inDropzone(event)) return;
+ event.preventDefault();
+ };
+ const onContextMenu = (event: MouseEvent) => {
+ if (event.defaultPrevented) return;
+ event.preventDefault();
+ const text = textTarget(event.target);
+ if (!text || !inTauri()) return;
+ void core()
+ .then(({ invoke }) => invoke("show_text_context_menu", { request: text }))
+ .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);
+ doc.removeEventListener("dragover", onDragOver);
+ doc.removeEventListener("drop", onDrop);
+ doc.removeEventListener("contextmenu", onContextMenu);
+ };
+}
diff --git a/src/lib/theme.test.ts b/src/lib/theme.test.ts
index 3ec497f..0605fbb 100644
--- a/src/lib/theme.test.ts
+++ b/src/lib/theme.test.ts
@@ -3,7 +3,7 @@
import { readdirSync, readFileSync } from "node:fs";
import { beforeEach, describe, expect, it } from "vitest";
import {
- applyTheme, loadTheme, resolveTheme, saveTheme, systemTheme,
+ applyTheme, BACKDROP_GLOBAL, hasMicaBackdrop, loadTheme, resolveTheme, saveTheme, systemTheme,
THEME_BACKGROUND, THEME_KEY, watchSystemTheme,
} from "./theme";
@@ -55,6 +55,8 @@ describe("theme preference", () => {
beforeEach(() => {
localStorage.clear();
document.documentElement.removeAttribute("data-theme");
+ document.documentElement.removeAttribute("data-backdrop");
+ delete (window as unknown as Record<string, unknown>)[BACKDROP_GLOBAL];
document.documentElement.style.backgroundColor = "";
stubMatchMedia(false);
});
@@ -99,6 +101,24 @@ describe("theme preference", () => {
expect(document.documentElement.style.backgroundColor).toBe("rgb(8, 10, 15)");
});
+ it("paints no ground at all over Mica, in either theme", () => {
+ /* Any inline colour would sit on top of the backdrop and hide it. */
+ (window as unknown as Record<string, unknown>)[BACKDROP_GLOBAL] = "mica";
+ stubMatchMedia(true);
+ applyTheme("system");
+ expect(document.documentElement.style.backgroundColor).toBe("transparent");
+ applyTheme("dark");
+ expect(document.documentElement.style.backgroundColor).toBe("transparent");
+ /* The native global becomes the attribute window.css keys on, even when
+ theme-boot.js never ran. */
+ expect(document.documentElement.getAttribute("data-backdrop")).toBe("mica");
+ });
+
+ it("keeps the solid ground where there is no Mica", () => {
+ expect(hasMicaBackdrop()).toBe(false);
+ expect(document.documentElement.hasAttribute("data-backdrop")).toBe(false);
+ });
+
it("reports OS changes and unsubscribes cleanly", () => {
const media = stubMatchMedia(false);
const seen: string[] = [];
@@ -216,10 +236,23 @@ describe("tokens.css", () => {
expect(rust).toContain("set_background_color");
expect(rust).toContain("tauri::Theme::Light");
- /* index.html's meta ships the dark ground and applyTheme rewrites it on
- every switch, so the static value only has to be a real palette entry. */
- expect(read("index.html").toLowerCase()).toContain(`content="${THEME_BACKGROUND.dark.toLowerCase()}"`);
- expect(read("src/lib/theme.ts")).toContain('meta[name="theme-color"]');
+ /* index.html used to ship a theme-color meta that applyTheme rewrote on
+ every switch. A desktop window has no browser chrome for it to tint, so
+ both are gone; this keeps them from drifting back in as a sixth copy. */
+ expect(read("index.html")).not.toContain("theme-color");
+ expect(read("src/lib/theme.ts")).not.toContain("theme-color");
+ });
+
+ it("goes transparent under Mica in the boot script as well as in theme.ts", () => {
+ /* theme-boot.js runs before the bundle, so it has to know about the
+ backdrop on its own; otherwise the first frame paints an opaque ground
+ over Mica and the window flashes solid before theme.ts clears it. */
+ const boot = read("public/theme-boot.js");
+ expect(boot).toContain(BACKDROP_GLOBAL);
+ expect(boot).toContain('setAttribute("data-backdrop", "mica")');
+ expect(boot).toContain('"transparent"');
+ /* And the global is the one Rust actually sets. */
+ expect(read("src-tauri/src/native_shell.rs")).toContain(`"${BACKDROP_GLOBAL}"`);
});
});
@@ -434,6 +467,16 @@ function ruleBlocks(css: string): { selector: string; body: string }[] {
/** Rule → why that rule is allowed to name a colour. Keyed by file name. */
const LITERALS_ALLOWED: Record<string, Record<string, string>> = {
+ "titlebar.css": {
+ /* Windows paints its own close button this way in every app and in both
+ themes: #C42B1C with a white glyph. It is the system's caption mark, not
+ a surface of this palette, and a themed red here would be the one close
+ button on the desktop that looks different. */
+ ".titlebar__caption--close:hover":
+ "the Windows caption close red with its white glyph, identical in both themes",
+ ".titlebar__caption--close:active":
+ "the pressed shade of the same Windows caption close red",
+ },
"library.css": {
/* library.css says all of this in prose above the rules; the point of
repeating it here is that the guard knows, not that a reader does. */
diff --git a/src/lib/theme.ts b/src/lib/theme.ts
index 1f7c137..d299357 100644
--- a/src/lib/theme.ts
+++ b/src/lib/theme.ts
@@ -21,6 +21,8 @@
* fall back to the bare `:root` dark palette. Do not "simplify" that guard.
*/
+import { setWindowTheme } from "./nativeShell";
+
export type ThemeChoice = "system" | "light" | "dark";
/** What actually gets painted once the choice is resolved against the OS. */
@@ -32,11 +34,13 @@ const LEGACY_THEME_KEY = "polstudio.theme.v1";
export const THEME_CHOICES: readonly ThemeChoice[] = ["system", "light", "dark"];
/* The two grounds, duplicated from tokens.css (--bg). They are needed BEFORE
- any stylesheet exists — the boot snippet in index.html paints the document
- with one of them so the window never flashes the other theme — so this is
- the one place a raw colour is allowed outside tokens.css. Keep them in step
- with `--bg`; the test in theme.test.ts reads tokens.css and fails if they
- drift. */
+ any stylesheet exists — public/theme-boot.js paints the document with one
+ of them so the window never flashes the other theme — so this is the one
+ place a raw colour is allowed outside tokens.css. Keep them in step with
+ `--bg`; the test in theme.test.ts reads tokens.css and fails if they drift.
+
+ Under Mica (Windows 11) neither is painted: the ground is the backdrop
+ itself, see `hasMicaBackdrop` below and src/styles/window.css. */
export const THEME_BACKGROUND: Record<ResolvedTheme, string> = {
dark: "#080a0f",
light: "#eef1f6",
@@ -78,22 +82,41 @@ export function resolveTheme(choice: ThemeChoice): ResolvedTheme {
return choice === "system" ? systemTheme() : choice;
}
+/** The global src-tauri/src/native_shell.rs sets from an initialization
+ * script — before any page script — when the window has Mica behind it. */
+export const BACKDROP_GLOBAL = "__SLOPUS_BACKDROP__";
+
+/** True when the window is transparent with Mica behind it. Read from the
+ * attribute theme-boot.js writes, or straight from the native global when
+ * that script never ran (a test renderer, a stripped index.html), in which
+ * case the attribute is written here. */
+export function hasMicaBackdrop(): boolean {
+ const root = document.documentElement;
+ if (root.getAttribute("data-backdrop") === "mica") return true;
+ const native = (window as unknown as Record<string, unknown>)[BACKDROP_GLOBAL] === "mica";
+ if (native) root.setAttribute("data-backdrop", "mica");
+ return native;
+}
+
/** Writes the choice onto <html> and repaints the document ground.
*
- * The ground is set inline as well as by CSS because index.html sets it that
- * way before the stylesheet has loaded; leaving a stale inline colour behind
- * would out-specify the stylesheet and strand the old theme's background
- * under the new theme's panels. */
+ * The ground is set inline as well as by CSS because theme-boot.js sets it
+ * that way before the stylesheet has loaded; leaving a stale inline colour
+ * behind would out-specify the stylesheet and strand the old theme's
+ * background under the new theme's panels. Under Mica the inline ground is
+ * `transparent`, for the same reason in reverse: any colour there would
+ * cover the backdrop.
+ *
+ * It also hands the choice to the native window, whose theme tints Mica and
+ * the system menus and message boxes. */
export function applyTheme(choice: ThemeChoice): ResolvedTheme {
const root = document.documentElement;
if (choice === "system") root.removeAttribute("data-theme");
else root.setAttribute("data-theme", choice);
const resolved = resolveTheme(choice);
- root.style.backgroundColor = THEME_BACKGROUND[resolved];
-
- const meta = document.querySelector('meta[name="theme-color"]');
- if (meta) meta.setAttribute("content", THEME_BACKGROUND[resolved]);
+ root.style.backgroundColor = hasMicaBackdrop() ? "transparent" : THEME_BACKGROUND[resolved];
+ void setWindowTheme(choice);
return resolved;
}
diff --git a/src/main.tsx b/src/main.tsx
index 9f65324..3d2c3ab 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -2,6 +2,7 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { installGlobalDiagnostics } from "./lib/diagnostics";
+import { followSystemAccent, installBrowserGuards } from "./lib/nativeShell";
import { applyTheme, loadTheme, watchSystemTheme } from "./lib/theme";
import "./styles/index.css";
@@ -11,24 +12,25 @@ import "./styles/index.css";
applyTheme(loadTheme());
installGlobalDiagnostics();
-/* Only "system" needs watching, and only for the inline ground colour and the
- theme-color meta — tokens.css repaints the app itself through
+/* Only "system" needs watching, and only for the inline ground colour —
+ tokens.css repaints the app itself through
`@media (prefers-color-scheme)` with no JavaScript involved. The listener is
never torn down because it lives exactly as long as the window does. */
watchSystemTheme(() => {
if (loadTheme() === "system") applyTheme("system");
});
+/* The Windows accent colour replaces the palette's own blue, live; with no
+ accent to read (a browser, Windows without UISettings) tokens.css stays. */
+followSystemAccent();
+
/* Slopus is an application window, not a web page. The browser's own
context menu offers Back, Reload, View source and Inspect — none of which
- mean anything here, and Reload throws away unsaved project edits. Text
- fields and compiled prompts keep theirs: copy/paste are useful here, and
- taking them away would cost the user more than the menu is worth. */
-document.addEventListener("contextmenu", (event) => {
- const target = event.target as HTMLElement | null;
- if (target?.closest("input, textarea, [contenteditable='true'], .compiled-prompt__text")) return;
- event.preventDefault();
-});
+ mean anything here — and F5 / Ctrl+R reload the page and throw away
+ unsaved project edits. Text fields and compiled prompts keep a menu, but a
+ native Cut/Copy/Paste/Select all one rather than Edge's. A dropped file
+ no longer navigates the window away. See installBrowserGuards. */
+installBrowserGuards();
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
diff --git a/src/styles/titlebar.css b/src/styles/titlebar.css
new file mode 100644
index 0000000..4d0f77a
--- /dev/null
+++ b/src/styles/titlebar.css
@@ -0,0 +1,153 @@
+/* ============================================================================
+ Title bar — src/components/TitleBar.tsx.
+
+ The window is frameless, so this row is the whole Windows caption: 48px
+ tall, like Photos, Clipchamp and Terminal, where the app's own header and
+ the caption are one strip. It is transparent on purpose: under Mica
+ (window.css) the backdrop shows through it exactly as it does through a
+ native caption, and on Windows 10 it sits on the solid ground.
+
+ The three caption buttons follow Windows 11's own metrics — 46px wide, the
+ full height of the bar, square, glyphs from Segoe Fluent Icons at 10px —
+ and its colours: a subtle wash on hover, a lighter one pressed, and on the
+ close button the system's #C42B1C with a white glyph in BOTH themes. That
+ red is the only colour literal in this file; theme.test.ts exempts exactly
+ those two rules and says why.
+
+ No cursor rule anywhere: the caption is arrow-cursor territory, as in every
+ native window.
+ ========================================================================== */
+
+.titlebar {
+ display: flex;
+ align-items: center;
+ flex: none;
+ height: 48px;
+ min-width: 0;
+ background: transparent;
+ color: var(--text-primary);
+ font-family: var(--font-sans);
+ font-size: 12px;
+ line-height: 16px;
+ -webkit-user-select: none;
+ user-select: none;
+}
+
+.titlebar__leading,
+.titlebar__actions {
+ display: flex;
+ align-items: center;
+ flex: none;
+ gap: 4px;
+ height: 100%;
+}
+
+.titlebar__leading {
+ padding-left: 4px;
+}
+
+.titlebar__actions {
+ padding: 0 8px;
+}
+
+.titlebar__identity {
+ display: flex;
+ align-items: center;
+ flex: 0 1 auto;
+ gap: 12px;
+ min-width: 0;
+ padding: 0 8px 0 16px;
+}
+
+/* A leading slot (Back) already provides the left inset. */
+.titlebar__leading + .titlebar__identity {
+ padding-left: 4px;
+}
+
+.titlebar__icon {
+ display: inline-grid;
+ place-items: center;
+ flex: none;
+ width: 16px;
+ height: 16px;
+}
+
+.titlebar__icon > img,
+.titlebar__icon > svg {
+ width: 16px;
+ height: 16px;
+}
+
+.titlebar__title,
+.titlebar__secondary {
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.titlebar__title {
+ flex: 0 1 auto;
+ min-width: 0;
+}
+
+.titlebar__secondary {
+ flex: 0 2 auto;
+ min-width: 0;
+ color: var(--text-secondary);
+}
+
+.titlebar__middle {
+ display: flex;
+ align-items: center;
+ flex: 1 1 0;
+ min-width: 0;
+ height: 100%;
+}
+
+/* A window that is not the active one greys its caption. */
+.titlebar--inactive .titlebar__title,
+.titlebar--inactive .titlebar__secondary,
+.titlebar--inactive .titlebar__caption {
+ color: var(--text-muted);
+}
+
+.titlebar__captions {
+ display: flex;
+ flex: none;
+ align-self: stretch;
+}
+
+.titlebar__caption {
+ display: grid;
+ place-items: center;
+ width: 46px;
+ height: 100%;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: var(--text-primary);
+ font-family: "Segoe Fluent Icons", "Segoe MDL2 Assets", sans-serif;
+ font-size: 10px;
+ line-height: 1;
+ transition: background-color var(--motion-fast) linear, color var(--motion-fast) linear;
+}
+
+.titlebar__caption:hover {
+ background: var(--wash-2);
+}
+
+.titlebar__caption:active {
+ background: var(--wash-1);
+ color: var(--text-secondary);
+}
+
+.titlebar__caption--close:hover {
+ background: #c42b1c;
+ color: #ffffff;
+}
+
+.titlebar__caption--close:active {
+ background: #c93f33;
+ color: #ffffff;
+}
diff --git a/src/styles/window.css b/src/styles/window.css
new file mode 100644
index 0000000..54ddaa1
--- /dev/null
+++ b/src/styles/window.css
@@ -0,0 +1,39 @@
+/* ============================================================================
+ The window itself — what sits under every screen.
+
+ MICA. On Windows 11 the window is transparent with the Mica backdrop behind
+ it (src-tauri/src/native_shell.rs), and <html data-backdrop="mica"> says so
+ from before the first paint (public/theme-boot.js). Here that attribute
+ turns the app's ground transparent, so the title bar and navigation stand
+ on Mica the way a native app's do; content layers keep painting their own
+ --panel on top. Without the attribute — Windows 10, a browser — nothing in
+ this block applies and the solid --bg from tokens.css stays.
+
+ `:root:root` outranks the three --bg declarations in tokens.css (bare
+ :root, the media-guarded light block and [data-theme="light"]) by one
+ class, so this holds in both themes whatever order the sheets load in.
+ The inline ground theme.ts writes is `transparent` under Mica too.
+
+ Anything that painted --bg as an OPAQUE plate — a cut-out, a mask edge, a
+ sticky header meant to hide what scrolls under it — becomes see-through
+ under Mica and must use --panel (or a layer token) instead.
+ ========================================================================== */
+
+:root:root[data-backdrop="mica"] {
+ --bg: transparent;
+}
+
+:root[data-backdrop="mica"],
+:root[data-backdrop="mica"] body {
+ background: transparent;
+}
+
+/* ── Nothing drags out of the window ──────────────────────────────────────
+ An image or a link dragged in a browser becomes a file or a URL on the
+ desktop; in an app window it is the logo and the card thumbnails coming
+ loose. Elements the app itself makes draggable (scene cards, clips, library
+ rows) set draggable="true" and are left alone. */
+img:not([draggable="true"]),
+a:not([draggable="true"]) {
+ -webkit-user-drag: none;
+}