Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(editor): copy an image or attachment from its menu

tianma-if90a8cf9cbb86
diff --git a/apps/desktop/src/main/clipboard-write.mjs b/apps/desktop/src/main/clipboard-write.mjs
index 827dcc2b..287eba33 100644
--- a/apps/desktop/src/main/clipboard-write.mjs
+++ b/apps/desktop/src/main/clipboard-write.mjs
@@ -1,3 +1,68 @@
+import { randomBytes } from "node:crypto";
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+
+const previousClipboardFolders = new Map();
+
+export const MAX_FILE_CLIPBOARD_BYTES = 32 * 1024 * 1024;
+
+const clipboardBytes = (value) => {
+ if (value instanceof Uint8Array) return value;
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ if (value && value.type === "Buffer" && Array.isArray(value.data)) return Uint8Array.from(value.data);
+ throw new TypeError("Clipboard file must be bytes");
+};
+
+const clipboardFilename = (value) => {
+ if (typeof value !== "string") throw new TypeError("Clipboard filename must be a string");
+ const base = value.split(/[\\/]/).pop() ?? "";
+ const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, "").replace(/^\.+$/, "").trim().slice(0, 180);
+ return cleaned || "attachment";
+};
+
+const removeFolder = async (folder) => {
+ if (!folder) return;
+ await rm(folder, { recursive: true, force: true }).catch(() => undefined);
+};
+
+// Electron maps text/uri-list onto the native copied-file clipboard
+// (NSFilenamesPboardType, CF_HDROP, or text/uri-list), so Finder, Explorer,
+// and chat apps can paste the attachment. The file has to stay on disk until
+// the next copy replaces it.
+export const writeFileClipboard = async (clipboard, ClipboardItem, input, options = {}) => {
+ const bytes = clipboardBytes(input?.bytes);
+ const filename = clipboardFilename(input?.filename);
+ const maxBytes = options.maxBytes ?? MAX_FILE_CLIPBOARD_BYTES;
+ if (bytes.byteLength === 0 || bytes.byteLength > maxBytes) return false;
+ if (typeof options.directory !== "string" || !options.directory) {
+ throw new TypeError("Clipboard file directory is required");
+ }
+
+ const folder = join(options.directory, randomBytes(8).toString("hex"));
+ const path = join(folder, filename);
+ try {
+ await mkdir(folder, { recursive: true });
+ await writeFile(path, bytes);
+ const uriList = `${pathToFileURL(path).href}\r\n`;
+ await clipboard.write([new ClipboardItem({ "text/uri-list": uriList })]);
+ if (!await clipboard.has("text/uri-list")) {
+ await removeFolder(folder);
+ return false;
+ }
+ } catch (error) {
+ await removeFolder(folder);
+ if (error instanceof TypeError) throw error;
+ return false;
+ }
+
+ const previous = previousClipboardFolders.get(options.directory);
+ previousClipboardFolders.set(options.directory, folder);
+ if (previous && previous !== folder) await removeFolder(previous);
+ return true;
+};
+
export const writeTextClipboard = async (clipboard, value) => {
if (typeof value !== "string") {
throw new TypeError("Clipboard value must be a string");
diff --git a/apps/desktop/src/main/clipboard-write.test.mjs b/apps/desktop/src/main/clipboard-write.test.mjs
index d34a7103..39e54728 100644
--- a/apps/desktop/src/main/clipboard-write.test.mjs
+++ b/apps/desktop/src/main/clipboard-write.test.mjs
@@ -1,6 +1,10 @@
import { describe, expect, test } from "bun:test";
+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
import { readFileSync } from "node:fs";
-import { writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";
+import { tmpdir } from "node:os";
+import { basename, join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+import { writeFileClipboard, writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";
const PNG = Uint8Array.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
@@ -97,6 +101,111 @@ describe("writeImageClipboard", () => {
});
});
+describe("writeFileClipboard", () => {
+ const clipboardWith = (writes, has = async (type) => type === "text/uri-list") => ({
+ write: async (value) => writes.push(value),
+ has,
+ });
+
+ const writtenPath = (writes) => fileURLToPath(String(writes.at(-1)[0].data["text/uri-list"]).trim());
+
+ test("copies the original filename inside the clipboard directory", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-clipboard-"));
+ const writes = [];
+ try {
+ const bytes = Uint8Array.from([1, 2, 3, 4]);
+ await expect(writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes,
+ filename: "notes/报告.pdf",
+ }, { directory })).resolves.toBe(true);
+ const path = writtenPath(writes);
+ expect(relative(directory, path).startsWith("..")).toBe(false);
+ expect(basename(path)).toBe("报告.pdf");
+ expect(new Uint8Array(await readFile(path))).toEqual(bytes);
+ expect(writes[0][0].data["text/uri-list"].endsWith("\r\n")).toBe(true);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ test("keeps only the latest copied file", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-clipboard-"));
+ const writes = [];
+ try {
+ await writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes: Uint8Array.from([1]),
+ filename: "first.txt",
+ }, { directory });
+ const first = writtenPath(writes);
+ await writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes: Uint8Array.from([2]),
+ filename: "second.txt",
+ }, { directory });
+ await expect(stat(first)).rejects.toThrow();
+ expect(new Uint8Array(await readFile(writtenPath(writes)))).toEqual(Uint8Array.from([2]));
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ test("drops path segments and refuses an empty or oversized payload", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-clipboard-"));
+ const writes = [];
+ try {
+ await expect(writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes: Uint8Array.from([9]),
+ filename: "../../etc/passwd",
+ }, { directory })).resolves.toBe(true);
+ expect(basename(writtenPath(writes))).toBe("passwd");
+ expect(relative(directory, writtenPath(writes)).startsWith("..")).toBe(false);
+
+ await expect(writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes: Uint8Array.from([]),
+ filename: "..",
+ }, { directory })).resolves.toBe(false);
+ await expect(writeFileClipboard(clipboardWith(writes), TestClipboardItem, {
+ bytes: Uint8Array.from([1, 2, 3, 4]),
+ filename: "big.bin",
+ }, { directory, maxBytes: 3 })).resolves.toBe(false);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ test("removes the file when the clipboard does not keep it", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-clipboard-"));
+ const writes = [];
+ try {
+ await expect(writeFileClipboard(clipboardWith(writes, async () => false), TestClipboardItem, {
+ bytes: Uint8Array.from([1]),
+ filename: "gone.txt",
+ }, { directory })).resolves.toBe(false);
+ await expect(stat(writtenPath(writes))).rejects.toThrow();
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ test("rejects malformed file input", async () => {
+ const clipboard = { write: async () => {}, has: async () => true };
+ await expect(writeFileClipboard(clipboard, TestClipboardItem, {
+ bytes: "nope",
+ filename: "a.txt",
+ }, { directory: "/tmp" })).rejects.toThrow("Clipboard file must be bytes");
+ await expect(writeFileClipboard(clipboard, TestClipboardItem, {
+ bytes: Uint8Array.from([1]),
+ filename: 12,
+ }, { directory: "/tmp" })).rejects.toThrow("Clipboard filename must be a string");
+ });
+
+ test("desktop file copy is wired through the main process", () => {
+ const main = readFileSync(new URL("./index.mjs", import.meta.url), "utf8");
+ const preload = readFileSync(new URL("../preload/index.cjs", import.meta.url), "utf8");
+ expect(main).toContain('ipcMain.handle("desktop:copy-file"');
+ expect(preload).toContain('ipcRenderer.invoke("desktop:copy-file"');
+ });
+});
+
describe("writeRichClipboard", () => {
test("writes and verifies both rich HTML and plain text with the Electron 44 API", async () => {
const writes = [];
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index f9db80c7..1120d088 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -37,7 +37,7 @@ import { isAllowedAppNavigation, isAllowedPrintPreviewUrl, isResourceDownloadUrl
import { showWindow } from "./window-visibility.mjs";
import { formatGlobalShortcutForHumans, globalShortcutAccelerator, globalShortcutAcceleratorsConflict, normalizeGlobalShortcutBinding, parseStoredGlobalShortcuts, replaceGlobalShortcut, toggleMainWindow } from "./global-shortcut.mjs";
import { trayIconPath } from "./tray-icon.mjs";
-import { writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";
+import { writeFileClipboard, writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";
import { registerClipboardReadIpc } from "./clipboard-read.mjs";
import { captureRegionScreenToNote, captureScreenToNote, createScreenshotCaptureGuard, screenshotImportIpcPayload, writeScreenshotTempPath } from "./screenshot-capture.mjs";
import { cancelScreenshotRegionSelection, openScreenshotRegionSelector } from "./screenshot-region.mjs";
@@ -1949,6 +1949,10 @@ const startApplication = async () => {
ipcMain.handle("desktop:copy-text", (_event, value) => writeTextClipboard(clipboard, value));
ipcMain.handle("desktop:copy-html", (_event, input) => writeRichClipboard(clipboard, ClipboardItem, input));
ipcMain.handle("desktop:copy-image", (_event, bytes) => writeImageClipboard(clipboard, ClipboardItem, bytes));
+ ipcMain.handle("desktop:copy-file", (_event, bytes, filename) => writeFileClipboard(clipboard, ClipboardItem, {
+ bytes,
+ filename,
+ }, { directory: join(app.getPath("temp"), "edgeever-clipboard") }));
registerClipboardReadIpc(ipcMain, {
clipboard,
getMainWindow: () => mainWindow,
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index ab22caeb..693c78f8 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -52,6 +52,7 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
copyText: (value) => ipcRenderer.invoke("desktop:copy-text", value),
copyHtml: (html, plainText) => ipcRenderer.invoke("desktop:copy-html", { html, plainText }),
copyImage: (bytes) => ipcRenderer.invoke("desktop:copy-image", bytes),
+ copyFile: (bytes, filename) => ipcRenderer.invoke("desktop:copy-file", bytes, filename),
readClipboard: () => {
// Check in the isolated preload world; renderer JavaScript cannot forge this
// gesture state. Clipboard reads are reserved for an explicit paste action.
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 541cdc23..48776849 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -168,7 +168,7 @@ import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate } fro
import {
getMemoSaveConflictInfoFromQueueItem,
} from "@/lib/memo-save-conflict";
-import { copyTextToClipboard } from "@/lib/clipboard";
+import { copyResourceToClipboard, copyTextToClipboard } from "@/lib/clipboard";
import { createClientUuid } from "@/lib/client-id";
import { isLocalMemoId, remapLocalDraftMemoId } from "@/lib/local-mirror";
import { shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";
@@ -566,6 +566,8 @@ const RichEditorPane = ({
}, [aiAssistantOpen, isLoading, memo?.id]);
const [phonePreviewOpen, setPhonePreviewOpen] = useState(readEditorPhonePreviewPreference);
const [memoIdCopyNotice, setMemoIdCopyNotice] = useState<{ status: "copied" | "error"; id: string } | null>(null);
+ const [resourceCopyNotice, setResourceCopyNotice] = useState<"copied" | "error" | null>(null);
+ const resourceCopyNoticeTimerRef = useRef<number | null>(null);
const handledSaveAndSyncTokenRef = useRef(saveAndSyncToken);
const handledReadingProtectionToggleTokenRef = useRef(readingProtectionToggleToken);
const handledEditorModeToggleTokenRef = useRef(editorModeToggleToken);
@@ -3386,31 +3388,31 @@ const RichEditorPane = ({
}), [attachmentTranscript, dismissAttachmentTranscript, editor?.isEditable, effectiveReadOnly,
insertAttachmentTranscript, memo?.id, retryAttachmentTranscript, useMarkdownSourceEditor, useMobilePlainTextEditor]);
- const handleResourceSaveAs = useCallback(async (target: ResourceMenuTarget) => {
+ const showResourceCopyNotice = useCallback((status: "copied" | "error") => {
+ if (resourceCopyNoticeTimerRef.current !== null) window.clearTimeout(resourceCopyNoticeTimerRef.current);
+ setResourceCopyNotice(status);
+ resourceCopyNoticeTimerRef.current = window.setTimeout(() => {
+ resourceCopyNoticeTimerRef.current = null;
+ setResourceCopyNotice(null);
+ }, status === "copied" ? 2200 : 3200);
+ }, []);
+
+ useEffect(() => () => {
+ if (resourceCopyNoticeTimerRef.current !== null) window.clearTimeout(resourceCopyNoticeTimerRef.current);
+ }, []);
+
+ const handleResourceCopy = useCallback((target: ResourceMenuTarget) => {
hideResourceMenu();
clearResourceActionError();
- try {
- const savePicker = (window as Window & {
- showSaveFilePicker?: (options: { suggestedName: string }) => Promise<{
- createWritable: () => Promise<WritableStream<Uint8Array>>;
- }>;
- }).showSaveFilePicker;
-
- if (!savePicker) {
- downloadResourceDirectly(target);
- return;
- }
-
- const handle = await savePicker.call(window, { suggestedName: target.filename });
- const response = await fetchResourceResponse(target);
- if (!response.body) throw new Error(getResourceActionFailure(target));
- const writable = await handle.createWritable();
- await response.body.pipeTo(writable);
- } catch (error) {
- if (error instanceof DOMException && error.name === "AbortError") return;
- failResourceAction(error instanceof Error ? error.message : getResourceActionFailure(target));
- }
- }, [clearResourceActionError, downloadResourceDirectly, failResourceAction, fetchResourceResponse, getResourceActionFailure, hideResourceMenu]);
+ // Start the clipboard write in this turn so Safari still has the click gesture.
+ void copyResourceToClipboard({
+ filename: target.filename,
+ asImage: target.kind === "image",
+ load: () => fetchResourceResponse(target),
+ }).then((copied) => {
+ showResourceCopyNotice(copied ? "copied" : "error");
+ });
+ }, [clearResourceActionError, fetchResourceResponse, hideResourceMenu, showResourceCopyNotice]);
const openResourceDialog = useCallback((action: ResourceDialogState["action"], target: ResourceMenuTarget) => {
openResourceActionDialog(action, target);
@@ -3874,7 +3876,7 @@ const RichEditorPane = ({
const resourceMenuLabels = {
download: t("editor.resourceActions.download"),
- saveAs: t("editor.resourceActions.saveAs"),
+ copy: t("editor.resourceActions.copy"),
transcribe: t("editor.resourceActions.transcribe"),
rename: t("editor.resourceActions.rename"),
delete: t("editor.resourceActions.delete"),
@@ -4668,7 +4670,7 @@ const RichEditorPane = ({
)}
labels={resourceMenuLabels}
onDownload={() => void handleResourceDownload(resourceMenuTarget)}
- onSaveAs={() => void handleResourceSaveAs(resourceMenuTarget)}
+ onCopy={() => handleResourceCopy(resourceMenuTarget)}
onTranscribe={() => void handleResourceTranscribe(resourceMenuTarget)}
onRename={() => openResourceDialog("rename", resourceMenuTarget)}
onDelete={() => openResourceDialog("delete", resourceMenuTarget)}
@@ -4695,6 +4697,12 @@ const RichEditorPane = ({
</ClipboardCopyNotice>
)}
+ {resourceCopyNotice && (
+ <ClipboardCopyNotice status={resourceCopyNotice}>
+ {t(resourceCopyNotice === "copied" ? "editor.resourceActions.copied" : "editor.resourceActions.copyFailed")}
+ </ClipboardCopyNotice>
+ )}
+
{wechatCopyState === "copying" && <WeChatCopyProgress />}
{(wechatCopyState === "copied" || wechatCopyState === "error") && (
diff --git a/apps/web/src/components/editor/EditorPaneChrome.tsx b/apps/web/src/components/editor/EditorPaneChrome.tsx
index 398d1ad0..016df18c 100644
--- a/apps/web/src/components/editor/EditorPaneChrome.tsx
+++ b/apps/web/src/components/editor/EditorPaneChrome.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { autoUpdate, useFloating } from "@floating-ui/react-dom";
-import { AudioLines, FileDown, Pencil, Save, Trash2, X } from "lucide-react";
+import { AudioLines, Copy, FileDown, Pencil, Trash2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import {
@@ -73,7 +73,7 @@ export const NoteLinkInteractionHint = ({
type ResourceActionLabels = {
download: string;
- saveAs: string;
+ copy: string;
transcribe: string;
rename: string;
delete: string;
@@ -87,7 +87,7 @@ export const ResourceActionMenu = ({
canTranscribe,
labels,
onDownload,
- onSaveAs,
+ onCopy,
onTranscribe,
onRename,
onDelete,
@@ -100,7 +100,7 @@ export const ResourceActionMenu = ({
canTranscribe: boolean;
labels: ResourceActionLabels;
onDownload: () => void;
- onSaveAs: () => void;
+ onCopy: () => void;
onTranscribe: () => void;
onRename: () => void;
onDelete: () => void;
@@ -147,10 +147,10 @@ export const ResourceActionMenu = ({
{labels.download}
</Button>
</IconTooltip>
- <IconTooltip label={labels.saveAs}>
- <Button type="button" size="sm" variant="ghost" aria-label={labels.saveAs} onClick={onSaveAs}>
- <Save className="h-3.5 w-3.5" />
- {labels.saveAs}
+ <IconTooltip label={labels.copy}>
+ <Button type="button" size="sm" variant="ghost" aria-label={labels.copy} onClick={onCopy}>
+ <Copy className="h-3.5 w-3.5" />
+ {labels.copy}
</Button>
</IconTooltip>
{canTranscribe ? (
diff --git a/apps/web/src/lib/clipboard.test.mjs b/apps/web/src/lib/clipboard.test.mjs
index c94c1b9f..e7b13b41 100644
--- a/apps/web/src/lib/clipboard.test.mjs
+++ b/apps/web/src/lib/clipboard.test.mjs
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
-import { copyHtmlToClipboard, copyImageBlobToClipboard, copyImageUrlToClipboard, copyTextToClipboard, installDesktopClipboardBridge } from "./clipboard.ts";
+import { copyHtmlToClipboard, copyImageBlobToClipboard, copyImageUrlToClipboard, copyResourceToClipboard, copyTextToClipboard, installDesktopClipboardBridge } from "./clipboard.ts";
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, "navigator");
@@ -356,3 +356,128 @@ describe("copyImageBlobToClipboard", () => {
expect(source).toContain('role="alert"');
});
});
+
+describe("copyResourceToClipboard", () => {
+ test("copies an image through the desktop image bridge", async () => {
+ const calls = [];
+ const png = new Blob([Uint8Array.from([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" });
+ globalThis.window = {
+ edgeeverDesktop: {
+ isAvailable: true,
+ copyImage: async (bytes) => {
+ calls.push(bytes);
+ return true;
+ },
+ copyFile: async () => {
+ throw new Error("file clipboard should not be used for an image");
+ },
+ },
+ };
+
+ await expect(copyResourceToClipboard({
+ filename: "portrait.png",
+ asImage: true,
+ load: async () => ({ ok: true, blob: async () => png }),
+ })).resolves.toBe(true);
+ expect(calls).toEqual([new Uint8Array(await png.arrayBuffer())]);
+ });
+
+ test("copies an attachment through the desktop file bridge", async () => {
+ const calls = [];
+ const pdf = new Blob([Uint8Array.from([7, 8, 9])], { type: "application/pdf" });
+ globalThis.window = {
+ edgeeverDesktop: {
+ isAvailable: true,
+ copyImage: async () => {
+ throw new Error("image clipboard should not be used for an attachment");
+ },
+ copyFile: async (bytes, filename) => {
+ calls.push([bytes, filename]);
+ return true;
+ },
+ },
+ };
+
+ await expect(copyResourceToClipboard({
+ filename: "notes/报告.pdf",
+ asImage: false,
+ load: async () => ({ ok: true, blob: async () => pdf }),
+ })).resolves.toBe(true);
+ expect(calls).toEqual([[new Uint8Array(await pdf.arrayBuffer()), "notes/报告.pdf"]]);
+ });
+
+ test("reports failure when the resource cannot be loaded", async () => {
+ globalThis.window = {
+ edgeeverDesktop: {
+ isAvailable: true,
+ copyImage: async () => true,
+ copyFile: async () => true,
+ },
+ };
+
+ await expect(copyResourceToClipboard({
+ filename: "missing.pdf",
+ asImage: false,
+ load: async () => {
+ throw new Error("Resource download failed");
+ },
+ })).resolves.toBe(false);
+ });
+
+ test("starts the browser image write during the click, before the response arrives", async () => {
+ const writes = [];
+ const png = new Blob([Uint8Array.from([9])], { type: "image/png" });
+ let resolveLoad = () => {};
+ globalThis.window = {};
+ installClipboardItem();
+ Object.defineProperty(globalThis, "navigator", {
+ configurable: true,
+ value: { clipboard: { write: async (items) => writes.push(items) } },
+ });
+
+ const pending = copyResourceToClipboard({
+ filename: "portrait.jpg",
+ asImage: true,
+ load: () => new Promise((resolve) => {
+ resolveLoad = () => resolve({ ok: true, blob: async () => png });
+ }),
+ });
+ expect(writes).toHaveLength(1);
+ const payload = writes[0][0].data["image/png"];
+ expect(payload).toBeInstanceOf(Promise);
+ resolveLoad();
+ await expect(payload).resolves.toBe(png);
+ await expect(pending).resolves.toBe(true);
+ });
+
+ test("does not pretend a browser can copy a non-image attachment", async () => {
+ const writes = [];
+ globalThis.window = {};
+ installClipboardItem();
+ Object.defineProperty(globalThis, "navigator", {
+ configurable: true,
+ value: { clipboard: { write: async (items) => writes.push(items) } },
+ });
+
+ await expect(copyResourceToClipboard({
+ filename: "报告.pdf",
+ asImage: false,
+ load: async () => {
+ throw new Error("should not fetch when the browser cannot hold the file");
+ },
+ })).resolves.toBe(false);
+ expect(writes).toEqual([]);
+ });
+
+ test("the image and attachment menu copies instead of exporting", () => {
+ const chrome = readFileSync(new URL("../components/editor/EditorPaneChrome.tsx", import.meta.url), "utf8");
+ const editor = readFileSync(new URL("../components/EditorPane.tsx", import.meta.url), "utf8");
+ expect(chrome).toContain("onCopy");
+ expect(chrome).not.toContain("onSaveAs");
+ expect(chrome).not.toContain("labels.saveAs");
+ expect(editor).toContain("copyResourceToClipboard");
+ expect(editor).toContain('t("editor.resourceActions.copy")');
+ expect(editor).not.toContain("handleResourceSaveAs");
+ expect(editor).not.toContain('editor.resourceActions.saveAs');
+ });
+});
diff --git a/apps/web/src/lib/clipboard.ts b/apps/web/src/lib/clipboard.ts
index 713a0535..69593cb2 100644
--- a/apps/web/src/lib/clipboard.ts
+++ b/apps/web/src/lib/clipboard.ts
@@ -149,6 +149,58 @@ export const copyImageUrlToClipboard = async (url: string): Promise<boolean> =>
}
};
+export const copyResourceToClipboard = async ({
+ load,
+ filename,
+ asImage,
+}: {
+ load: () => Promise<Response>;
+ filename: string;
+ asImage: boolean;
+}): Promise<boolean> => {
+ const desktop = typeof window !== "undefined" ? window.edgeeverDesktop : undefined;
+ if (desktop?.copyImage || desktop?.copyFile) {
+ try {
+ const response = await load();
+ if (!response.ok) return false;
+ const blob = await response.blob();
+ if (asImage) return await copyImageBlobToClipboard(blob);
+ if (!desktop.copyFile) return false;
+ return await desktop.copyFile(new Uint8Array(await blob.arrayBuffer()), filename || "attachment");
+ } catch {
+ return false;
+ }
+ }
+
+ if (!asImage || typeof window === "undefined" || !navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
+ return false;
+ }
+
+ try {
+ // Safari keeps the click gesture only when write() runs now and the
+ // ClipboardItem payload is still a Promise. Fetch and PNG conversion stay inside it.
+ const pngPromise = load()
+ .then((response) => {
+ if (!response.ok) throw new Error("Resource fetch failed");
+ return response.blob();
+ })
+ .then((blob) => toPngBlob(blob))
+ .then((png) => {
+ if (!png) throw new Error("PNG conversion failed");
+ return png;
+ });
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ "image/png": pngPromise,
+ }),
+ ]);
+ return true;
+ } catch (error) {
+ console.warn("Failed to copy resource to clipboard:", error);
+ return false;
+ }
+};
+
export const copyImageBlobToClipboard = async (blob: Blob): Promise<boolean> => {
const copyImage = typeof window !== "undefined" ? window.edgeeverDesktop?.copyImage : undefined;
if (copyImage) {
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 656bbd10..2a9ba658 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -50,6 +50,7 @@ interface EdgeEverDesktopBridge {
copyText(value: string): Promise<boolean>;
copyHtml(html: string, plainText: string): Promise<boolean>;
copyImage(bytes: Uint8Array): Promise<boolean>;
+ copyFile(bytes: Uint8Array, filename: string): Promise<boolean>;
readClipboard?(): Promise<{ html: string; text: string; images: Uint8Array[] }>;
setSessionToken(value: string): Promise<{ stored: boolean }>;
clearSessionToken(): Promise<{ stored: false }>;
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 61b96385..443f1744 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2504,7 +2504,9 @@ export const enUS = {
resourceActions: {
download: "Download",
transcribe: "Transcribe",
- saveAs: "Export",
+ copy: "Copy",
+ copied: "Copied",
+ copyFailed: "Couldn't copy this file. Use Download instead.",
rename: "Rename",
delete: "Delete",
unavailable: "This action is available after the resource has synced and the note is editable",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 18dcb233..bd48125c 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2493,7 +2493,9 @@ export const ja = {
resourceActions: {
download: "ダウンロード",
transcribe: "文字起こし",
- saveAs: "エクスポート",
+ copy: "コピー",
+ copied: "コピーしました",
+ copyFailed: "コピーできませんでした。ダウンロードを使ってください",
rename: "名前を変更",
delete: "削除",
unavailable: "リソースの同期が完了し、ノートが編集可能なときだけ使えます",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 79ba3ee9..ba187efe 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2493,7 +2493,9 @@ export const pl = {
resourceActions: {
download: "Pobierz",
transcribe: "Transkrybuj",
- saveAs: "Eksportuj",
+ copy: "Kopiuj",
+ copied: "Skopiowano",
+ copyFailed: "Nie udało się skopiować. Użyj pobierania",
rename: "Zmień nazwę",
delete: "Usuń",
unavailable: "To działanie będzie dostępne po zsynchronizowaniu zasobu, gdy notatkę będzie można edytować",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index 9110e329..fba7106b 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -2504,7 +2504,9 @@ export const ru = {
resourceActions: {
download: "Скачать",
transcribe: "Расшифровать",
- saveAs: "Экспорт",
+ copy: "Копировать",
+ copied: "Скопировано",
+ copyFailed: "Не удалось скопировать. Используйте скачивание",
rename: "Переименовать",
delete: "Удалить",
unavailable: "Это действие доступно после синхронизации ресурса и когда заметка доступна для редактирования",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index ad8d4926..967736aa 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2504,7 +2504,9 @@ export const zhCN = {
resourceActions: {
download: "下载",
transcribe: "转录",
- saveAs: "导出",
+ copy: "复制",
+ copied: "已复制",
+ copyFailed: "复制失败,请使用下载",
rename: "重命名",
delete: "删除",
unavailable: "资源同步完成且当前笔记可编辑后才能执行此操作",