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): adjustable crop frame and pictures added beside, below or on top in the full editor

rubenluetke10-beepc1c390adb8c4
diff --git a/docs/appshots.md b/docs/appshots.md
index 96a979e814..675ca8bbf8 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -173,7 +173,8 @@ app. Nothing navigates away.
menu (presets + any colour) and the size slider, then **Save** and
**Done**.
- **Options capsule:** under the top bar, only for tools that have options
- (text style, pixelate or blur, crop ratio, background) or a hint.
+ (text style, pixelate or blur, crop ratio with size, Reset and Crop,
+ background) or a hint. **Add picture** opens a side panel instead.
- **Bottom bar:** zoom (Fit, 50 %, 100 %, 200 %), undo and redo; a **Drag me**
handle in the middle; delete (with a selection), save and copy on the right.
@@ -188,8 +189,17 @@ app. Nothing navigates away.
| 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. |
+| K | Crop | A frame over the whole document with corner grips (and edge grips for a free crop), a thirds grid and its size in pixels. Drag a grip or the frame itself, or drag outside it for a new one; Free, 1:1, 4:3 or 16:9 (a ratio reshapes the frame at once). Enter or **Crop** finishes, **Reset** shows everything again, 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. |
+| I | Add picture | Puts another picture into the document: an earlier appshot from the gallery, a file, a pasted picture (Ctrl+V) or one dropped onto the editor. It goes **beside** (same height), **below** (same width) or **on top** (small, in the middle) of what is visible; the choice is remembered. |
+
+**Several pictures in one.** An added picture is a layer of the document,
+painted under every annotation, so an arrow or a highlight can run from one
+picture into the next. The select tool (V) moves it and its corner grips
+resize it without distorting it; Delete removes it. The document grows with
+its pictures, a crop that is in place grows to take a new picture in, and
+Copy, Save, Drag me and Done hand on the combined picture. Pixelate and blur
+hide whatever picture lies under them.
Taking hold of annotations: the **select tool** picks up any annotation —
the pointer turns into a move cursor over it, a drag moves it, a click
@@ -235,7 +245,8 @@ it outside the editor; **not done** = not built, with the reason.
| Text styles (7) | Partly: 3 styles |
| Move/select annotations | Done |
| Rotate, flip, resize image | Not done |
-| Combine images, editable project file | Not done |
+| Combine images | Done: add pictures beside, below or on top (gallery, file, paste, drop) |
+| Editable project file | Not done |
| Capture area / window / fullscreen, freeze, crosshair with coordinates | Elsewhere: the area picker and the window shortcut ([Selecting an area](#selecting-an-area)); no fullscreen mode |
| Corner card (copy / save / annotate / drag after capture) | Elsewhere: the corner card (click = editor, drag = file) |
| Editor window: drag handle, zoom, Save / Done | Done: "Drag me" (Windows, macOS), zoom Fit/50/100/200 %, Save to Downloads, Done = use in the next message |
diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx
index 060971b2b6..cc909e1044 100644
--- a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx
@@ -247,6 +247,74 @@ describe("AppshotEditorHost", () => {
expect(await screen.findByTestId("appshot-editor-failed")).toBeDefined();
});
+
+ it("crops with a frame whose grips stay adjustable until Enter", async () => {
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ const canvas = await screen.findByTestId("appshot-editor-canvas");
+ const size = () => screen.getByTestId("appshot-editor-crop-size").textContent;
+ const drag = (id: number, from: [number, number], to: [number, number]) => {
+ fireEvent.pointerDown(canvas, { button: 0, clientX: from[0], clientY: from[1], pointerId: id });
+ fireEvent.pointerMove(canvas, { clientX: to[0], clientY: to[1], pointerId: id });
+ fireEvent.pointerUp(canvas, { clientX: to[0], clientY: to[1], pointerId: id });
+ };
+
+ fireEvent.keyDown(window, { key: "k" });
+ expect(size()).toBe("400 × 300");
+ drag(1, [50, 50], [250, 200]);
+ await waitFor(() => expect(size()).toBe("200 × 150"));
+ // Still cropping: the right edge's grip widens the frame.
+ drag(2, [250, 125], [300, 125]);
+ await waitFor(() => expect(size()).toBe("250 × 150"));
+
+ fireEvent.keyDown(window, { key: "Enter" });
+ expect(screen.getByTestId("appshot-editor-tool-move").getAttribute("aria-pressed")).toBe("true");
+ expect(screen.queryByTestId("appshot-editor")).not.toBeNull();
+
+ fireEvent.keyDown(window, { key: "k" });
+ fireEvent.click(screen.getByTestId("appshot-editor-crop-reset"));
+ await waitFor(() => expect(size()).toBe("400 × 300"));
+ });
+
+ it("adds an earlier appshot beside the picture", async () => {
+ const item = {
+ id: "abc123",
+ variant: "original",
+ path: "/kept/appshot.png",
+ mime: "image/png",
+ width: 400,
+ height: 300,
+ label: "",
+ app_name: "Code",
+ trigger: "hotkey",
+ taken_at: 1,
+ edited_at: 0,
+ has_edit: false,
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).startsWith("/api/appshot/library")
+ ? json({ items: [item], max_entries: 500 })
+ : json({ native_file_actions: false, platform: "linux" }),
+ ),
+ );
+ render(<AppshotEditorHost />);
+ act(() => useAppshotEditor.getState().open("shot-1"));
+ await screen.findByTestId("appshot-editor-canvas");
+
+ fireEvent.keyDown(window, { key: "i" });
+ expect(screen.getByTestId("appshot-editor-place-beside").getAttribute("aria-pressed")).toBe("true");
+ fireEvent.click((await screen.findAllByTestId("appshot-editor-import-item"))[0]);
+
+ // The picture joins at the same height and is selected to be moved or sized.
+ await waitFor(() => expect(screen.queryByTestId("appshot-editor-import-panel")).toBeNull());
+ expect(screen.getByTestId("appshot-editor-tool-move").getAttribute("aria-pressed")).toBe("true");
+ expect((screen.getByTestId("appshot-editor-undo") as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent.keyDown(window, { key: "k" });
+ expect(screen.getByTestId("appshot-editor-crop-size").textContent).toBe("800 × 300");
+ });
});
describe("handleAppshotEditRequest", () => {
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
index a81f1dae43..6edbb160de 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json
@@ -44,6 +44,21 @@
"redact_blur": "Weichzeichnen",
"crop_ratio": "Seitenverhältnis",
"crop_free": "Frei",
+ "crop_reset": "Zurücksetzen",
+ "crop_apply": "Zuschneiden",
+ "hint_crop": "Zieh an einem Griff oder verschieb den Rahmen. Außerhalb ziehen startet einen neuen.",
+ "import": "Bild hinzufügen",
+ "import_place": "Platzieren",
+ "place_beside": "Daneben",
+ "place_below": "Darunter",
+ "place_over": "Darüber",
+ "import_library": "Deine Appshots",
+ "import_library_empty": "Noch keine aufbewahrten Appshots. Wähl stattdessen eine Datei.",
+ "import_library_failed": "Deine Appshots konnten nicht geladen werden. Wähl stattdessen eine Datei.",
+ "import_file": "Datei auswählen…",
+ "import_paste_hint": "Oder ein Bild einfügen (Strg+V) oder hierher ziehen.",
+ "import_drop": "Loslassen zum Hinzufügen: {0}",
+ "import_failed": "Dieses Bild konnte nicht hinzugefügt werden.",
"background_enabled": "Bild einrahmen",
"background_preset": "Hintergrund",
"background_padding": "Abstand",
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
index 7c428c9818..fe18cac10e 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json
@@ -44,6 +44,21 @@
"redact_blur": "Blur",
"crop_ratio": "Aspect ratio",
"crop_free": "Free",
+ "crop_reset": "Reset",
+ "crop_apply": "Crop",
+ "hint_crop": "Drag a grip or the frame. Drag outside it for a new one.",
+ "import": "Add picture",
+ "import_place": "Place it",
+ "place_beside": "Beside",
+ "place_below": "Below",
+ "place_over": "On top",
+ "import_library": "Your appshots",
+ "import_library_empty": "No kept appshots yet. Pick a file instead.",
+ "import_library_failed": "Your appshots could not be loaded. Pick a file instead.",
+ "import_file": "Choose a file…",
+ "import_paste_hint": "Or paste a picture (Ctrl+V) or drop one here.",
+ "import_drop": "Drop to add it: {0}",
+ "import_failed": "This picture could not be added.",
"background_enabled": "Frame the picture",
"background_preset": "Backdrop",
"background_padding": "Padding",
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
index e28896d86e..e1ba150b5f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json
@@ -44,6 +44,21 @@
"redact_blur": "Difuminar",
"crop_ratio": "Proporción",
"crop_free": "Libre",
+ "crop_reset": "Restablecer",
+ "crop_apply": "Recortar",
+ "hint_crop": "Arrastra un tirador o el marco. Arrastra fuera para uno nuevo.",
+ "import": "Añadir imagen",
+ "import_place": "Colocar",
+ "place_beside": "Al lado",
+ "place_below": "Debajo",
+ "place_over": "Encima",
+ "import_library": "Tus appshots",
+ "import_library_empty": "Aún no hay appshots guardados. Elige un archivo.",
+ "import_library_failed": "No se pudieron cargar tus appshots. Elige un archivo.",
+ "import_file": "Elegir un archivo…",
+ "import_paste_hint": "O pega una imagen (Ctrl+V) o suéltala aquí.",
+ "import_drop": "Suelta para añadirla: {0}",
+ "import_failed": "No se pudo añadir esta imagen.",
"background_enabled": "Enmarcar la imagen",
"background_preset": "Fondo",
"background_padding": "Margen",
diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
index 6dfe8bf767..bb99e5c924 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts
@@ -2,6 +2,16 @@ import { describe, expect, it } from "vitest";
import {
ARROW_STYLES,
+ addImage,
+ coversAll,
+ cropHandleAt,
+ cropHandles,
+ extent,
+ fitRatio,
+ moveCrop,
+ placeImage,
+ resizeCrop,
+ withCrop,
handleAt,
handleCursor,
handles,
@@ -331,3 +341,74 @@ describe("grabScope", () => {
expect(grabScope("background")).toBe("none");
});
});
+
+describe("crop frame", () => {
+ const area = { x: 0, y: 0, w: 200, h: 100 };
+
+ it("offers edge grips only for a free crop", () => {
+ expect(cropHandles({ x: 10, y: 10, w: 50, h: 40 }, null)).toHaveLength(8);
+ expect(cropHandles({ x: 10, y: 10, w: 50, h: 40 }, 1).map((h) => h.id)).toEqual(["nw", "ne", "se", "sw"]);
+ expect(cropHandleAt({ x: 10, y: 10, w: 50, h: 40 }, { x: 35, y: 11 }, 4, null)).toBe("n");
+ expect(cropHandleAt({ x: 10, y: 10, w: 50, h: 40 }, { x: 35, y: 11 }, 4, 1)).toBeNull();
+ });
+
+ it("moves one edge, or a corner against the opposite one, inside the document", () => {
+ const rect = { x: 20, y: 20, w: 100, h: 50 };
+ expect(resizeCrop(rect, "e", { x: 150, y: 0 }, area, null)).toEqual({ x: 20, y: 20, w: 130, h: 50 });
+ expect(resizeCrop(rect, "n", { x: 0, y: -40 }, area, null)).toEqual({ x: 20, y: 0, w: 100, h: 70 });
+ expect(resizeCrop(rect, "se", { x: 400, y: 400 }, area, null)).toEqual({ x: 20, y: 20, w: 180, h: 80 });
+ // A fixed ratio holds even where the document stops it.
+ const square = resizeCrop(rect, "se", { x: 400, y: 400 }, area, 1);
+ expect(square.w).toBeCloseTo(80);
+ expect(square.h).toBeCloseTo(80);
+ });
+
+ it("never lets the frame turn inside out or leave the document", () => {
+ const rect = { x: 20, y: 20, w: 100, h: 50 };
+ expect(resizeCrop(rect, "w", { x: 500, y: 0 }, area, null).w).toBe(8);
+ expect(moveCrop(rect, 500, -500, area)).toEqual({ x: 100, y: 0, w: 100, h: 50 });
+ });
+
+ it("fits a ratio into the middle of what is visible", () => {
+ expect(fitRatio({ x: 0, y: 0, w: 200, h: 100 }, 1)).toEqual({ x: 50, y: 0, w: 100, h: 100 });
+ });
+
+ it("keeps a single crop, and none for the whole document", () => {
+ const once = withCrop([pen, crop], { x: 0, y: 0, w: 30, h: 30 });
+ expect(once.filter((op) => op.kind === "crop")).toHaveLength(1);
+ expect(withCrop(once, null).some((op) => op.kind === "crop")).toBe(false);
+ expect(coversAll({ x: 0, y: 0, w: 200, h: 100 }, area)).toBe(true);
+ });
+});
+
+describe("more pictures", () => {
+ it("places a picture beside at the same height, below at the same width, or over the middle", () => {
+ const view = { x: 0, y: 0, w: 400, h: 200 };
+ expect(placeImage(view, 100, 100, "beside")).toEqual({ x: 400, y: 0, w: 200, h: 200 });
+ expect(placeImage(view, 200, 100, "below")).toEqual({ x: 0, y: 200, w: 400, h: 200 });
+ const over = placeImage(view, 1000, 1000, "over");
+ expect(over.w).toBeCloseTo(90);
+ expect(over.x + over.w / 2).toBeCloseTo(200);
+ });
+
+ it("grows the document with the pictures added to it", () => {
+ const { ops, id } = addImage([], 400, 200, { src: "a.png", width: 100, height: 100 }, "beside");
+ expect(ops.find((op) => op.id === id)?.kind).toBe("image");
+ expect(extent(ops, 400, 200)).toEqual({ x: 0, y: 0, w: 600, h: 200 });
+ expect(viewport(ops, 400, 200)).toEqual({ x: 0, y: 0, w: 600, h: 200 });
+ });
+
+ it("widens a crop so an added picture is never out of sight", () => {
+ const cropped = [withId({ kind: "crop", rect: { x: 50, y: 50, w: 100, h: 50 } } as const)];
+ const { ops } = addImage(cropped, 400, 200, { src: "a.png", width: 100, height: 100 }, "beside");
+ expect(viewport(ops, 400, 200)).toEqual({ x: 50, y: 50, w: 150, h: 50 });
+ });
+
+ it("is moved only with the select tool and keeps its shape when resized", () => {
+ const picture = withId({ kind: "image", rect: { x: 0, y: 0, w: 200, h: 100 }, src: "a.png" } as const);
+ expect(hitTest([picture], { x: 50, y: 50 }, 2)?.id).toBe(picture.id);
+ expect(hitTest([picture], { x: 50, y: 50 }, 2, undefined, { areas: false })).toBeNull();
+ const grown = reshape(picture, "se", { x: 400, y: 120 });
+ expect(grown.rect).toEqual({ x: 0, y: 0, w: 400, h: 200 });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
index 7c13f54fcf..3ccc64d75f 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts
@@ -11,6 +11,11 @@
*
* A crop is an annotation too: the last one sets the visible part of the
* picture, and undo brings the rest back.
+ *
+ * More pictures can join the first one (``image`` layers: an earlier appshot
+ * or a file placed beside, below or on top). The document then spans all of
+ * them — its extent — and they are painted under every annotation, so marks
+ * can cross from one picture to the next.
*/
export type Tool =
@@ -62,7 +67,9 @@ type Shape =
| { 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 };
+ | { kind: "crop"; rect: Rect }
+ /** Another picture placed into the document; ``src`` names it in the editor's sources. */
+ | { kind: "image"; rect: Rect; src: string };
/** One annotation. `id` survives moves, so a selection outlives an edit. */
export type Op = Shape & { id: number };
@@ -210,25 +217,205 @@ 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. */
+/** The smallest rectangle around both. */
+export function unionRect(a: Rect, b: Rect): Rect {
+ const x = Math.min(a.x, b.x);
+ const y = Math.min(a.y, b.y);
+ return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y };
+}
+
+/** The whole document: the first picture and every picture placed with it. */
+export function extent(ops: readonly Draft[], width: number, height: number): Rect {
+ let area: Rect = { x: 0, y: 0, w: width, h: height };
+ for (const op of ops) if (op.kind === "image") area = unionRect(area, op.rect);
+ return area;
+}
+
+/** The visible part of the document: the last crop, or all of it. */
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;
}
- return { x: 0, y: 0, w: width, h: height };
+ return extent(ops, width, height);
}
-/** Clamp a rect to the picture; `null` when nothing of it is left. */
-export function clampRect(rect: Rect, width: number, height: number): Rect | null {
- const x = Math.max(0, Math.min(width, rect.x));
- const y = Math.max(0, Math.min(height, rect.y));
- const right = Math.max(0, Math.min(width, rect.x + rect.w));
- const bottom = Math.max(0, Math.min(height, rect.y + rect.h));
+/** Clamp a rect into ``area``; `null` when nothing of it is left. */
+export function clampInto(rect: Rect, area: Rect): Rect | null {
+ const x = Math.max(area.x, Math.min(area.x + area.w, rect.x));
+ const y = Math.max(area.y, Math.min(area.y + area.h, rect.y));
+ const right = Math.max(area.x, Math.min(area.x + area.w, rect.x + rect.w));
+ const bottom = Math.max(area.y, Math.min(area.y + area.h, rect.y + rect.h));
if (right - x < 2 || bottom - y < 2) return null;
return { x, y, w: right - x, h: bottom - y };
}
+/** Clamp a rect to a picture of this size; `null` when nothing of it is left. */
+export function clampRect(rect: Rect, width: number, height: number): Rect | null {
+ return clampInto(rect, { x: 0, y: 0, w: width, h: height });
+}
+
+// -- crop: an adjustable frame over the document ----------------------------------
+
+/** A grip on the crop frame: four corners, and the four edges for a free crop. */
+export type CropHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
+
+/** The smallest crop, in document pixels. */
+const MIN_CROP = 8;
+
+/** The grips the crop frame shows; a fixed ratio keeps only the corners. */
+export function cropHandles(rect: Rect, ratio: number | null): { id: CropHandle; at: Point }[] {
+ const { x, y, w, h } = rect;
+ const corners: { id: CropHandle; at: Point }[] = [
+ { id: "nw", at: { x, y } },
+ { id: "ne", at: { x: x + w, y } },
+ { id: "se", at: { x: x + w, y: y + h } },
+ { id: "sw", at: { x, y: y + h } },
+ ];
+ if (ratio !== null) return corners;
+ return [
+ ...corners,
+ { id: "n", at: { x: x + w / 2, y } },
+ { id: "e", at: { x: x + w, y: y + h / 2 } },
+ { id: "s", at: { x: x + w / 2, y: y + h } },
+ { id: "w", at: { x, y: y + h / 2 } },
+ ];
+}
+
+/** The crop grip under ``p`` (within ``radius``), nearest first. */
+export function cropHandleAt(rect: Rect, p: Point, radius: number, ratio: number | null): CropHandle | null {
+ let best: CropHandle | null = null;
+ let bestDistance = radius;
+ for (const handle of cropHandles(rect, ratio)) {
+ const distance = Math.hypot(handle.at.x - p.x, handle.at.y - p.y);
+ if (distance <= bestDistance) {
+ best = handle.id;
+ bestDistance = distance;
+ }
+ }
+ return best;
+}
+
+/**
+ * The crop frame ``original`` with grip ``handle`` dragged to ``p``, kept
+ * inside ``area``. A corner pulls against the opposite corner (and keeps a
+ * fixed ratio); an edge moves only itself.
+ */
+export function resizeCrop(original: Rect, handle: CropHandle, p: Point, area: Rect, ratio: number | null): Rect {
+ const left = original.x;
+ const top = original.y;
+ const right = original.x + original.w;
+ const bottom = original.y + original.h;
+ const px = Math.max(area.x, Math.min(area.x + area.w, p.x));
+ const py = Math.max(area.y, Math.min(area.y + area.h, p.y));
+ if (handle === "n") {
+ const y = Math.min(py, bottom - MIN_CROP);
+ return { x: left, y, w: original.w, h: bottom - y };
+ }
+ if (handle === "s") return { x: left, y: top, w: original.w, h: Math.max(py, top + MIN_CROP) - top };
+ if (handle === "w") {
+ const x = Math.min(px, right - MIN_CROP);
+ return { x, y: top, w: right - x, h: original.h };
+ }
+ if (handle === "e") return { x: left, y: top, w: Math.max(px, left + MIN_CROP) - left, h: original.h };
+ const anchor = {
+ x: handle === "nw" || handle === "sw" ? right : left,
+ y: handle === "nw" || handle === "ne" ? bottom : top,
+ };
+ const dirX = handle === "ne" || handle === "se" ? 1 : -1;
+ const dirY = handle === "sw" || handle === "se" ? 1 : -1;
+ const roomX = dirX > 0 ? area.x + area.w - anchor.x : anchor.x - area.x;
+ const roomY = dirY > 0 ? area.y + area.h - anchor.y : anchor.y - area.y;
+ let w = Math.max(MIN_CROP, Math.min(roomX, (px - anchor.x) * dirX));
+ let h = Math.max(MIN_CROP, Math.min(roomY, (py - anchor.y) * dirY));
+ if (ratio !== null && ratio > 0) {
+ w = Math.max(w, h * ratio);
+ h = w / ratio;
+ if (w > roomX) {
+ w = roomX;
+ h = w / ratio;
+ }
+ if (h > roomY) {
+ h = roomY;
+ w = h * ratio;
+ }
+ }
+ return { x: dirX > 0 ? anchor.x : anchor.x - w, y: dirY > 0 ? anchor.y : anchor.y - h, w, h };
+}
+
+/** The crop frame moved by ``dx``/``dy``, stopping at the edges of ``area``. */
+export function moveCrop(rect: Rect, dx: number, dy: number, area: Rect): Rect {
+ return {
+ ...rect,
+ x: Math.max(area.x, Math.min(area.x + area.w - rect.w, rect.x + dx)),
+ y: Math.max(area.y, Math.min(area.y + area.h - rect.h, rect.y + dy)),
+ };
+}
+
+/** The largest rectangle of ``ratio`` inside ``rect``, centred in it. */
+export function fitRatio(rect: Rect, ratio: number): Rect {
+ const w = Math.min(rect.w, rect.h * ratio);
+ const h = w / ratio;
+ return { x: rect.x + (rect.w - w) / 2, y: rect.y + (rect.h - h) / 2, w, h };
+}
+
+/** Is ``rect`` all of ``area`` (so no crop is needed)? */
+export function coversAll(rect: Rect, area: Rect): boolean {
+ return (
+ Math.abs(rect.x - area.x) < 0.5 &&
+ Math.abs(rect.y - area.y) < 0.5 &&
+ Math.abs(rect.w - area.w) < 0.5 &&
+ Math.abs(rect.h - area.h) < 0.5
+ );
+}
+
+/** The document with one crop (or none): an earlier crop is replaced, not stacked. */
+export function withCrop(ops: readonly Op[], rect: Rect | null): Op[] {
+ const rest = ops.filter((op) => op.kind !== "crop");
+ return rect ? [...rest, withId({ kind: "crop", rect } as const)] : rest;
+}
+
+// -- more pictures ------------------------------------------------------------------
+
+/** Where another picture goes: right of what is visible, under it, or over its middle. */
+export type Placement = "beside" | "below" | "over";
+
+export const PLACEMENTS: readonly Placement[] = ["beside", "below", "over"];
+
+/**
+ * Place a ``width`` x ``height`` picture against what is visible now
+ * (``view``): beside it at the same height, below it at the same width, or
+ * over its middle at under half its size. The picture keeps its shape.
+ */
+export function placeImage(view: Rect, width: number, height: number, placement: Placement): Rect {
+ const aspect = Math.max(1, width) / Math.max(1, height);
+ if (placement === "beside") return { x: view.x + view.w, y: view.y, w: view.h * aspect, h: view.h };
+ if (placement === "below") return { x: view.x, y: view.y + view.h, w: view.w, h: view.w / aspect };
+ const w = Math.min(view.w * 0.45, view.h * 0.45 * aspect, width);
+ const h = w / aspect;
+ return { x: view.x + (view.w - w) / 2, y: view.y + (view.h - h) / 2, w, h };
+}
+
+/**
+ * The document with another picture added, and the new layer's id. With a
+ * crop in place the crop grows to take the new picture in, so it never lands
+ * out of sight.
+ */
+export function addImage(
+ ops: readonly Op[],
+ width: number,
+ height: number,
+ image: { src: string; width: number; height: number },
+ placement: Placement,
+): { ops: Op[]; id: number } {
+ const view = viewport(ops, width, height);
+ const rect = placeImage(view, image.width, image.height, placement);
+ const layer = withId({ kind: "image", rect, src: image.src } as const);
+ const next = [...ops, layer];
+ const cropped = ops.some((op) => op.kind === "crop");
+ return { ops: cropped ? withCrop(next, unionRect(view, rect)) : next, id: layer.id };
+}
+
/** The number the next counter badge carries. */
export function nextCounter(ops: readonly Op[]): number {
let highest = 0;
@@ -288,7 +475,7 @@ function inside(p: Point, box: Rect, slop: number): boolean {
}
/** Areas that cover others: picked only when nothing drawn on them is hit. */
-const AREA_KINDS: ReadonlySet<Op["kind"]> = new Set(["spotlight", "redact"]);
+const AREA_KINDS: ReadonlySet<Op["kind"]> = new Set(["spotlight", "redact", "image"]);
function hits(op: Op, p: Point, slop: number, measure?: MeasureText): boolean {
switch (op.kind) {
@@ -468,6 +655,17 @@ export function reshape<T extends Draft>(original: T, handle: HandleId, p: Point
return original;
case "crop":
return original;
+ case "image": {
+ // A picture keeps its shape: the larger pull wins, the opposite corner stays.
+ if (handle === "from" || handle === "to" || handle === "mid" || handle === "size") return original;
+ const anchor = corner(op.rect, OPPOSITE[handle]);
+ const aspect = op.rect.w / Math.max(1e-6, op.rect.h);
+ const w = Math.max(8, Math.abs(p.x - anchor.x), Math.abs(p.y - anchor.y) * aspect);
+ const h = w / aspect;
+ const x = handle === "ne" || handle === "se" ? anchor.x : anchor.x - w;
+ const y = handle === "sw" || handle === "se" ? anchor.y : anchor.y - h;
+ return { ...op, rect: { x, y, w, h } } as T;
+ }
case "counter":
return { ...op, size: Math.max(8, Math.hypot(p.x - op.at.x, p.y - op.at.y)) } as T;
case "text": {
@@ -504,10 +702,11 @@ export function reshape<T extends Draft>(original: T, handle: HandleId, p: Point
}
/** The pointer cursor that fits a grip. */
-export function handleCursor(handle: HandleId): string {
+export function handleCursor(handle: HandleId | CropHandle): string {
if (handle === "nw" || handle === "se") return "nwse-resize";
if (handle === "ne" || handle === "sw") return "nesw-resize";
- if (handle === "size") return "ew-resize";
+ if (handle === "size" || handle === "e" || handle === "w") return "ew-resize";
+ if (handle === "n" || handle === "s") return "ns-resize";
return "grab";
}
@@ -803,19 +1002,52 @@ function makeCanvas(width: number, height: number): HTMLCanvasElement {
return canvas;
}
+/**
+ * The pictures of a document, flattened: ``source`` drawn at ``origin``
+ * covers ``area``. Redactions read their pixels from it, so they hide what
+ * any of the pictures shows.
+ */
+export interface Scene {
+ source: CanvasImageSource;
+ origin: Point;
+ area: Rect;
+}
+
+/** Flatten the first picture and every placed picture into one scene. */
+export function buildScene(
+ base: CanvasImageSource,
+ width: number,
+ height: number,
+ ops: readonly Draft[],
+ sources?: ReadonlyMap<string, CanvasImageSource>,
+): Scene {
+ const area = extent(ops, width, height);
+ const layers = ops.filter((op): op is Extract<Draft, { kind: "image" }> => op.kind === "image");
+ if (layers.length === 0) return { source: base, origin: { x: 0, y: 0 }, area };
+ const canvas = makeCanvas(area.w, area.h);
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return { source: base, origin: { x: 0, y: 0 }, area };
+ ctx.drawImage(base, -area.x, -area.y);
+ for (const layer of layers) {
+ const picture = sources?.get(layer.src);
+ if (picture) ctx.drawImage(picture, layer.rect.x - area.x, layer.rect.y - area.y, layer.rect.w, layer.rect.h);
+ }
+ return { source: canvas, origin: { x: area.x, y: area.y }, area };
+}
+
/**
* 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) {
+function redact(ctx: CanvasRenderingContext2D, scene: Scene, 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 = 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);
+ sctx.drawImage(scene.source, rect.x - scene.origin.x, rect.y - scene.origin.y, rect.w, rect.h, 0, 0, w, h);
ctx.save();
ctx.beginPath();
ctx.rect(rect.x, rect.y, rect.w, rect.h);
@@ -900,8 +1132,8 @@ function paintCounter(ctx: CanvasRenderingContext2D, op: Extract<Draft, { kind:
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) {
+/** Paint one annotation (crops, spotlights and pictures excluded — see paintOps). */
+export function paintShape(ctx: CanvasRenderingContext2D, scene: Scene, op: Draft) {
ctx.save();
ctx.lineCap = "round";
ctx.lineJoin = "round";
@@ -977,22 +1209,23 @@ export function paintShape(ctx: CanvasRenderingContext2D, base: CanvasImageSourc
paintCounter(ctx, op);
break;
case "redact":
- redact(ctx, base, op.rect, op.mode, op.block);
+ redact(ctx, scene, op.rect, op.mode, op.block);
break;
case "spotlight":
case "crop":
+ case "image":
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) {
+function paintSpotlights(ctx: CanvasRenderingContext2D, spots: Rect[], area: Rect) {
if (spots.length === 0) return;
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.55)";
ctx.beginPath();
- ctx.rect(0, 0, width, height);
+ ctx.rect(area.x, area.y, area.w, area.h);
for (const spot of spots) {
roundedRectPath(ctx, spot, Math.min(spot.w, spot.h) * 0.06);
}
@@ -1011,22 +1244,17 @@ function roundedRectPath(ctx: CanvasRenderingContext2D, rect: Rect, radius: numb
}
/**
- * Paint the picture and every annotation in picture space. The caller sets
+ * Paint the pictures and every annotation in document space. The caller sets
* the transform: identity for an export, a scale + offset for the screen.
*/
-export function paintOps(
- ctx: CanvasRenderingContext2D,
- base: CanvasImageSource,
- ops: readonly Draft[],
- size: { width: number; height: number },
-) {
- ctx.drawImage(base, 0, 0);
+export function paintOps(ctx: CanvasRenderingContext2D, scene: Scene, ops: readonly Draft[]) {
+ ctx.drawImage(scene.source, scene.origin.x, scene.origin.y);
const spots: Rect[] = [];
for (const op of ops) {
if (op.kind === "spotlight") spots.push(op.rect);
- else paintShape(ctx, base, op);
+ else paintShape(ctx, scene, op);
}
- paintSpotlights(ctx, spots, size.width, size.height);
+ paintSpotlights(ctx, spots, scene.area);
}
/** Render the finished picture: cropped, annotated and framed. */
@@ -1034,6 +1262,7 @@ export function renderResult(
base: HTMLImageElement,
ops: readonly Op[],
background: Background,
+ sources?: ReadonlyMap<string, CanvasImageSource>,
): HTMLCanvasElement {
const iw = base.naturalWidth;
const ih = base.naturalHeight;
@@ -1042,7 +1271,7 @@ export function renderResult(
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 });
+ paintOps(pctx, buildScene(base, iw, ih, ops, sources), ops);
if (!background.enabled) return picture;
const layout = frameLayout(picture.width, picture.height, background);
@@ -1077,8 +1306,13 @@ export function renderResult(
}
/** 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);
+export async function exportPng(
+ base: HTMLImageElement,
+ ops: readonly Op[],
+ background: Background,
+ sources?: ReadonlyMap<string, CanvasImageSource>,
+): Promise<Blob> {
+ const canvas = renderResult(base, ops, background, sources);
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/views/AppshotEditor.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
index 0926913c08..bb95ed9023 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx
@@ -1,11 +1,18 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
+ Check,
ChevronDown,
+ Columns2,
Copy,
Download,
+ FolderOpen,
GripVertical,
+ ImagePlus,
Loader2,
+ PictureInPicture2,
Redo2,
+ RotateCcw,
+ Rows2,
Trash2,
Undo2,
X,
@@ -17,24 +24,43 @@ import { QuickTooltip } from "@/components/ui/tooltip";
import { useCapabilities } from "@/hooks/useCapabilities";
import { fill, useLocaleChunk, useT } from "@/i18n";
import { copyAppshotPng } from "@/lib/appshotClipboard";
-import { latestAppshotImageUrl } from "@/lib/appshotApi";
+import {
+ appshotLibraryImageUrl,
+ fetchAppshotLibrary,
+ latestAppshotImageUrl,
+ type AppshotLibraryItem,
+} from "@/lib/appshotApi";
import {
ARROW_STYLES,
BACKGROUND_PRESETS,
COLORS,
CROP_RATIOS,
DEFAULT_BACKGROUND,
+ PLACEMENTS,
STROKE_LEVELS,
TOOL_KEYS,
+ addImage,
bounds,
+ buildScene,
canvasMeasure,
- clampRect,
+ clampInto,
commit,
constrainEnd,
counterSize,
+ coversAll,
+ cropHandleAt,
+ cropHandles,
emptyHistory,
exportPng,
+ extent,
+ fitRatio,
frameLayout,
+ moveCrop,
+ resizeCrop,
+ withCrop,
+ type CropHandle,
+ type Placement,
+ type Rect,
grabScope,
hitTest,
isMeaningful,
@@ -76,8 +102,11 @@ import { useEventStore } from "@/store/events";
* The appshot editor — annotate a capture with 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
- * one-letter keys. The result can be copied, saved, or put back in place of
+ * (free or fixed ratio, an adjustable frame with grips) and a background
+ * frame, with undo/redo and one-letter keys. "Add picture" (I) places an
+ * earlier appshot from the gallery, a file, a pasted or a dropped picture
+ * beside, below or on top of this one, so several pictures are marked up and
+ * shared as one. The result can be copied, saved, or put back in place of
* the appshot so the next message carries the edited picture.
*
* Copy goes through the OS clipboard on the desktop (`/api/appshot/clipboard`)
@@ -158,7 +187,38 @@ type Gesture =
| { kind: "draw"; shape: Draft; start: Point }
| { kind: "move"; id: number; start: Point; dx: number; dy: number }
/** A grip of the selected annotation being dragged; `original` as it was. */
- | { kind: "resize"; id: number; handle: HandleId; original: Op; at: Point };
+ | { kind: "resize"; id: number; handle: HandleId; original: Op; at: Point }
+ /** A grip of the crop frame being dragged. */
+ | { kind: "crop-resize"; handle: CropHandle; original: Rect; at: Point }
+ /** The whole crop frame being dragged. */
+ | { kind: "crop-move"; original: Rect; start: Point; at: Point };
+
+const PLACEMENT_KEY = "jarvis.appshotEditor.placement";
+const isPlacement = (value: unknown): value is Placement =>
+ typeof value === "string" && (PLACEMENTS as readonly string[]).includes(value);
+
+/** A picture of the user's to add: the first image file of a paste or a drop. */
+function imageFile(items: DataTransferItemList | FileList | null | undefined): File | null {
+ if (!items) return null;
+ for (const entry of Array.from(items as ArrayLike<DataTransferItem | File>)) {
+ const file = entry instanceof File ? entry : entry.kind === "file" ? entry.getAsFile() : null;
+ if (file && file.type.startsWith("image/")) return file;
+ }
+ return null;
+}
+
+function insideRect(p: Point, rect: Rect): boolean {
+ return p.x >= rect.x && p.x <= rect.x + rect.w && p.y >= rect.y && p.y <= rect.y + rect.h;
+}
+
+function loadPicture(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error("The picture could not be loaded."));
+ img.src = src;
+ });
+}
type LoadState = "loading" | "ready" | "failed";
@@ -225,6 +285,17 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
({ ...readStored(BACKGROUND_KEY, DEFAULT_BACKGROUND, isBackground), enabled: false }),
);
const [selectedId, setSelectedId] = useState<number | null>(null);
+ // Pictures added to this one, by the ``src`` their layers name.
+ const [sources, setSources] = useState<ReadonlyMap<string, HTMLImageElement>>(() => new Map());
+ const blobUrls = useRef<string[]>([]);
+ const [importOpen, setImportOpen] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const [placement, setPlacementState] = useState<Placement>(() => readStored(PLACEMENT_KEY, "beside" as Placement, isPlacement));
+ const setPlacement = (next: Placement) => {
+ setPlacementState(next);
+ writeStored(PLACEMENT_KEY, next);
+ };
+ const [dropping, setDropping] = useState(false);
// 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);
@@ -304,8 +375,10 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
const widths = strokeWidths(iw || 1, ih || 1);
const width = widths[widthIndex];
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;
+ // Everything there is: the first picture and every picture added to it.
+ const area = extent(ops, iw, ih);
+ // While cropping, show all of it so a crop can also grow back.
+ const shown = tool === "crop" ? area : view;
const framing = tool === "crop" ? { ...background, enabled: false } : background;
const layout = frameLayout(shown.w || 1, shown.h || 1, framing);
const fitScale =
@@ -316,6 +389,15 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
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;
+ // The crop frame as it looks right now: drawn, reshaped or moved by the drag in progress.
+ const cropRect: Rect =
+ gesture?.kind === "draw" && gesture.shape.kind === "crop"
+ ? gesture.shape.rect
+ : gesture?.kind === "crop-resize"
+ ? resizeCrop(gesture.original, gesture.handle, gesture.at, area, ratio)
+ : gesture?.kind === "crop-move"
+ ? moveCrop(gesture.original, gesture.at.x - gesture.start.x, gesture.at.y - gesture.start.y, area)
+ : view;
// An annotation as it looks right now: moved or reshaped by the drag in progress.
const live = useCallback(
@@ -351,18 +433,53 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
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);
- paintOps(ctx, image, drawn, { width: iw, height: ih });
+ paintOps(ctx, buildScene(image, iw, ih, drawn, sources), drawn);
if (tool === "crop") {
- const crop = gesture?.kind === "draw" && gesture.shape.kind === "crop" ? gesture.shape.rect : view;
+ const crop = cropRect;
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.55)";
ctx.beginPath();
- ctx.rect(0, 0, iw, ih);
+ ctx.rect(area.x, area.y, area.w, area.h);
ctx.rect(crop.x, crop.y, crop.w, crop.h);
ctx.fill("evenodd");
+ // Thirds, to line the picture up.
+ ctx.strokeStyle = "rgba(255,255,255,0.35)";
+ ctx.lineWidth = 1 / scale;
+ ctx.beginPath();
+ for (const third of [1 / 3, 2 / 3]) {
+ ctx.moveTo(crop.x + crop.w * third, crop.y);
+ ctx.lineTo(crop.x + crop.w * third, crop.y + crop.h);
+ ctx.moveTo(crop.x, crop.y + crop.h * third);
+ ctx.lineTo(crop.x + crop.w, crop.y + crop.h * third);
+ }
+ ctx.stroke();
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 1.5 / scale;
ctx.strokeRect(crop.x, crop.y, crop.w, crop.h);
+ // Grips: an L at each corner, a bar on each edge of a free crop.
+ ctx.lineWidth = 4 / scale;
+ ctx.lineCap = "round";
+ ctx.shadowColor = "rgba(0,0,0,0.5)";
+ ctx.shadowBlur = 3 / scale;
+ const arm = Math.min(18 / scale, crop.w / 3, crop.h / 3);
+ ctx.beginPath();
+ for (const grip of cropHandles(crop, ratio)) {
+ const { x, y } = grip.at;
+ if (grip.id === "n" || grip.id === "s") {
+ ctx.moveTo(x - arm / 2, y);
+ ctx.lineTo(x + arm / 2, y);
+ } else if (grip.id === "e" || grip.id === "w") {
+ ctx.moveTo(x, y - arm / 2);
+ ctx.lineTo(x, y + arm / 2);
+ } else {
+ const sx = grip.id === "nw" || grip.id === "sw" ? 1 : -1;
+ const sy = grip.id === "nw" || grip.id === "ne" ? 1 : -1;
+ ctx.moveTo(x + sx * arm, y);
+ ctx.lineTo(x, y);
+ ctx.lineTo(x, y + sy * arm);
+ }
+ }
+ ctx.stroke();
ctx.restore();
}
if (selectedLive) {
@@ -395,7 +512,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
}
ctx.restore();
}
- }, [image, drawn, gesture, tool, cw, ch, scale, shown.x, shown.y, shown.w, shown.h, iw, ih, view, selectedLive, measure]);
+ }, [image, drawn, tool, cw, ch, scale, shown.x, shown.y, shown.w, shown.h, iw, ih, area, cropRect, ratio, sources, selectedLive, measure]);
// -- editing -------------------------------------------------------------
const apply = useCallback((next: Op[]) => {
@@ -445,6 +562,71 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
[setBackground],
);
+ // -- crop ------------------------------------------------------------------
+ /** Crop to ``rect``; all of the document (or null) means no crop at all. */
+ const setCrop = useCallback(
+ (rect: Rect | null) => {
+ const next = rect && !coversAll(rect, area) ? rect : null;
+ if (!next && !ops.some((op) => op.kind === "crop")) return;
+ apply(withCrop(ops, next));
+ },
+ [apply, area, ops],
+ );
+
+ /** A fixed ratio reshapes the crop at once: the largest such frame in what is visible. */
+ const chooseRatio = (id: string) => {
+ setCropRatio(id);
+ const next = CROP_RATIOS.find((entry) => entry.id === id)?.ratio ?? null;
+ if (next !== null) setCrop(fitRatio(view, next));
+ };
+
+ // -- more pictures -----------------------------------------------------------
+ // Read when an added picture has finished loading, after other edits may have landed.
+ const opsRef = useRef(ops);
+ opsRef.current = ops;
+
+ useEffect(() => {
+ const urls = blobUrls.current;
+ return () => urls.forEach((url) => URL.revokeObjectURL(url));
+ }, []);
+
+ const addPicture = useCallback(
+ async (src: string) => {
+ if (!image) return;
+ setImporting(true);
+ try {
+ const picture = await loadPicture(src);
+ setSources((current) => new Map(current).set(src, picture));
+ const added = addImage(
+ opsRef.current,
+ iw,
+ ih,
+ { src, width: picture.naturalWidth, height: picture.naturalHeight },
+ placement,
+ );
+ apply(added.ops);
+ setImportOpen(false);
+ // Selected with the select tool, so it can be moved and sized at once.
+ setTool("move");
+ setSelectedId(added.id);
+ } catch {
+ pushToast("error", t("appshot_editor.import_failed"));
+ } finally {
+ setImporting(false);
+ }
+ },
+ [apply, ih, image, iw, placement, pushToast, t],
+ );
+
+ const addFile = useCallback(
+ (file: File) => {
+ const url = URL.createObjectURL(file);
+ blobUrls.current.push(url);
+ void addPicture(url);
+ },
+ [addPicture],
+ );
+
const toImage = (event: { clientX: number; clientY: number }): Point => {
const rect = canvasRef.current!.getBoundingClientRect();
return {
@@ -490,33 +672,47 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
if (!image || event.button !== 0) return;
const p = toImage(event);
if (tool === "background") return;
- if (tool !== "crop") {
- // A grip of the selected annotation reshapes it; any drawn annotation
- // under the pointer is taken and moved (the select tool also takes
- // spotlights and redactions); pen and highlighter only take grips.
- const scope = grabScope(tool);
- if (scope !== "none" && selected && selectedLive) {
- const grip = handleAt(selectedLive, p, (GRIP_RADIUS + 4) / scale, measure);
- if (grip) {
- event.preventDefault();
- event.currentTarget.setPointerCapture?.(event.pointerId);
- setGesture({ kind: "resize", id: selected.id, handle: grip, original: selected, at: p });
- return;
- }
+ if (tool === "crop") {
+ // A grip reshapes the crop frame, a press inside it moves it, a press
+ // outside draws a new one.
+ event.preventDefault();
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ const grip = cropHandleAt(view, p, (GRIP_RADIUS + 6) / scale, ratio);
+ if (grip) {
+ setGesture({ kind: "crop-resize", handle: grip, original: view, at: p });
+ } else if (!coversAll(view, area) && insideRect(p, view)) {
+ setGesture({ kind: "crop-move", original: view, start: p, at: p });
+ } else {
+ setGesture({ kind: "draw", shape: { kind: "crop", rect: { x: p.x, y: p.y, w: 0, h: 0 } }, start: p });
}
- // Spotlights and redactions cover what lies in them, so only the
- // select tool picks them; with a drawing tool they stay drawable on.
- const hit = grabbable(p);
- if (hit) {
+ return;
+ }
+ // A grip of the selected annotation reshapes it; any drawn annotation
+ // under the pointer is taken and moved (the select tool also takes
+ // spotlights, redactions and added pictures); pen and highlighter only
+ // take grips.
+ const scope = grabScope(tool);
+ if (scope !== "none" && selected && selectedLive) {
+ const grip = handleAt(selectedLive, p, (GRIP_RADIUS + 4) / scale, measure);
+ if (grip) {
event.preventDefault();
- if (typing) commitText();
event.currentTarget.setPointerCapture?.(event.pointerId);
- setSelectedId(hit.id);
- setGesture({ kind: "move", id: hit.id, start: p, dx: 0, dy: 0 });
+ setGesture({ kind: "resize", id: selected.id, handle: grip, original: selected, at: p });
return;
}
- setSelectedId(null);
}
+ // Spotlights, redactions and added pictures cover what lies in them, so
+ // only the select tool picks them; with a drawing tool they stay drawable on.
+ const hit = grabbable(p);
+ if (hit) {
+ event.preventDefault();
+ if (typing) commitText();
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ setSelectedId(hit.id);
+ setGesture({ kind: "move", id: hit.id, start: p, dx: 0, dy: 0 });
+ return;
+ }
+ setSelectedId(null);
if (tool === "text") {
// Keep the press from moving focus away: it would blur (and so close)
// the text box this click is about to open.
@@ -554,11 +750,8 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
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:
- shape = { kind: "crop", rect: zero };
+ shape = { kind: "redact", rect: zero, mode: redactMode, block: Math.max(8, width * 3) };
}
setGesture({ kind: "draw", shape, start: p });
};
@@ -568,7 +761,12 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
const p = toImage(event);
if (!current) {
// Say with the pointer what a press here would do: reshape, move, or draw.
- if (!image || tool === "crop" || tool === "background") return setHoverCursor(null);
+ if (!image || tool === "background") return setHoverCursor(null);
+ if (tool === "crop") {
+ const cropGrip = cropHandleAt(view, p, (GRIP_RADIUS + 6) / scale, ratio);
+ if (cropGrip) return setHoverCursor(handleCursor(cropGrip));
+ return setHoverCursor(!coversAll(view, area) && insideRect(p, view) ? "move" : null);
+ }
const grip =
selectedLive && grabScope(tool) !== "none"
? handleAt(selectedLive, p, (GRIP_RADIUS + 4) / scale, measure)
@@ -577,7 +775,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
setHoverCursor(grabbable(p) ? "move" : null);
return;
}
- if (current.kind === "resize") {
+ if (current.kind === "resize" || current.kind === "crop-resize" || current.kind === "crop-move") {
setGesture({ ...current, at: p });
return;
}
@@ -610,18 +808,29 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
}
return;
}
+ if (current.kind === "crop-resize") {
+ setCrop(resizeCrop(current.original, current.handle, current.at, area, ratio));
+ return;
+ }
+ if (current.kind === "crop-move") {
+ const dx = current.at.x - current.start.x;
+ const dy = current.at.y - current.start.y;
+ if (dx !== 0 || dy !== 0) setCrop(moveCrop(current.original, dx, dy, area));
+ return;
+ }
let shape = current.shape;
if (shape.kind === "crop" || shape.kind === "redact" || shape.kind === "spotlight") {
- const rect = clampRect(shape.rect, iw, ih);
+ const rect = clampInto(shape.rect, area);
if (!rect) return;
shape = { ...shape, rect } as Draft;
}
if (!isMeaningful(shape)) return;
- const id = push(shape);
- if (shape.kind === "crop") setTool("move");
+ // A crop stays in crop mode with its grips, to be fine-tuned; Enter or
+ // another tool finishes it.
+ if (shape.kind === "crop") return setCrop(shape.rect);
// Every fresh annotation is selected at once, so its grips are right
// there (the previous one loses them) and it can be moved again.
- else setSelectedId(id);
+ setSelectedId(push(shape));
};
const onDoubleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
@@ -634,8 +843,8 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
// -- results -------------------------------------------------------------
const render = useCallback(async () => {
if (!image) throw new Error(t("appshot_editor.gone"));
- return await exportPng(image, ops, background);
- }, [background, image, ops, t]);
+ return await exportPng(image, ops, background, sources);
+ }, [background, image, ops, sources, t]);
const copy = useCallback(async () => {
setBusy("copy");
@@ -738,12 +947,25 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
event.preventDefault();
if (menu) setMenu("");
else if (confirmDiscard) setConfirmDiscard(false);
+ else if (importOpen) setImportOpen(false);
else if (gestureRef.current) setGesture(null);
else if (selectedId !== null) setSelectedId(null);
+ else if (tool === "crop") chooseTool("move");
else requestClose();
return;
}
if (confirmDiscard) return;
+ if (event.key === "Enter" && !event.shiftKey && !mod && tool === "crop") {
+ // Enter finishes the crop first; the next Enter is Done.
+ event.preventDefault();
+ chooseTool("move");
+ return;
+ }
+ if (!mod && !event.altKey && key === "i") {
+ event.preventDefault();
+ setImportOpen((open) => !open);
+ return;
+ }
if (mod && key === "z" && !event.shiftKey) {
event.preventDefault();
undo();
@@ -777,7 +999,20 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [chooseTool, confirmDiscard, copy, menu, nudgeSelected, redo, removeSelected, requestClose, save, scale, selectedId, setGesture, typing, undo, use]);
+ }, [chooseTool, confirmDiscard, copy, importOpen, menu, nudgeSelected, redo, removeSelected, requestClose, save, scale, selectedId, setGesture, tool, typing, undo, use]);
+
+ // A picture pasted while the editor is open joins this one.
+ useEffect(() => {
+ const onPaste = (event: ClipboardEvent) => {
+ if (typingRef.current || !image) return;
+ const file = imageFile(event.clipboardData?.items);
+ if (!file) return;
+ event.preventDefault();
+ addFile(file);
+ };
+ window.addEventListener("paste", onPaste);
+ return () => window.removeEventListener("paste", onPaste);
+ }, [addFile, image]);
// -- drag out --------------------------------------------------------------
// The handle writes the finished picture to a file only when pressed, then
@@ -852,7 +1087,9 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
? label("hint_counter")
: tool === "spotlight"
? label("hint_spotlight")
- : "";
+ : tool === "crop"
+ ? label("hint_crop")
+ : "";
const showCapsule = tool === "text" || tool === "redact" || tool === "crop" || tool === "background" || hint !== "";
const toolButton = (name: Tool) => {
@@ -902,6 +1139,24 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
<div className="mx-0.5 h-5 w-px shrink-0 bg-border" aria-hidden />
{toolButton("crop")}
{toolButton("background")}
+ <div className="mx-0.5 h-5 w-px shrink-0 bg-border" aria-hidden />
+ <QuickTooltip content={`${label("import")} (I)`} side="bottom">
+ <button
+ type="button"
+ aria-label={label("import")}
+ aria-pressed={importOpen}
+ onClick={() => setImportOpen((open) => !open)}
+ disabled={!image}
+ data-testid="appshot-editor-import"
+ className={cn(
+ "flex h-7 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors",
+ "hover:bg-foreground/10 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-40",
+ importOpen && "bg-accent text-accent-foreground hover:bg-accent hover:text-accent-foreground",
+ )}
+ >
+ {importing ? <Loader2 className="h-[17px] w-[17px] animate-spin" aria-hidden /> : <ImagePlus className="h-[17px] w-[17px]" aria-hidden />}
+ </button>
+ </QuickTooltip>
</div>
{/* Colour (a menu) and size (a slider). */}
@@ -1044,8 +1299,42 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
</div>
</div>
- {/* The picture. */}
- <div className="relative min-h-0 flex-1 bg-background/70">
+ {/* The picture; an image file dropped here joins it. */}
+ <div
+ className="relative min-h-0 flex-1 bg-background/70"
+ onDragOver={(event) => {
+ if (!image || !Array.from(event.dataTransfer.types).includes("Files")) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ setDropping(true);
+ }}
+ onDragLeave={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDropping(false);
+ }}
+ onDrop={(event) => {
+ setDropping(false);
+ const file = imageFile(event.dataTransfer.files);
+ if (!file || !image) return;
+ event.preventDefault();
+ addFile(file);
+ }}
+ >
+ {dropping && (
+ <div className="pointer-events-none absolute inset-3 z-30 flex items-center justify-center rounded-2xl border-2 border-dashed border-accent bg-accent/10 text-sm font-medium text-foreground" data-testid="appshot-editor-drop">
+ {fill(label("import_drop"), { 0: label(`place_${placement}`) })}
+ </div>
+ )}
+ {importOpen && image && (
+ <ImportPanel
+ label={label}
+ placement={placement}
+ onPlacement={setPlacement}
+ busy={importing}
+ onPick={(item) => void addPicture(appshotLibraryImageUrl(item))}
+ onFile={addFile}
+ onClose={() => setImportOpen(false)}
+ />
+ )}
{/* Floats over the picture, so it never changes the space the picture fits into. */}
{showCapsule && (
<div className="pointer-events-none absolute inset-x-0 top-0 z-10 flex justify-center px-3 pt-3">
@@ -1079,13 +1368,39 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla
/>
)}
{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"
- />
+ <>
+ <Segmented
+ label={label("crop_ratio")}
+ value={cropRatio}
+ onChange={chooseRatio}
+ options={CROP_RATIOS.map((entry) => ({ value: entry.id, label: entry.id === "free" ? label("crop_free") : entry.id }))}
+ testId="appshot-editor-crop-ratio"
+ />
+ <span className="tabular-nums text-muted-foreground" data-testid="appshot-editor-crop-size">
+ {Math.round(cropRect.w)} × {Math.round(cropRect.h)}
+ </span>
+ <button
+ type="button"
+ onClick={() => setCrop(null)}
+ disabled={coversAll(view, area)}
+ data-testid="appshot-editor-crop-reset"
+ className="flex h-7 items-center gap-1.5 rounded-lg px-2 text-muted-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
+ >
+ <RotateCcw className="h-3.5 w-3.5" aria-hidden />
+ {label("crop_reset")}
+ </button>
+ <QuickTooltip content={`${label("crop_apply")} (Enter)`} side="bottom">
+ <button
+ type="button"
+ onClick={() => chooseTool("move")}
+ data-testid="appshot-editor-crop-apply"
+ className="flex h-7 items-center gap-1.5 rounded-lg bg-accent px-2.5 font-medium text-accent-foreground transition-colors hover:bg-accent/90"
+ >
+ <Check className="h-3.5 w-3.5" aria-hidden />
+ {label("crop_apply")}
+ </button>
+ </QuickTooltip>
+ </>
)}
{tool === "background" && (
<>
@@ -1437,6 +1752,159 @@ function ArrowStyleIcon({ style }: { style: ArrowStyle }) {
);
}
+const PLACEMENT_ICON: Record<Placement, typeof Columns2> = {
+ beside: Columns2,
+ below: Rows2,
+ over: PictureInPicture2,
+};
+
+/**
+ * "Add picture": where the next picture goes (beside, below, on top), the
+ * user's kept appshots to pick from, and a file from the disk.
+ */
+function ImportPanel({
+ label,
+ placement,
+ onPlacement,
+ busy,
+ onPick,
+ onFile,
+ onClose,
+}: {
+ label: (key: string) => string;
+ placement: Placement;
+ onPlacement: (next: Placement) => void;
+ busy: boolean;
+ onPick: (item: AppshotLibraryItem) => void;
+ onFile: (file: File) => void;
+ onClose: () => void;
+}) {
+ const [items, setItems] = useState<AppshotLibraryItem[] | null>(null);
+ const [failed, setFailed] = useState(false);
+ const fileRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ fetchAppshotLibrary()
+ .then((body) => alive && setItems(Array.isArray(body.items) ? body.items : []))
+ .catch(() => {
+ // The gallery is optional here: a file still works without it.
+ if (alive) {
+ setFailed(true);
+ setItems([]);
+ }
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ return (
+ <div
+ className="absolute bottom-3 right-3 top-3 z-20 flex w-[min(340px,calc(100%-1.5rem))] flex-col overflow-hidden rounded-2xl border border-border bg-popover/95 text-[13px] shadow-2xl backdrop-blur"
+ role="dialog"
+ aria-label={label("import")}
+ data-testid="appshot-editor-import-panel"
+ >
+ <div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
+ <p className="font-semibold">{label("import")}</p>
+ <button type="button" onClick={onClose} aria-label={label("close")} className={ROUND_ICON}>
+ <X className="h-4 w-4" aria-hidden />
+ </button>
+ </div>
+ <div className="flex flex-col gap-1.5 border-b border-border px-3 py-2.5">
+ <span className="text-muted-foreground">{label("import_place")}</span>
+ <div className="grid grid-cols-3 gap-1 rounded-lg bg-foreground/10 p-0.5" role="group" aria-label={label("import_place")}>
+ {PLACEMENTS.map((entry) => {
+ const Icon = PLACEMENT_ICON[entry];
+ return (
+ <button
+ key={entry}
+ type="button"
+ aria-pressed={placement === entry}
+ onClick={() => onPlacement(entry)}
+ data-testid={`appshot-editor-place-${entry}`}
+ className={cn(
+ "flex h-8 items-center justify-center gap-1.5 rounded-md text-muted-foreground transition-colors hover:bg-popover hover:text-foreground",
+ placement === entry && "bg-popover text-foreground shadow-sm",
+ )}
+ >
+ <Icon className="h-3.5 w-3.5" aria-hidden />
+ {label(`place_${entry}`)}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-2.5">
+ <p className="mb-2 text-muted-foreground">{label("import_library")}</p>
+ {items === null ? (
+ <div className="flex items-center gap-2 text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ {label("loading")}
+ </div>
+ ) : items.length === 0 ? (
+ <p className="text-muted-foreground" data-testid="appshot-editor-import-empty">
+ {label(failed ? "import_library_failed" : "import_library_empty")}
+ </p>
+ ) : (
+ <ul className="grid grid-cols-2 gap-2" data-testid="appshot-editor-import-list">
+ {items.map((item) => (
+ <li key={`${item.id}:${item.variant}`}>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onPick(item)}
+ title={item.app_name || item.label}
+ data-testid="appshot-editor-import-item"
+ className="group relative block w-full overflow-hidden rounded-lg border border-border bg-background transition-colors hover:border-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50"
+ >
+ <img
+ src={appshotLibraryImageUrl(item, true)}
+ alt={item.app_name || item.label}
+ loading="lazy"
+ draggable={false}
+ className="aspect-[4/3] w-full object-cover"
+ />
+ {item.variant === "edited" && (
+ <span className="absolute left-1 top-1 rounded bg-accent px-1.5 py-px text-[11px] font-medium text-accent-foreground">
+ {label("library_edited_badge")}
+ </span>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <div className="border-t border-border px-3 py-2.5">
+ <input
+ ref={fileRef}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ data-testid="appshot-editor-import-file"
+ onChange={(event) => {
+ const file = imageFile(event.currentTarget.files);
+ event.currentTarget.value = "";
+ if (file) onFile(file);
+ }}
+ />
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => fileRef.current?.click()}
+ className="flex h-8 w-full items-center justify-center gap-2 rounded-lg border border-border font-medium transition-colors hover:bg-foreground/10 disabled:opacity-50"
+ >
+ <FolderOpen className="h-4 w-4 text-muted-foreground" aria-hidden />
+ {label("import_file")}
+ </button>
+ <p className="mt-1.5 text-center text-[12px] text-muted-foreground">{label("import_paste_hint")}</p>
+ </div>
+ </div>
+ );
+}
+
const ROUND_ICON =
"flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:pointer-events-none disabled:opacity-40";