A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Fix copy to clipboard on Safari (#8587)
Tony Chen59df5f8f525c
diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex d37333b837..cfb3a98120 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -25,7 +25,7 @@ import { CellOutputId } from "@/core/cells/ids";import { isOutputEmpty } from "@/core/cells/outputs";import { goToDefinitionAtCursorPosition } from "@/core/codemirror/go-to-definition/utils";import { sendToPanelManager } from "@/core/vscode/vscode-bindings";-import { copyToClipboard } from "@/utils/copy";+import { copyImageToClipboard, copyToClipboard } from "@/utils/copy";import { getImageExtension } from "@/utils/filenames";import { Logger } from "@/utils/Logger";import type { ActionButton } from "../actions/types";@@ -127,11 +127,7 @@ export const CellActionsContextMenu = ({icon: <ClipboardCopyIcon size={13} strokeWidth={1.5} />,handle: async () => {if (imageRightClicked) {- const response = await fetch(imageRightClicked.src);- const blob = await response.blob();- const item = new ClipboardItem({ [blob.type]: blob });- await navigator.clipboard- .write([item])+ await copyImageToClipboard(imageRightClicked.src).then(() => {toast({title: "Copied image to clipboard",diff --git a/frontend/src/utils/__tests__/copy.test.ts b/frontend/src/utils/__tests__/copy.test.tsnew file mode 100644index 0000000000..82b19d6cdc--- /dev/null+++ b/frontend/src/utils/__tests__/copy.test.ts@@ -0,0 +1,129 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { copyImageToClipboard, isSafari } from "../copy";++describe("isSafari", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("returns true for Safari on macOS", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",+ );+ expect(isSafari()).toBe(true);+ });++ it("returns true for Safari on iOS", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",+ );+ expect(isSafari()).toBe(true);+ });++ it("returns false for Chrome", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",+ );+ expect(isSafari()).toBe(false);+ });++ it("returns false for Chrome on iOS (CriOS)", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0.0.0 Mobile/15E148 Safari/604.1",+ );+ expect(isSafari()).toBe(false);+ });++ it("returns false for Firefox on iOS (FxiOS)", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/120.0 Mobile/15E148 Safari/604.1",+ );+ expect(isSafari()).toBe(false);+ });++ it("returns false for Edge on iOS (EdgiOS)", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/120.0.0.0 Mobile/15E148 Safari/604.1",+ );+ expect(isSafari()).toBe(false);+ });++ it("returns false for Firefox on desktop", () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:120.0) Gecko/20100101 Firefox/120.0",+ );+ expect(isSafari()).toBe(false);+ });+});++describe("copyImageToClipboard", () => {+ let writeMock: ReturnType<typeof vi.fn>;+ let clipboardItemSpy: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ writeMock = vi.fn().mockResolvedValue(undefined);+ Object.assign(navigator, {+ clipboard: { write: writeMock },+ });++ // ClipboardItem is not available in jsdom, so we mock it+ clipboardItemSpy = vi.fn().mockImplementation((data) => ({ data }));+ vi.stubGlobal("ClipboardItem", clipboardItemSpy);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("uses blob type from response on non-Safari browsers", async () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36",+ );++ const fakeBlob = new Blob(["fake"], { type: "image/jpeg" });+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(fakeBlob, {+ headers: { "Content-Type": "image/jpeg" },+ }),+ );++ await copyImageToClipboard("https://example.com/image.jpg");++ expect(writeMock).toHaveBeenCalledOnce();+ // Non-Safari path: awaits blob, uses blob.type as key+ const arg = clipboardItemSpy.mock.calls[0][0];+ expect(arg).toHaveProperty("image/jpeg");+ expect(arg["image/jpeg"].type).toBe("image/jpeg");+ });++ it("uses image/png on Safari", async () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",+ );++ const fakeBlob = new Blob(["fake"], { type: "image/png" });+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(fakeBlob));++ await copyImageToClipboard("https://example.com/image.png");++ expect(writeMock).toHaveBeenCalledOnce();+ // Safari path: uses "image/png" key with a Promise<Blob>+ expect(clipboardItemSpy).toHaveBeenCalledWith({+ "image/png": expect.any(Promise),+ });+ });++ it("propagates fetch errors", async () => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(+ "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36",+ );++ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network error"));++ await expect(+ copyImageToClipboard("https://example.com/image.png"),+ ).rejects.toThrow("Network error");+ });+});diff --git a/frontend/src/utils/copy.ts b/frontend/src/utils/copy.tsindex a5691db2de..f30c08a6c6 100644--- a/frontend/src/utils/copy.ts+++ b/frontend/src/utils/copy.ts@@ -21,3 +21,46 @@ export async function copyToClipboard(text: string) {window.prompt("Copy to clipboard: Ctrl+C, Enter", text);});}++/**+ * Returns true if the current browser is Safari.+ *+ * Safari requires special handling for clipboard operations because it+ * drops the user-activation context during async operations like fetch.+ */+export function isSafari(): boolean {+ const ua = navigator.userAgent;+ // Safari includes "Safari" but not "Chrome"/"Chromium" in its UA string.+ // iOS in-app browsers (CriOS, FxiOS, EdgiOS) also include "Safari"+ // but are excluded by checking for their specific tokens.+ return (+ /safari/i.test(ua) && !/chrome|chromium|crios|fxios|edgios|opios/i.test(ua)+ );+}++/**+ * Copies an image to the clipboard from a URL.+ *+ * On Safari, the ClipboardItem is constructed synchronously with a+ * Promise<Blob> to preserve the user-activation context, which Safari+ * drops during async operations like fetch. This means we must assume+ * the MIME type (image/png) since we can't inspect the response first.+ *+ * On other browsers, we await the fetch and use the actual MIME type.+ */+export async function copyImageToClipboard(imageSrc: string): Promise<void> {+ let item: ClipboardItem;+ if (isSafari()) {+ // Safari drops user-activation context during await, so we must+ // construct the ClipboardItem synchronously with a Promise<Blob>.+ item = new ClipboardItem({+ "image/png": fetch(imageSrc).then((response) => response.blob()),+ });+ } else {+ const response = await fetch(imageSrc);+ const blob = await response.blob();+ item = new ClipboardItem({ [blob.type]: blob });+ }++ await navigator.clipboard.write([item]);+}