Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(webv2): share one downloadBlob across the app

joshistoast931cce05d301
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 4ce3b64016..deb11bd21f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -8,6 +8,7 @@ import {
uploadGalleryImage,
} from '@features/gallery/data/backend';
import { invalidateGallery } from '@features/gallery/data/queryCache';
+import { downloadBlob } from '@platform/browser/downloadBlob';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -25,13 +26,7 @@ const ACCEPTED_UPLOAD_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp'])
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const saveBlobToDisk = (blob: Blob, fileName: string): void => {
- const objectUrl = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
-
- anchor.href = objectUrl;
- anchor.download = fileName;
- anchor.click();
- URL.revokeObjectURL(objectUrl);
+ downloadBlob(blob, fileName);
};
export const useGalleryActions = ({
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
index 2bcccac91b..bbe7c2688f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
@@ -8,6 +8,7 @@ import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTem
import { toPromptTemplateSnapshot } from '@features/generation/data/promptTemplates';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
+import { downloadBlob } from '@platform/browser/downloadBlob';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
@@ -205,14 +206,7 @@ const PromptTemplateTransferActions = ({ catalog }: { catalog: PromptTemplateCat
setIsBusy(true);
try {
- const blob = await catalog.exportCsv();
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
-
- link.download = 'prompt_templates.csv';
- link.href = url;
- link.click();
- URL.revokeObjectURL(url);
+ downloadBlob(await catalog.exportCsv(), 'prompt_templates.csv');
} catch (caught) {
reportError('export-prompt-templates', caught, t('widgets.generate.promptTemplates.couldNotExport'));
} finally {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
index cd40e4b637..1bf6d14a3d 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
@@ -15,6 +15,7 @@ import {
wildcardsFromNestedRecord,
wildcardsToNestedRecord,
} from '@features/generation/core/wildcardTransfer';
+import { downloadText } from '@platform/browser/downloadBlob';
export type WildcardExportFormat = 'json' | 'yaml';
@@ -155,12 +156,5 @@ export const downloadWildcards = async (
): Promise<void> => {
const nested = wildcardsToNestedRecord(wildcards);
const text = format === 'json' ? `${JSON.stringify(nested, null, 2)}\n` : (await import('yaml')).stringify(nested);
- const blob = new Blob([text], { type: format === 'json' ? 'application/json' : 'text/yaml' });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
-
- anchor.href = url;
- anchor.download = `wildcards.${format}`;
- anchor.click();
- URL.revokeObjectURL(url);
+ downloadText(text, `wildcards.${format}`, format === 'json' ? 'application/json' : 'text/yaml');
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts
index ff52fb57c3..d4ae729b8f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts
@@ -1,18 +1,16 @@
import type { ProjectGraphState } from '@features/workflow/contracts';
import { serializeWorkflowJson } from '@features/workflow/utility';
+import { downloadText } from '@platform/browser/downloadBlob';
/** Export-side helpers shared by the workflow menu items and panels. */
export const downloadWorkflowJson = (document: ProjectGraphState): void => {
- const blob = new Blob([JSON.stringify(serializeWorkflowJson(document), null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const anchor = window.document.createElement('a');
-
- anchor.href = url;
- anchor.download = `${document.name.trim() || 'workflow'}.json`;
- anchor.click();
- URL.revokeObjectURL(url);
+ downloadText(
+ JSON.stringify(serializeWorkflowJson(document), null, 2),
+ `${document.name.trim() || 'workflow'}.json`,
+ 'application/json'
+ );
};
export const getWorkflowJsonText = (document: ProjectGraphState): string =>
diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts
new file mode 100644
index 0000000000..6672a4abcc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts
@@ -0,0 +1,77 @@
+import { downloadBlob, downloadText } from '@platform/browser/downloadBlob';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Records each anchor *and whether it was in the document at the moment it was
+ * clicked* — the helper detaches it immediately afterwards, so reading that
+ * later always says no.
+ */
+const capture = () => {
+ const clicked: { download: string; href: string; wasConnected: boolean }[] = [];
+
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function mockClick(this: HTMLAnchorElement) {
+ clicked.push({ download: this.download, href: this.href, wasConnected: this.isConnected });
+ });
+
+ return { clicked };
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('downloadBlob', () => {
+ it('names the download and points it at the blob', () => {
+ const { clicked } = capture();
+
+ downloadBlob(new Blob(['hi'], { type: 'text/plain' }), 'notes.txt');
+
+ expect(clicked).toHaveLength(1);
+ expect(clicked[0]!.download).toBe('notes.txt');
+ expect(clicked[0]!.href.startsWith('blob:')).toBe(true);
+ });
+
+ // A detached anchor's click has historically not worked in Firefox, which is
+ // how "export does nothing" bugs get reported against one browser only.
+ it('attaches the anchor to the document before clicking it', () => {
+ const { clicked } = capture();
+
+ downloadBlob(new Blob(['hi']), 'notes.txt');
+
+ expect(clicked[0]!.wasConnected).toBe(true);
+ });
+
+ it('leaves nothing behind in the document', () => {
+ capture();
+
+ downloadBlob(new Blob(['hi']), 'notes.txt');
+
+ expect(document.querySelector('a[download="notes.txt"]')).toBeNull();
+ });
+
+ // Revoking in the same tick races the browser's own read of the URL and loses
+ // often enough on Safari to produce an empty download.
+ it('keeps the object URL alive past the click', async () => {
+ const { clicked } = capture();
+ const revoke = vi.spyOn(URL, 'revokeObjectURL');
+
+ downloadBlob(new Blob(['hi']), 'notes.txt');
+
+ expect(revoke).not.toHaveBeenCalled();
+
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ });
+
+ expect(revoke).toHaveBeenCalledWith(clicked[0]!.href);
+ });
+
+ it('wraps text with its content type', async () => {
+ const { clicked } = capture();
+
+ downloadText('a,b\n1,2', 'table.csv', 'text/csv');
+
+ expect(clicked[0]!.download).toBe('table.csv');
+ await expect(fetch(clicked[0]!.href).then((response) => response.text())).resolves.toBe('a,b\n1,2');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts
new file mode 100644
index 0000000000..aa9454942a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts
@@ -0,0 +1,40 @@
+/**
+ * Hand a blob to the browser as a download.
+ *
+ * This was written out longhand in eight places — workflows, projects, PSD
+ * export, the gallery, image actions, prompt templates and wildcards — each
+ * with its own spelling of the same five lines, and each carrying the same two
+ * mistakes.
+ *
+ * The anchor is appended to the document before it is clicked. A detached
+ * anchor works in Chromium but has historically not in Firefox, which is the
+ * sort of thing nobody notices until someone reports that export does nothing.
+ *
+ * The object URL is revoked on the next frame rather than immediately after the
+ * click. Revoking synchronously races the browser's own read of the URL, and
+ * loses often enough on Safari to produce an empty or failed download; a frame
+ * is long enough for the download to have been claimed and short enough that the
+ * blob is not left pinned in memory.
+ */
+export const downloadBlob = (blob: Blob, fileName: string): void => {
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+
+ anchor.href = url;
+ anchor.download = fileName;
+ anchor.rel = 'noopener';
+ anchor.style.display = 'none';
+
+ document.body.append(anchor);
+ anchor.click();
+ anchor.remove();
+
+ requestAnimationFrame(() => {
+ URL.revokeObjectURL(url);
+ });
+};
+
+/** The same, for content already in hand as text. */
+export const downloadText = (text: string, fileName: string, type: string): void => {
+ downloadBlob(new Blob([text], { type }), fileName);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
index 6b3c17174e..5ee63ec0e0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
@@ -37,6 +37,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
import type { BlendMode, Layer as AgPsdLayer, Psd } from 'ag-psd';
+import { downloadBlob } from '@platform/browser/downloadBlob';
import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';
@@ -259,12 +260,7 @@ const defaultWritePsd = async (psd: Psd): Promise<ArrayBuffer> => {
/** Triggers a browser download of the PSD bytes (Blob + anchor click). */
const defaultDownload = (data: ArrayBuffer, fileName: string): void => {
const blob = new Blob([data], { type: 'image/vnd.adobe.photoshop' });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
- anchor.href = url;
- anchor.download = fileName;
- anchor.click();
- URL.revokeObjectURL(url);
+ downloadBlob(blob, fileName);
};
/** Injected dependencies for {@link executePsdExport}. */
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 452e648112..f17133dc6c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -11,6 +11,7 @@ import { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } f
import { setPendingPromptTemplateDraft } from '@features/generation/react';
import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
+import { downloadBlob } from '@platform/browser/downloadBlob';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
assertAccountScopeCurrent,
@@ -66,13 +67,7 @@ export interface ImageActions {
}
export const saveBlobToDisk = (blob: Blob, fileName: string): void => {
- const objectUrl = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
-
- anchor.href = objectUrl;
- anchor.download = fileName;
- anchor.click();
- URL.revokeObjectURL(objectUrl);
+ downloadBlob(blob, fileName);
};
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
@@ -192,13 +187,7 @@ export const useImageActions = ({
const blob = await response.blob();
assertAccountScopeCurrent(owner);
- const objectUrl = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
-
- anchor.href = objectUrl;
- anchor.download = image.imageName;
- anchor.click();
- URL.revokeObjectURL(objectUrl);
+ downloadBlob(blob, image.imageName);
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 066b9d8332..5d16715ad8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -1,5 +1,6 @@
import type { Project } from '@workbench/projectContracts';
+import { downloadText } from '@platform/browser/downloadBlob';
import {
type AccountScope,
assertAccountScopeCurrent,
@@ -62,14 +63,11 @@ export const parseProjectFile = (text: string): Record<string, unknown> | null =
const sanitizeFileName = (name: string): string => name.replace(/[^\w\- ]+/gu, '').trim() || 'project';
const downloadProjectFile = (name: string, projectDocument: Record<string, unknown>): void => {
- const blob = new Blob([JSON.stringify(buildProjectFile(projectDocument), null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
-
- anchor.href = url;
- anchor.download = `${sanitizeFileName(name)}.invokeproject.json`;
- anchor.click();
- URL.revokeObjectURL(url);
+ downloadText(
+ JSON.stringify(buildProjectFile(projectDocument), null, 2),
+ `${sanitizeFileName(name)}.invokeproject.json`,
+ 'application/json'
+ );
};
/** Export a closed project straight from its server record. */