Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(attachments): copy an image from the preview

AdityaUmalee7cf03d832d7
diff --git a/src/components/AttachmentPreview.test.ts b/src/components/AttachmentPreview.test.ts
index 7a79246d83..c922a937cd 100644
--- a/src/components/AttachmentPreview.test.ts
+++ b/src/components/AttachmentPreview.test.ts
@@ -9,6 +9,7 @@ import { describe, expect, it, vi } from "vitest";
import {
AttachedFileChips,
AttachedImageGallery,
+ AttachmentPreviewDialog,
MarkdownImagePreview,
OutsideWorkspaceFile,
canonicalDownloadFilename,
@@ -301,3 +302,48 @@ describe("local Markdown image lifecycle", () => {
);
});
});
+
+describe("image preview copy button", () => {
+ const image = { src: "/api/files/shot.png", name: "shot.png", downloadUrl: "/api/files/shot.png" };
+
+ async function openPreview() {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => { root.render(createElement(AttachmentPreviewDialog, { image, onClose: () => {} })); });
+ const button = () => document.querySelector<HTMLButtonElement>('button[title="Copy image"], button[title="Image copied"]');
+ return { button, close: () => act(() => root.unmount()) };
+ }
+
+ it("copies the shown image as a PNG and says so", async () => {
+ const write = vi.fn(async (items: { items: Record<string, Promise<Blob>> }[]) => {
+ await items[0]!.items["image/png"];
+ });
+ vi.stubGlobal("ClipboardItem", class { constructor(readonly items: Record<string, Promise<Blob>>) {} });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Blob(["png"], { type: "image/png" }))));
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: { write } });
+ const preview = await openPreview();
+ try {
+ expect(preview.button()?.getAttribute("aria-label")).toBe("Copy shot.png as an image");
+ await act(async () => { preview.button()!.click(); });
+ expect(write).toHaveBeenCalledOnce();
+ expect(fetch).toHaveBeenCalledWith("/api/files/shot.png");
+ expect(preview.button()?.title).toBe("Image copied");
+ } finally {
+ await preview.close();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("is hidden where the clipboard cannot take images", async () => {
+ vi.stubGlobal("ClipboardItem", undefined);
+ const preview = await openPreview();
+ try {
+ expect(preview.button()).toBeNull();
+ expect(document.querySelector('a[title="Download"]')).not.toBeNull();
+ } finally {
+ await preview.close();
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index 1db1299929..e32a78e73e 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -34,6 +34,7 @@ import {
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { serverErrorText } from "@/lib/server-error";
+import { CopyImageButton } from "./CopyImageButton";
import { FilePreviewButton } from "./FilePreviewButton";
import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu";
@@ -561,13 +562,11 @@ export function AttachmentPreviewDialog({
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
+ <CopyImageButton key={current.src} src={current.src} name={current.name} />
{current.downloadUrl && (
<a
href={current.downloadUrl}
- download={current.downloadName ?? canonicalDownloadFilename({
- fallback: current.name,
- source: current.downloadUrl,
- })}
+ download={current.downloadName ?? canonicalDownloadFilename({ fallback: current.name, source: current.downloadUrl })}
className="flex size-9 items-center justify-center rounded-lg text-white/65 hover:bg-white/10 hover:text-white"
aria-label={t("attach.downloadAria", { name: current.name })}
title={t("attach.download")}
diff --git a/src/components/CopyImageButton.tsx b/src/components/CopyImageButton.tsx
new file mode 100644
index 0000000000..b3375bc105
--- /dev/null
+++ b/src/components/CopyImageButton.tsx
@@ -0,0 +1,31 @@
+import { Check, Copy } from "lucide-react";
+
+import { cn } from "@/lib/cn";
+import { canCopyImage, copyImage } from "@/lib/copy-image";
+import { useCopyFeedback } from "@/lib/copy-text";
+import { t } from "@/lib/i18n";
+
+/** Sits beside Download in the image preview; hidden where the clipboard cannot take images. */
+export function CopyImageButton({ src, name }: { src: string; name: string }) {
+ const { state, copy } = useCopyFeedback(src, copyImage);
+ if (!canCopyImage()) return null;
+ const label = state === "copied"
+ ? t("attach.imageCopied")
+ : state === "failed"
+ ? t("attach.copyImageFailed")
+ : t("attach.copyImage");
+ return (
+ <button
+ type="button"
+ onClick={copy}
+ className={cn(
+ "flex size-9 items-center justify-center rounded-lg hover:bg-white/10 hover:text-white",
+ state === "failed" ? "text-red-300" : "text-white/65",
+ )}
+ aria-label={state === "idle" ? t("attach.copyImageAria", { name }) : label}
+ title={label}
+ >
+ {state === "copied" ? <Check size={17} /> : <Copy size={17} />}
+ </button>
+ );
+}
diff --git a/src/lib/copy-image.test.ts b/src/lib/copy-image.test.ts
new file mode 100644
index 0000000000..097a3273c1
--- /dev/null
+++ b/src/lib/copy-image.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { canCopyImage, copyImage } from "./copy-image";
+
+class FakeClipboardItem {
+ constructor(readonly items: Record<string, Promise<Blob>>) {}
+}
+
+type Write = (items: FakeClipboardItem[]) => Promise<void>;
+
+function stubClipboard(write: Write = async (items) => void (await items[0]!.items["image/png"])) {
+ const spy = vi.fn(write);
+ vi.stubGlobal("ClipboardItem", FakeClipboardItem);
+ vi.stubGlobal("navigator", { clipboard: { write: spy } });
+ return spy;
+}
+
+const blob = (type: string) => new Blob(["x"], { type });
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("copyImage", () => {
+ it("is offered only where the clipboard takes images", () => {
+ vi.stubGlobal("ClipboardItem", undefined);
+ vi.stubGlobal("navigator", { clipboard: { writeText: vi.fn() } });
+ expect(canCopyImage()).toBe(false);
+ stubClipboard();
+ expect(canCopyImage()).toBe(true);
+ });
+
+ it("puts a PNG on the clipboard as it is", async () => {
+ const write = stubClipboard();
+ const png = blob("image/png");
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(png)));
+ const toPng = vi.fn(async (b: Blob) => b);
+ expect(await copyImage("/api/files/a.png", toPng)).toBe("copied");
+ const item = write.mock.calls[0]![0][0]!;
+ expect(Object.keys(item.items)).toEqual(["image/png"]);
+ expect((await item.items["image/png"]).type).toBe("image/png");
+ expect(toPng).not.toHaveBeenCalled();
+ });
+
+ it("redraws other image types as PNG", async () => {
+ const write = stubClipboard();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(blob("image/jpeg"))));
+ const png = blob("image/png");
+ const toPng = vi.fn(async () => png);
+ expect(await copyImage("/api/files/a.jpg", toPng)).toBe("copied");
+ expect(await write.mock.calls[0]![0][0]!.items["image/png"]).toBe(png);
+ expect(toPng).toHaveBeenCalledOnce();
+ });
+
+ it("reports a failure when the image is missing", async () => {
+ stubClipboard();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("gone", { status: 404 })));
+ expect(await copyImage("/api/files/missing.png")).toBe("failed");
+ });
+
+ it("reports a failure when the clipboard refuses", async () => {
+ stubClipboard(async () => {
+ throw new Error("denied");
+ });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(blob("image/png"))));
+ expect(await copyImage("/api/files/a.png")).toBe("failed");
+ });
+
+ it("does nothing where the clipboard cannot take images", async () => {
+ vi.stubGlobal("ClipboardItem", undefined);
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ expect(await copyImage("/api/files/a.png")).toBe("failed");
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/lib/copy-image.ts b/src/lib/copy-image.ts
new file mode 100644
index 0000000000..86d747a907
--- /dev/null
+++ b/src/lib/copy-image.ts
@@ -0,0 +1,51 @@
+import type { CopyResult } from "./copy-text";
+
+/** PNG is the one image type every browser clipboard accepts, so other types are redrawn as PNG first. */
+export function canCopyImage(): boolean {
+ return (
+ typeof ClipboardItem !== "undefined" &&
+ typeof navigator !== "undefined" &&
+ typeof navigator.clipboard?.write === "function"
+ );
+}
+
+async function drawAsPng(blob: Blob): Promise<Blob> {
+ const url = URL.createObjectURL(blob);
+ try {
+ const image = new Image();
+ image.src = url;
+ await image.decode();
+ const canvas = document.createElement("canvas");
+ canvas.width = image.naturalWidth;
+ canvas.height = image.naturalHeight;
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("no canvas");
+ context.drawImage(image, 0, 0);
+ return await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob((png) => (png ? resolve(png) : reject(new Error("no png"))), "image/png");
+ });
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
+
+async function imageAsPng(source: string, toPng: (blob: Blob) => Promise<Blob>): Promise<Blob> {
+ const response = await fetch(source);
+ if (!response.ok) throw new Error(`image ${response.status}`);
+ const blob = await response.blob();
+ return blob.type === "image/png" ? blob : toPng(blob);
+}
+
+/** The PNG goes in as a promise so Safari keeps the click's permission while the image loads. */
+export async function copyImage(
+ source: string,
+ toPng: (blob: Blob) => Promise<Blob> = drawAsPng,
+): Promise<CopyResult> {
+ if (!canCopyImage()) return "failed";
+ try {
+ await navigator.clipboard.write([new ClipboardItem({ "image/png": imageAsPng(source, toPng) })]);
+ return "copied";
+ } catch {
+ return "failed";
+ }
+}
diff --git a/src/lib/copy-text.ts b/src/lib/copy-text.ts
index 99d4f945ee..f2f7f287e5 100644
--- a/src/lib/copy-text.ts
+++ b/src/lib/copy-text.ts
@@ -116,17 +116,17 @@ export function createCopyFeedback({
};
}
-export function useCopyFeedback(text: string) {
+export function useCopyFeedback(text: string, write: (text: string) => Promise<CopyResult> = copyText) {
const [state, setState] = useState<CopyFeedback>("idle");
const controller = useRef<ReturnType<typeof createCopyFeedback> | null>(null);
useEffect(() => {
- const next = createCopyFeedback({ copy: copyText, onChange: setState });
+ const next = createCopyFeedback({ copy: write, onChange: setState });
controller.current = next;
return () => {
next.dispose();
controller.current = null;
};
- }, []);
+ }, [write]);
const copy = useCallback(() => void controller.current?.click(text), [text]);
return { state, copy };
}
diff --git a/src/locales/en.json b/src/locales/en.json
index bf963b7654..00b4df3605 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3078,6 +3078,10 @@
"attach.position": "{index} of {count}",
"attach.downloadAria": "Download {name}",
"attach.download": "Download",
+ "attach.copyImage": "Copy image",
+ "attach.copyImageAria": "Copy {name} as an image",
+ "attach.imageCopied": "Image copied",
+ "attach.copyImageFailed": "Couldn't copy the image",
"attach.openOriginalAria": "Open original {name}",
"attach.openOriginal": "Open original",
"attach.close": "Close image preview",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index c0b918a2a6..4488e8f4d9 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2905,6 +2905,10 @@
"attach.position": "{index} de {count}",
"attach.downloadAria": "Baixar {name}",
"attach.download": "Baixar",
+ "attach.copyImage": "Copiar imagem",
+ "attach.copyImageAria": "Copiar {name} como imagem",
+ "attach.imageCopied": "Imagem copiada",
+ "attach.copyImageFailed": "Não foi possível copiar a imagem",
"attach.openOriginalAria": "Abrir o original de {name}",
"attach.openOriginal": "Abrir o original",
"attach.close": "Fechar a prévia da imagem",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index aefdc23670..94bfab850e 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -28614,6 +28614,10 @@
"attach.position": "f144dcc35b2082337fd3e692aee8402f09f9f3f85b153060b140114716e46c48",
"attach.downloadAria": "c807156b8e24f0a378cd22e57f3bddcd25555680645c9f0636d3b59d5e4563c3",
"attach.download": "d6eafe82359100423c93c5ce53c352c1b51ca1e699215fcec3f5c5dd9bf12d24",
+ "attach.copyImage": "3cb27ae0fbca8ae3efdf8fa92493efc9cae666d90b99ae18d2cadf586f5dad32",
+ "attach.copyImageAria": "29bcb449a544d268db71d0014ec64ea9d2b79195c8e17b4e775ddb483b579f2d",
+ "attach.imageCopied": "d2f93ee383fa87452f9a67e88bcfd22d6b26782d777a4d751c3e16b260fc54d4",
+ "attach.copyImageFailed": "1b711a9276f5accb89acffd2a86b0c86c379e9382cb74f8cddb0da27c7e1494c",
"attach.openOriginalAria": "ee7fac6ba188dd8cca558718cca20f42099290765c9330e82c839e76071acaa9",
"attach.openOriginal": "44a915faf3a909dc942739e32d327fe88bee550d1697741de10631f6fdabad5c",
"attach.close": "1b9e1aa135771a2f7b0166bf5a915055b8d1a02a168378745b07e49ba9124905",
@@ -45719,6 +45723,10 @@
"attach.position": "f144dcc35b2082337fd3e692aee8402f09f9f3f85b153060b140114716e46c48",
"attach.downloadAria": "c807156b8e24f0a378cd22e57f3bddcd25555680645c9f0636d3b59d5e4563c3",
"attach.download": "d6eafe82359100423c93c5ce53c352c1b51ca1e699215fcec3f5c5dd9bf12d24",
+ "attach.copyImage": "3cb27ae0fbca8ae3efdf8fa92493efc9cae666d90b99ae18d2cadf586f5dad32",
+ "attach.copyImageAria": "29bcb449a544d268db71d0014ec64ea9d2b79195c8e17b4e775ddb483b579f2d",
+ "attach.imageCopied": "d2f93ee383fa87452f9a67e88bcfd22d6b26782d777a4d751c3e16b260fc54d4",
+ "attach.copyImageFailed": "1b711a9276f5accb89acffd2a86b0c86c379e9382cb74f8cddb0da27c7e1494c",
"attach.openOriginalAria": "ee7fac6ba188dd8cca558718cca20f42099290765c9330e82c839e76071acaa9",
"attach.openOriginal": "44a915faf3a909dc942739e32d327fe88bee550d1697741de10631f6fdabad5c",
"attach.close": "1b9e1aa135771a2f7b0166bf5a915055b8d1a02a168378745b07e49ba9124905",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 0367326096..9f7287853f 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -2923,6 +2923,10 @@
"attach.position": "第 {index} 張,共 {count} 張",
"attach.downloadAria": "下載 {name}",
"attach.download": "下載",
+ "attach.copyImage": "複製圖片",
+ "attach.copyImageAria": "將 {name} 複製為圖片",
+ "attach.imageCopied": "已複製圖片",
+ "attach.copyImageFailed": "無法複製圖片",
"attach.openOriginalAria": "開啟原始檔 {name}",
"attach.openOriginal": "開啟原始檔",
"attach.close": "關閉圖片預覽",