Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(appshot): a CleanShot X-style editor that opens over any view

rubenluetke10-beepc9c80f12b3e6
diff --git a/docs/appshots.md b/docs/appshots.md
index 7856b55dc1..eccd5cf3b1 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -60,13 +60,9 @@ After the shutter the picture flies into the bottom-right corner of its
screen and rests there as a card for about six seconds (longer while the
pointer is on it):
-- **Click** opens the app on the Appshots page with the **appshot editor**:
- arrow, rectangle, ellipse, pen, highlighter, text, pixelate and crop, with
- undo/redo (Ctrl+Z / Ctrl+Y) and one-key tools (A, R, E, P, H, T, B, C).
- **Copy** puts the result on the clipboard, **Save** downloads a PNG, and
- **Use this version** replaces the held appshot, so the next message carries
- the edited picture (a picture already sent into a voice call stays as it
- was). The last appshot on the Appshots page opens the same editor.
+- **Click** brings the app to the front with the **appshot editor** open
+ over whatever was on screen (nothing navigates away). See
+ [The editor](#the-editor).
- **Drag** the card into any app that accepts files or images (chat, mail,
Explorer/Finder) to drop the picture there.
- **Right-click** dismisses it.
@@ -78,6 +74,72 @@ moment an appshot touches disk: the picture is written to
on the next drag. With `[screen_context].deck_preview_s = 0` (keep nothing)
the card only opens the editor and shares nothing.
+## The editor
+
+The editor follows CleanShot X's annotate tool — same tools, same one-letter
+keys — in this app's own look. It opens from the corner card or from
+**Edit** on the last appshot (Settings → Appshots), as a full-window layer
+over the current view.
+
+| Key | Tool | What it does |
+|---|---|---|
+| V | Select and move | Click an annotation to select it; drag moves it, arrow keys nudge it (Shift = 10 px), Delete removes it. Double-click a text to change it. |
+| A / L | Arrow / Line | Shift snaps to 45°. |
+| R / F / E | Rectangle / Filled rectangle / Ellipse | Shift makes a square or circle. |
+| D | Draw | Freehand, smoothed. |
+| M | Highlighter | Translucent marker that keeps text underneath readable. |
+| T | Text | Plain, label (filled box) or outline style; Enter commits, Shift+Enter breaks the line. |
+| C | Counter | Numbered badges; each click adds the next number. |
+| H | Spotlight | Dims everything outside the dragged areas. |
+| P | Pixelate or blur | Hides a region; the options bar switches between pixelate and blur. |
+| K | Crop | Free, 1:1, 4:3 or 16:9; undo brings the rest back. |
+| B | Background | Frames the picture on a backdrop (eight presets, padding, corner radius, shadow); applied on copy, save and use. |
+
+Colours: eight presets plus any colour from the system picker; the last one
+is remembered. Sizes: 1 / 2 / 3. History: Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y
+(⌘ on macOS).
+
+Results: **Copy** (Ctrl+C) puts the PNG on the clipboard — natively through
+`POST /api/appshot/clipboard` on the desktop, the browser clipboard
+elsewhere. **Save** (Ctrl+S) writes it to Downloads through the backend
+(the desktop WebView drops browser downloads) and the toast offers "Show in
+folder". **Use this version** (Ctrl+Enter) replaces the held appshot so the
+next message carries the edit (a picture already sent into a voice call stays
+as it was). Escape cancels a stroke, then a selection, then closes; with
+unsaved edits it asks first.
+
+### Compared with CleanShot X
+
+Reference: [cleanshot.com/features](https://cleanshot.com/features) (checked
+2026-10-03). Status here: **done** = in the editor; **elsewhere** = Personal
+Jarvis covers it outside the editor; **not done** = not built, with the
+reason.
+
+| CleanShot X | Status |
+|---|---|
+| Arrow, line, rectangle, filled rectangle, ellipse, pencil, highlighter, text, counter, spotlight, pixelate, blur, crop with aspect ratio | Done |
+| Background tool (presets, padding, aspect/position) | Done: presets, padding, corners, shadow. Custom uploads, saved presets, auto-balance and aspect ratio of the frame are not done. |
+| Colour picker with saved palette | Done: presets + any colour, last one remembered (not a palette of several) |
+| Arrow styles (4 curved) | Not done: one straight arrow |
+| Text styles (7) | Partly: 3 styles |
+| Move/select annotations | Done |
+| Rotate, flip, resize image | Not done |
+| Combine images, editable project file | Not done |
+| Capture area / window / fullscreen, freeze, magnifier, crosshair | Elsewhere: the area picker and the window shortcut ([Selecting an area](#selecting-an-area)); no fullscreen mode |
+| Quick Access Overlay (copy / save / annotate / drag after capture) | Elsewhere: the corner card (click = editor, drag = file) |
+| Scrolling capture, self-timer | Not done (the page's "in 3 s" button is the only timer) |
+| Screen recording, video editor, GIF | Not done |
+| Cloud upload and sharing | Not done — appshots stay on this machine by design |
+| Text recognition (OCR), QR codes | Not done in the editor; the model reads the picture itself when it gets it |
+| Pin to screen (floating screenshot) | Not done: needs an always-on-top native window per OS |
+| Capture history | Not done: only the last appshot is kept, in memory |
+
+Every editor feature is web code in the app's own WebView, so it behaves the
+same on Windows, macOS and Linux. The two native paths are the clipboard
+(Windows `CF_DIB` + PNG, macOS `osascript`, Linux `wl-copy` or `xclip` —
+without either, Copy falls back to the browser clipboard and says so if that
+fails too) and Save (`~/Downloads` on every OS).
+
## Where a shortcut appshot goes
| Destination | Running voice call | No voice call |
@@ -155,8 +217,11 @@ last appshot, memory only), `gesture.py` (both-Alt watcher), `hotkey.py`
mapping), `picker/` (the area picker sidecar), `effect.py` (shutter hook),
`delivery.py` (voice calls). The corner card lives in the indicator sidecar
(`jarvis/cu/indicator/renderer.py`, `_CardWindow`); the editor is
-`frontend/src/views/AppshotEditor.tsx` with its document model in
-`lib/appshotEditorModel.ts`.
+`frontend/src/views/AppshotEditor.tsx`, hosted by
+`components/appshot/AppshotEditorHost.tsx` (opened through
+`store/appshotEditor.ts`), with its document model in
+`lib/appshotEditorModel.ts`, the copy path in `lib/appshotClipboard.ts` and
+the native clipboard in `jarvis/platform/clipboard_image.py`.
The live model's `take_appshot` tool is `jarvis/plugins/tool/appshot.py`; the
REST surface is `jarvis/ui/web/appshot_routes.py`; the page is
`frontend/src/views/AppshotsView.tsx`.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 323a9b1884..695e67307d 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -640,7 +640,7 @@ implementations, not stubs.
|---|---|
| Computer-Use / desktop actions (click, type, hotkey, scroll, drag, windows, apps, screenshots, UI trees) | Full per-OS backends (Win32/UIA, Quartz/AX, xdotool/AT-SPI); honest degradation on Wayland/headless/missing TCC grants |
| On-demand Screen Context | One-shot capture is wired into the production brain on Windows, macOS, and Linux/X11; UIA/AX/AT-SPI text is source-filtered, the indicator precedes capture, and Wayland/headless/missing grants refuse honestly |
-| Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The two-sided shortcuts (both Alt, both Shift, both Ctrl) read key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (Input Monitoring grant), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash and the area picker (both Shift keys, drag a rectangle) are PySide6 overlays where one can run; Wayland/headless report the area picker unavailable. Verified live on Windows only; see `docs/appshots.md` |
+| Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The two-sided shortcuts (both Alt, both Shift, both Ctrl) read key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (Input Monitoring grant), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash and the area picker (both Shift keys, drag a rectangle) are PySide6 overlays where one can run; Wayland/headless report the area picker unavailable. The appshot editor is web code and behaves the same everywhere; its Copy writes the PNG natively (`jarvis/platform/clipboard_image.py`): Windows `CF_DIB` + the registered PNG format, macOS `osascript` as `«class PNGf»`, Linux `wl-copy` or `xclip`, and with neither the browser clipboard. Save goes to `~/Downloads` on every OS. Verified live on Windows only; see `docs/appshots.md` |
| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows |
| Core (launcher, config, keyring, restart, autostart, tray, elevation, paths) | Clean; per-OS autostart (Registry / LaunchAgent / XDG `.desktop`), keyring falls back to a 0600 file on headless hosts |
| Data / agents (wiki, contacts, telephony, sessions, missions, skills, self-mod, channels, MCP) | Clean; mission workers run on POSIX with a real process-group reaper |
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index a3d5be31de..e006145dff 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -27,6 +27,7 @@ import { VoiceWarmingBanner } from "@/components/layout/VoiceWarmingBanner";
import { MainView } from "@/components/layout/MainView";
import { ToastLayer } from "@/components/ToastLayer";
import { CommandActivityLayer } from "@/components/CommandActivityLayer";
+import { AppshotEditorHost } from "@/components/appshot/AppshotEditorHost";
import { EditContextMenu } from "@/components/EditContextMenu";
/*
Lazy on purpose. The overlay pulls in the dialog primitives, the keyboard
@@ -347,6 +348,9 @@ export default function App() {
</main>
<ToastLayer />
<CommandActivityLayer />
+ {/* Only this window's own "Edit" opens it here; the card's request
+ goes to the main window (handleAppshotEditRequest). */}
+ <AppshotEditorHost />
<EditContextMenu />
<ZoomIndicator />
{shortcutsOpen && (
@@ -421,6 +425,9 @@ export default function App() {
<ToastLayer />
<CommandActivityLayer />
+ {/* The appshot editor, over whatever is open (a click on the appshot
+ card in the screen corner opens it). */}
+ <AppshotEditorHost />
{/* Right-click Cut/Copy/Paste. The desktop WebView ships with its own
context menu disabled, so without this there is no mouse-driven paste
anywhere in the app — including the IDE terminals. */}
diff --git a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx b/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
index 29a4e7ed14..fb7c863b9a 100644
--- a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
@@ -41,12 +41,13 @@ export function ToastLayer() {
const dismiss = useEventStore((s) => s.dismissToast);
return (
- // z-[60]: the onboarding gate overlays the whole app at z-50 and renders
- // later in the DOM; toasts (e.g. failed permission requests during
- // first-run setup) must stay visible above it.
+ // z-[100]: above everything that reports through a toast — the
+ // onboarding gate (z-50, rendered later in the DOM), dialogs, and the
+ // full-window appshot editor (z-95), whose Save toast carries the "Show
+ // in folder" action.
// top-12: below the caption strip — at the top edge a toast covered the
// restart and window buttons whose outcome it reports.
- <div className="pointer-events-none fixed right-4 top-12 z-[60] flex w-[320px] flex-col gap-2">
+ <div className="pointer-events-none fixed right-4 top-12 z-[100] flex w-[320px] flex-col gap-2">
{toasts.map((toast) => {
const Icon = ICON_FOR_KIND[toast.kind];
// A saved-file toast in the desktop shell is a native drag handle: press
diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx
new file mode 100644
index 0000000000..59c675a42c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx
@@ -0,0 +1,184 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { AppshotEditorHost } from "@/components/appshot/AppshotEditorHost";
+import { handleAppshotEditRequest, useAppshotEditor } from "@/store/appshotEditor";
+import { useEventStore } from "@/store/events";
+
+/**
+ * The appshot editor's lifecycle: a click on the appshot card (the
+ * `AppshotEditRequested` event) opens it over whatever is on screen — it
+ * never navigates — and closing it, with or without edits, leaves the app
+ * where it was. The reload that used to wipe it lived in the desktop shell
+ * (tests/unit/ui/test_desktop_show_window.py).
+ */
+
+class LoadedImage {
+ naturalWidth = 400;
+ naturalHeight = 300;
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+}
+
+class BrokenImage extends LoadedImage {
+ set src(_value: string) {
+ queueMicrotask(() => this.onerror?.());
+ }
+}
+
+// jsdom has no PointerEvent; without one the coordinates of a fired pointer
+// event are lost and every stroke looks like a stray click.
+class TestPointerEvent extends MouseEvent {
+ pointerId: number;
+ constructor(type: string, init: PointerEventInit = {}) {
+ super(type, init);
+ this.pointerId = init.pointerId ?? 1;
+ }
+}
+
+function json(body: unknown, status = 200): Response {
+ return { ok: status < 400, status, json: async () => body } as Response;
+}
+
+describe("AppshotEditorHost", () => {
+ beforeEach(() => {
+ useEventStore.setState({ events: [], toasts: [], assistantName: "Jarvis", activeSection: "chats" });
+ useAppshotEditor.setState({ openId: null, revision: 0 });
+ vi.stubGlobal("Image", LoadedImage);
+ vi.stubGlobal("PointerEvent", TestPointerEvent);
+ vi.stubGlobal("fetch", vi.fn(async () => json({ native_file_actions: false, platform: "linux" })));
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("opens over the current view when the card asks, without navigating", async () => {
+ render(<AppshotEditorHost />);
+ expect(screen.queryByTestId("appshot-editor")).toBeNull();
+
+ act(() => {
+ expect(handleAppshotEditRequest({ appshot_id: "shot-1" }, { solo: false })).toBe("opened");
+ });
+
+ expect(await screen.findByTestId("appshot-editor")).toBeDefined();
+ expect(useEventStore.getState().activeSection).toBe("chats");
+ await waitFor(() => expect(screen.getByTestId("appshot-editor-canvas")).toBeDefined());
+ });
+
+ it("closes on Escape when nothing was edited", async () => {
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ await screen.findByTestId("appshot-editor-canvas");
+
+ fireEvent.keyDown(window, { key: "Escape" });
+
+ await waitFor(() => expect(screen.queryByTestId("appshot-editor")).toBeNull());
+ expect(useAppshotEditor.getState().openId).toBeNull();
+ });
+
+ it("switches tools with CleanShot's keys", async () => {
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ await screen.findByTestId("appshot-editor-canvas");
+
+ fireEvent.keyDown(window, { key: "r" });
+ expect(screen.getByTestId("appshot-editor-tool-rect").getAttribute("aria-pressed")).toBe("true");
+ fireEvent.keyDown(window, { key: "k" });
+ expect(screen.getByTestId("appshot-editor-tool-crop").getAttribute("aria-pressed")).toBe("true");
+ expect(screen.getByTestId("appshot-editor-crop-ratio")).toBeDefined();
+ fireEvent.keyDown(window, { key: "p" });
+ expect(screen.getByTestId("appshot-editor-redact-mode")).toBeDefined();
+ });
+
+ it("asks before throwing edits away, and undo/redo follow the drawing", async () => {
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ const canvas = await screen.findByTestId("appshot-editor-canvas");
+
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 10, clientY: 10, pointerId: 1 });
+ fireEvent.pointerMove(canvas, { clientX: 120, clientY: 90, pointerId: 1 });
+ fireEvent.pointerUp(canvas, { clientX: 120, clientY: 90, pointerId: 1 });
+
+ const undoButton = screen.getByTestId("appshot-editor-undo") as HTMLButtonElement;
+ await waitFor(() => expect(undoButton.disabled).toBe(false));
+
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(await screen.findByTestId("appshot-editor-discard")).toBeDefined();
+ // Escape again keeps editing.
+ fireEvent.keyDown(window, { key: "Escape" });
+ await waitFor(() => expect(screen.queryByTestId("appshot-editor-discard")).toBeNull());
+ expect(screen.getByTestId("appshot-editor")).toBeDefined();
+
+ fireEvent.keyDown(window, { key: "z", ctrlKey: true });
+ await waitFor(() => expect(undoButton.disabled).toBe(true));
+ expect((screen.getByTestId("appshot-editor-redo") as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.keyDown(window, { key: "z", ctrlKey: true, shiftKey: true });
+ await waitFor(() => expect(undoButton.disabled).toBe(false));
+
+ fireEvent.click(screen.getByTestId("appshot-editor-close"));
+ fireEvent.click(await screen.findByTestId("appshot-editor-discard-confirm"));
+ await waitFor(() => expect(useAppshotEditor.getState().openId).toBeNull());
+ });
+
+ it("selects, nudges and deletes an annotation with the move tool", async () => {
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ const canvas = await screen.findByTestId("appshot-editor-canvas");
+
+ fireEvent.keyDown(window, { key: "f" });
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 20, clientY: 20, pointerId: 1 });
+ fireEvent.pointerMove(canvas, { clientX: 80, clientY: 80, pointerId: 1 });
+ fireEvent.pointerUp(canvas, { clientX: 80, clientY: 80, pointerId: 1 });
+
+ fireEvent.keyDown(window, { key: "v" });
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 50, clientY: 50, pointerId: 2 });
+ fireEvent.pointerUp(canvas, { clientX: 50, clientY: 50, pointerId: 2 });
+ expect(await screen.findByTestId("appshot-editor-delete")).toBeDefined();
+
+ fireEvent.keyDown(window, { key: "ArrowRight", shiftKey: true });
+ fireEvent.keyDown(window, { key: "Delete" });
+ await waitFor(() => expect(screen.queryByTestId("appshot-editor-delete")).toBeNull());
+ // Drawing, nudging and removing are three undoable steps.
+ for (let i = 0; i < 2; i += 1) {
+ fireEvent.keyDown(window, { key: "z", ctrlKey: true });
+ expect((screen.getByTestId("appshot-editor-undo") as HTMLButtonElement).disabled).toBe(false);
+ }
+ fireEvent.keyDown(window, { key: "z", ctrlKey: true });
+ await waitFor(() =>
+ expect((screen.getByTestId("appshot-editor-undo") as HTMLButtonElement).disabled).toBe(true),
+ );
+ });
+
+ it("says when the appshot is gone instead of showing an empty editor", async () => {
+ vi.stubGlobal("Image", BrokenImage);
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("gone-1"));
+
+ expect(await screen.findByTestId("appshot-editor-failed")).toBeDefined();
+ });
+});
+
+describe("handleAppshotEditRequest", () => {
+ beforeEach(() => useAppshotEditor.setState({ openId: null, revision: 0 }));
+
+ it("opens the editor on the requested appshot", () => {
+ expect(handleAppshotEditRequest({ appshot_id: "a1" }, { solo: false })).toBe("opened");
+ expect(useAppshotEditor.getState().openId).toBe("a1");
+ });
+
+ it("leaves a detached window alone", () => {
+ expect(handleAppshotEditRequest({ appshot_id: "a1" }, { solo: true })).toBe("ignored");
+ expect(useAppshotEditor.getState().openId).toBeNull();
+ });
+
+ it("reports an appshot that is no longer kept", () => {
+ expect(handleAppshotEditRequest({ appshot_id: "" }, { solo: false })).toBe("gone");
+ expect(handleAppshotEditRequest(null, { solo: false })).toBe("gone");
+ expect(useAppshotEditor.getState().openId).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx
new file mode 100644
index 0000000000..274b02c12e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx
@@ -0,0 +1,48 @@
+import { Suspense, lazy } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+
+import { useAppshotEditor } from "@/store/appshotEditor";
+
+// The editor and its strings load only when someone edits an appshot.
+const AppshotEditor = lazy(() =>
+ import("@/views/AppshotEditor").then((m) => ({ default: m.AppshotEditor })),
+);
+
+/**
+ * The one place the appshot editor lives: a full-window dialog over whatever
+ * view is open, so a click on the appshot card opens it without navigating
+ * anywhere.
+ *
+ * A Radix dialog, not a plain layer: over the Settings dialog (the Appshots
+ * page's "Edit" button) it stacks as the top modal — its clicks are not
+ * "outside" Settings, its text box can take focus, and Escape reaches only
+ * the editor. Escape and outside presses are left to the editor itself, which
+ * cancels a stroke or asks before discarding edits.
+ */
+export function AppshotEditorHost() {
+ const openId = useAppshotEditor((s) => s.openId);
+ const close = useAppshotEditor((s) => s.close);
+ const applied = useAppshotEditor((s) => s.applied);
+
+ return (
+ <Dialog.Root open={openId !== null} onOpenChange={(open) => !open && close()}>
+ <Dialog.Portal>
+ <Dialog.Content
+ aria-describedby={undefined}
+ onEscapeKeyDown={(event) => event.preventDefault()}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ onInteractOutside={(event) => event.preventDefault()}
+ className="fixed inset-0 z-[95] outline-none"
+ data-testid="appshot-editor-host"
+ >
+ <Dialog.Title className="sr-only">Appshot editor</Dialog.Title>
+ {openId !== null && (
+ <Suspense fallback={<div className="h-full w-full bg-background" />}>
+ <AppshotEditor key={openId} appshotId={openId} onClose={close} onApplied={applied} />
+ </Suspense>
+ )}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index a58ac905af..249fa995e0 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -24,7 +24,7 @@ import {
useCommandActivityStore,
COMMAND_ACTIVITY_EVENTS,
} from "@/store/commandActivity";
-import { useAppshotEditor } from "@/store/appshotEditor";
+import { handleAppshotEditRequest } from "@/store/appshotEditor";
import { useDeckStore } from "@/store/deck";
import { useHomeStore } from "@/store/home";
import { PANE_ACTIVITY_EVENT } from "@/store/workspacePanes";
@@ -156,17 +156,11 @@ export function useWebSocket(): void {
}
}
- // A click on the appshot card in the screen corner: open the editor on
- // the Appshots page. A detached solo window leaves it to the main one.
- if (env.event_name === "AppshotEditRequested" && !useEventStore.getState().solo) {
- const id = (env.payload as { appshot_id?: unknown }).appshot_id;
- if (typeof id === "string" && id) {
- setActiveSection("appshots");
- useAppshotEditor.getState().open(id);
- } else {
- setActiveSection("appshots");
- pushToast("warning", translate("appshots.editor.gone"));
- }
+ // A click on the appshot card in the screen corner: the editor opens
+ // over whatever is on screen (AppshotEditorHost) — no navigation.
+ if (env.event_name === "AppshotEditRequested") {
+ const outcome = handleAppshotEditRequest(env.payload, { solo: useEventStore.getState().solo });
+ if (outcome === "gone") pushToast("warning", translate("appshots.editor.gone"));
}
// Live reasoning trace: while the text chat is waiting on a reply,
diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.ts
index 237c5502de..3bb1605f97 100644
--- a/jarvis/ui/web/frontend/src/i18n/index.ts
+++ b/jarvis/ui/web/frontend/src/i18n/index.ts
@@ -98,7 +98,13 @@ export function loadUiLocale(lang: UiLanguage): Promise<void> {
* it mounts. Until the chunk has arrived, `t()` returns the key, so a view
* that cares waits for `ready` before it paints.
*/
-export type LocaleChunk = "marketplace" | "local_models" | "society" | "computers" | "onboarding";
+export type LocaleChunk =
+ | "marketplace"
+ | "local_models"
+ | "society"
+ | "computers"
+ | "onboarding"
+ | "appshot_editor";
const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {
marketplace: {
@@ -127,6 +133,12 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknow
de: () => import("./locales/onboarding/de.json"),
es: () => import("./locales/onboarding/es.json"),
},
+ // The appshot editor: opened from a capture, never on start.
+ appshot_editor: {
+ en: () => import("./locales/appshot_editor/en.json"),
+ de: () => import("./locales/appshot_editor/de.json"),
+ es: () => import("./locales/appshot_editor/es.json"),
+ },
};
const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [] };
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json
new file mode 100644
index 0000000000..f7d6596306
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json
@@ -0,0 +1,68 @@
+{
+ "appshot_editor": {
+ "title": "Appshot bearbeiten",
+ "close": "Schließen",
+ "loading": "Appshot wird geladen …",
+ "gone": "Dieser Appshot wird nicht mehr aufbewahrt. Nimm einen neuen auf, um ihn zu bearbeiten.",
+ "load_failed": "Das Bild konnte nicht geladen werden.",
+ "tools": "Werkzeuge",
+ "tool_move": "Auswählen und verschieben",
+ "tool_arrow": "Pfeil",
+ "tool_line": "Linie",
+ "tool_rect": "Rechteck",
+ "tool_filled": "Gefülltes Rechteck",
+ "tool_ellipse": "Ellipse",
+ "tool_pen": "Zeichnen",
+ "tool_highlight": "Textmarker",
+ "tool_text": "Text",
+ "tool_counter": "Nummerierung",
+ "tool_spotlight": "Spotlight",
+ "tool_redact": "Verpixeln oder weichzeichnen",
+ "tool_crop": "Zuschneiden",
+ "tool_background": "Hintergrund",
+ "color": "Farbe",
+ "custom_color": "Beliebige Farbe wählen",
+ "size": "Größe",
+ "size_small": "Klein",
+ "size_medium": "Mittel",
+ "size_large": "Groß",
+ "undo": "Rückgängig",
+ "redo": "Wiederholen",
+ "delete": "Auswahl löschen",
+ "copy": "Kopieren",
+ "save": "Speichern",
+ "apply": "Diese Version nutzen",
+ "apply_hint": "Ersetzt den Appshot, sodass deine nächste Nachricht an {name} das bearbeitete Bild mitschickt.",
+ "copied": "In die Zwischenablage kopiert.",
+ "copy_failed": "Kopieren hat nicht geklappt: {0}",
+ "copy_timeout": "die Zwischenablage hat nicht geantwortet",
+ "saved_to": "Gespeichert unter {0}",
+ "save_failed": "Speichern hat nicht geklappt: {0}",
+ "applied": "Das bearbeitete Bild ersetzt den Appshot.",
+ "apply_failed": "Die Bearbeitung konnte nicht übernommen werden: {0}",
+ "text_placeholder": "Tippen, dann Enter",
+ "text_style": "Textstil",
+ "text_plain": "Schlicht",
+ "text_label": "Etikett",
+ "text_outline": "Kontur",
+ "redact_mode": "Verdecken durch",
+ "redact_pixelate": "Verpixeln",
+ "redact_blur": "Weichzeichnen",
+ "crop_ratio": "Seitenverhältnis",
+ "crop_free": "Frei",
+ "background_enabled": "Bild einrahmen",
+ "background_preset": "Hintergrund",
+ "background_padding": "Abstand",
+ "background_radius": "Ecken",
+ "background_shadow": "Schatten",
+ "hint_move": "Klick auf eine Markierung wählt sie aus. Ziehen verschiebt sie, Pfeiltasten schieben sie, Entf löscht sie. Doppelklick auf Text ändert ihn.",
+ "hint_crop": "Zieh über den Teil, der bleiben soll. Rückgängig holt den Rest zurück.",
+ "hint_counter": "Jeder Klick setzt die nächste Zahl.",
+ "hint_spotlight": "Zieh über das Wichtige; alles andere wird abgedunkelt.",
+ "hint_background": "Der Rahmen kommt beim Kopieren, Speichern oder Nutzen dazu.",
+ "discard_title": "Änderungen verwerfen?",
+ "discard_body": "Bisher wurde nichts kopiert, gespeichert oder übernommen.",
+ "discard_keep": "Weiter bearbeiten",
+ "discard_confirm": "Verwerfen"
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json
new file mode 100644
index 0000000000..033a7d3a33
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json
@@ -0,0 +1,68 @@
+{
+ "appshot_editor": {
+ "title": "Edit appshot",
+ "close": "Close",
+ "loading": "Loading the appshot…",
+ "gone": "This appshot is no longer kept. Take a new one to edit it.",
+ "load_failed": "The picture could not be loaded.",
+ "tools": "Tools",
+ "tool_move": "Select and move",
+ "tool_arrow": "Arrow",
+ "tool_line": "Line",
+ "tool_rect": "Rectangle",
+ "tool_filled": "Filled rectangle",
+ "tool_ellipse": "Ellipse",
+ "tool_pen": "Draw",
+ "tool_highlight": "Highlighter",
+ "tool_text": "Text",
+ "tool_counter": "Counter",
+ "tool_spotlight": "Spotlight",
+ "tool_redact": "Pixelate or blur",
+ "tool_crop": "Crop",
+ "tool_background": "Background",
+ "color": "Colour",
+ "custom_color": "Pick any colour",
+ "size": "Size",
+ "size_small": "Small",
+ "size_medium": "Medium",
+ "size_large": "Large",
+ "undo": "Undo",
+ "redo": "Redo",
+ "delete": "Delete selection",
+ "copy": "Copy",
+ "save": "Save",
+ "apply": "Use this version",
+ "apply_hint": "Replaces the appshot, so your next message to {name} carries the edited picture.",
+ "copied": "Copied to the clipboard.",
+ "copy_failed": "Copying did not work: {0}",
+ "copy_timeout": "the clipboard did not answer",
+ "saved_to": "Saved to {0}",
+ "save_failed": "Saving did not work: {0}",
+ "applied": "The edited picture replaces the appshot.",
+ "apply_failed": "The edit could not be used: {0}",
+ "text_placeholder": "Type, then Enter",
+ "text_style": "Text style",
+ "text_plain": "Plain",
+ "text_label": "Label",
+ "text_outline": "Outline",
+ "redact_mode": "How to hide",
+ "redact_pixelate": "Pixelate",
+ "redact_blur": "Blur",
+ "crop_ratio": "Aspect ratio",
+ "crop_free": "Free",
+ "background_enabled": "Frame the picture",
+ "background_preset": "Backdrop",
+ "background_padding": "Padding",
+ "background_radius": "Corners",
+ "background_shadow": "Shadow",
+ "hint_move": "Click an annotation to select it. Drag to move it, arrow keys nudge it, Delete removes it. Double-click text to change it.",
+ "hint_crop": "Drag over the part to keep. Undo brings the rest back.",
+ "hint_counter": "Each click adds the next number.",
+ "hint_spotlight": "Drag over what matters; everything else dims.",
+ "hint_background": "The frame is added when you copy, save or use the picture.",
+ "discard_title": "Discard your edits?",
+ "discard_body": "Nothing has been copied, saved or used yet.",
+ "discard_keep": "Keep editing",
+ "discard_confirm": "Discard"
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json
new file mode 100644
index 0000000000..fc2d70c212
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json
@@ -0,0 +1,68 @@
+{
+ "appshot_editor": {
+ "title": "Editar appshot",
+ "close": "Cerrar",
+ "loading": "Cargando el appshot…",
+ "gone": "Este appshot ya no se conserva. Toma uno nuevo para editarlo.",
+ "load_failed": "No se pudo cargar la imagen.",
+ "tools": "Herramientas",
+ "tool_move": "Seleccionar y mover",
+ "tool_arrow": "Flecha",
+ "tool_line": "Línea",
+ "tool_rect": "Rectángulo",
+ "tool_filled": "Rectángulo relleno",
+ "tool_ellipse": "Elipse",
+ "tool_pen": "Dibujar",
+ "tool_highlight": "Resaltador",
+ "tool_text": "Texto",
+ "tool_counter": "Numeración",
+ "tool_spotlight": "Foco",
+ "tool_redact": "Pixelar o difuminar",
+ "tool_crop": "Recortar",
+ "tool_background": "Fondo",
+ "color": "Color",
+ "custom_color": "Elegir cualquier color",
+ "size": "Tamaño",
+ "size_small": "Pequeño",
+ "size_medium": "Mediano",
+ "size_large": "Grande",
+ "undo": "Deshacer",
+ "redo": "Rehacer",
+ "delete": "Eliminar selección",
+ "copy": "Copiar",
+ "save": "Guardar",
+ "apply": "Usar esta versión",
+ "apply_hint": "Sustituye el appshot, así tu próximo mensaje a {name} lleva la imagen editada.",
+ "copied": "Copiado al portapapeles.",
+ "copy_failed": "No se pudo copiar: {0}",
+ "copy_timeout": "el portapapeles no respondió",
+ "saved_to": "Guardado en {0}",
+ "save_failed": "No se pudo guardar: {0}",
+ "applied": "La imagen editada sustituye al appshot.",
+ "apply_failed": "No se pudo usar la edición: {0}",
+ "text_placeholder": "Escribe y pulsa Intro",
+ "text_style": "Estilo de texto",
+ "text_plain": "Simple",
+ "text_label": "Etiqueta",
+ "text_outline": "Contorno",
+ "redact_mode": "Cómo ocultar",
+ "redact_pixelate": "Pixelar",
+ "redact_blur": "Difuminar",
+ "crop_ratio": "Proporción",
+ "crop_free": "Libre",
+ "background_enabled": "Enmarcar la imagen",
+ "background_preset": "Fondo",
+ "background_padding": "Margen",
+ "background_radius": "Esquinas",
+ "background_shadow": "Sombra",
+ "hint_move": "Haz clic en una anotación para seleccionarla. Arrástrala para moverla, las flechas la desplazan y Supr la elimina. Doble clic en un texto para cambiarlo.",
+ "hint_crop": "Arrastra sobre la parte que quieres conservar. Deshacer recupera el resto.",
+ "hint_counter": "Cada clic añade el siguiente número.",
+ "hint_spotlight": "Arrastra sobre lo importante; el resto se oscurece.",
+ "hint_background": "El marco se añade al copiar, guardar o usar la imagen.",
+ "discard_title": "¿Descartar los cambios?",
+ "discard_body": "Todavía no se ha copiado, guardado ni usado nada.",
+ "discard_keep": "Seguir editando",
+ "discard_confirm": "Descartar"
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/lib/appshotClipboard.test.ts b/jarvis/ui/web/frontend/src/lib/appshotClipboard.test.ts
new file mode 100644
index 0000000000..920a319c41
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/appshotClipboard.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { copyAppshotPng } from "@/lib/appshotClipboard";
+
+const blob = new Blob([new Uint8Array([137, 80, 78, 71])], { type: "image/png" });
+
+function reply(status: number, body: unknown = {}): Response {
+ return { ok: status < 400, status, json: async () => body } as Response;
+}
+
+describe("copyAppshotPng", () => {
+ beforeEach(() => {
+ vi.stubGlobal(
+ "ClipboardItem",
+ class {
+ constructor(public items: Record<string, Blob>) {}
+ },
+ );
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("copies natively on the desktop and never touches the browser clipboard", async () => {
+ const fetchImpl = vi.fn(async () => reply(200, { copied: true }));
+ const clipboard = { write: vi.fn(async () => undefined) };
+
+ await expect(
+ copyAppshotPng(blob, { native: true, timeoutMessage: "t", fetchImpl, clipboard }),
+ ).resolves.toBe("native");
+
+ expect(fetchImpl).toHaveBeenCalledWith("/api/appshot/clipboard", expect.objectContaining({ method: "POST" }));
+ expect(clipboard.write).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the browser clipboard when the OS refuses", async () => {
+ const fetchImpl = vi.fn(async () => reply(503, { detail: "native-clipboard-unavailable" }));
+ const clipboard = { write: vi.fn(async () => undefined) };
+
+ await expect(
+ copyAppshotPng(blob, { native: true, timeoutMessage: "t", fetchImpl, clipboard }),
+ ).resolves.toBe("browser");
+ expect(clipboard.write).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses only the browser clipboard in a browser", async () => {
+ const fetchImpl = vi.fn();
+ const clipboard = { write: vi.fn(async () => undefined) };
+
+ await copyAppshotPng(blob, { native: false, timeoutMessage: "t", fetchImpl, clipboard });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it("gives up on a browser clipboard that never answers", async () => {
+ const clipboard = { write: vi.fn(() => new Promise<void>(() => undefined)) };
+
+ await expect(
+ copyAppshotPng(blob, { native: false, timeoutMessage: "no answer", clipboard, timeoutMs: 10 }),
+ ).rejects.toThrow("no answer");
+ });
+
+ it("names the native reason when no clipboard is left", async () => {
+ const fetchImpl = vi.fn(async () => reply(503, { detail: "native-clipboard-unavailable" }));
+
+ await expect(
+ copyAppshotPng(blob, { native: true, timeoutMessage: "t", fetchImpl, clipboard: null }),
+ ).rejects.toThrow("native-clipboard-unavailable");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/appshotClipboard.ts b/jarvis/ui/web/frontend/src/lib/appshotClipboard.ts
new file mode 100644
index 0000000000..b7617bb92b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/appshotClipboard.ts
@@ -0,0 +1,61 @@
+/**
+ * Copy an edited appshot (a PNG) to the clipboard, on every surface.
+ *
+ * Desktop first goes through the backend, which writes the OS clipboard
+ * natively (`POST /api/appshot/clipboard`): the embedded WebView cannot be
+ * trusted with images — WebView2 may never settle `navigator.clipboard.write`
+ * and WKWebView rejects it once the click handler has awaited the export.
+ * A browser (or a desktop route that refuses) uses the browser clipboard,
+ * raced against a timeout so a promise that never settles cannot hang the
+ * button.
+ */
+
+export const BROWSER_COPY_TIMEOUT_MS = 5_000;
+
+export interface CopyOptions {
+ /** True in the desktop shell (`native_file_actions`). */
+ native: boolean;
+ /** The error message when the browser clipboard never answers. */
+ timeoutMessage: string;
+ /** Test seams. */
+ fetchImpl?: typeof fetch;
+ clipboard?: Pick<Clipboard, "write"> | null;
+ timeoutMs?: number;
+}
+
+/** Resolves once the picture is on the clipboard; rejects with a reason. */
+export async function copyAppshotPng(blob: Blob, options: CopyOptions): Promise<"native" | "browser"> {
+ const fetchImpl = options.fetchImpl ?? fetch;
+ let nativeReason = "";
+ if (options.native) {
+ try {
+ const response = await fetchImpl("/api/appshot/clipboard", {
+ method: "POST",
+ headers: { "content-type": "image/png" },
+ body: blob,
+ });
+ if (response.ok) return "native";
+ const body = (await response.json().catch(() => null)) as { detail?: string } | null;
+ nativeReason = body?.detail || `HTTP ${response.status}`;
+ } catch (error) {
+ nativeReason = (error as Error).message;
+ }
+ }
+ const clipboard =
+ options.clipboard !== undefined ? options.clipboard : typeof navigator !== "undefined" ? navigator.clipboard : null;
+ if (!clipboard || typeof ClipboardItem === "undefined") {
+ throw new Error(nativeReason || "no clipboard is available here");
+ }
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ clipboard.write([new ClipboardItem({ "image/png": blob })]),
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(options.timeoutMessage)), options.timeoutMs ?? BROWSER_COPY_TIMEOUT_MS);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+ return "browser";
+}
diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
index d362cec143..45c4e0aaac 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
@@ -1,6 +1,34 @@
import { describe, expect, it } from "vitest";
-import { clampRect, rectFrom, strokeWidths, textSize, viewport, type Op } from "@/lib/appshotEditorModel";
+import {
+ BACKGROUND_PRESETS,
+ DEFAULT_BACKGROUND,
+ TOOL_KEYS,
+ bounds,
+ clampRect,
+ commit,
+ constrainEnd,
+ contrastOn,
+ emptyHistory,
+ frameLayout,
+ hitTest,
+ isMeaningful,
+ nextCounter,
+ presetCss,
+ rectFrom,
+ redo,
+ strokeWidths,
+ textSize,
+ toolForKey,
+ translate,
+ undo,
+ viewport,
+ withId,
+ type Op,
+} from "@/lib/appshotEditorModel";
+
+const pen = withId({ kind: "pen", points: [{ x: 1, y: 1 }], color: "#fff", width: 3 });
+const crop = withId({ kind: "crop", rect: { x: 10, y: 10, w: 50, h: 40 } });
describe("appshot editor model", () => {
it("builds the same rectangle for a drag in any direction", () => {
@@ -13,8 +41,6 @@ describe("appshot editor model", () => {
});
it("shows the last crop, and the whole picture again once it is undone", () => {
- const crop: Op = { kind: "crop", rect: { x: 10, y: 10, w: 50, h: 40 } };
- const pen: Op = { kind: "pen", points: [{ x: 1, y: 1 }], color: "#fff", width: 3 };
expect(viewport([pen, crop], 200, 100)).toEqual(crop.rect);
expect(viewport([pen], 200, 100)).toEqual({ x: 0, y: 0, w: 200, h: 100 });
});
@@ -27,3 +53,161 @@ describe("appshot editor model", () => {
expect(textSize(6)).toBe(30);
});
});
+
+describe("tools and keys", () => {
+ it("uses CleanShot X's one-letter keys, each once", () => {
+ const keys = TOOL_KEYS.map((entry) => entry.key);
+ expect(new Set(keys).size).toBe(keys.length);
+ expect(toolForKey("V")).toBe("move");
+ expect(toolForKey("a")).toBe("arrow");
+ expect(toolForKey("f")).toBe("filled");
+ expect(toolForKey("d")).toBe("pen");
+ expect(toolForKey("m")).toBe("highlight");
+ expect(toolForKey("c")).toBe("counter");
+ expect(toolForKey("h")).toBe("spotlight");
+ expect(toolForKey("p")).toBe("redact");
+ expect(toolForKey("k")).toBe("crop");
+ expect(toolForKey("b")).toBe("background");
+ expect(toolForKey("q")).toBeNull();
+ });
+});
+
+describe("constraints", () => {
+ const start = { x: 0, y: 0 };
+
+ it("snaps a line to 45° with Shift", () => {
+ const end = constrainEnd("line", start, { x: 100, y: 10 }, true, null);
+ expect(end.y).toBeCloseTo(0, 5);
+ const diagonal = constrainEnd("arrow", start, { x: 100, y: 90 }, true, null);
+ expect(diagonal.x).toBeCloseTo(diagonal.y, 5);
+ });
+
+ it("makes a square with Shift and leaves a free drag alone", () => {
+ expect(constrainEnd("rect", start, { x: 100, y: 40 }, true, null)).toEqual({ x: 100, y: 100 });
+ expect(constrainEnd("rect", start, { x: 100, y: 40 }, false, null)).toEqual({ x: 100, y: 40 });
+ });
+
+ it("keeps a crop's aspect ratio in any drag direction", () => {
+ const end = constrainEnd("crop", start, { x: -160, y: -10 }, false, 16 / 9);
+ expect(end.x).toBe(-160);
+ expect(end.y).toBeCloseTo(-90, 5);
+ });
+});
+
+describe("counter", () => {
+ it("numbers on from the highest badge, so undo frees the number", () => {
+ const one = withId({ kind: "counter", at: { x: 1, y: 1 }, n: 1, color: "#f00", size: 12 });
+ const two = withId({ kind: "counter", at: { x: 5, y: 5 }, n: 2, color: "#f00", size: 12 });
+ expect(nextCounter([])).toBe(1);
+ expect(nextCounter([one, two])).toBe(3);
+ expect(nextCounter([one])).toBe(2);
+ });
+});
+
+describe("selection and moving", () => {
+ const arrow = withId({ kind: "arrow", from: { x: 10, y: 10 }, to: { x: 110, y: 10 }, color: "#f00", width: 4 });
+ const box = withId({ kind: "rect", rect: { x: 200, y: 200, w: 50, h: 50 }, color: "#f00", width: 4 });
+ const text = withId({ kind: "text", at: { x: 300, y: 20 }, text: "Hi", color: "#fff", size: 20, style: "label" });
+
+ it("finds the annotation under the pointer, top-most first", () => {
+ const covering = withId({ kind: "filled", rect: { x: 190, y: 190, w: 80, h: 80 }, color: "#000", width: 4 });
+ expect(hitTest([arrow, box], { x: 60, y: 12 }, 3)?.id).toBe(arrow.id);
+ expect(hitTest([arrow, box], { x: 60, y: 40 }, 3)).toBeNull();
+ expect(hitTest([box, covering], { x: 220, y: 220 }, 3)?.id).toBe(covering.id);
+ });
+
+ it("picks what sits in a spotlight or redaction before the area itself", () => {
+ // Live 2026-10-03: dragging a caption inside a spotlight moved the spotlight.
+ const spot = withId({ kind: "spotlight", rect: { x: 280, y: 0, w: 200, h: 200 } });
+ expect(hitTest([text, spot], { x: 310, y: 30 }, 2, () => 30)?.id).toBe(text.id);
+ expect(hitTest([text, spot], { x: 450, y: 150 }, 2, () => 30)?.id).toBe(spot.id);
+ });
+
+ it("picks an outline at its edge, so what it frames stays reachable", () => {
+ expect(hitTest([box], { x: 225, y: 225 }, 2)).toBeNull();
+ expect(hitTest([box], { x: 201, y: 225 }, 2)?.id).toBe(box.id);
+ const ring = withId({ kind: "ellipse", rect: { x: 0, y: 0, w: 100, h: 100 }, color: "#f00", width: 4 });
+ expect(hitTest([ring], { x: 50, y: 50 }, 2)).toBeNull();
+ expect(hitTest([ring], { x: 50, y: 2 }, 2)?.id).toBe(ring.id);
+ });
+
+ it("never selects a crop", () => {
+ expect(hitTest([crop], { x: 20, y: 20 }, 3)).toBeNull();
+ });
+
+ it("measures text with the given measure, padded for a label", () => {
+ const measured = bounds(text, () => 30);
+ expect(measured.w).toBeGreaterThan(30);
+ expect(hitTest([text], { x: 310, y: 30 }, 2, () => 30)?.id).toBe(text.id);
+ });
+
+ it("moves every kind of annotation and keeps its id", () => {
+ expect(translate(arrow, 5, 5)).toMatchObject({ id: arrow.id, from: { x: 15, y: 15 }, to: { x: 115, y: 15 } });
+ expect(translate(box, -10, 0).rect.x).toBe(190);
+ expect(translate(text, 0, 10).at.y).toBe(30);
+ expect(translate(pen, 1, 1).points[0]).toEqual({ x: 2, y: 2 });
+ });
+
+ it("drops a stray click instead of keeping an empty shape", () => {
+ expect(isMeaningful({ kind: "line", from: { x: 0, y: 0 }, to: { x: 1, y: 1 }, color: "#f00", width: 2 })).toBe(false);
+ expect(isMeaningful({ kind: "redact", rect: { x: 0, y: 0, w: 2, h: 40 }, mode: "blur", block: 8 })).toBe(false);
+ expect(isMeaningful({ kind: "spotlight", rect: { x: 0, y: 0, w: 40, h: 40 } })).toBe(true);
+ });
+});
+
+describe("history", () => {
+ it("undoes and redoes whole states, and a new edit drops the redo", () => {
+ let history = emptyHistory();
+ history = commit(history, [pen]);
+ history = commit(history, [pen, crop]);
+ history = undo(history);
+ expect(history.present).toEqual([pen]);
+ history = redo(history);
+ expect(history.present).toEqual([pen, crop]);
+ history = undo(history);
+ history = commit(history, []);
+ expect(history.future).toEqual([]);
+ expect(undo(emptyHistory())).toEqual(emptyHistory());
+ });
+
+ it("undoes a move as one step", () => {
+ const moved: Op[] = [translate(pen, 10, 0)];
+ const history = undo(commit(commit(emptyHistory(), [pen]), moved));
+ expect(history.present).toEqual([pen]);
+ });
+});
+
+describe("background frame", () => {
+ it("adds the same padding on every side and leaves an unframed picture alone", () => {
+ expect(frameLayout(1000, 500, DEFAULT_BACKGROUND)).toEqual({
+ width: 1000,
+ height: 500,
+ image: { x: 0, y: 0, w: 1000, h: 500 },
+ radius: 0,
+ });
+ const framed = frameLayout(1000, 500, { ...DEFAULT_BACKGROUND, enabled: true, padding: 0.1, radius: 12 });
+ expect(framed.image).toEqual({ x: 100, y: 100, w: 1000, h: 500 });
+ expect(framed.width).toBe(1200);
+ expect(framed.height).toBe(700);
+ expect(framed.radius).toBe(12);
+ });
+
+ it("caps the padding", () => {
+ const framed = frameLayout(100, 100, { ...DEFAULT_BACKGROUND, enabled: true, padding: 5 });
+ expect(framed.image.x).toBe(25);
+ });
+
+ it("previews every preset as CSS", () => {
+ for (const preset of BACKGROUND_PRESETS) expect(presetCss(preset)).toBeTruthy();
+ expect(presetCss({ id: "x", stops: ["#111111"] })).toBe("#111111");
+ });
+});
+
+describe("contrast", () => {
+ it("puts dark ink on light colours and white on dark ones", () => {
+ expect(contrastOn("#ffcc00")).toBe("#111111");
+ expect(contrastOn("#ffffff")).toBe("#111111");
+ expect(contrastOn("#0a84ff")).toBe("#ffffff");
+ expect(contrastOn("#1c1c1e")).toBe("#ffffff");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
index 45c8d80baa..d08e59c40e 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
@@ -1,13 +1,33 @@
/**
- * The appshot editor's document: a base picture plus a list of operations,
- * drawn in the picture's own pixel space. Pure data + one renderer, so the
- * on-screen canvas and the exported PNG are painted by the same code.
+ * The appshot editor's document: a base picture plus a list of annotations,
+ * drawn in the picture's own pixel space, and an optional background frame
+ * around the result. Pure data + one renderer, so the on-screen canvas and
+ * the exported PNG are painted by the same code.
*
- * A crop is an operation too: the last one sets the visible part of the
+ * The tool set and its one-letter keys follow CleanShot X's annotate tool
+ * (V move, A arrow, L line, R rectangle, F filled rectangle, E ellipse,
+ * D draw, M highlighter, T text, C counter, H spotlight, P redact, K crop,
+ * B background), so anyone who knows it can work here without looking.
+ *
+ * A crop is an annotation too: the last one sets the visible part of the
* picture, and undo brings the rest back.
*/
-export type Tool = "arrow" | "rect" | "ellipse" | "pen" | "highlight" | "text" | "pixelate" | "crop";
+export type Tool =
+ | "move"
+ | "arrow"
+ | "line"
+ | "rect"
+ | "filled"
+ | "ellipse"
+ | "pen"
+ | "highlight"
+ | "text"
+ | "counter"
+ | "spotlight"
+ | "redact"
+ | "crop"
+ | "background";
export interface Point {
x: number;
@@ -21,15 +41,65 @@ export interface Rect {
h: number;
}
-export type Op =
- | { kind: "arrow"; from: Point; to: Point; color: string; width: number }
- | { kind: "rect" | "ellipse"; rect: Rect; color: string; width: number }
+export type TextStyle = "plain" | "label" | "outline";
+export type RedactMode = "pixelate" | "blur";
+
+type Shape =
+ | { kind: "arrow" | "line"; from: Point; to: Point; color: string; width: number }
+ | { kind: "rect" | "filled" | "ellipse"; rect: Rect; color: string; width: number }
| { kind: "pen" | "highlight"; points: Point[]; color: string; width: number }
- | { kind: "text"; at: Point; text: string; color: string; size: number }
- | { kind: "pixelate"; rect: Rect; block: number }
+ | { kind: "text"; at: Point; text: string; color: string; size: number; style: TextStyle }
+ | { kind: "counter"; at: Point; n: number; color: string; size: number }
+ | { kind: "spotlight"; rect: Rect }
+ | { kind: "redact"; rect: Rect; mode: RedactMode; block: number }
| { kind: "crop"; rect: Rect };
-export const COLORS = ["#ef4444", "#f97316", "#facc15", "#22c55e", "#3b82f6", "#ffffff", "#111111"];
+/** One annotation. `id` survives moves, so a selection outlives an edit. */
+export type Op = Shape & { id: number };
+
+/** A shape before it has an id (what a tool produces). */
+export type Draft = Shape;
+
+/** Tool → its key, in toolbar order. */
+export const TOOL_KEYS: readonly { tool: Tool; key: string }[] = [
+ { tool: "move", key: "v" },
+ { tool: "arrow", key: "a" },
+ { tool: "line", key: "l" },
+ { tool: "rect", key: "r" },
+ { tool: "filled", key: "f" },
+ { tool: "ellipse", key: "e" },
+ { tool: "pen", key: "d" },
+ { tool: "highlight", key: "m" },
+ { tool: "text", key: "t" },
+ { tool: "counter", key: "c" },
+ { tool: "spotlight", key: "h" },
+ { tool: "redact", key: "p" },
+ { tool: "crop", key: "k" },
+ { tool: "background", key: "b" },
+];
+
+export function toolForKey(key: string): Tool | null {
+ const lower = key.toLowerCase();
+ return TOOL_KEYS.find((entry) => entry.key === lower)?.tool ?? null;
+}
+
+export const COLORS = ["#ff3b30", "#ff9500", "#ffcc00", "#34c759", "#0a84ff", "#af52de", "#ffffff", "#1c1c1e"];
+
+/** Crop aspect ratios offered next to the crop tool (width / height). */
+export const CROP_RATIOS: readonly { id: string; ratio: number | null }[] = [
+ { id: "free", ratio: null },
+ { id: "1:1", ratio: 1 },
+ { id: "4:3", ratio: 4 / 3 },
+ { id: "16:9", ratio: 16 / 9 },
+];
+
+let nextId = 1;
+
+/** Give a finished shape its id. */
+export function withId<T extends Draft>(shape: T): T & { id: number } {
+ nextId += 1;
+ return { ...shape, id: nextId };
+}
/** Stroke widths (S / M / L) for a picture of this size, in its own pixels. */
export function strokeWidths(width: number, height: number): [number, number, number] {
@@ -41,6 +111,11 @@ export function textSize(stroke: number): number {
return Math.max(14, Math.round(stroke * 5));
}
+/** Counter badge radius for a stroke width. */
+export function counterSize(stroke: number): number {
+ return Math.max(12, Math.round(stroke * 3));
+}
+
/** A rectangle from two corners, in any drag direction. */
export function rectFrom(a: Point, b: Point): Rect {
return {
@@ -51,8 +126,36 @@ export function rectFrom(a: Point, b: Point): Rect {
};
}
+/**
+ * Where the drag ends once Shift (or a crop ratio) has its say: lines snap to
+ * 45°, boxes become squares, a crop keeps its aspect ratio.
+ */
+export function constrainEnd(tool: Tool, start: Point, end: Point, shift: boolean, ratio: number | null): Point {
+ const dx = end.x - start.x;
+ const dy = end.y - start.y;
+ if ((tool === "arrow" || tool === "line") && shift) {
+ const angle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
+ const length = Math.hypot(dx, dy);
+ return { x: start.x + Math.cos(angle) * length, y: start.y + Math.sin(angle) * length };
+ }
+ const boxRatio = tool === "crop" ? ratio : shift ? 1 : null;
+ if (boxRatio !== null && boxRatio > 0 && (tool === "crop" || isBoxTool(tool))) {
+ const w = Math.abs(dx);
+ const h = Math.abs(dy);
+ // Follow whichever side the pointer pulled further.
+ const width = Math.max(w, h * boxRatio);
+ const height = width / boxRatio;
+ return { x: start.x + Math.sign(dx || 1) * width, y: start.y + Math.sign(dy || 1) * height };
+ }
+ return end;
+}
+
+function isBoxTool(tool: Tool): boolean {
+ return tool === "rect" || tool === "filled" || tool === "ellipse" || tool === "spotlight" || tool === "redact";
+}
+
/** The visible part of the picture: the last crop, or all of it. */
-export function viewport(ops: Op[], width: number, height: number): Rect {
+export function viewport(ops: readonly Op[], width: number, height: number): Rect {
for (let i = ops.length - 1; i >= 0; i -= 1) {
const op = ops[i];
if (op.kind === "crop") return op.rect;
@@ -70,6 +173,269 @@ export function clampRect(rect: Rect, width: number, height: number): Rect | nul
return { x, y, w: right - x, h: bottom - y };
}
+/** The number the next counter badge carries. */
+export function nextCounter(ops: readonly Op[]): number {
+ let highest = 0;
+ for (const op of ops) if (op.kind === "counter") highest = Math.max(highest, op.n);
+ return highest + 1;
+}
+
+/** Measures text the way the canvas will draw it; replaceable in tests. */
+export type MeasureText = (text: string, size: number) => number;
+
+const roughMeasure: MeasureText = (text, size) => text.length * size * 0.55;
+
+function textLines(text: string): string[] {
+ return text.split("\n");
+}
+
+/** The box a shape covers, for selection and hit testing. */
+export function bounds(op: Draft, measure: MeasureText = roughMeasure): Rect {
+ switch (op.kind) {
+ case "arrow":
+ case "line":
+ return rectFrom(op.from, op.to);
+ case "pen":
+ case "highlight": {
+ const xs = op.points.map((p) => p.x);
+ const ys = op.points.map((p) => p.y);
+ return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
+ }
+ case "text": {
+ const lines = textLines(op.text);
+ const width = Math.max(...lines.map((line) => measure(line, op.size)));
+ const pad = op.style === "label" ? op.size * 0.4 : 0;
+ return { x: op.at.x - pad, y: op.at.y - pad, w: width + pad * 2, h: lines.length * op.size * 1.25 + pad * 2 };
+ }
+ case "counter":
+ return { x: op.at.x - op.size, y: op.at.y - op.size, w: op.size * 2, h: op.size * 2 };
+ default:
+ return op.rect;
+ }
+}
+
+function distanceToSegment(p: Point, a: Point, b: Point): number {
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+ const lengthSq = dx * dx + dy * dy;
+ const t = lengthSq === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq));
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
+}
+
+function inside(p: Point, box: Rect, slop: number): boolean {
+ return p.x >= box.x - slop && p.x <= box.x + box.w + slop && p.y >= box.y - slop && p.y <= box.y + box.h + slop;
+}
+
+/** Areas that cover others: picked only when nothing drawn on them is hit. */
+const AREA_KINDS: ReadonlySet<Op["kind"]> = new Set(["spotlight", "redact"]);
+
+function hits(op: Op, p: Point, slop: number, measure?: MeasureText): boolean {
+ switch (op.kind) {
+ case "crop":
+ return false;
+ case "arrow":
+ case "line":
+ return distanceToSegment(p, op.from, op.to) <= slop + op.width;
+ case "pen":
+ case "highlight": {
+ const reach = slop + (op.kind === "highlight" ? op.width * 2 : op.width);
+ if (op.points.length === 1) return Math.hypot(p.x - op.points[0].x, p.y - op.points[0].y) <= reach;
+ for (let j = 1; j < op.points.length; j += 1) {
+ if (distanceToSegment(p, op.points[j - 1], op.points[j]) <= reach) return true;
+ }
+ return false;
+ }
+ case "rect": {
+ // An outline is picked at its edge, so what it frames stays clickable.
+ const reach = slop + op.width;
+ const r = op.rect;
+ return inside(p, r, reach) && !inside(p, { x: r.x + reach, y: r.y + reach, w: r.w - reach * 2, h: r.h - reach * 2 }, 0);
+ }
+ case "ellipse": {
+ const rx = Math.max(1, op.rect.w / 2);
+ const ry = Math.max(1, op.rect.h / 2);
+ const dx = (p.x - (op.rect.x + rx)) / rx;
+ const dy = (p.y - (op.rect.y + ry)) / ry;
+ return Math.abs(Math.hypot(dx, dy) - 1) * Math.min(rx, ry) <= slop + op.width;
+ }
+ default:
+ return inside(p, bounds(op, measure), slop);
+ }
+}
+
+/**
+ * The top-most annotation under `p`, or null. Lines and strokes count near
+ * their path, outlines near their edge, filled shapes, text and counters
+ * anywhere on them. Spotlights and redactions come last — they cover
+ * whatever sits in them — and crops are never picked.
+ */
+export function hitTest(ops: readonly Op[], p: Point, slop: number, measure?: MeasureText): Op | null {
+ for (const areas of [false, true]) {
+ for (let i = ops.length - 1; i >= 0; i -= 1) {
+ const op = ops[i];
+ if (AREA_KINDS.has(op.kind) !== areas) continue;
+ if (hits(op, p, slop, measure)) return op;
+ }
+ }
+ return null;
+}
+
+function shiftPoint(p: Point, dx: number, dy: number): Point {
+ return { x: p.x + dx, y: p.y + dy };
+}
+
+/** The same annotation, moved. */
+export function translate<T extends Draft>(op: T, dx: number, dy: number): T {
+ switch (op.kind) {
+ case "arrow":
+ case "line":
+ return { ...op, from: shiftPoint(op.from, dx, dy), to: shiftPoint(op.to, dx, dy) };
+ case "pen":
+ case "highlight":
+ return { ...op, points: op.points.map((p) => shiftPoint(p, dx, dy)) };
+ case "text":
+ case "counter":
+ return { ...op, at: shiftPoint(op.at, dx, dy) };
+ default:
+ return { ...op, rect: { ...op.rect, x: op.rect.x + dx, y: op.rect.y + dy } };
+ }
+}
+
+/** Is this freshly drawn shape big enough to keep (not a stray click)? */
+export function isMeaningful(op: Draft): boolean {
+ switch (op.kind) {
+ case "arrow":
+ case "line":
+ return Math.hypot(op.to.x - op.from.x, op.to.y - op.from.y) >= 4;
+ case "pen":
+ case "highlight":
+ return op.points.length > 0;
+ case "text":
+ return op.text.trim().length > 0;
+ case "counter":
+ return true;
+ default:
+ return op.rect.w >= 4 && op.rect.h >= 4;
+ }
+}
+
+// -- history ------------------------------------------------------------------
+
+export interface History {
+ past: Op[][];
+ present: Op[];
+ future: Op[][];
+}
+
+const HISTORY_LIMIT = 100;
+
+export function emptyHistory(): History {
+ return { past: [], present: [], future: [] };
+}
+
+/** A new document state; the old one becomes undoable, redo is dropped. */
+export function commit(history: History, next: Op[]): History {
+ return { past: [...history.past, history.present].slice(-HISTORY_LIMIT), present: next, future: [] };
+}
+
+export function undo(history: History): History {
+ if (history.past.length === 0) return history;
+ return {
+ past: history.past.slice(0, -1),
+ present: history.past[history.past.length - 1],
+ future: [history.present, ...history.future],
+ };
+}
+
+export function redo(history: History): History {
+ if (history.future.length === 0) return history;
+ return { past: [...history.past, history.present], present: history.future[0], future: history.future.slice(1) };
+}
+
+// -- background ---------------------------------------------------------------
+
+export interface BackgroundPreset {
+ id: string;
+ /** Two or three colour stops, drawn diagonally; one stop is a solid fill. */
+ stops: string[];
+}
+
+/** Our own palette — soft gradients and quiet solids, no third-party art. */
+export const BACKGROUND_PRESETS: readonly BackgroundPreset[] = [
+ { id: "dawn", stops: ["#ff9a8b", "#ff6a88", "#ff99ac"] },
+ { id: "lagoon", stops: ["#43cea2", "#185a9d"] },
+ { id: "dusk", stops: ["#7f7fd5", "#86a8e7", "#91eae4"] },
+ { id: "ember", stops: ["#f7971e", "#ffd200"] },
+ { id: "orchid", stops: ["#c471f5", "#fa71cd"] },
+ { id: "slate", stops: ["#434343", "#1c1c1e"] },
+ { id: "paper", stops: ["#f5f5f7"] },
+ { id: "ink", stops: ["#111113"] },
+];
+
+export interface Background {
+ enabled: boolean;
+ preset: string;
+ /** Space around the picture, as a share of its longer side (0 – 0.25). */
+ padding: number;
+ /** Corner radius of the picture, in its own pixels before scaling. */
+ radius: number;
+ shadow: boolean;
+}
+
+export const DEFAULT_BACKGROUND: Background = {
+ enabled: false,
+ preset: "dusk",
+ padding: 0.08,
+ radius: 12,
+ shadow: true,
+};
+
+export function presetById(id: string): BackgroundPreset {
+ return BACKGROUND_PRESETS.find((preset) => preset.id === id) ?? BACKGROUND_PRESETS[0];
+}
+
+export interface Layout {
+ width: number;
+ height: number;
+ /** Where the picture sits inside the framed result. */
+ image: Rect;
+ radius: number;
+}
+
+/** The size of the result and where the picture sits in it. */
+export function frameLayout(width: number, height: number, background: Background): Layout {
+ if (!background.enabled) {
+ return { width, height, image: { x: 0, y: 0, w: width, h: height }, radius: 0 };
+ }
+ const pad = Math.round(Math.max(width, height) * Math.max(0, Math.min(0.25, background.padding)));
+ const unit = Math.max(1, Math.max(width, height) / 1400);
+ return {
+ width: width + pad * 2,
+ height: height + pad * 2,
+ image: { x: pad, y: pad, w: width, h: height },
+ radius: Math.round(Math.max(0, background.radius) * unit),
+ };
+}
+
+/** The same gradient as CSS, for the on-screen preview of the frame. */
+export function presetCss(preset: BackgroundPreset): string {
+ if (preset.stops.length === 1) return preset.stops[0];
+ return `linear-gradient(135deg, ${preset.stops.join(", ")})`;
+}
+
+// -- painting -----------------------------------------------------------------
+
+/** Black or white, whichever reads on `hex`. */
+export function contrastOn(hex: string): string {
+ const value = hex.replace("#", "");
+ const full = value.length === 3 ? value.split("").map((c) => c + c).join("") : value;
+ const r = parseInt(full.slice(0, 2), 16);
+ const g = parseInt(full.slice(2, 4), 16);
+ const b = parseInt(full.slice(4, 6), 16);
+ const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
+ return luminance > 0.6 ? "#111111" : "#ffffff";
+}
+
function arrow(ctx: CanvasRenderingContext2D, from: Point, to: Point, width: number) {
const angle = Math.atan2(to.y - from.y, to.x - from.x);
const head = Math.max(10, width * 4);
@@ -86,109 +452,295 @@ function arrow(ctx: CanvasRenderingContext2D, from: Point, to: Point, width: num
ctx.fill();
}
-function pixelate(ctx: CanvasRenderingContext2D, base: CanvasImageSource, rect: Rect, block: number) {
+/** A hand-drawn stroke smoothed through the midpoints of its samples. */
+function smoothStroke(ctx: CanvasRenderingContext2D, points: Point[]) {
+ ctx.beginPath();
+ ctx.moveTo(points[0].x, points[0].y);
+ if (points.length === 1) {
+ ctx.lineTo(points[0].x + 0.1, points[0].y);
+ } else {
+ for (let i = 1; i < points.length - 1; i += 1) {
+ const mid = { x: (points[i].x + points[i + 1].x) / 2, y: (points[i].y + points[i + 1].y) / 2 };
+ ctx.quadraticCurveTo(points[i].x, points[i].y, mid.x, mid.y);
+ }
+ const last = points[points.length - 1];
+ ctx.lineTo(last.x, last.y);
+ }
+ ctx.stroke();
+}
+
+function makeCanvas(width: number, height: number): HTMLCanvasElement {
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.max(1, Math.round(width));
+ canvas.height = Math.max(1, Math.round(height));
+ return canvas;
+}
+
+/**
+ * Hide a region. Pixelate keeps hard blocks; blur shrinks and grows the
+ * region twice with smoothing, which every engine supports (canvas `filter`
+ * is missing in some WebKit builds the macOS and Linux shells use).
+ */
+function redact(ctx: CanvasRenderingContext2D, base: CanvasImageSource, rect: Rect, mode: RedactMode, block: number) {
const w = Math.max(1, Math.round(rect.w / block));
const h = Math.max(1, Math.round(rect.h / block));
- const small = document.createElement("canvas");
- small.width = w;
- small.height = h;
+ const small = makeCanvas(w, h);
const sctx = small.getContext("2d");
if (!sctx) return;
sctx.imageSmoothingEnabled = true;
sctx.drawImage(base, rect.x, rect.y, rect.w, rect.h, 0, 0, w, h);
ctx.save();
- ctx.imageSmoothingEnabled = false;
- ctx.drawImage(small, 0, 0, w, h, rect.x, rect.y, rect.w, rect.h);
+ ctx.beginPath();
+ ctx.rect(rect.x, rect.y, rect.w, rect.h);
+ ctx.clip();
+ if (mode === "pixelate") {
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(small, 0, 0, w, h, rect.x, rect.y, rect.w, rect.h);
+ } else {
+ const tiny = makeCanvas(Math.max(1, Math.round(w / 2)), Math.max(1, Math.round(h / 2)));
+ const tctx = tiny.getContext("2d");
+ ctx.imageSmoothingEnabled = true;
+ if (tctx) {
+ tctx.imageSmoothingEnabled = true;
+ tctx.drawImage(small, 0, 0, tiny.width, tiny.height);
+ ctx.drawImage(tiny, 0, 0, tiny.width, tiny.height, rect.x, rect.y, rect.w, rect.h);
+ } else {
+ ctx.drawImage(small, 0, 0, w, h, rect.x, rect.y, rect.w, rect.h);
+ }
+ }
ctx.restore();
}
+function roundedRect(ctx: CanvasRenderingContext2D, rect: Rect, radius: number) {
+ ctx.beginPath();
+ roundedRectPath(ctx, rect, radius);
+}
+
+export function textFont(size: number): string {
+ return `600 ${size}px Inter, "Segoe UI", system-ui, -apple-system, sans-serif`;
+}
+
+/** A text measure backed by a real canvas, or the rough one without it. */
+export function canvasMeasure(ctx: CanvasRenderingContext2D | null): MeasureText {
+ if (!ctx) return roughMeasure;
+ return (text, size) => {
+ ctx.font = textFont(size);
+ return ctx.measureText(text).width;
+ };
+}
+
+function paintText(ctx: CanvasRenderingContext2D, op: Extract<Draft, { kind: "text" }>) {
+ ctx.font = textFont(op.size);
+ ctx.textBaseline = "top";
+ const lines = textLines(op.text);
+ const lineHeight = op.size * 1.25;
+ if (op.style === "label") {
+ const pad = op.size * 0.4;
+ const width = Math.max(...lines.map((line) => ctx.measureText(line).width));
+ ctx.fillStyle = op.color;
+ roundedRect(ctx, { x: op.at.x - pad, y: op.at.y - pad, w: width + pad * 2, h: lines.length * lineHeight + pad * 2 }, pad);
+ ctx.fill();
+ ctx.fillStyle = contrastOn(op.color);
+ } else if (op.style === "outline") {
+ ctx.lineJoin = "round";
+ ctx.lineWidth = Math.max(2, op.size / 6);
+ ctx.strokeStyle = contrastOn(op.color);
+ lines.forEach((line, i) => ctx.strokeText(line, op.at.x, op.at.y + i * lineHeight));
+ ctx.fillStyle = op.color;
+ } else {
+ ctx.fillStyle = op.color;
+ ctx.shadowColor = "rgba(0,0,0,0.45)";
+ ctx.shadowBlur = Math.max(2, op.size / 8);
+ }
+ lines.forEach((line, i) => ctx.fillText(line, op.at.x, op.at.y + i * lineHeight));
+}
+
+function paintCounter(ctx: CanvasRenderingContext2D, op: Extract<Draft, { kind: "counter" }>) {
+ ctx.beginPath();
+ ctx.arc(op.at.x, op.at.y, op.size, 0, Math.PI * 2);
+ ctx.fillStyle = op.color;
+ ctx.shadowColor = "rgba(0,0,0,0.35)";
+ ctx.shadowBlur = Math.max(2, op.size / 4);
+ ctx.fill();
+ ctx.shadowColor = "transparent";
+ ctx.lineWidth = Math.max(1.5, op.size / 9);
+ ctx.strokeStyle = "rgba(255,255,255,0.9)";
+ ctx.stroke();
+ ctx.fillStyle = contrastOn(op.color);
+ ctx.font = textFont(Math.round(op.size * (op.n > 9 ? 0.95 : 1.15)));
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText(String(op.n), op.at.x, op.at.y + op.size * 0.06);
+}
+
+/** Paint one annotation (crops and spotlights excluded — see paintOps). */
+export function paintShape(ctx: CanvasRenderingContext2D, base: CanvasImageSource, op: Draft) {
+ ctx.save();
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ switch (op.kind) {
+ case "arrow":
+ ctx.strokeStyle = op.color;
+ ctx.fillStyle = op.color;
+ ctx.lineWidth = op.width;
+ arrow(ctx, op.from, op.to, op.width);
+ break;
+ case "line":
+ ctx.strokeStyle = op.color;
+ ctx.lineWidth = op.width;
+ ctx.beginPath();
+ ctx.moveTo(op.from.x, op.from.y);
+ ctx.lineTo(op.to.x, op.to.y);
+ ctx.stroke();
+ break;
+ case "rect":
+ ctx.strokeStyle = op.color;
+ ctx.lineWidth = op.width;
+ roundedRect(ctx, op.rect, op.width);
+ ctx.stroke();
+ break;
+ case "filled":
+ ctx.fillStyle = op.color;
+ roundedRect(ctx, op.rect, op.width);
+ ctx.fill();
+ break;
+ case "ellipse":
+ ctx.strokeStyle = op.color;
+ ctx.lineWidth = op.width;
+ ctx.beginPath();
+ ctx.ellipse(
+ op.rect.x + op.rect.w / 2,
+ op.rect.y + op.rect.h / 2,
+ Math.max(1, op.rect.w / 2),
+ Math.max(1, op.rect.h / 2),
+ 0,
+ 0,
+ Math.PI * 2,
+ );
+ ctx.stroke();
+ break;
+ case "pen":
+ case "highlight":
+ if (op.points.length === 0) break;
+ ctx.strokeStyle = op.color;
+ ctx.lineWidth = op.kind === "highlight" ? op.width * 4 : op.width;
+ if (op.kind === "highlight") {
+ // Multiply keeps the text under the marker readable, like ink.
+ ctx.globalAlpha = 0.4;
+ ctx.globalCompositeOperation = "multiply";
+ ctx.lineCap = "butt";
+ }
+ smoothStroke(ctx, op.points);
+ break;
+ case "text":
+ paintText(ctx, op);
+ break;
+ case "counter":
+ paintCounter(ctx, op);
+ break;
+ case "redact":
+ redact(ctx, base, op.rect, op.mode, op.block);
+ break;
+ case "spotlight":
+ case "crop":
+ break;
+ }
+ ctx.restore();
+}
+
+/** Dim everything outside the spotlights, in one layer so they never stack. */
+function paintSpotlights(ctx: CanvasRenderingContext2D, spots: Rect[], width: number, height: number) {
+ if (spots.length === 0) return;
+ ctx.save();
+ ctx.fillStyle = "rgba(0,0,0,0.55)";
+ ctx.beginPath();
+ ctx.rect(0, 0, width, height);
+ for (const spot of spots) {
+ roundedRectPath(ctx, spot, Math.min(spot.w, spot.h) * 0.06);
+ }
+ ctx.fill("evenodd");
+ ctx.restore();
+}
+
+function roundedRectPath(ctx: CanvasRenderingContext2D, rect: Rect, radius: number) {
+ const r = Math.max(0, Math.min(radius, rect.w / 2, rect.h / 2));
+ ctx.moveTo(rect.x + r, rect.y);
+ ctx.arcTo(rect.x + rect.w, rect.y, rect.x + rect.w, rect.y + rect.h, r);
+ ctx.arcTo(rect.x + rect.w, rect.y + rect.h, rect.x, rect.y + rect.h, r);
+ ctx.arcTo(rect.x, rect.y + rect.h, rect.x, rect.y, r);
+ ctx.arcTo(rect.x, rect.y, rect.x + rect.w, rect.y, r);
+ ctx.closePath();
+}
+
/**
- * Paint the picture and every operation (crops excluded) in picture space.
- * The caller sets the transform: identity for an export, a scale + offset
- * for the screen.
+ * Paint the picture and every annotation in picture space. The caller sets
+ * the transform: identity for an export, a scale + offset for the screen.
*/
-export function paintOps(ctx: CanvasRenderingContext2D, base: CanvasImageSource, ops: Op[]) {
+export function paintOps(
+ ctx: CanvasRenderingContext2D,
+ base: CanvasImageSource,
+ ops: readonly Draft[],
+ size: { width: number; height: number },
+) {
ctx.drawImage(base, 0, 0);
+ const spots: Rect[] = [];
for (const op of ops) {
- ctx.save();
- ctx.lineCap = "round";
- ctx.lineJoin = "round";
- switch (op.kind) {
- case "arrow":
- ctx.strokeStyle = op.color;
- ctx.fillStyle = op.color;
- ctx.lineWidth = op.width;
- arrow(ctx, op.from, op.to, op.width);
- break;
- case "rect":
- ctx.strokeStyle = op.color;
- ctx.lineWidth = op.width;
- ctx.strokeRect(op.rect.x, op.rect.y, op.rect.w, op.rect.h);
- break;
- case "ellipse":
- ctx.strokeStyle = op.color;
- ctx.lineWidth = op.width;
- ctx.beginPath();
- ctx.ellipse(
- op.rect.x + op.rect.w / 2,
- op.rect.y + op.rect.h / 2,
- Math.max(1, op.rect.w / 2),
- Math.max(1, op.rect.h / 2),
- 0,
- 0,
- Math.PI * 2,
- );
- ctx.stroke();
- break;
- case "pen":
- case "highlight":
- if (op.points.length === 0) break;
- ctx.strokeStyle = op.color;
- ctx.lineWidth = op.kind === "highlight" ? op.width * 4 : op.width;
- if (op.kind === "highlight") {
- ctx.globalAlpha = 0.35;
- ctx.lineCap = "square";
- }
- ctx.beginPath();
- ctx.moveTo(op.points[0].x, op.points[0].y);
- for (const p of op.points.slice(1)) ctx.lineTo(p.x, p.y);
- if (op.points.length === 1) ctx.lineTo(op.points[0].x + 0.1, op.points[0].y);
- ctx.stroke();
- break;
- case "text": {
- ctx.font = `600 ${op.size}px Inter, "Segoe UI", system-ui, sans-serif`;
- ctx.textBaseline = "top";
- ctx.fillStyle = op.color;
- ctx.shadowColor = "rgba(0,0,0,0.45)";
- ctx.shadowBlur = Math.max(2, op.size / 8);
- op.text.split("\n").forEach((line, i) => {
- ctx.fillText(line, op.at.x, op.at.y + i * op.size * 1.25);
- });
- break;
- }
- case "pixelate":
- pixelate(ctx, base, op.rect, op.block);
- break;
- case "crop":
- break;
- }
- ctx.restore();
+ if (op.kind === "spotlight") spots.push(op.rect);
+ else paintShape(ctx, base, op);
}
+ paintSpotlights(ctx, spots, size.width, size.height);
}
-/** Render the finished picture (cropped, with every edit) to a PNG blob. */
-export async function exportPng(
+/** Render the finished picture: cropped, annotated and framed. */
+export function renderResult(
base: HTMLImageElement,
- ops: Op[],
-): Promise<Blob> {
- const view = viewport(ops, base.naturalWidth, base.naturalHeight);
- const canvas = document.createElement("canvas");
- canvas.width = Math.round(view.w);
- canvas.height = Math.round(view.h);
- const ctx = canvas.getContext("2d");
+ ops: readonly Op[],
+ background: Background,
+): HTMLCanvasElement {
+ const iw = base.naturalWidth;
+ const ih = base.naturalHeight;
+ const view = viewport(ops, iw, ih);
+ const picture = makeCanvas(view.w, view.h);
+ const pctx = picture.getContext("2d");
+ if (!pctx) throw new Error("No 2D canvas available.");
+ pctx.translate(-view.x, -view.y);
+ paintOps(pctx, base, ops, { width: iw, height: ih });
+ if (!background.enabled) return picture;
+
+ const layout = frameLayout(picture.width, picture.height, background);
+ const framed = makeCanvas(layout.width, layout.height);
+ const ctx = framed.getContext("2d");
if (!ctx) throw new Error("No 2D canvas available.");
- ctx.translate(-view.x, -view.y);
- paintOps(ctx, base, ops);
+ const preset = presetById(background.preset);
+ if (preset.stops.length === 1) {
+ ctx.fillStyle = preset.stops[0];
+ } else {
+ const gradient = ctx.createLinearGradient(0, 0, layout.width, layout.height);
+ preset.stops.forEach((stop, i) => gradient.addColorStop(i / (preset.stops.length - 1), stop));
+ ctx.fillStyle = gradient;
+ }
+ ctx.fillRect(0, 0, layout.width, layout.height);
+ if (background.shadow) {
+ ctx.save();
+ ctx.shadowColor = "rgba(0,0,0,0.35)";
+ ctx.shadowBlur = Math.max(12, layout.image.x * 0.5);
+ ctx.shadowOffsetY = Math.max(4, layout.image.x * 0.12);
+ ctx.fillStyle = "#000";
+ roundedRect(ctx, layout.image, layout.radius);
+ ctx.fill();
+ ctx.restore();
+ }
+ ctx.save();
+ roundedRect(ctx, layout.image, layout.radius);
+ ctx.clip();
+ ctx.drawImage(picture, layout.image.x, layout.image.y);
+ ctx.restore();
+ return framed;
+}
+
+/** The finished picture as a PNG blob. */
+export async function exportPng(base: HTMLImageElement, ops: readonly Op[], background: Background): Promise<Blob> {
+ const canvas = renderResult(base, ops, background);
return await new Promise<Blob>((resolve, reject) =>
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("Export failed."))), "image/png"),
);
diff --git a/jarvis/ui/web/frontend/src/store/appshotEditor.ts b/jarvis/ui/web/frontend/src/store/appshotEditor.ts
index fbfeff4d93..a96b5536c6 100644
--- a/jarvis/ui/web/frontend/src/store/appshotEditor.ts
+++ b/jarvis/ui/web/frontend/src/store/appshotEditor.ts
@@ -1,19 +1,45 @@
/**
- * Which appshot the editor should open. Set by a click on the appshot card in
- * the screen corner (the `AppshotEditRequested` event) or on the last appshot
- * on the Appshots page; the Appshots view renders the editor while it is set.
+ * Which appshot the editor shows. Set by a click on the appshot card in the
+ * screen corner (the `AppshotEditRequested` event) or on the last appshot on
+ * the Appshots page; `AppshotEditorHost` renders the editor over whatever view
+ * is open while it is set — nothing navigates away.
*/
import { create } from "zustand";
interface AppshotEditorState {
/** The appshot id to edit, or null when the editor is closed. */
openId: string | null;
+ /** Bumped whenever an edit replaced the held appshot, so previews refresh. */
+ revision: number;
open: (id: string) => void;
close: () => void;
+ applied: () => void;
}
export const useAppshotEditor = create<AppshotEditorState>((set) => ({
openId: null,
+ revision: 0,
open: (id) => set({ openId: id }),
close: () => set({ openId: null }),
+ applied: () => set((state) => ({ revision: state.revision + 1 })),
}));
+
+/**
+ * What the app does with an `AppshotEditRequested` event (a click on the
+ * appshot card). Only the main window acts — a detached solo window leaves it
+ * to the main one, which the backend also brings to the front.
+ *
+ * Returns what happened, for the toast and for tests.
+ */
+export function handleAppshotEditRequest(
+ payload: unknown,
+ { solo }: { solo: boolean },
+): "opened" | "gone" | "ignored" {
+ if (solo) return "ignored";
+ const id = (payload as { appshot_id?: unknown } | null)?.appshot_id;
+ if (typeof id === "string" && id) {
+ useAppshotEditor.getState().open(id);
+ return "opened";
+ }
+ return "gone";
+}
diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
index cbd9b6f923..56a4b9372e 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
@@ -1,107 +1,238 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
Check,
Circle,
Copy,
Crop,
Download,
+ Focus,
+ Image as ImageIcon,
Grid3x3,
Highlighter,
Loader2,
+ Minus,
+ MousePointer2,
MoveUpRight,
Pencil,
Redo2,
Square,
+ Trash2,
Type,
Undo2,
X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
import { QuickTooltip } from "@/components/ui/tooltip";
-import { useT } from "@/i18n";
+import { useCapabilities } from "@/hooks/useCapabilities";
+import { fill, useLocaleChunk, useT } from "@/i18n";
+import { copyAppshotPng } from "@/lib/appshotClipboard";
import { latestAppshotImageUrl } from "@/lib/appshotApi";
import {
+ BACKGROUND_PRESETS,
COLORS,
+ CROP_RATIOS,
+ DEFAULT_BACKGROUND,
+ TOOL_KEYS,
+ bounds,
+ canvasMeasure,
clampRect,
+ commit,
+ constrainEnd,
+ counterSize,
+ emptyHistory,
exportPng,
+ frameLayout,
+ hitTest,
+ isMeaningful,
+ nextCounter,
paintOps,
+ presetById,
+ presetCss,
rectFrom,
+ redo as redoHistory,
strokeWidths,
textSize,
+ toolForKey,
+ translate,
+ undo as undoHistory,
viewport,
+ withId,
+ type Background,
+ type Draft,
+ type History,
type Op,
type Point,
+ type RedactMode,
+ type TextStyle,
type Tool,
} from "@/lib/appshotEditorModel";
+import { saveOrDownload } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
/**
- * The appshot editor — annotate the last appshot the way ShareX's image
- * editor does: arrow, rectangle, ellipse, pen, highlighter, text, pixelate and
- * crop, with undo/redo. The result can be copied, saved, or put back in place
- * of the appshot so the next message carries the edited picture.
+ * The appshot editor — annotate a capture the way CleanShot X's annotate tool
+ * does: select/move, arrow, line, rectangle, filled rectangle, ellipse, draw,
+ * highlighter, text (three styles), counter, spotlight, pixelate/blur, crop
+ * (free or fixed ratio) and a background frame, with undo/redo and CleanShot's
+ * one-letter keys. The result can be copied, saved, or put back in place of
+ * the appshot so the next message carries the edited picture.
*
- * Everything happens in this window's memory; only "Save" writes a file (a
- * normal download the user asked for).
- *
- * Rendered in place (a fixed full-window layer), not portalled: inside the
- * Settings dialog it then counts as that dialog's nested modal, so its clicks
- * and Escape never read as "outside" and its text box can take focus.
+ * Copy goes through the OS clipboard on the desktop (`/api/appshot/clipboard`)
+ * because the WebView cannot be trusted with images; Save writes into
+ * Downloads through the backend because the desktop WebView drops browser
+ * downloads. In a plain browser both fall back to the browser's own paths.
*/
-const TOOLS: { tool: Tool; icon: typeof Square; key: string }[] = [
- { tool: "arrow", icon: MoveUpRight, key: "a" },
- { tool: "rect", icon: Square, key: "r" },
- { tool: "ellipse", icon: Circle, key: "e" },
- { tool: "pen", icon: Pencil, key: "p" },
- { tool: "highlight", icon: Highlighter, key: "h" },
- { tool: "text", icon: Type, key: "t" },
- { tool: "pixelate", icon: Grid3x3, key: "b" },
- { tool: "crop", icon: Crop, key: "c" },
-];
-
-interface Draft {
- op: Op;
- start: Point;
+const TOOL_ICONS: Record<Tool, typeof Square | null> = {
+ move: MousePointer2,
+ arrow: MoveUpRight,
+ line: Minus,
+ rect: Square,
+ filled: null,
+ ellipse: Circle,
+ pen: Pencil,
+ highlight: Highlighter,
+ text: Type,
+ counter: null,
+ spotlight: Focus,
+ redact: Grid3x3,
+ crop: Crop,
+ background: ImageIcon,
+};
+
+/** Tools whose colour and stroke size matter. */
+const INKED: ReadonlySet<Tool> = new Set(["arrow", "line", "rect", "filled", "ellipse", "pen", "highlight", "text", "counter"]);
+
+const COLOR_KEY = "jarvis.appshotEditor.color";
+const BACKGROUND_KEY = "jarvis.appshotEditor.background";
+
+function readStored<T>(key: string, fallback: T, valid: (value: unknown) => value is T): T {
+ try {
+ const raw = localStorage.getItem(key);
+ if (raw === null) return fallback;
+ const value: unknown = JSON.parse(raw);
+ return valid(value) ? value : fallback;
+ } catch {
+ return fallback;
+ }
}
+function writeStored(key: string, value: unknown) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // Storage can be off (private mode, a locked profile); the choice simply
+ // is not remembered.
+ }
+}
+
+const isColor = (value: unknown): value is string => typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value);
+const isBackground = (value: unknown): value is Background =>
+ typeof value === "object" && value !== null && "preset" in value && "padding" in value;
+
function stamp(): string {
return new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "").replace("T", "-");
}
-export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClose: () => void }) {
+type Gesture =
+ | { kind: "draw"; shape: Draft; start: Point }
+ | { kind: "move"; id: number; start: Point; dx: number; dy: number };
+
+type LoadState = "loading" | "ready" | "failed";
+
+interface Typing {
+ at: Point;
+ text: string;
+ /** The text annotation being changed, or null for a new one. */
+ replaceId: number | null;
+}
+
+export interface AppshotEditorProps {
+ appshotId: string;
+ onClose: () => void;
+ /** The edited picture replaced the held appshot. */
+ onApplied?: () => void;
+}
+
+export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorProps) {
const t = useT();
+ const ready = useLocaleChunk("appshot_editor");
+ const caps = useCapabilities();
+ const native = caps.data?.native_file_actions ?? false;
const pushToast = useEventStore((s) => s.pushToast);
+ const assistantName = useEventStore((s) => s.assistantName);
+
const [image, setImage] = useState<HTMLImageElement | null>(null);
- const [failed, setFailed] = useState(false);
- const [ops, setOps] = useState<Op[]>([]);
- const [redo, setRedo] = useState<Op[]>([]);
+ const [load, setLoad] = useState<LoadState>("loading");
+ const [history, setHistory] = useState<History>(emptyHistory);
+ const ops = history.present;
const [tool, setTool] = useState<Tool>("arrow");
- const [color, setColor] = useState(COLORS[0]);
+ const [color, setColorState] = useState(() => readStored(COLOR_KEY, COLORS[0], isColor));
const [widthIndex, setWidthIndex] = useState(1);
- const [draft, setDraftState] = useState<Draft | null>(null);
+ const [textStyle, setTextStyle] = useState<TextStyle>("plain");
+ const [redactMode, setRedactMode] = useState<RedactMode>("pixelate");
+ const [cropRatio, setCropRatio] = useState<string>("free");
+ const [background, setBackgroundState] = useState<Background>(() =>
+ ({ ...readStored(BACKGROUND_KEY, DEFAULT_BACKGROUND, isBackground), enabled: false }),
+ );
+ const [selectedId, setSelectedId] = useState<number | null>(null);
+ // The text box: state for painting, a ref so a commit reads the latest
+ // text without side effects inside a state updater.
+ const [typing, setTypingState] = useState<Typing | null>(null);
+ const typingRef = useRef<Typing | null>(null);
+ const setTyping = useCallback((next: Typing | null) => {
+ typingRef.current = next;
+ setTypingState(next);
+ }, []);
+ const [busy, setBusy] = useState<"" | "copy" | "save" | "apply">("");
+ const [dirty, setDirty] = useState(false);
+ const [confirmDiscard, setConfirmDiscard] = useState(false);
+
// Pointer events can outrun React's re-render (a quick flick sends its
// moves and the release before the press has rendered), so the handlers
- // read and write the draft through a ref; the state only drives painting.
- const draftRef = useRef<Draft | null>(null);
- const setDraft = useCallback((next: Draft | null) => {
- draftRef.current = next;
- setDraftState(next);
+ // read and write the gesture through a ref; the state only drives painting.
+ const gestureRef = useRef<Gesture | null>(null);
+ const [gesture, setGestureState] = useState<Gesture | null>(null);
+ const setGesture = useCallback((next: Gesture | null) => {
+ gestureRef.current = next;
+ setGestureState(next);
}, []);
- const [typing, setTyping] = useState<{ at: Point; text: string } | null>(null);
- const [busy, setBusy] = useState<"" | "copy" | "save" | "apply">("");
+
const stageRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [stage, setStage] = useState({ w: 0, h: 0 });
+ const measure = useMemo(() => {
+ let ctx: CanvasRenderingContext2D | null = null;
+ try {
+ ctx = document.createElement("canvas").getContext("2d");
+ } catch {
+ ctx = null;
+ }
+ return canvasMeasure(ctx);
+ }, []);
+
+ const setColor = (next: string) => {
+ setColorState(next);
+ writeStored(COLOR_KEY, next);
+ };
+ const setBackground = useCallback((patch: Partial<Background>) => {
+ setBackgroundState((current) => ({ ...current, ...patch }));
+ }, []);
+ useEffect(() => writeStored(BACKGROUND_KEY, background), [background]);
// -- load ----------------------------------------------------------------
useEffect(() => {
let alive = true;
const img = new Image();
- img.onload = () => alive && setImage(img);
- img.onerror = () => alive && setFailed(true);
+ img.onload = () => {
+ if (!alive) return;
+ setImage(img);
+ setLoad("ready");
+ };
+ img.onerror = () => alive && setLoad("failed");
img.src = latestAppshotImageUrl(appshotId);
return () => {
alive = false;
@@ -111,13 +242,13 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
useLayoutEffect(() => {
const el = stageRef.current;
if (!el) return;
- const measure = () => setStage({ w: el.clientWidth, h: el.clientHeight });
- measure();
+ const measureStage = () => setStage({ w: el.clientWidth, h: el.clientHeight });
+ measureStage();
if (typeof ResizeObserver === "undefined") {
- window.addEventListener("resize", measure);
- return () => window.removeEventListener("resize", measure);
+ window.addEventListener("resize", measureStage);
+ return () => window.removeEventListener("resize", measureStage);
}
- const observer = new ResizeObserver(measure);
+ const observer = new ResizeObserver(measureStage);
observer.observe(el);
return () => observer.disconnect();
}, []);
@@ -129,10 +260,27 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
const view = viewport(ops, iw, ih);
// While cropping, show the whole picture so a crop can also grow back.
const shown = tool === "crop" ? { x: 0, y: 0, w: iw, h: ih } : view;
+ const framing = tool === "crop" ? { ...background, enabled: false } : background;
+ const layout = frameLayout(shown.w || 1, shown.h || 1, framing);
const scale =
- shown.w > 0 && stage.w > 0 ? Math.min((stage.w - 48) / shown.w, (stage.h - 48) / shown.h, 1) : 1;
+ shown.w > 0 && stage.w > 0
+ ? Math.min((stage.w - 48) / layout.width, (stage.h - 48) / layout.height, 1)
+ : 1;
const cw = Math.max(1, Math.round(shown.w * scale));
const ch = Math.max(1, Math.round(shown.h * scale));
+ const ratio = CROP_RATIOS.find((entry) => entry.id === cropRatio)?.ratio ?? null;
+
+ // What is on screen: the document, a move in progress, and the shape being drawn.
+ const drawn = useMemo<Draft[]>(() => {
+ const live: Draft[] =
+ gesture?.kind === "move"
+ ? ops.map((op) => (op.id === gesture.id ? translate(op, gesture.dx, gesture.dy) : op))
+ : [...ops];
+ if (gesture?.kind === "draw" && gesture.shape.kind !== "crop") live.push(gesture.shape);
+ return live;
+ }, [gesture, ops]);
+
+ const selected = selectedId === null ? null : ops.find((op) => op.id === selectedId) ?? null;
// -- paint ---------------------------------------------------------------
useEffect(() => {
@@ -145,10 +293,9 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
if (!ctx) return;
ctx.setTransform(dpr * scale, 0, 0, dpr * scale, -shown.x * dpr * scale, -shown.y * dpr * scale);
ctx.clearRect(shown.x, shown.y, shown.w, shown.h);
- const drawn = draft && draft.op.kind !== "crop" ? [...ops, draft.op] : ops;
- paintOps(ctx, image, drawn.filter((op) => op.kind !== "crop"));
+ paintOps(ctx, image, drawn, { width: iw, height: ih });
if (tool === "crop") {
- const crop = draft?.op.kind === "crop" ? draft.op.rect : view;
+ const crop = gesture?.kind === "draw" && gesture.shape.kind === "crop" ? gesture.shape.rect : view;
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.55)";
ctx.beginPath();
@@ -157,31 +304,69 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
ctx.fill("evenodd");
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 1.5 / scale;
- ctx.setLineDash([6 / scale, 4 / scale]);
ctx.strokeRect(crop.x, crop.y, crop.w, crop.h);
ctx.restore();
}
- }, [image, ops, draft, tool, cw, ch, scale, shown.x, shown.y, shown.w, shown.h, iw, ih, view]);
+ const outlined =
+ selected && gesture?.kind === "move" && gesture.id === selected.id
+ ? translate(selected, gesture.dx, gesture.dy)
+ : selected;
+ if (outlined) {
+ const box = bounds(outlined, measure);
+ const pad = 6 / scale;
+ ctx.save();
+ ctx.lineWidth = 1.5 / scale;
+ ctx.setLineDash([5 / scale, 4 / scale]);
+ ctx.strokeStyle = "rgba(0,0,0,0.6)";
+ ctx.strokeRect(box.x - pad, box.y - pad, box.w + pad * 2, box.h + pad * 2);
+ ctx.lineDashOffset = 4.5 / scale;
+ ctx.strokeStyle = "#ffffff";
+ ctx.strokeRect(box.x - pad, box.y - pad, box.w + pad * 2, box.h + pad * 2);
+ ctx.restore();
+ }
+ }, [image, drawn, gesture, tool, cw, ch, scale, shown.x, shown.y, shown.w, shown.h, iw, ih, view, selected, measure]);
// -- editing -------------------------------------------------------------
- const push = useCallback((op: Op) => {
- setOps((prev) => [...prev, op]);
- setRedo([]);
+ const apply = useCallback((next: Op[]) => {
+ setHistory((current) => commit(current, next));
+ setDirty(true);
}, []);
+ const push = useCallback((shape: Draft) => apply([...history.present, withId(shape)]), [apply, history.present]);
+
const undo = useCallback(() => {
- if (ops.length === 0) return;
- setRedo([...redo, ops[ops.length - 1]]);
- setOps(ops.slice(0, -1));
- }, [ops, redo]);
-
- const redoOne = useCallback(() => {
- if (redo.length === 0) return;
- setOps([...ops, redo[redo.length - 1]]);
- setRedo(redo.slice(0, -1));
- }, [ops, redo]);
-
- const toImage = (event: React.PointerEvent): Point => {
+ setHistory(undoHistory);
+ setSelectedId(null);
+ }, []);
+ const redo = useCallback(() => {
+ setHistory(redoHistory);
+ setSelectedId(null);
+ }, []);
+
+ const removeSelected = useCallback(() => {
+ if (selectedId === null) return;
+ apply(ops.filter((op) => op.id !== selectedId));
+ setSelectedId(null);
+ }, [apply, ops, selectedId]);
+
+ const nudgeSelected = useCallback(
+ (dx: number, dy: number) => {
+ if (selectedId === null) return;
+ apply(ops.map((op) => (op.id === selectedId ? translate(op, dx, dy) : op)));
+ },
+ [apply, ops, selectedId],
+ );
+
+ const chooseTool = useCallback(
+ (next: Tool) => {
+ setTool(next);
+ if (next !== "move") setSelectedId(null);
+ if (next === "background") setBackground({ enabled: true });
+ },
+ [setBackground],
+ );
+
+ const toImage = (event: { clientX: number; clientY: number }): Point => {
const rect = canvasRef.current!.getBoundingClientRect();
return {
x: shown.x + (event.clientX - rect.left) / scale,
@@ -190,125 +375,159 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
};
const commitText = useCallback(() => {
- setTyping((current) => {
- if (current && current.text.trim()) {
- push({ kind: "text", at: current.at, text: current.text, color, size: textSize(width) });
- }
- return null;
- });
- }, [color, push, width]);
+ const current = typingRef.current;
+ setTyping(null);
+ if (!current) return;
+ const text = current.text.replace(/\s+$/, "");
+ if (current.replaceId !== null) {
+ const id = current.replaceId;
+ apply(
+ text
+ ? ops.map((op) => (op.id === id && op.kind === "text" ? { ...op, text } : op))
+ : ops.filter((op) => op.id !== id),
+ );
+ } else if (text.trim()) {
+ push({ kind: "text", at: current.at, text, color, size: textSize(width), style: textStyle });
+ }
+ }, [apply, color, ops, push, setTyping, textStyle, width]);
+
+ const editTextAt = (p: Point): boolean => {
+ const hit = hitTest(ops, p, 6 / scale, measure);
+ if (!hit || hit.kind !== "text") return false;
+ setTyping({ at: hit.at, text: hit.text, replaceId: hit.id });
+ return true;
+ };
- const onPointerDown = (event: React.PointerEvent) => {
+ const onPointerDown = (event: React.PointerEvent<HTMLCanvasElement>) => {
if (!image || event.button !== 0) return;
const p = toImage(event);
+ if (tool === "background") return;
if (tool === "text") {
- // Keep the press from moving focus to the dialog behind the canvas: it
- // would blur (and so close) the text box this click is about to open.
+ // Keep the press from moving focus away: it would blur (and so close)
+ // the text box this click is about to open.
event.preventDefault();
if (typing) commitText();
- setTyping({ at: p, text: "" });
+ if (!editTextAt(p)) setTyping({ at: p, text: "", replaceId: null });
+ return;
+ }
+ if (tool === "counter") {
+ push({ kind: "counter", at: p, n: nextCounter(ops), color, size: counterSize(width) });
+ return;
+ }
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ if (tool === "move") {
+ const hit = hitTest(ops, p, 6 / scale, measure);
+ setSelectedId(hit?.id ?? null);
+ if (hit) setGesture({ kind: "move", id: hit.id, start: p, dx: 0, dy: 0 });
return;
}
- (event.target as Element).setPointerCapture(event.pointerId);
const zero = { x: p.x, y: p.y, w: 0, h: 0 };
- let op: Op;
+ let shape: Draft;
switch (tool) {
case "arrow":
- op = { kind: "arrow", from: p, to: p, color, width };
+ case "line":
+ shape = { kind: tool, from: p, to: p, color, width };
break;
case "rect":
+ case "filled":
case "ellipse":
- op = { kind: tool, rect: zero, color, width };
+ shape = { kind: tool, rect: zero, color, width };
break;
case "pen":
case "highlight":
- op = { kind: tool, points: [p], color, width };
+ shape = { kind: tool, points: [p], color, width };
break;
- case "pixelate":
- op = { kind: "pixelate", rect: zero, block: Math.max(6, width * 2) };
+ case "spotlight":
+ shape = { kind: "spotlight", rect: zero };
+ break;
+ case "redact":
+ shape = { kind: "redact", rect: zero, mode: redactMode, block: Math.max(8, width * 3) };
break;
default:
- op = { kind: "crop", rect: zero };
+ shape = { kind: "crop", rect: zero };
}
- setDraft({ op, start: p });
+ setGesture({ kind: "draw", shape, start: p });
};
- const onPointerMove = (event: React.PointerEvent) => {
- const draft = draftRef.current;
- if (!draft) return;
+ const onPointerMove = (event: React.PointerEvent<HTMLCanvasElement>) => {
+ const current = gestureRef.current;
+ if (!current) return;
const p = toImage(event);
- const op = draft.op;
- let next: Op = op;
- if (op.kind === "arrow") next = { ...op, to: p };
- else if (op.kind === "pen" || op.kind === "highlight") next = { ...op, points: [...op.points, p] };
- else if (op.kind === "rect" || op.kind === "ellipse" || op.kind === "pixelate" || op.kind === "crop") {
- next = { ...op, rect: rectFrom(draft.start, p) };
+ if (current.kind === "move") {
+ setGesture({ ...current, dx: p.x - current.start.x, dy: p.y - current.start.y });
+ return;
}
- setDraft({ ...draft, op: next });
+ const shape = current.shape;
+ const end = constrainEnd(tool, current.start, p, event.shiftKey, ratio);
+ let next: Draft = shape;
+ if (shape.kind === "arrow" || shape.kind === "line") next = { ...shape, to: end };
+ else if (shape.kind === "pen" || shape.kind === "highlight") next = { ...shape, points: [...shape.points, p] };
+ else if ("rect" in shape) next = { ...shape, rect: rectFrom(current.start, end) } as Draft;
+ setGesture({ ...current, shape: next });
};
const onPointerUp = () => {
- const draft = draftRef.current;
- if (!draft) return;
- const op = draft.op;
- setDraft(null);
- if (op.kind === "arrow" && Math.hypot(op.to.x - op.from.x, op.to.y - op.from.y) < 4) return;
- if ("rect" in op) {
- const rect = clampRect(op.rect, iw, ih);
- if (!rect || rect.w < 4 || rect.h < 4) return;
- push({ ...op, rect } as Op);
- if (op.kind === "crop") setTool("arrow");
+ const current = gestureRef.current;
+ if (!current) return;
+ setGesture(null);
+ if (current.kind === "move") {
+ if (current.dx !== 0 || current.dy !== 0) {
+ apply(ops.map((op) => (op.id === current.id ? translate(op, current.dx, current.dy) : op)));
+ }
return;
}
- push(op);
+ let shape = current.shape;
+ if (shape.kind === "crop" || shape.kind === "redact" || shape.kind === "spotlight") {
+ const rect = clampRect(shape.rect, iw, ih);
+ if (!rect) return;
+ shape = { ...shape, rect } as Draft;
+ }
+ if (!isMeaningful(shape)) return;
+ push(shape);
+ if (shape.kind === "crop") setTool("move");
+ };
+
+ const onDoubleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
+ if (!image || typing) return;
+ editTextAt(toImage(event));
};
// -- results -------------------------------------------------------------
const render = useCallback(async () => {
- if (!image) throw new Error(t("appshots.editor.gone"));
- return await exportPng(image, ops);
- }, [image, ops, t]);
+ if (!image) throw new Error(t("appshot_editor.gone"));
+ return await exportPng(image, ops, background);
+ }, [background, image, ops, t]);
const copy = useCallback(async () => {
setBusy("copy");
try {
const blob = await render();
- // A browser that waits for focus or a permission never settles this
- // promise; the button must not spin forever.
- await Promise.race([
- navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]),
- new Promise((_, reject) =>
- window.setTimeout(() => reject(new Error(t("appshots.editor.copy_timeout"))), 5000),
- ),
- ]);
- pushToast("success", t("appshots.editor.copied"));
+ await copyAppshotPng(blob, { native, timeoutMessage: t("appshot_editor.copy_timeout") });
+ setDirty(false);
+ pushToast("success", t("appshot_editor.copied"));
} catch (error) {
- pushToast("error", t("appshots.editor.copy_failed").replace("{0}", (error as Error).message));
+ pushToast("error", fill(t("appshot_editor.copy_failed"), { 0: (error as Error).message }));
} finally {
setBusy("");
}
- }, [pushToast, render, t]);
+ }, [native, pushToast, render, t]);
const save = useCallback(async () => {
setBusy("save");
try {
const blob = await render();
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `appshot-${stamp()}.png`;
- document.body.appendChild(a);
- a.click();
- a.remove();
- window.setTimeout(() => URL.revokeObjectURL(url), 10_000);
+ const filename = `appshot-${stamp()}.png`;
+ const path = await saveOrDownload({ filename, blob, native });
+ setDirty(false);
+ if (path) pushToast("success", fill(t("appshot_editor.saved_to"), { 0: path }), { filePath: path, filename });
} catch (error) {
- pushToast("error", (error as Error).message);
+ pushToast("error", fill(t("appshot_editor.save_failed"), { 0: (error as Error).message }));
} finally {
setBusy("");
}
- }, [pushToast, render]);
+ }, [native, pushToast, render, t]);
- const apply = useCallback(async () => {
+ const use = useCallback(async () => {
setBusy("apply");
try {
const blob = await render();
@@ -321,195 +540,480 @@ export function AppshotEditor({ appshotId, onClose }: { appshotId: string; onClo
const body = (await response.json().catch(() => null)) as { detail?: string } | null;
throw new Error(body?.detail || `HTTP ${response.status}`);
}
- pushToast("success", t("appshots.editor.applied"));
+ pushToast("success", t("appshot_editor.applied"));
+ onApplied?.();
onClose();
} catch (error) {
- pushToast("error", (error as Error).message);
+ pushToast("error", fill(t("appshot_editor.apply_failed"), { 0: (error as Error).message }));
} finally {
setBusy("");
}
- }, [appshotId, onClose, pushToast, render, t]);
+ }, [appshotId, onApplied, onClose, pushToast, render, t]);
+
+ const requestClose = useCallback(() => {
+ if (dirty && ops.length > 0) setConfirmDiscard(true);
+ else onClose();
+ }, [dirty, onClose, ops.length]);
// -- keyboard ------------------------------------------------------------
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (typing) return; // the text box owns the keys while it is open
+ const target = event.target as HTMLElement | null;
+ if (target && (target.tagName === "INPUT" || target.tagName === "SELECT" || target.isContentEditable)) return;
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (event.key === "Escape") {
event.preventDefault();
- if (draftRef.current) setDraft(null);
- else onClose();
- } else if (mod && key === "z" && !event.shiftKey) {
+ if (confirmDiscard) setConfirmDiscard(false);
+ else if (gestureRef.current) setGesture(null);
+ else if (selectedId !== null) setSelectedId(null);
+ else requestClose();
+ return;
+ }
+ if (confirmDiscard) return;
+ if (mod && key === "z" && !event.shiftKey) {
event.preventDefault();
undo();
} else if (mod && (key === "y" || (key === "z" && event.shiftKey))) {
event.preventDefault();
- redoOne();
+ redo();
} else if (mod && key === "c") {
event.preventDefault();
void copy();
} else if (mod && key === "s") {
event.preventDefault();
void save();
+ } else if (mod && event.key === "Enter") {
+ event.preventDefault();
+ void use();
+ } else if ((event.key === "Delete" || event.key === "Backspace") && selectedId !== null) {
+ event.preventDefault();
+ removeSelected();
+ } else if (event.key.startsWith("Arrow") && selectedId !== null) {
+ event.preventDefault();
+ const step = (event.shiftKey ? 10 : 1) / Math.max(scale, 0.01);
+ const dx = event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0;
+ const dy = event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0;
+ nudgeSelected(dx, dy);
+ } else if (!mod && !event.altKey && ["1", "2", "3"].includes(event.key)) {
+ setWidthIndex(Number(event.key) - 1);
} else if (!mod && !event.altKey) {
- const hit = TOOLS.find((entry) => entry.key === key);
- if (hit) setTool(hit.tool);
+ const next = toolForKey(event.key);
+ if (next) chooseTool(next);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [copy, onClose, redoOne, save, setDraft, typing, undo]);
+ }, [chooseTool, confirmDiscard, copy, nudgeSelected, redo, removeSelected, requestClose, save, scale, selectedId, setGesture, typing, undo, use]);
- const toolLabel = (name: Tool) => t(`appshots.editor.tool_${name}`);
+ const label = (key: string) => (ready ? t(`appshot_editor.${key}`) : "");
+ const toolLabel = (name: Tool) => label(`tool_${name}`);
const textScreen = typing
? { left: (typing.at.x - shown.x) * scale, top: (typing.at.y - shown.y) * scale }
: null;
+ const cursor =
+ tool === "text" ? "text" : tool === "move" ? (gesture?.kind === "move" ? "grabbing" : "default") : tool === "background" ? "default" : "crosshair";
+ const frameOn = framing.enabled;
+ const preset = presetById(background.preset);
- return (
- <div
- className="fixed inset-0 z-[80] flex flex-col bg-background/95 backdrop-blur-sm"
- role="dialog"
- aria-modal="true"
- aria-label={t("appshots.editor.title")}
- data-testid="appshot-editor"
- >
- <div className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">
- <p className="mr-2 text-base font-medium text-foreground">{t("appshots.editor.title")}</p>
-
- <div className="flex items-center gap-0.5 rounded-lg bg-secondary/60 p-0.5" role="toolbar">
- {TOOLS.map(({ tool: name, icon: Icon, key }) => (
- <QuickTooltip key={name} content={`${toolLabel(name)} (${key.toUpperCase()})`} side="bottom">
- <button
- type="button"
- aria-label={toolLabel(name)}
- aria-pressed={tool === name}
- onClick={() => setTool(name)}
- data-testid={`appshot-editor-tool-${name}`}
- className={cn(
- "flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors",
- "hover:bg-popover hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
- tool === name && "bg-popover text-foreground shadow-sm",
- )}
- >
- <Icon className="h-4 w-4" aria-hidden />
- </button>
- </QuickTooltip>
- ))}
- </div>
+ const hint =
+ tool === "move"
+ ? label("hint_move")
+ : tool === "crop"
+ ? label("hint_crop")
+ : tool === "counter"
+ ? label("hint_counter")
+ : tool === "spotlight"
+ ? label("hint_spotlight")
+ : tool === "background"
+ ? label("hint_background")
+ : "";
- <div className="flex items-center gap-1.5" aria-label={t("appshots.editor.color")}>
- {COLORS.map((swatch) => (
- <button
- key={swatch}
- type="button"
- aria-label={swatch}
- aria-pressed={color === swatch}
- onClick={() => setColor(swatch)}
- className={cn(
- "h-5 w-5 rounded-full border border-border transition-transform focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
- color === swatch && "scale-110 ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",
- )}
- style={{ backgroundColor: swatch }}
- />
- ))}
+ return (
+ <div className="flex h-full w-full flex-col bg-background text-foreground" data-testid="appshot-editor">
+ {/* Top bar: close + title · tools · history and results. */}
+ <div className="flex shrink-0 items-center gap-3 border-b border-border px-3 py-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <QuickTooltip content={`${label("close")} (Esc)`} side="bottom">
+ <Button type="button" variant="ghost" size="sm" onClick={requestClose} aria-label={label("close")} data-testid="appshot-editor-close">
+ <X aria-hidden />
+ </Button>
+ </QuickTooltip>
+ <p className="hidden truncate text-sm font-medium text-foreground xl:block">{label("title")}</p>
</div>
- <div className="flex items-center gap-0.5 rounded-lg bg-secondary/60 p-0.5" aria-label={t("appshots.editor.size")}>
- {[0, 1, 2].map((index) => (
- <button
- key={index}
- type="button"
- aria-label={`${t("appshots.editor.size")} ${index + 1}`}
- aria-pressed={widthIndex === index}
- onClick={() => setWidthIndex(index)}
- className={cn(
- "flex h-8 w-8 items-center justify-center rounded-md transition-colors hover:bg-popover",
- widthIndex === index && "bg-popover shadow-sm",
- )}
- >
- <span className="rounded-full bg-foreground" style={{ width: 4 + index * 4, height: 4 + index * 4 }} />
- </button>
- ))}
+ <div className="flex min-w-0 flex-1 justify-center overflow-x-auto">
+ <div className="flex items-center gap-0.5 rounded-xl bg-secondary/70 p-1" role="toolbar" aria-label={label("tools")}>
+ {TOOL_KEYS.map(({ tool: name, key }) => {
+ const Icon = TOOL_ICONS[name];
+ return (
+ <QuickTooltip key={name} content={`${toolLabel(name)} (${key.toUpperCase()})`} side="bottom">
+ <button
+ type="button"
+ aria-label={toolLabel(name)}
+ aria-pressed={tool === name}
+ onClick={() => chooseTool(name)}
+ data-testid={`appshot-editor-tool-${name}`}
+ className={cn(
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors",
+ "hover:bg-popover hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
+ tool === name && "bg-popover text-foreground shadow-sm",
+ (name === "redact" || name === "move" || name === "background") && "ml-1",
+ )}
+ >
+ {name === "filled" ? (
+ <Square className="h-4 w-4" fill="currentColor" aria-hidden />
+ ) : name === "counter" ? (
+ <span className="flex h-4 w-4 items-center justify-center rounded-full bg-current text-[10px] font-bold leading-none">
+ <span className="text-popover">1</span>
+ </span>
+ ) : Icon ? (
+ <Icon className="h-4 w-4" aria-hidden />
+ ) : null}
+ </button>
+ </QuickTooltip>
+ );
+ })}
+ </div>
</div>
- <div className="flex items-center gap-0.5">
- <QuickTooltip content={`${t("appshots.editor.undo")} (Ctrl+Z)`} side="bottom">
- <Button type="button" variant="ghost" size="sm" onClick={undo} disabled={ops.length === 0} aria-label={t("appshots.editor.undo")}>
+ <div className="flex shrink-0 items-center gap-1.5">
+ <QuickTooltip content={`${label("undo")} (Ctrl+Z)`} side="bottom">
+ <Button type="button" variant="ghost" size="sm" onClick={undo} disabled={history.past.length === 0} aria-label={label("undo")} data-testid="appshot-editor-undo">
<Undo2 aria-hidden />
</Button>
</QuickTooltip>
- <QuickTooltip content={`${t("appshots.editor.redo")} (Ctrl+Y)`} side="bottom">
- <Button type="button" variant="ghost" size="sm" onClick={redoOne} disabled={redo.length === 0} aria-label={t("appshots.editor.redo")}>
+ <QuickTooltip content={`${label("redo")} (Ctrl+Shift+Z)`} side="bottom">
+ <Button type="button" variant="ghost" size="sm" onClick={redo} disabled={history.future.length === 0} aria-label={label("redo")} data-testid="appshot-editor-redo">
<Redo2 aria-hidden />
</Button>
</QuickTooltip>
+ <div className="mx-1 h-5 w-px bg-border" aria-hidden />
+ <QuickTooltip content={`${label("copy")} (Ctrl+C)`} side="bottom">
+ <Button type="button" variant="secondary" size="sm" onClick={() => void copy()} disabled={!image || busy !== ""} data-testid="appshot-editor-copy">
+ {busy === "copy" ? <Loader2 className="animate-spin" aria-hidden /> : <Copy aria-hidden />}
+ <span className="hidden lg:inline">{label("copy")}</span>
+ </Button>
+ </QuickTooltip>
+ <QuickTooltip content={`${label("save")} (Ctrl+S)`} side="bottom">
+ <Button type="button" variant="secondary" size="sm" onClick={() => void save()} disabled={!image || busy !== ""} data-testid="appshot-editor-save">
+ {busy === "save" ? <Loader2 className="animate-spin" aria-hidden /> : <Download aria-hidden />}
+ <span className="hidden lg:inline">{label("save")}</span>
+ </Button>
+ </QuickTooltip>
+ <QuickTooltip content={`${fill(label("apply_hint"), { name: assistantName })} (Ctrl+Enter)`} side="bottom">
+ <Button type="button" size="sm" onClick={() => void use()} disabled={!image || busy !== ""} data-testid="appshot-editor-apply">
+ {busy === "apply" ? <Loader2 className="animate-spin" aria-hidden /> : <Check aria-hidden />}
+ <span className="hidden md:inline">{label("apply")}</span>
+ </Button>
+ </QuickTooltip>
</div>
+ </div>
- <div className="ml-auto flex items-center gap-2">
- <Button type="button" variant="secondary" size="sm" onClick={() => void copy()} disabled={!image || busy !== ""} data-testid="appshot-editor-copy">
- {busy === "copy" ? <Loader2 className="animate-spin" aria-hidden /> : <Copy aria-hidden />}
- {t("appshots.editor.copy")}
- </Button>
- <Button type="button" variant="secondary" size="sm" onClick={() => void save()} disabled={!image || busy !== ""} data-testid="appshot-editor-save">
- {busy === "save" ? <Loader2 className="animate-spin" aria-hidden /> : <Download aria-hidden />}
- {t("appshots.editor.save")}
- </Button>
- <Button type="button" size="sm" onClick={() => void apply()} disabled={!image || busy !== ""} data-testid="appshot-editor-apply">
- {busy === "apply" ? <Loader2 className="animate-spin" aria-hidden /> : <Check aria-hidden />}
- {t("appshots.editor.apply")}
- </Button>
- <Button type="button" variant="ghost" size="sm" onClick={onClose} aria-label={t("appshots.editor.close")} data-testid="appshot-editor-close">
- <X aria-hidden />
+ {/* Options for the active tool. */}
+ <div className="flex min-h-11 shrink-0 flex-wrap items-center justify-center gap-x-4 gap-y-1.5 border-b border-border px-3 py-1.5 text-sm" data-testid="appshot-editor-options">
+ {INKED.has(tool) && (
+ <>
+ <div className="flex items-center gap-1.5" role="group" aria-label={label("color")}>
+ {COLORS.map((swatch) => (
+ <button
+ key={swatch}
+ type="button"
+ aria-label={swatch}
+ aria-pressed={color === swatch}
+ onClick={() => setColor(swatch)}
+ className={cn(
+ "h-5 w-5 rounded-full border border-border-strong transition-transform focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
+ color === swatch && "scale-110 ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",
+ )}
+ style={{ backgroundColor: swatch }}
+ />
+ ))}
+ <QuickTooltip content={label("custom_color")} side="bottom">
+ <label
+ className={cn(
+ "relative h-5 w-5 cursor-pointer overflow-hidden rounded-full border border-border-strong",
+ !COLORS.includes(color) && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",
+ )}
+ style={{ background: "conic-gradient(#ff3b30, #ffcc00, #34c759, #0a84ff, #af52de, #ff3b30)" }}
+ >
+ <input
+ type="color"
+ value={color}
+ onChange={(event) => setColor(event.target.value)}
+ aria-label={label("custom_color")}
+ className="absolute inset-0 cursor-pointer opacity-0"
+ data-testid="appshot-editor-custom-color"
+ />
+ </label>
+ </QuickTooltip>
+ </div>
+ <div className="flex items-center gap-0.5 rounded-lg bg-secondary/70 p-0.5" role="group" aria-label={label("size")}>
+ {(["size_small", "size_medium", "size_large"] as const).map((name, index) => (
+ <QuickTooltip key={name} content={`${label(name)} (${index + 1})`} side="bottom">
+ <button
+ type="button"
+ aria-label={label(name)}
+ aria-pressed={widthIndex === index}
+ onClick={() => setWidthIndex(index)}
+ className={cn(
+ "flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-popover",
+ widthIndex === index && "bg-popover shadow-sm",
+ )}
+ >
+ <span className="rounded-full bg-foreground" style={{ width: 3 + index * 3, height: 3 + index * 3 }} />
+ </button>
+ </QuickTooltip>
+ ))}
+ </div>
+ </>
+ )}
+
+ {tool === "text" && (
+ <Segmented
+ label={label("text_style")}
+ value={textStyle}
+ onChange={(value) => setTextStyle(value as TextStyle)}
+ options={[
+ { value: "plain", label: label("text_plain") },
+ { value: "label", label: label("text_label") },
+ { value: "outline", label: label("text_outline") },
+ ]}
+ testId="appshot-editor-text-style"
+ />
+ )}
+
+ {tool === "redact" && (
+ <Segmented
+ label={label("redact_mode")}
+ value={redactMode}
+ onChange={(value) => setRedactMode(value as RedactMode)}
+ options={[
+ { value: "pixelate", label: label("redact_pixelate") },
+ { value: "blur", label: label("redact_blur") },
+ ]}
+ testId="appshot-editor-redact-mode"
+ />
+ )}
+
+ {tool === "crop" && (
+ <Segmented
+ label={label("crop_ratio")}
+ value={cropRatio}
+ onChange={setCropRatio}
+ options={CROP_RATIOS.map((entry) => ({ value: entry.id, label: entry.id === "free" ? label("crop_free") : entry.id }))}
+ testId="appshot-editor-crop-ratio"
+ />
+ )}
+
+ {tool === "background" && (
+ <>
+ <label className="flex items-center gap-2 text-muted-foreground">
+ <Switch
+ checked={background.enabled}
+ onCheckedChange={(enabled) => setBackground({ enabled })}
+ aria-label={label("background_enabled")}
+ data-testid="appshot-editor-background-enabled"
+ />
+ {label("background_enabled")}
+ </label>
+ <div className="flex items-center gap-1.5" role="group" aria-label={label("background_preset")}>
+ {BACKGROUND_PRESETS.map((entry) => (
+ <button
+ key={entry.id}
+ type="button"
+ aria-label={entry.id}
+ aria-pressed={background.preset === entry.id}
+ onClick={() => setBackground({ preset: entry.id, enabled: true })}
+ className={cn(
+ "h-6 w-6 rounded-md border border-border-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
+ background.preset === entry.id && background.enabled && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",
+ )}
+ style={{ background: presetCss(entry) }}
+ />
+ ))}
+ </div>
+ <Slider label={label("background_padding")} min={0} max={0.2} step={0.01} value={background.padding} onChange={(padding) => setBackground({ padding, enabled: true })} />
+ <Slider label={label("background_radius")} min={0} max={40} step={1} value={background.radius} onChange={(radius) => setBackground({ radius, enabled: true })} />
+ <label className="flex items-center gap-2 text-muted-foreground">
+ <Switch checked={background.shadow} onCheckedChange={(shadow) => setBackground({ shadow })} aria-label={label("background_shadow")} />
+ {label("background_shadow")}
+ </label>
+ </>
+ )}
+
+ {tool === "move" && selected && (
+ <Button type="button" variant="ghost" size="sm" onClick={removeSelected} data-testid="appshot-editor-delete">
+ <Trash2 aria-hidden />
+ {label("delete")}
</Button>
- </div>
+ )}
+
+ {hint && <p className="text-muted-foreground">{hint}</p>}
</div>
- <div ref={stageRef} className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden">
- {failed ? (
- <p className="text-base text-muted-foreground">{t("appshots.editor.gone")}</p>
+ {/* The picture. */}
+ <div ref={stageRef} className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-muted/40">
+ {load === "failed" ? (
+ <div className="flex max-w-sm flex-col items-center gap-3 text-center" data-testid="appshot-editor-failed">
+ <p className="text-base text-muted-foreground">{label("gone")}</p>
+ <Button type="button" variant="secondary" size="sm" onClick={onClose}>
+ {label("close")}
+ </Button>
+ </div>
) : !image ? (
- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
+ {label("loading")}
+ </div>
) : (
- <div className="relative shadow-2xl ring-1 ring-border" style={{ width: cw, height: ch }}>
- <canvas
- ref={canvasRef}
- style={{ width: cw, height: ch, cursor: tool === "text" ? "text" : "crosshair", touchAction: "none" }}
- onPointerDown={onPointerDown}
- onPointerMove={onPointerMove}
- onPointerUp={onPointerUp}
- data-testid="appshot-editor-canvas"
- />
- {typing && textScreen && (
- <textarea
- autoFocus
- value={typing.text}
- placeholder={t("appshots.editor.text_placeholder")}
- onChange={(event) => setTyping({ ...typing, text: event.target.value })}
- onBlur={commitText}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !event.shiftKey) {
- event.preventDefault();
- commitText();
- } else if (event.key === "Escape") {
- event.preventDefault();
- setTyping(null);
- }
- }}
- rows={1}
- className="absolute resize-none border border-dashed border-white/70 bg-black/20 p-0 font-semibold leading-tight outline-none placeholder:text-white/50"
- style={{
- left: textScreen.left,
- top: textScreen.top,
- color,
- fontSize: textSize(width) * scale,
- minWidth: 120,
- }}
+ <div
+ className={cn(frameOn ? "" : "shadow-2xl ring-1 ring-border")}
+ style={
+ frameOn
+ ? { padding: layout.image.x * scale, background: presetCss(preset), borderRadius: 4 }
+ : undefined
+ }
+ data-testid="appshot-editor-frame"
+ >
+ <div
+ className="relative overflow-hidden"
+ style={{
+ width: cw,
+ height: ch,
+ borderRadius: frameOn ? layout.radius * scale : 0,
+ boxShadow: frameOn && background.shadow ? "0 12px 40px rgba(0,0,0,0.35)" : undefined,
+ }}
+ >
+ <canvas
+ ref={canvasRef}
+ style={{ width: cw, height: ch, cursor, touchAction: "none", display: "block" }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={() => setGesture(null)}
+ onDoubleClick={onDoubleClick}
+ data-testid="appshot-editor-canvas"
/>
- )}
+ {typing && textScreen && (
+ <textarea
+ autoFocus
+ value={typing.text}
+ placeholder={label("text_placeholder")}
+ onChange={(event) => setTyping({ ...typing, text: event.target.value })}
+ onBlur={commitText}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ commitText();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ setTyping(null);
+ }
+ }}
+ rows={Math.max(1, typing.text.split("\n").length)}
+ data-testid="appshot-editor-text-input"
+ className="absolute resize-none border border-dashed border-white/70 bg-black/25 p-0 font-semibold leading-tight outline-none placeholder:text-white/60"
+ style={{
+ left: textScreen.left,
+ top: textScreen.top,
+ color,
+ fontSize: textSize(width) * scale,
+ minWidth: 140,
+ }}
+ />
+ )}
+ </div>
</div>
)}
+
+ {confirmDiscard && (
+ <div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-[2px]" data-testid="appshot-editor-discard">
+ <div className="w-[min(360px,calc(100%-2rem))] rounded-2xl border border-border bg-popover p-5 text-popover-foreground shadow-2xl" role="alertdialog" aria-label={label("discard_title")}>
+ <p className="text-base font-semibold">{label("discard_title")}</p>
+ <p className="mt-1.5 text-sm text-muted-foreground">{label("discard_body")}</p>
+ <div className="mt-4 flex justify-end gap-2">
+ <Button type="button" variant="secondary" size="sm" autoFocus onClick={() => setConfirmDiscard(false)}>
+ {label("discard_keep")}
+ </Button>
+ <Button type="button" variant="destructive" size="sm" onClick={onClose} data-testid="appshot-editor-discard-confirm">
+ {label("discard_confirm")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Segmented({
+ label,
+ value,
+ onChange,
+ options,
+ testId,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ options: { value: string; label: string }[];
+ testId: string;
+}) {
+ return (
+ <div className="flex items-center gap-2" data-testid={testId}>
+ <span className="text-muted-foreground">{label}</span>
+ <div className="flex items-center gap-0.5 rounded-lg bg-secondary/70 p-0.5" role="group" aria-label={label}>
+ {options.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ aria-pressed={value === option.value}
+ onClick={() => onChange(option.value)}
+ className={cn(
+ "h-7 rounded-md px-2.5 text-sm text-muted-foreground transition-colors hover:bg-popover hover:text-foreground",
+ value === option.value && "bg-popover text-foreground shadow-sm",
+ )}
+ >
+ {option.label}
+ </button>
+ ))}
</div>
</div>
);
}
+
+function Slider({
+ label,
+ min,
+ max,
+ step,
+ value,
+ onChange,
+}: {
+ label: string;
+ min: number;
+ max: number;
+ step: number;
+ value: number;
+ onChange: (value: number) => void;
+}) {
+ return (
+ <label className="flex items-center gap-2 text-muted-foreground">
+ {label}
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ aria-label={label}
+ onChange={(event) => onChange(Number(event.currentTarget.value))}
+ className="h-1 w-24 cursor-pointer accent-primary"
+ />
+ </label>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx
index fe99484c06..64e262977b 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { formatAppshotHotkey } from "@/lib/appshotApi";
@@ -236,7 +236,7 @@ describe("AppshotsView editor", () => {
beforeEach(() => {
useEventStore.setState({ events: [], toasts: [], assistantName: "Jarvis" });
- useAppshotEditor.setState({ openId: null });
+ useAppshotEditor.setState({ openId: null, revision: 0 });
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
@@ -252,26 +252,27 @@ describe("AppshotsView editor", () => {
vi.unstubAllGlobals();
});
- it("opens from the last appshot and closes on Escape", async () => {
+ it("opens the editor on the last appshot without leaving the page", async () => {
+ useEventStore.setState({ activeSection: "appshots" });
render(<AppshotsView />);
fireEvent.click(await screen.findByTestId("appshots-preview-edit"));
- expect(await screen.findByTestId("appshot-editor")).toBeDefined();
- expect(useAppshotEditor.getState().openId).toBe("shot-1");
-
- fireEvent.keyDown(window, { key: "r" });
- expect(
- screen.getByTestId("appshot-editor-tool-rect").getAttribute("aria-pressed"),
- ).toBe("true");
- fireEvent.keyDown(window, { key: "Escape" });
- await waitFor(() => expect(screen.queryByTestId("appshot-editor")).toBeNull());
- expect(useAppshotEditor.getState().openId).toBeNull();
+ // AppshotEditorHost (mounted by App) draws it; the page only asks.
+ expect(useAppshotEditor.getState().openId).toBe("shot-1");
+ expect(useEventStore.getState().activeSection).toBe("appshots");
+ expect(screen.queryByTestId("appshot-editor")).toBeNull();
});
- it("opens when the card in the screen corner asked for it", async () => {
- useAppshotEditor.getState().open("shot-1");
+ it("shows the edited picture once an edit replaced the appshot", async () => {
render(<AppshotsView />);
- expect(await screen.findByTestId("appshot-editor")).toBeDefined();
+ await screen.findByTestId("appshots-preview-edit");
+ const latestCalls = () =>
+ (fetch as unknown as ReturnType<typeof vi.fn>).mock.calls.filter(([url]) => url === "/api/appshot/latest").length;
+ const before = latestCalls();
+
+ act(() => useAppshotEditor.getState().applied());
+
+ await waitFor(() => expect(latestCalls()).toBe(before + 1));
});
});
diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
index a0f66a83f4..ac2d4f2081 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
@@ -23,7 +23,6 @@ import { cn } from "@/lib/utils";
import { AppshotShortcutField } from "@/views/AppshotShortcutField";
import { useAppshotEditor } from "@/store/appshotEditor";
import { useEventStore } from "@/store/events";
-import { AppshotEditor } from "@/views/AppshotEditor";
/**
* Appshots — show the assistant the window you are working in.
@@ -215,10 +214,9 @@ export function AppshotsView() {
const [saving, setSaving] = useState(false);
const [countdown, setCountdown] = useState<number | null>(null);
const [picking, setPicking] = useState(false);
- const editorId = useAppshotEditor((s) => s.openId);
const openEditor = useAppshotEditor((s) => s.open);
- const closeEditor = useAppshotEditor((s) => s.close);
- const [revision, setRevision] = useState(0);
+ // Bumped by AppshotEditorHost when an edit replaced the held picture.
+ const revision = useAppshotEditor((s) => s.revision);
// While a shortcut field records (or refuses a gesture), its row says so
// in place of the description.
const [fieldStatus, setFieldStatus] = useState<{ window: string | null; region: string | null }>({
@@ -247,7 +245,8 @@ export function AppshotsView() {
};
}, [pushToast]);
- // Refetch the last appshot whenever the backend reports a new one.
+ // Refetch the last appshot whenever the backend reports a new one, or an
+ // edit replaced it.
useEffect(() => {
let active = true;
fetchLatestAppshot()
@@ -256,7 +255,7 @@ export function AppshotsView() {
return () => {
active = false;
};
- }, [lastAppshotEvent]);
+ }, [lastAppshotEvent, revision]);
useEffect(
() => () => {
@@ -575,19 +574,6 @@ export function AppshotsView() {
<p className="mt-5 text-sm text-muted-foreground">{t("appshots.voice_hint")}</p>
</div>
- {editorId !== null && (
- <AppshotEditor
- appshotId={editorId}
- onClose={() => {
- closeEditor();
- // An applied edit changed the held picture: show the new one.
- setRevision((n) => n + 1);
- fetchLatestAppshot()
- .then((body) => setLatest(body.appshot))
- .catch(() => undefined);
- }}
- />
- )}
</div>
);
}