The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Clipboard: Copy works inside menus and dialogs on plain-http LAN addresses
Claude0f1a5a38370e
diff --git a/src/lib/clipboard.ts b/src/lib/clipboard.tsindex c7b0919f..cadef515 100644--- a/src/lib/clipboard.ts+++ b/src/lib/clipboard.ts@@ -3,8 +3,8 @@ import { toast } from "sonner";/*** Copy text to the clipboard, also where the Clipboard API is missing: a self-hosted Fuobe opened* over plain http on a LAN address is not a secure context, so `navigator.clipboard` is undefined- * there. Falls back to selecting a hidden textarea and `document.execCommand("copy")`.- * Resolves to whether the text was copied.+ * there. Falls back to `document.execCommand("copy")` (see legacyCopy). Resolves to whether the+ * text was copied.*/export async function copyText(text: string): Promise<boolean> {try {@@ -18,24 +18,56 @@ export async function copyText(text: string): Promise<boolean> {return legacyCopy(text);}+/** Containers that trap the focus (Radix dialogs, sheets, popovers and menus). */+const FOCUS_TRAPS = '[role="dialog"],[role="alertdialog"],[role="menu"]';++/**+ * Where the hidden textarea goes: inside the dialog or menu that holds the focus. Most Copy buttons+ * sit in one (the feed's ⋯ menu, the viewer), and its focus trap pulls the focus straight back out+ * of a textarea on <body>, so the copy would find nothing selected.+ */+function hostFor(active: Element | null): Element {+ if (!active || active === document.body || active === document.documentElement) return document.body;+ return active.closest?.(FOCUS_TRAPS) ?? active.parentElement ?? document.body;+}++/**+ * execCommand("copy") from the click that asked for it. Its copy event carries the text itself+ * (clipboardData), so the copy doesn't depend on a selection surviving; the selected textarea+ * backs that up for a browser without clipboardData. Only says it worked when one of them held:+ * execCommand returns true even when it copied nothing.+ */function legacyCopy(text: string): boolean {if (typeof document === "undefined") return false;+ const active = document.activeElement as HTMLElement | null;const ta = document.createElement("textarea");ta.value = text;ta.setAttribute("readonly", "");+ ta.setAttribute("aria-hidden", "true");+ ta.tabIndex = -1;// Off-screen but still selectable (display: none can't be selected).ta.style.cssText = "position:fixed;top:0;left:-9999px;opacity:0;pointer-events:none";- const active = document.activeElement as HTMLElement | null;- document.body.appendChild(ta);+ let wrote = false;+ const onCopy = (e: ClipboardEvent) => {+ if (!e.clipboardData) return;+ e.clipboardData.setData("text/plain", text);+ e.preventDefault();+ wrote = true;+ };+ hostFor(active).appendChild(ta);+ document.addEventListener("copy", onCopy, true);try {+ ta.focus({ preventScroll: true });ta.select();ta.setSelectionRange(0, text.length);- return document.execCommand("copy");+ const ok = document.execCommand("copy");+ return ok && (wrote || (document.activeElement === ta && ta.selectionEnd - ta.selectionStart === text.length));} catch {return false;} finally {+ document.removeEventListener("copy", onCopy, true);ta.remove();- active?.focus?.();+ active?.focus?.({ preventScroll: true });}}diff --git a/tests/e2e/clipboard.mjs b/tests/e2e/clipboard.mjsnew file mode 100644index 00000000..14167915--- /dev/null+++ b/tests/e2e/clipboard.mjs@@ -0,0 +1,128 @@+// Copy buttons without the Clipboard API (src/lib/clipboard.ts), in a real browser. A self-hosted+// Fuobe on a plain-http LAN address has no navigator.clipboard, so copyText falls back to+// execCommand("copy"). Most Copy buttons sit in a Radix menu or dialog, whose focus trap pulls the+// focus away from anything outside it, so this reads the clipboard back to check what was really+// copied (the toast alone says nothing). The app must be running; demo mode is fine.+// Usage: node tests/e2e/clipboard.mjs [appUrl]. Exits 1 on the first failure.+//+// 1. A result's ⋯ menu in the feed → Copy prompt (a non-modal menu).+// 2. The viewer (a modal dialog): both of its Copy prompt buttons.+// 3. Cinema projects: a project's ⋯ menu → Copy link (a modal menu, which traps the focus).+// 4. On a phone: the viewer's "More actions and details" sheet (a dialog in a dialog) → Copy prompt.+import assert from "node:assert/strict";+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";++const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");+const browser = await launch();+const step = (name) => console.log(`- ${name}`);++/** A plain-http LAN origin, as far as the page can tell: no navigator.clipboard (the test keeps it to read back). */+async function context(device) {+ const ctx = await browser.newContext(device);+ await ctx.grantPermissions(["clipboard-read", "clipboard-write"], { origin: app });+ await ctx.addInitScript(() => {+ window.__clipboard = navigator.clipboard;+ Object.defineProperty(Navigator.prototype, "clipboard", { configurable: true, get: () => undefined });+ });+ return ctx;+}++const clipboard = (page) => page.evaluate(() => window.__clipboard.readText());+const reset = (page) => page.evaluate(() => window.__clipboard.writeText("UNCHANGED"));++/** Click a Copy button and check the clipboard really holds `want` (and the toast said so). */+async function copies(page, click, want, toastText) {+ await reset(page);+ assert.equal(await page.evaluate(() => navigator.clipboard), undefined, "the page should see no Clipboard API");+ await click();+ await page.getByText(toastText, { exact: true }).first().waitFor({ timeout: 5_000 });+ assert.equal(await clipboard(page), want);+}++const call = async (route, method = "GET", body) => {+ const res = await fetch(app + route, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined });+ if (!res.ok) throw new Error(`${method} ${route}: ${res.status}`);+ return res.status === 204 ? null : res.json();+};++/** A finished demo image to copy the prompt of. */+async function result(prompt) {+ const { items } = await call("/api/generations", "POST", { feature: "image", modelId: "nano-banana-pro", prompt });+ const id = items[0].id;+ for (let i = 0; i < 60; i++) {+ const g = await call(`/api/generations/${id}`);+ if (g.status === "succeeded") return g;+ if (g.status === "failed" || g.status === "canceled") throw new Error(`the demo job ${g.status}`);+ await new Promise((r) => setTimeout(r, 1000));+ }+ throw new Error("the demo job didn't finish");+}++let project = null;+try {+ const prompt = `a lighthouse at dusk ${Date.now().toString(36)}`;+ await result(prompt);+ {+ const ctx = await context(DESKTOP);+ const page = await ctx.newPage();+ await openRoute(page, `${app}/image`);++ step("feed: a result's ⋯ menu → Copy prompt");+ const header = page.locator("header", { has: page.locator("h3", { hasText: prompt }) });+ await copies(+ page,+ async () => {+ await header.getByRole("button", { name: "More", exact: true }).click();+ await page.getByRole("menuitem", { name: "Copy prompt" }).click();+ },+ prompt,+ "Prompt copied",+ );++ step("viewer (a modal dialog): its Copy prompt buttons");+ await page.keyboard.press("Escape");+ const open = page.getByRole("button", { name: `Open “${prompt}”` }).first();+ await open.focus();+ await page.keyboard.press("Enter");+ const dialog = page.getByRole("dialog");+ await dialog.waitFor({ timeout: 10_000 });+ const buttons = dialog.getByRole("button", { name: "Copy prompt" });+ const n = await buttons.count();+ assert.ok(n >= 1, "the viewer has a Copy prompt button");+ for (let i = 0; i < n; i++) await copies(page, () => buttons.nth(i).click(), prompt, "Prompt copied");+ await page.keyboard.press("Escape");++ step("Cinema projects: a project's ⋯ menu (modal, traps the focus) → Copy link");+ project = await call("/api/cinema/projects", "POST", { name: `Copy check ${Date.now().toString(36)}` });+ await openRoute(page, `${app}/cinema`);+ await copies(+ page,+ async () => {+ await page.getByRole("button", { name: `${project.name} actions` }).click();+ await page.getByRole("menuitem", { name: "Copy link" }).click();+ },+ `${app}/cinema/${project.id}`,+ "Link copied",+ );+ await ctx.close();+ }+ {+ step("phone: the viewer's details sheet (a dialog in a dialog) → Copy prompt");+ const ctx = await context(PHONE);+ const page = await ctx.newPage();+ await openRoute(page, `${app}/image`);+ await page.getByRole("button", { name: `Open “${prompt}”` }).first().dispatchEvent("click");+ await page.getByRole("dialog").first().waitFor({ timeout: 10_000 });+ await page.getByRole("button", { name: "More actions and details" }).click();+ const sheet = page.getByRole("dialog").filter({ has: page.getByRole("button", { name: "Copy prompt" }) }).last();+ await copies(page, () => sheet.getByRole("button", { name: "Copy prompt" }).first().click(), prompt, "Prompt copied");+ await ctx.close();+ }+ console.log("\nclipboard: all checks passed");+} catch (e) {+ console.error(`\nFAILED: ${e.message}`);+ process.exitCode = 1;+} finally {+ if (project) await call(`/api/cinema/projects/${project.id}`, "DELETE").catch(() => {});+ await browser.close();+}diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.tsindex d5148faa..c396a66e 100644--- a/tests/shell-logic.test.ts+++ b/tests/shell-logic.test.ts@@ -301,6 +301,32 @@ describe("releasing color grading's media", () => {describe("copyText", () => {afterEach(() => vi.unstubAllGlobals());+ /**+ * Just enough DOM for the execCommand fallback: `copy` dispatches the copy event (with+ * clipboardData unless `noClipboardData`); `active` is what holds the focus.+ */+ function fakeDom({ result = true, fires = true, noClipboardData = false, active = null as unknown }: { result?: boolean; fires?: boolean; noClipboardData?: boolean; active?: unknown } = {}) {+ const ta = { value: "", style: { cssText: "" }, tabIndex: 0, selectionStart: 0, selectionEnd: 0, setAttribute() {}, focus: vi.fn(), select() {}, setSelectionRange: vi.fn(), remove: vi.fn() };+ const listeners = new Set<(e: unknown) => void>();+ const setData = vi.fn();+ const preventDefault = vi.fn();+ const body = { appendChild: vi.fn() };+ const doc = {+ createElement: () => ta,+ body,+ documentElement: {},+ activeElement: active,+ addEventListener: (type: string, fn: (e: unknown) => void) => type === "copy" && listeners.add(fn),+ removeEventListener: (type: string, fn: (e: unknown) => void) => listeners.delete(fn),+ execCommand: vi.fn(() => {+ if (fires) listeners.forEach((fn) => fn({ clipboardData: noClipboardData ? null : { setData }, preventDefault }));+ return result;+ }),+ };+ vi.stubGlobal("document", doc);+ return { ta, doc, body, setData, preventDefault, listeners };+ }+it("uses the Clipboard API when there is one", async () => {const writeText = vi.fn(async () => {});vi.stubGlobal("navigator", { clipboard: { writeText } });@@ -308,25 +334,50 @@ describe("copyText", () => {expect(writeText).toHaveBeenCalledWith("hi");});- it("falls back to a selected textarea on plain-http origins (no navigator.clipboard)", async () => {+ it("falls back to execCommand on plain-http origins (no navigator.clipboard): the copy event carries the text", async () => {vi.stubGlobal("navigator", {});- const ta = { value: "", style: { cssText: "" }, setAttribute() {}, select() {}, setSelectionRange() {}, remove: vi.fn() };- const execCommand = vi.fn(() => true);- vi.stubGlobal("document", { createElement: () => ta, body: { appendChild() {} }, activeElement: null, execCommand });+ const dom = fakeDom();expect(await copyText("fuobe_secret")).toBe(true);- expect(ta.value).toBe("fuobe_secret");- expect(execCommand).toHaveBeenCalledWith("copy");- expect(ta.remove).toHaveBeenCalled();+ expect(dom.doc.execCommand).toHaveBeenCalledWith("copy");+ // Set on the event itself, so a focus trap that takes the selection away doesn't matter.+ expect(dom.setData).toHaveBeenCalledWith("text/plain", "fuobe_secret");+ expect(dom.preventDefault).toHaveBeenCalled();+ expect(dom.ta.value).toBe("fuobe_secret");+ expect(dom.ta.remove).toHaveBeenCalled();+ expect(dom.listeners.size).toBe(0);+ });++ it("puts the textarea inside the dialog or menu holding the focus, and gives the focus back", async () => {+ // A Radix dialog or menu traps the focus: a textarea on <body> loses it (and its selection) at once.+ vi.stubGlobal("navigator", {});+ const menu = { appendChild: vi.fn() };+ const item = { closest: vi.fn((sel: string) => (sel.includes('[role="menu"]') ? menu : null)), parentElement: { appendChild: vi.fn() }, focus: vi.fn() };+ const dom = fakeDom({ active: item });+ expect(await copyText("a prompt")).toBe(true);+ expect(menu.appendChild).toHaveBeenCalledWith(dom.ta);+ expect(dom.body.appendChild).not.toHaveBeenCalled();+ expect(item.focus).toHaveBeenCalled();+ // Nothing focused: <body>.+ const plain = fakeDom();+ expect(await copyText("x")).toBe(true);+ expect(plain.body.appendChild).toHaveBeenCalledWith(plain.ta);+ });++ it("doesn't claim a copy that didn't happen (execCommand says true but nothing held)", async () => {+ vi.stubGlobal("navigator", {});+ // No copy event, and the selection is gone (the focus went elsewhere).+ fakeDom({ fires: false });+ expect(await copyText("x")).toBe(false);+ // A browser without clipboardData copies the selection: fine while the textarea still holds it.+ const dom = fakeDom({ noClipboardData: true });+ dom.doc.activeElement = dom.ta;+ dom.ta.selectionEnd = 1;+ expect(await copyText("x")).toBe(true);});it("says when nothing could be copied", async () => {vi.stubGlobal("navigator", { clipboard: { writeText: async () => Promise.reject(new Error("denied")) } });- vi.stubGlobal("document", {- createElement: () => ({ style: {}, setAttribute() {}, select() {}, setSelectionRange() {}, remove() {} }),- body: { appendChild() {} },- activeElement: null,- execCommand: () => false,- });+ fakeDom({ result: false, fires: false });expect(await copyText("x")).toBe(false);});@@ -336,7 +387,7 @@ describe("copyText", () => {expect(toasts.ok.at(-1)).toBe("Prompt copied");// Plain-http LAN origin and a browser that refuses execCommand too: say how to copy by hand.vi.stubGlobal("navigator", {});- vi.stubGlobal("document", { createElement: () => ({ style: {}, setAttribute() {}, select() {}, setSelectionRange() {}, remove() {} }), body: { appendChild() {} }, activeElement: null, execCommand: () => false });+ fakeDom({ result: false, fires: false });expect(await copyWithToast("a link")).toBe(false);expect(toasts.error.at(-1)).toMatch(/select the text/);});