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.

feat(workflows): export webv2 workflows as PNG

JPPhoto0bab23b99d51
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 2a311bde90..ae08cc6288 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3099,6 +3099,8 @@
"detailsWithEllipsis": "Workflow details…",
"renameWithEllipsis": "Rename workflow…",
"exportJson": "Export workflow JSON",
+ "exportAsPng": "Download workflow as PNG",
+ "exportImageFailed": "Could not export workflow image.",
"form": "Form",
"importFailed": "Failed to import workflow",
"importInvalid": "The file is not a valid workflow JSON.",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsx
index b02618a929..acf66929a6 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsx
@@ -50,7 +50,16 @@ const ConnectorFlowNodeComponent = ({ data, selected }: NodeProps<ConnectorFlowN
<Handle id={CONNECTOR_INPUT_HANDLE} position={Position.Left} style={inputHandleStyle} type="target" />
</Tooltip>
<Tooltip content={getConnectorTitle(data.inputFieldType, data.outputFieldType)} showArrow>
- <Box bg="bg" h="1rem" rounded="full" w="2.5rem" {...getWorkflowNodeChromeProps({ selected })} />
+ <Box
+ bg="bg"
+ data-connector-node-body="true"
+ data-is-selected={selected}
+ data-workflow-node-shell="true"
+ h="1rem"
+ rounded="full"
+ w="2.5rem"
+ {...getWorkflowNodeChromeProps({ selected })}
+ />
</Tooltip>
<Tooltip content={getHandleTypeTooltip(data.outputFieldType, 'Any output')} showArrow>
<Handle id={CONNECTOR_OUTPUT_HANDLE} position={Position.Right} style={outputHandleStyle} type="source" />
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx
index d4c5fa5181..70275bac35 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx
@@ -27,11 +27,17 @@ const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImag
const latestImage = getLatestImage(galleryValues);
return (
- <Box overflow="hidden" w="20rem" {...getWorkflowNodeShellProps({ selected })}>
+ <Box
+ data-is-selected={selected}
+ data-workflow-node-shell="true"
+ overflow="hidden"
+ w="20rem"
+ {...getWorkflowNodeShellProps({ selected })}
+ >
<Flex {...getWorkflowNodeHeaderProps()}>
<Text fontWeight="700">{node.data.label || 'Current Image'}</Text>
{progressImage ? (
- <Text color="brand.solid" fontSize="2xs" ms="auto">
+ <Text color="brand.solid" data-node-status-indicator="true" fontSize="2xs" ms="auto">
generating…
</Text>
) : null}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
index b4369a1432..b219d9d8a8 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
@@ -3,13 +3,37 @@ import { applyThemeToRoot } from '@theme/applyTheme';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const toolbarMocks = vi.hoisted(() => ({
+ exportWorkflowAsPng: vi.fn(),
+ error: vi.fn(),
+ fitView: vi.fn(),
+ getNodes: vi.fn(() => [{ id: 'seed' }]),
+ getNodesBounds: vi.fn(() => ({ x: 12, y: 34, width: 56, height: 78 })),
+ info: vi.fn(),
+ onExportPendingChange: vi.fn(),
+ success: vi.fn(),
+ zoomIn: vi.fn(),
+ zoomOut: vi.fn(),
+}));
-vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({ useWorkflowPreferencesSelector: () => false }));
+vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({
+ useWorkflowNotifications: () => ({
+ error: toolbarMocks.error,
+ info: toolbarMocks.info,
+ success: toolbarMocks.success,
+ }),
+ useWorkflowPreferencesSelector: () => false,
+ useWorkflowProjectSelector: (selector: (project: unknown) => unknown) =>
+ selector({ activeWorkflow: { document: { name: 'Test workflow' } } }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@xyflow/react', async (importOriginal) => ({
...(await importOriginal<object>()),
- useReactFlow: () => ({ fitView: vi.fn(), zoomIn: vi.fn(), zoomOut: vi.fn() }),
+ useReactFlow: () => toolbarMocks,
}));
+vi.mock('./workflowImageExport', () => ({ exportWorkflowAsPng: toolbarMocks.exportWorkflowAsPng }));
const { EditorToolbar } = await import('./EditorToolbar');
@@ -25,9 +49,12 @@ const settle = (action: () => void): Promise<void> =>
});
});
+beforeEach(() => vi.clearAllMocks());
+
const render = async (nodeOpacity: number) => {
applyThemeToRoot('mono');
host = document.createElement('div');
+ host.className = 'react-flow';
host.style.cssText = 'height:520px;position:relative;width:320px';
document.body.append(host);
root = createRoot(host);
@@ -35,7 +62,13 @@ const render = async (nodeOpacity: number) => {
await settle(() => {
root?.render(
<ChakraProvider value={system}>
- <EditorToolbar nodeOpacity={nodeOpacity} tool="pan" onNodeOpacityChange={vi.fn()} onToolChange={vi.fn()} />
+ <EditorToolbar
+ nodeOpacity={nodeOpacity}
+ tool="pan"
+ onExportPendingChange={toolbarMocks.onExportPendingChange}
+ onNodeOpacityChange={vi.fn()}
+ onToolChange={vi.fn()}
+ />
</ChakraProvider>
);
});
@@ -117,4 +150,37 @@ describe('editor toolbar', () => {
expect(paintedFill(opacity)).toBe(paintedFill(activeTool));
expect(new Set(buttonBoxes())).toEqual(new Set(['28x28']));
});
+
+ it('offers a camera action for exporting the workflow image', async () => {
+ toolbarMocks.exportWorkflowAsPng.mockResolvedValue(undefined);
+ await render(1);
+
+ const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="workflow.exportAsPng"]')!;
+
+ expect(camera).not.toBeNull();
+ await settle(() => camera.click());
+ await vi.waitFor(() => expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledOnce());
+
+ expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledWith({
+ bounds: { x: 12, y: 34, width: 56, height: 78 },
+ fallbackWorkflowName: 'workflow.untitled',
+ flowElement: host,
+ workflowName: 'Test workflow',
+ });
+ expect(toolbarMocks.onExportPendingChange.mock.calls).toEqual([[true], [false]]);
+ expect(camera.disabled).toBe(false);
+ });
+
+ it('reports an export failure and releases the camera action', async () => {
+ toolbarMocks.exportWorkflowAsPng.mockRejectedValueOnce(new Error('rasterization failed'));
+ await render(1);
+
+ const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="workflow.exportAsPng"]')!;
+ await settle(() => camera.click());
+ await vi.waitFor(() => expect(toolbarMocks.error).toHaveBeenCalledWith('workflow.exportImageFailed'));
+
+ expect(toolbarMocks.error).toHaveBeenCalledWith('workflow.exportImageFailed');
+ expect(toolbarMocks.onExportPendingChange.mock.calls).toEqual([[true], [false]]);
+ expect(camera.disabled).toBe(false);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
index fe552c5849..5360dc3244 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
@@ -1,10 +1,15 @@
import { Box, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';
-import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';
+import {
+ useWorkflowNotifications,
+ useWorkflowPreferencesSelector,
+ useWorkflowProjectSelector,
+} from '@features/workflow/ui/WorkflowUiContext';
import { IconButton, PopoverContent, Toolbar, ToolbarButton, ToolbarSeparator, Tooltip } from '@platform/ui';
import { useReactFlow } from '@xyflow/react';
import {
BlendIcon,
BoxSelectIcon,
+ CameraIcon,
EraserIcon,
HandIcon,
LassoIcon,
@@ -13,7 +18,7 @@ import {
ZoomInIcon,
ZoomOutIcon,
} from 'lucide-react';
-import { useCallback, useId, useMemo, useRef } from 'react';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
/**
@@ -39,10 +44,20 @@ const TOOLTIP_POSITIONING = { placement: 'right-start' } as const;
*/
const EDITOR_TOOLBAR_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';
+const waitForExportFrame = () =>
+ new Promise<void>((resolve) => {
+ if (document.visibilityState === 'hidden') {
+ window.setTimeout(resolve, 0);
+ } else {
+ window.requestAnimationFrame(() => resolve());
+ }
+ });
+
export const EditorToolbar = ({
nodeOpacity,
tool,
updatableNodeCount = 0,
+ onExportPendingChange,
onNodeOpacityChange,
onToolChange,
onUpdateNodes,
@@ -52,19 +67,69 @@ export const EditorToolbar = ({
/** Nodes with a newer same-major template; the update button shows only while there are some. */
updatableNodeCount?: number;
onNodeOpacityChange: (opacity: number) => void;
+ onExportPendingChange?: (isExporting: boolean) => void;
onToolChange: (tool: EditorTool) => void;
onUpdateNodes?: () => void;
}) => {
const { t } = useTranslation();
- const { fitView, zoomIn, zoomOut } = useReactFlow();
+ const { fitView, getNodes, getNodesBounds, zoomIn, zoomOut } = useReactFlow();
const reduceMotion = useWorkflowPreferencesSelector((preferences) => preferences.reduceMotion);
+ const workflowName = useWorkflowProjectSelector((project) => project.activeWorkflow.document.name);
+ const notifications = useWorkflowNotifications();
const opacityTriggerId = useId();
+ const toolbarRef = useRef<HTMLDivElement>(null);
+ const isExportingWorkflowRef = useRef(false);
+ const [isExportingWorkflow, setIsExportingWorkflow] = useState(false);
const fitViewDuration = reduceMotion ? 0 : 300;
+ const fallbackWorkflowName = t('workflow.untitled');
+ const exportFailedLabel = t('workflow.exportImageFailed');
const opacityIds = useMemo(() => ({ trigger: opacityTriggerId }), [opacityTriggerId]);
const opacityValue = useMemo(() => [Math.round(nodeOpacity * 100)], [nodeOpacity]);
const onZoomInClick = useCallback(() => void zoomIn(), [zoomIn]);
const onZoomOutClick = useCallback(() => void zoomOut(), [zoomOut]);
const onFitViewClick = useCallback(() => void fitView({ duration: fitViewDuration }), [fitView, fitViewDuration]);
+ const onExportWorkflowClick = useCallback(() => {
+ if (isExportingWorkflowRef.current) {
+ return;
+ }
+
+ const flowElement = toolbarRef.current?.closest<HTMLElement>('.react-flow');
+ if (!flowElement) {
+ notifications.error(exportFailedLabel);
+ return;
+ }
+
+ isExportingWorkflowRef.current = true;
+ setIsExportingWorkflow(true);
+ onExportPendingChange?.(true);
+ void (async () => {
+ try {
+ await waitForExportFrame();
+ await waitForExportFrame();
+ const { exportWorkflowAsPng } = await import('./workflowImageExport');
+ await exportWorkflowAsPng({
+ bounds: getNodesBounds(getNodes()),
+ fallbackWorkflowName,
+ flowElement,
+ workflowName,
+ });
+ } catch {
+ notifications.error(exportFailedLabel);
+ } finally {
+ isExportingWorkflowRef.current = false;
+ setIsExportingWorkflow(false);
+ onExportPendingChange?.(false);
+ }
+ })();
+ }, [
+ exportFailedLabel,
+ fallbackWorkflowName,
+ getNodes,
+ getNodesBounds,
+ notifications,
+ onExportPendingChange,
+ workflowName,
+ ]);
const fitViewRef = useRef<HTMLButtonElement>(null);
// The update button leaves with the last outdated node; keyboard focus steps to its stable neighbour first.
const onUpdateNodesClick = useCallback(() => {
@@ -77,7 +142,14 @@ export const EditorToolbar = ({
);
return (
- <Box left="2" position="absolute" top={EDITOR_TOOLBAR_TOP} zIndex="5">
+ <Box
+ ref={toolbarRef}
+ data-workflow-export-control="true"
+ left="2"
+ position="absolute"
+ top={EDITOR_TOOLBAR_TOP}
+ zIndex="5"
+ >
<Toolbar>
{TOOLS.map(({ icon, id, label }) => (
<EditorToolButton
@@ -93,6 +165,13 @@ export const EditorToolbar = ({
<ToolbarButton icon={ZoomInIcon} label="Zoom in" onClick={onZoomInClick} />
<ToolbarButton icon={ZoomOutIcon} label="Zoom out" onClick={onZoomOutClick} />
<ToolbarButton ref={fitViewRef} icon={MaximizeIcon} label="Fit view" onClick={onFitViewClick} />
+ <ToolbarButton
+ disabled={isExportingWorkflow}
+ icon={CameraIcon}
+ label={t('workflow.exportAsPng')}
+ loading={isExportingWorkflow}
+ onClick={onExportWorkflowClick}
+ />
{updatableNodeCount > 0 ? (
<>
<ToolbarSeparator />
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
index 3a64dcf623..31ed591c85 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
@@ -16,7 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { page, userEvent } from 'vitest/browser';
import { toFlowEdges, toFlowNodes } from './flowAdapters';
-import { InvocationFlowNode } from './InvocationFlowNode';
+import { InvocationFlowNode, WorkflowImageExportProvider } from './InvocationFlowNode';
import '@xyflow/react/dist/style.css';
@@ -243,19 +243,21 @@ describe('InvocationFlowNode output preview', () => {
host.remove();
});
- const render = (adapter: WorkflowUiAdapter, zoom = 1) =>
+ const render = (adapter: WorkflowUiAdapter, zoom = 1, isExporting = false, nodes = flowNodes) =>
act(() =>
root.render(
<ChakraProvider value={system}>
- <WorkflowUiProvider adapter={adapter}>
- <ReactFlow
- defaultViewport={{ x: 0, y: 0, zoom }}
- edges={[]}
- minZoom={0.1}
- nodes={flowNodes}
- nodeTypes={nodeTypes}
- />
- </WorkflowUiProvider>
+ <WorkflowImageExportProvider isExporting={isExporting}>
+ <WorkflowUiProvider adapter={adapter}>
+ <ReactFlow
+ defaultViewport={{ x: 0, y: 0, zoom }}
+ edges={[]}
+ minZoom={0.1}
+ nodes={nodes}
+ nodeTypes={nodeTypes}
+ />
+ </WorkflowUiProvider>
+ </WorkflowImageExportProvider>
</ChakraProvider>
)
);
@@ -319,6 +321,34 @@ describe('InvocationFlowNode output preview', () => {
await vi.waitFor(() => expect(image()).toBeNull());
expect(node().offsetHeight).toBe(layoutHeight);
});
+
+ it('renders full node content for image export when the viewport is zoomed out', async () => {
+ const execution = createExecutionPort();
+ const adapter = createAdapter(execution.port);
+ execution.set(completed(outputImage(400, 100)));
+
+ await render(adapter, 0.3, true);
+
+ await vi.waitFor(() => expect(image()).not.toBeNull());
+ });
+
+ it('renders full fields for compact nodes during image export', async () => {
+ const execution = createExecutionPort();
+ const adapter = createAdapter(execution.port);
+ const compactNode = {
+ ...documentNode,
+ data: { ...documentNode.data, inputs: { a: { label: '', name: 'a', value: 42 } } },
+ };
+ const compactTemplates = {
+ preview: { ...template, inputs: { a: { ...template.inputs.a!, input: 'any' as const } } },
+ };
+ const compactNodes = toFlowNodes({ ...projectGraph, nodes: [compactNode] }, [], compactTemplates, undefined, true);
+
+ await render(adapter, 1, true, compactNodes);
+
+ expect(host.querySelector('[data-node-input-field-title="true"]')?.textContent).toContain('A');
+ expect(host.querySelector<HTMLInputElement>('.react-flow__node input')?.value).toBe('42');
+ });
});
describe('InvocationFlowNode failure outcome', () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
index d6b5e25c18..168a404909 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -54,7 +54,16 @@ import { Tooltip } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';
import { ChevronDownIcon, ChevronRightIcon, PinIcon, PinOffIcon, RotateCcwIcon, TriangleAlertIcon } from 'lucide-react';
-import { memo, useId, useState, type ChangeEvent, type KeyboardEvent } from 'react';
+import {
+ createContext,
+ memo,
+ useContext,
+ useId,
+ useState,
+ type ChangeEvent,
+ type KeyboardEvent,
+ type ReactNode,
+} from 'react';
import { useTranslation } from 'react-i18next';
import type { InvocationFlowNode as InvocationFlowNodeType, InvocationNodeTemplateView } from './flowAdapters';
@@ -67,8 +76,25 @@ const ROW_PADDING_X = 12;
/** Below this viewport zoom, field content renders as skeleton bars (ComfyUI-style) for performance/readability. */
const CONTENT_VISIBILITY_ZOOM = 0.4;
+const WorkflowImageExportContext = createContext(false);
+
+export const WorkflowImageExportProvider = ({
+ children,
+ isExporting,
+}: {
+ children: ReactNode;
+ isExporting: boolean;
+}) => <WorkflowImageExportContext value={isExporting}>{children}</WorkflowImageExportContext>;
+
+export const useIsWorkflowImageExport = () => useContext(WorkflowImageExportContext);
+
/** True while the viewport is zoomed out far enough that field content is unreadable noise. */
-const useIsZoomedOut = (): boolean => useStore((state) => state.transform[2] < CONTENT_VISIBILITY_ZOOM);
+const useIsZoomedOut = (): boolean => {
+ const isWorkflowImageExport = useIsWorkflowImageExport();
+ const isZoomedOut = useStore((state) => state.transform[2] < CONTENT_VISIBILITY_ZOOM);
+
+ return isZoomedOut && !isWorkflowImageExport;
+};
/** The node-level loading hint is only useful while a selected child signature is being fetched. */
export const shouldShowCallSavedWorkflowLoadingHint = (node: WorkflowInvocationNode): boolean =>
@@ -142,6 +168,8 @@ const NodeShell = ({
return (
<Box
+ data-is-selected={selected}
+ data-workflow-node-shell="true"
w={NODE_WIDTH}
{...getWorkflowNodeShellProps({
invalid: isInvalid,
@@ -615,6 +643,7 @@ const InputFieldRow = ({
>
<Text
color={isInvalid ? 'fg.error' : isConnected ? 'fg.muted' : 'fg'}
+ data-node-input-field-title="true"
fontSize="2xs"
lineHeight="shorter"
minW="0"
@@ -892,6 +921,7 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeT
const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {
const { t } = useTranslation();
const { editGraph } = useProjectGraphCommands();
+ const isWorkflowImageExport = useIsWorkflowImageExport();
const isZoomedOut = useIsZoomedOut();
const node = data.documentNode;
const templateView = data.template;
@@ -924,7 +954,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
const isOpen = node.data.isOpen;
const isRunning = execution?.status === 'running';
const isMissingRequiredInput = hasMissingRequiredInputs(node, inputTemplates, connectedFieldNames);
- const isCompact = data.isCompact && !selected;
+ const isCompact = data.isCompact && !selected && !isWorkflowImageExport;
const withFooter = !isZoomedOut && templateView.isExecutable && templateView.hasImageOutput;
const withOutputPreview = Boolean(execution?.outputImageUrl);
const latestResult = execution?.latestOutput;
@@ -1017,11 +1047,14 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
);
};
-const InvocationFlowNodeComponent = (props: NodeProps<InvocationFlowNodeType>) =>
- props.data.isCompact && !props.selected ? (
+const InvocationFlowNodeComponent = (props: NodeProps<InvocationFlowNodeType>) => {
+ const isWorkflowImageExport = useIsWorkflowImageExport();
+
+ return props.data.isCompact && !props.selected && !isWorkflowImageExport ? (
<CompactInvocationNode {...props} />
) : (
<ExpandedInvocationNode {...props} />
);
+};
export const InvocationFlowNode = memo(InvocationFlowNodeComponent);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsx
index 0ba9780ebb..6a2db52c73 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsx
@@ -22,7 +22,15 @@ const NotesFlowNodeComponent = ({ data, selected }: NodeProps<NotesFlowNodeType>
);
return (
- <Box bg="bg.subtle" p="2" rounded="lg" w="16rem" {...getWorkflowNodeChromeProps({ selected })}>
+ <Box
+ bg="bg.subtle"
+ data-is-selected={selected}
+ data-workflow-node-shell="true"
+ p="2"
+ rounded="lg"
+ w="16rem"
+ {...getWorkflowNodeChromeProps({ selected })}
+ >
<Input
aria-label="Note title"
className="nodrag"
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.ts
index 855664d421..cb620b20f1 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';
import { WORKFLOW_INITIAL_RENDER_NODE_COUNT } from './performanceConstants';
-import { getInitialRenderFlowModel } from './WorkflowEditorView';
+import { getInitialRenderFlowModel, getRenderedFlowModel } from './WorkflowEditorView';
const createNode = (id: string, x: number): WorkflowFlowNode => ({
data: { documentNode: { data: { label: '', notes: '' }, id, position: { x, y: 0 }, type: 'notes' } },
@@ -48,4 +48,30 @@ describe('getInitialRenderFlowModel', () => {
expect(windowed.nodes.map((node) => node.id)).not.toContain(`node-${WORKFLOW_INITIAL_RENDER_NODE_COUNT + 1}`);
expect(windowed.edges.map((edge) => edge.id)).toEqual(['inside']);
});
+
+ it('renders the full graph during image export, even before the large-graph window expands', () => {
+ const nodes = Array.from({ length: WORKFLOW_INITIAL_RENDER_NODE_COUNT + 2 }, (_, index) =>
+ createNode(`node-${index}`, index)
+ );
+ const model = {
+ nodes,
+ edges: [
+ createEdge('inside', 'node-0', 'node-1'),
+ createEdge('outside', 'node-0', `node-${WORKFLOW_INITIAL_RENDER_NODE_COUNT + 1}`),
+ ],
+ };
+
+ const rendered = getRenderedFlowModel(
+ model,
+ { x: 0, y: 0, zoom: 1 },
+ {
+ isExportingWorkflow: true,
+ isFullGraphMounted: false,
+ isLargeGraph: true,
+ }
+ );
+
+ expect(rendered?.nodes).toHaveLength(nodes.length);
+ expect(rendered?.edges.map((edge) => edge.id)).toEqual(['inside', 'outside']);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
index 5f68206444..1736a7f7bc 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -76,7 +76,7 @@ import {
releaseWorkflowFlowInstance,
type WorkflowFlowInstance,
} from './flowInstanceStore';
-import { InvocationFlowNode } from './InvocationFlowNode';
+import { InvocationFlowNode, WorkflowImageExportProvider } from './InvocationFlowNode';
import LoopBodyBoundaryOverlay from './LoopBodyBoundaryOverlay';
import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';
import { NotesFlowNode } from './NotesFlowNode';
@@ -239,6 +239,19 @@ export const getInitialRenderFlowModel = (model: WorkflowFlowModel, viewport: Vi
return { edges, nodes };
};
+export const getRenderedFlowModel = (
+ model: WorkflowFlowModel | null,
+ viewport: Viewport,
+ {
+ isExportingWorkflow,
+ isFullGraphMounted,
+ isLargeGraph,
+ }: { isExportingWorkflow: boolean; isFullGraphMounted: boolean; isLargeGraph: boolean }
+): WorkflowFlowModel | null =>
+ model && isLargeGraph && !isExportingWorkflow && !isFullGraphMounted
+ ? getInitialRenderFlowModel(model, viewport)
+ : model;
+
const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);
const projectId = useWorkflowProjectSelector((project) => project.id);
@@ -311,6 +324,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
const shouldDeferInitialBuild = isLargeGraph && flowModel === null;
const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);
const [isFullGraphMounted, setIsFullGraphMounted] = useState(!isLargeGraph);
+ const [isExportingWorkflow, setIsExportingWorkflow] = useState(false);
const [tool, setTool] = useState<EditorTool>('pan');
const [nodeOpacity, setNodeOpacity] = useState(1);
const [isMinimapReady, setIsMinimapReady] = useState(!isLargeGraph);
@@ -397,11 +411,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
});
const pointerToolHandlers = tool === 'lasso' ? lassoHandlers : tool === 'eraser' ? eraserHandlers : {};
const renderedFlowModel = useMemo(
- () =>
- flowModel && isLargeGraph && !isFullGraphMounted
- ? getInitialRenderFlowModel(flowModel, defaultViewport)
- : flowModel,
- [defaultViewport, flowModel, isFullGraphMounted, isLargeGraph]
+ () => getRenderedFlowModel(flowModel, defaultViewport, { isExportingWorkflow, isFullGraphMounted, isLargeGraph }),
+ [defaultViewport, flowModel, isExportingWorkflow, isFullGraphMounted, isLargeGraph]
);
const renderedFlowNodes = renderedFlowModel?.nodes ?? EMPTY_FLOW_NODES;
const renderedFlowEdges = renderedFlowModel?.edges ?? EMPTY_FLOW_EDGES;
@@ -1138,65 +1149,68 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
onContextMenuCapture={onEditorContextMenuCapture}
{...pointerToolHandlers}
>
- <ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>
- key={viewportKey}
- colorMode={getFlowColorMode(themeId)}
- connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}
- defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
- defaultViewport={defaultViewport}
- deleteKeyCode={DELETE_KEY_CODES}
- elevateEdgesOnSelect={!workflowEdgesBehindNodes}
- edges={renderedFlowEdges}
- edgeTypes={edgeTypes}
- isValidConnection={isValidConnection}
- maxZoom={2}
- minZoom={0.1}
- nodes={renderedFlowNodes}
- nodeTypes={nodeTypes}
- onlyRenderVisibleElements={isLargeGraph}
- panOnDrag={panOnDrag}
- proOptions={proOptions}
- selectionMode={SelectionMode.Partial}
- selectionOnDrag={tool === 'box-select'}
- snapGrid={SNAP_GRID}
- snapToGrid={workflowSnapToGrid || isSnapHeld}
- style={flowStyle}
- onConnect={onConnect}
- onConnectEnd={onConnectEnd}
- onReconnect={onReconnect}
- onReconnectEnd={onReconnectEnd}
- onReconnectStart={onReconnectStart}
- onEdgeClick={onEdgeClick}
- onEdgesChange={onEdgesChange}
- onInit={onFlowInit}
- onNodeClick={onNodeClick}
- onNodeContextMenu={onNodeContextMenu}
- onNodeMouseEnter={onNodeMouseEnter}
- onNodeMouseLeave={onNodeMouseLeave}
- onNodesChange={onNodesChange}
- onMoveEnd={onMoveEnd}
- onPaneContextMenu={onPaneContextMenu}
- onSelectionChange={onSelectionChange}
- >
- <Background
- bgColor="var(--xy-background-color)"
- color="var(--wb-flow-grid)"
- gap={GRID_SIZE}
- id={`workflow-grid-${backgroundId}`}
- size={1.5}
- variant={BackgroundVariant.Dots}
- />
- <LoopBodyBoundaryOverlay edges={projectGraph.edges} nodes={projectGraph.nodes} />
- <EditorToolbar
- nodeOpacity={nodeOpacity}
- tool={tool}
- updatableNodeCount={updatableNodeCount}
- onNodeOpacityChange={setNodeOpacity}
- onToolChange={setTool}
- onUpdateNodes={onUpdateNodes}
- />
- {workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}
- </ReactFlow>
+ <WorkflowImageExportProvider isExporting={isExportingWorkflow}>
+ <ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>
+ key={viewportKey}
+ colorMode={getFlowColorMode(themeId)}
+ connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}
+ defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
+ defaultViewport={defaultViewport}
+ deleteKeyCode={DELETE_KEY_CODES}
+ elevateEdgesOnSelect={!workflowEdgesBehindNodes}
+ edges={renderedFlowEdges}
+ edgeTypes={edgeTypes}
+ isValidConnection={isValidConnection}
+ maxZoom={2}
+ minZoom={0.1}
+ nodes={renderedFlowNodes}
+ nodeTypes={nodeTypes}
+ onlyRenderVisibleElements={isLargeGraph && !isExportingWorkflow}
+ panOnDrag={panOnDrag}
+ proOptions={proOptions}
+ selectionMode={SelectionMode.Partial}
+ selectionOnDrag={tool === 'box-select'}
+ snapGrid={SNAP_GRID}
+ snapToGrid={workflowSnapToGrid || isSnapHeld}
+ style={flowStyle}
+ onConnect={onConnect}
+ onConnectEnd={onConnectEnd}
+ onReconnect={onReconnect}
+ onReconnectEnd={onReconnectEnd}
+ onReconnectStart={onReconnectStart}
+ onEdgeClick={onEdgeClick}
+ onEdgesChange={onEdgesChange}
+ onInit={onFlowInit}
+ onNodeClick={onNodeClick}
+ onNodeContextMenu={onNodeContextMenu}
+ onNodeMouseEnter={onNodeMouseEnter}
+ onNodeMouseLeave={onNodeMouseLeave}
+ onNodesChange={onNodesChange}
+ onMoveEnd={onMoveEnd}
+ onPaneContextMenu={onPaneContextMenu}
+ onSelectionChange={onSelectionChange}
+ >
+ <Background
+ bgColor="var(--xy-background-color)"
+ color="var(--wb-flow-grid)"
+ gap={GRID_SIZE}
+ id={`workflow-grid-${backgroundId}`}
+ size={1.5}
+ variant={BackgroundVariant.Dots}
+ />
+ <LoopBodyBoundaryOverlay edges={projectGraph.edges} nodes={projectGraph.nodes} />
+ <EditorToolbar
+ nodeOpacity={nodeOpacity}
+ tool={tool}
+ updatableNodeCount={updatableNodeCount}
+ onExportPendingChange={setIsExportingWorkflow}
+ onNodeOpacityChange={setNodeOpacity}
+ onToolChange={setTool}
+ onUpdateNodes={onUpdateNodes}
+ />
+ {workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}
+ </ReactFlow>
+ </WorkflowImageExportProvider>
{flowInstance ? (
<WorkflowSelectionRequestRuntime
flowInstance={flowInstance}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts
new file mode 100644
index 0000000000..f281f9eb08
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { exportWorkflowAsPng } from './workflowImageExport';
+
+let host: HTMLDivElement | null = null;
+
+afterEach(() => {
+ host?.remove();
+ host = null;
+ vi.restoreAllMocks();
+});
+
+/** Pixels that differ from the corner pixel, i.e. anything painted over the background. */
+const countPaintedPixels = async (image: Blob): Promise<{ height: number; painted: number; width: number }> => {
+ const bitmap = await createImageBitmap(image);
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d')!;
+ context.drawImage(bitmap, 0, 0);
+ const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ const [r, g, b] = [data[0], data[1], data[2]];
+ let painted = 0;
+
+ for (let index = 0; index < data.length; index += 4) {
+ if (Math.abs(data[index]! - r!) + Math.abs(data[index + 1]! - g!) + Math.abs(data[index + 2]! - b!) > 24) {
+ painted += 1;
+ }
+ }
+
+ return { height: bitmap.height, painted, width: bitmap.width };
+};
+
+describe('workflow image export in the browser', () => {
+ it('downloads a full resolution PNG containing the graph', async () => {
+ const clicked: { download: string }[] = [];
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function mockClick(this: HTMLAnchorElement) {
+ clicked.push({ download: this.download });
+ });
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL');
+
+ host = document.createElement('div');
+ host.style.cssText = 'height:480px;position:relative;width:640px';
+ document.body.append(host);
+ const flowElement = document.createElement('div');
+ flowElement.className = 'react-flow';
+ flowElement.style.cssText = 'background-color:rgb(18, 20, 24);height:480px;position:relative;width:640px';
+ flowElement.innerHTML = `
+ <div class="react-flow__edges" style="height:100%;position:absolute;width:100%">
+ <svg height="120" width="200">
+ <path class="react-flow__edge-path" d="M 80 45 C 110 45 120 45 150 45" style="fill:none;stroke:rgb(220, 220, 220);stroke-width:4px" />
+ </svg>
+ </div>
+ <div class="react-flow__viewport" style="position:absolute;transform:translate(0px,0px) scale(1)">
+ <div class="react-flow__nodes" style="height:120px;position:absolute;width:200px">
+ <div class="react-flow__node" style="height:60px;left:20px;position:absolute;top:20px;width:90px">
+ <div data-workflow-node-shell="true" style="background-color:rgb(192, 36, 52);height:60px;width:90px">Test node</div>
+ </div>
+ </div>
+ </div>
+ <div data-workflow-export-control="true" style="background-color:rgb(0, 255, 0);height:30px;position:absolute;width:30px"></div>
+ `;
+ host.append(flowElement);
+
+ await exportWorkflowAsPng({
+ bounds: { x: 0, y: 0, width: 200, height: 120 },
+ fallbackWorkflowName: 'Unnamed Workflow',
+ flowElement,
+ workflowName: 'Camera workflow',
+ });
+
+ expect(clicked).toEqual([{ download: 'Camera workflow.png' }]);
+ expect(createObjectURL).toHaveBeenCalledOnce();
+ expect(host.children).toHaveLength(1);
+
+ const capturedSource = createObjectURL.mock.calls[0]![0];
+ if (!(capturedSource instanceof Blob)) {
+ throw new Error('Workflow export did not download a Blob.');
+ }
+
+ const blob = capturedSource;
+ expect(blob.type).toBe('image/png');
+ const { height, painted, width } = await countPaintedPixels(blob);
+ expect([width, height]).toEqual([800, 640]);
+ expect(painted).toBeGreaterThan(width * height * 0.01);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts
new file mode 100644
index 0000000000..f5eefd17ec
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts
@@ -0,0 +1,262 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('html-to-image', () => ({
+ toBlob: vi.fn(),
+}));
+vi.mock('@platform/browser/downloadBlob', () => ({
+ downloadBlob: vi.fn(),
+}));
+
+import { downloadBlob } from '@platform/browser/downloadBlob';
+import { toBlob } from 'html-to-image';
+
+import {
+ EXPORT_STYLE_PROPERTIES,
+ exportWorkflowAsPng,
+ getWorkflowContentBounds,
+ getWorkflowExportOptions,
+ WORKFLOW_EXPORT_TIMEOUT_MS,
+} from './workflowImageExport';
+
+type FakeElement = {
+ appendChild: (child: FakeElement) => void;
+ attributes: Array<{ name: string; value: string }>;
+ children: FakeElement[];
+ cloneNode: () => FakeElement;
+ id?: string;
+ matches: () => boolean;
+ parentElement: FakeElement | null;
+ getBoundingClientRect: () => { left: number; top: number; width: number; height: number };
+ querySelector: (selector: string) => FakeElement | null;
+ querySelectorAll: (selector: string) => FakeElement[];
+ remove: () => void;
+ setAttribute: (name: string, value: string) => void;
+ scrollHeight?: number;
+ scrollWidth?: number;
+ style: { setProperty: ReturnType<typeof vi.fn> } & Record<string, unknown>;
+};
+
+const createFakeElement = (overrides: Partial<FakeElement> = {}): FakeElement => {
+ const element: FakeElement = {
+ appendChild: (child) => element.children.push(child),
+ attributes: [],
+ children: [],
+ cloneNode: () => element,
+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 1000, height: 1000 }),
+ matches: () => false,
+ parentElement: null,
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ remove: vi.fn(),
+ setAttribute: (name, value) => {
+ const attribute = element.attributes.find((candidate) => candidate.name === name);
+ if (attribute) {
+ attribute.value = value;
+ } else {
+ element.attributes.push({ name, value });
+ }
+ },
+ style: { setProperty: vi.fn() },
+ ...overrides,
+ };
+ return element;
+};
+
+const createExportDom = () => {
+ const parent = createFakeElement();
+ const root = createFakeElement();
+ const viewport = createFakeElement();
+ const clone = createFakeElement({ id: 'workflow-editor' });
+ const stagingWrapper = createFakeElement();
+ const flowElement = createFakeElement({ id: 'workflow-editor', parentElement: parent, cloneNode: () => clone });
+ flowElement.getBoundingClientRect = () => ({ left: 0, top: 0, width: 1000, height: 1000 });
+
+ clone.querySelector = (selector) => {
+ if (selector === '.react-flow') {
+ return root;
+ }
+ if (selector === '.react-flow__viewport') {
+ return viewport;
+ }
+ return null;
+ };
+ stagingWrapper.remove = vi.fn();
+
+ vi.stubGlobal('document', {
+ body: parent,
+ createElement: () => stagingWrapper,
+ });
+ vi.stubGlobal('getComputedStyle', () => ({ backgroundColor: 'rgb(1, 2, 3)', transform: 'none', direction: 'ltr' }));
+
+ return { clone, flowElement, stagingWrapper };
+};
+
+describe('workflow image export edge cases', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('settles and cleans up when rasterization never settles', async () => {
+ vi.useFakeTimers();
+ let finishRasterization: (blob: Blob | null) => void = () => undefined;
+ vi.mocked(toBlob).mockReturnValue(
+ new Promise((resolve) => {
+ finishRasterization = resolve;
+ })
+ );
+ const { flowElement, stagingWrapper } = createExportDom();
+ const exportOptions = {
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ };
+ const exportPromise = exportWorkflowAsPng(exportOptions);
+ const rejection = expect(exportPromise).rejects.toThrow('timed out');
+ try {
+ await vi.advanceTimersByTimeAsync(WORKFLOW_EXPORT_TIMEOUT_MS);
+
+ await rejection;
+ expect(stagingWrapper.remove).toHaveBeenCalledOnce();
+
+ const retry = exportWorkflowAsPng(exportOptions);
+ const retryRejection = expect(retry).rejects.toThrow('still running');
+
+ await vi.advanceTimersByTimeAsync(0);
+ await retryRejection;
+ expect(toBlob).toHaveBeenCalledOnce();
+ expect(stagingWrapper.remove).toHaveBeenCalledOnce();
+ finishRasterization(null);
+ await vi.advanceTimersByTimeAsync(0);
+
+ vi.mocked(toBlob).mockResolvedValueOnce(new Blob(['png'], { type: 'image/png' }));
+ await exportWorkflowAsPng(exportOptions);
+ expect(toBlob).toHaveBeenCalledTimes(2);
+ expect(stagingWrapper.remove).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('downloads the rendered PNG using a sanitized workflow filename', async () => {
+ const blob = new Blob(['png'], { type: 'image/png' });
+ vi.mocked(toBlob).mockResolvedValue(blob);
+ const { flowElement, stagingWrapper } = createExportDom();
+
+ await exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow: 01 / test?',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ });
+
+ expect(downloadBlob).toHaveBeenCalledWith(blob, 'Workflow- 01 - test-.png');
+ expect(stagingWrapper.remove).toHaveBeenCalledOnce();
+ });
+
+ it('configures failed image embedding to degrade instead of aborting export', () => {
+ const options = getWorkflowExportOptions(
+ { width: 100, height: 100, canvasWidth: 200, canvasHeight: 200 },
+ 'rgb(1, 2, 3)'
+ );
+
+ expect(options.imagePlaceholder).toBeTruthy();
+ });
+
+ it('keeps the Invoke font available to the serialized image', () => {
+ const options = getWorkflowExportOptions(
+ { width: 100, height: 100, canvasWidth: 200, canvasHeight: 200 },
+ 'rgb(1, 2, 3)'
+ );
+
+ expect(options.skipFonts).toBe(false);
+ });
+
+ it('includes overflowing input labels in content bounds', () => {
+ const label = {
+ getBoundingClientRect: () => ({ left: 590, top: 220, width: 100, height: 20 }),
+ scrollWidth: 200,
+ scrollHeight: 20,
+ };
+ const viewport = { getBoundingClientRect: () => ({ left: 100, top: 200, width: 1000, height: 1000 }) };
+ const flowElement = {
+ getBoundingClientRect: () => ({ left: 100, top: 200 }),
+ querySelector: (selector: string) => (selector === '.react-flow__viewport' ? viewport : null),
+ querySelectorAll: (selector: string) => (selector === '[data-node-input-field-title="true"]' ? [label] : []),
+ };
+
+ expect(
+ getWorkflowContentBounds(flowElement as unknown as HTMLElement, { x: 0, y: 0, width: 500, height: 100 })
+ ).toMatchObject({ x: 0, y: 0, width: 690, height: 100 });
+ });
+
+ it('measures overflowing labels after export styles are applied', async () => {
+ vi.mocked(toBlob).mockResolvedValue(null);
+ const label = createFakeElement({
+ getBoundingClientRect: () => ({ left: 500, top: 100, width: 100, height: 20 }),
+ scrollWidth: 100,
+ scrollHeight: 20,
+ });
+ label.style.setProperty = vi.fn((property: string) => {
+ if (property === 'white-space') {
+ label.scrollWidth = 200;
+ }
+ });
+ const { clone, flowElement } = createExportDom();
+ clone.querySelectorAll = (selector) => (selector === '[data-node-input-field-title="true"]' ? [label] : []);
+
+ await expect(
+ exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ })
+ ).rejects.toThrow('empty Blob');
+
+ expect(vi.mocked(toBlob).mock.calls[0]?.[1]).toMatchObject({ width: 900, height: 320 });
+ });
+
+ it('preserves flex wrapping and document direction in the export clone', () => {
+ expect(EXPORT_STYLE_PROPERTIES).toEqual(expect.arrayContaining(['flex-wrap', 'direction']));
+ });
+
+ it('does not put a duplicate workflow-editor id in the live document', async () => {
+ vi.mocked(toBlob).mockResolvedValue(null);
+ const { clone, flowElement } = createExportDom();
+
+ await expect(
+ exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ })
+ ).rejects.toThrow('empty Blob');
+
+ expect(clone.id).not.toBe(flowElement.id);
+ });
+
+ it('namespaces cloned SVG ids and references', async () => {
+ vi.mocked(toBlob).mockResolvedValue(null);
+ const marker = createFakeElement({ id: 'edge-marker' });
+ const edgePath = createFakeElement({
+ attributes: [{ name: 'marker-end', value: 'url(#edge-marker)' }],
+ });
+ const { clone, flowElement } = createExportDom();
+ clone.querySelectorAll = (selector) => (selector === '*' ? [marker, edgePath] : []);
+
+ await expect(
+ exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ })
+ ).rejects.toThrow('empty Blob');
+
+ expect(marker.id).toBe('edge-marker-workflow-export');
+ expect(edgePath.attributes).toEqual([{ name: 'marker-end', value: 'url(#edge-marker-workflow-export)' }]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts
new file mode 100644
index 0000000000..9a89916f48
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ EXPORT_MAX_CANVAS_DIMENSION,
+ EXPORT_PADDING,
+ EXPORT_SCALE,
+ EXPORT_STYLE_PROPERTIES,
+ getWorkflowExportCloneStyle,
+ getWorkflowExportOptions,
+ getWorkflowExportStagingStyle,
+ getWorkflowImageDimensions,
+ getWorkflowSvgExportStyles,
+ hideWorkflowExportInfoIcons,
+ hideWorkflowExportStatusIndicators,
+ sanitizeWorkflowImageFilename,
+ setWorkflowExportInputFieldTitleStyles,
+ setWorkflowExportNodeOpacity,
+ SVG_EXPORT_STYLE_PROPERTIES,
+} from './workflowImageExport';
+
+describe('workflow image export', () => {
+ it('uses padded logical bounds and export scale for output dimensions', () => {
+ expect(getWorkflowImageDimensions({ x: -100, y: 50, width: 1600, height: 900 })).toEqual({
+ width: 1600 + EXPORT_PADDING * 2,
+ height: 900 + EXPORT_PADDING * 2,
+ canvasWidth: (1600 + EXPORT_PADDING * 2) * EXPORT_SCALE,
+ canvasHeight: (900 + EXPORT_PADDING * 2) * EXPORT_SCALE,
+ });
+ });
+
+ it('preserves the aspect ratio when large exports reach the canvas limit', () => {
+ const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width: 9000, height: 9000 });
+
+ expect(dimensions.canvasWidth).toBe(EXPORT_MAX_CANVAS_DIMENSION);
+ expect(dimensions.canvasHeight).toBe(EXPORT_MAX_CANVAS_DIMENSION);
+ });
+
+ it('keeps capture clone local to an offscreen staging wrapper', () => {
+ const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width: 400, height: 300 });
+
+ expect(getWorkflowExportStagingStyle(dimensions)).toEqual({
+ position: 'fixed',
+ left: '-100000px',
+ top: '0',
+ width: '600px',
+ height: '500px',
+ pointerEvents: 'none',
+ });
+ expect(getWorkflowExportCloneStyle(dimensions)).toEqual({
+ width: '600px',
+ height: '500px',
+ position: 'relative',
+ left: '0',
+ top: '0',
+ pointerEvents: 'none',
+ });
+ });
+
+ it('uses Blob-friendly image export dimensions', () => {
+ const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width: 400, height: 300 });
+
+ expect(getWorkflowExportOptions(dimensions, 'rgb(1, 2, 3)')).toEqual({
+ width: 600,
+ height: 500,
+ canvasWidth: 1200,
+ canvasHeight: 1000,
+ backgroundColor: 'rgb(1, 2, 3)',
+ pixelRatio: 1,
+ includeStyleProperties: [...EXPORT_STYLE_PROPERTIES],
+ imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=',
+ onImageErrorHandler: expect.any(Function),
+ skipFonts: false,
+ });
+ });
+
+ it('preserves single-line field title styles in the export clone', () => {
+ expect(EXPORT_STYLE_PROPERTIES).toEqual(
+ expect.arrayContaining(['aspect-ratio', 'text-overflow', '-webkit-line-clamp', '-webkit-box-orient'])
+ );
+ });
+
+ it('extracts computed SVG edge styles for inline capture', () => {
+ const computedStyle = {
+ getPropertyValue: (property: string) =>
+ ({ stroke: 'rgb(1, 2, 3)', 'stroke-width': '3px', fill: 'none' })[property] ?? '',
+ };
+
+ expect(getWorkflowSvgExportStyles(computedStyle)).toEqual({
+ stroke: 'rgb(1, 2, 3)',
+ 'stroke-width': '3px',
+ fill: 'none',
+ });
+ expect(SVG_EXPORT_STYLE_PROPERTIES).toContain('stroke');
+ expect(SVG_EXPORT_STYLE_PROPERTIES).toContain('marker-end');
+ });
+
+ it('makes node wrappers opaque regardless of the node opacity slider', () => {
+ const setProperty = vi.fn();
+ const nodeWrapper = { style: { setProperty } } as unknown as HTMLElement;
+ const root = {
+ querySelectorAll: (selector: string) =>
+ selector === '.react-flow__node > [data-is-selected]' ? [nodeWrapper] : [],
+ } as unknown as HTMLElement;
+
+ setWorkflowExportNodeOpacity(root);
+
+ expect(setProperty).toHaveBeenCalledWith('opacity', '1', 'important');
+ });
+
+ it('hides node status indicators from the export clone', () => {
+ const setProperty = vi.fn();
+ const statusIndicator = { style: { setProperty } } as unknown as HTMLElement;
+ const root = {
+ querySelectorAll: (selector: string) =>
+ selector === '[data-node-status-indicator="true"]' ? [statusIndicator] : [],
+ } as unknown as HTMLElement;
+
+ hideWorkflowExportStatusIndicators(root);
+
+ expect(setProperty).toHaveBeenCalledWith('display', 'none', 'important');
+ });
+
+ it('hides node information icons from the export clone', () => {
+ const setProperty = vi.fn();
+ const infoIcon = { style: { setProperty } } as unknown as SVGElement;
+ const root = {
+ querySelectorAll: (selector: string) => (selector === '[data-node-info-icon="true"]' ? [infoIcon] : []),
+ } as unknown as HTMLElement;
+
+ hideWorkflowExportInfoIcons(root);
+
+ expect(setProperty).toHaveBeenCalledWith('display', 'none', 'important');
+ });
+
+ it('keeps input field titles on one line in the export clone', () => {
+ const setProperty = vi.fn();
+ const fieldTitle = { style: { setProperty } } as unknown as HTMLElement;
+ const root = {
+ querySelectorAll: (selector: string) => (selector === '[data-node-input-field-title="true"]' ? [fieldTitle] : []),
+ } as unknown as HTMLElement;
+
+ setWorkflowExportInputFieldTitleStyles(root);
+
+ expect(setProperty).toHaveBeenCalledWith('display', 'block', 'important');
+ expect(setProperty).toHaveBeenCalledWith('white-space', 'nowrap', 'important');
+ expect(setProperty).toHaveBeenCalledWith('overflow', 'visible', 'important');
+ expect(setProperty).toHaveBeenCalledWith('text-overflow', 'clip', 'important');
+ });
+
+ it('keeps ordinary workflow names unchanged', () => {
+ expect(sanitizeWorkflowImageFilename('Hi-Res Two Stage', 'Unnamed Workflow')).toBe('Hi-Res Two Stage');
+ });
+
+ it('replaces filesystem-invalid characters and falls back for blank names', () => {
+ expect(sanitizeWorkflowImageFilename('Workflow: 01 / test?', 'Unnamed Workflow')).toBe('Workflow- 01 - test-');
+ expect(sanitizeWorkflowImageFilename(' ... ', 'Unnamed Workflow')).toBe('Unnamed Workflow');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
new file mode 100644
index 0000000000..a6f89aa3cb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
@@ -0,0 +1,542 @@
+import type { Rect } from '@xyflow/react';
+
+import { downloadBlob } from '@platform/browser/downloadBlob';
+
+const WORKFLOW_GRID_SIZE = 25;
+
+export const EXPORT_PADDING = 100;
+export const EXPORT_SCALE = 2;
+export const EXPORT_MAX_CANVAS_DIMENSION = 16_384;
+export const WORKFLOW_EXPORT_TIMEOUT_MS = 30_000;
+const WORKFLOW_EXPORT_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
+// html-to-image has no abort signal; block another capture until a timed-out rasterization settles.
+let isWorkflowRasterizationPending = false;
+export const EXPORT_STYLE_PROPERTIES = [
+ 'box-sizing',
+ 'display',
+ 'position',
+ 'inset',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+ 'width',
+ 'height',
+ 'min-width',
+ 'min-height',
+ 'max-width',
+ 'max-height',
+ 'padding',
+ 'padding-top',
+ 'padding-right',
+ 'padding-bottom',
+ 'padding-left',
+ 'margin',
+ 'margin-top',
+ 'margin-right',
+ 'margin-bottom',
+ 'margin-left',
+ 'flex',
+ 'flex-direction',
+ 'flex-wrap',
+ 'aspect-ratio',
+ 'flex-grow',
+ 'flex-shrink',
+ 'flex-basis',
+ 'align-items',
+ 'align-content',
+ 'align-self',
+ 'justify-content',
+ 'gap',
+ 'row-gap',
+ 'column-gap',
+ 'grid-template-columns',
+ 'grid-template-rows',
+ 'grid-column',
+ 'grid-row',
+ 'overflow',
+ 'overflow-x',
+ 'overflow-y',
+ 'visibility',
+ 'opacity',
+ 'transform',
+ 'transform-origin',
+ 'color',
+ 'background',
+ 'background-color',
+ 'background-image',
+ 'background-size',
+ 'background-position',
+ 'background-repeat',
+ 'background-clip',
+ 'background-origin',
+ 'border',
+ 'border-width',
+ 'border-style',
+ 'border-color',
+ 'border-radius',
+ 'box-shadow',
+ 'font-family',
+ 'font-size',
+ 'font-weight',
+ 'font-style',
+ 'direction',
+ 'line-height',
+ 'letter-spacing',
+ 'text-align',
+ 'text-overflow',
+ 'text-decoration',
+ 'text-transform',
+ 'text-shadow',
+ '-webkit-line-clamp',
+ '-webkit-box-orient',
+ 'white-space',
+ 'word-break',
+ 'overflow-wrap',
+ 'filter',
+ 'object-fit',
+ 'object-position',
+ 'fill',
+ 'stroke',
+ 'stroke-width',
+ 'stroke-linecap',
+ 'stroke-linejoin',
+ 'stroke-dasharray',
+ 'stroke-dashoffset',
+ 'z-index',
+ 'pointer-events',
+ 'vertical-align',
+] as const;
+export const SVG_EXPORT_STYLE_PROPERTIES = [
+ ...EXPORT_STYLE_PROPERTIES,
+ 'fill-opacity',
+ 'stroke-opacity',
+ 'marker-start',
+ 'marker-mid',
+ 'marker-end',
+ 'paint-order',
+ 'shape-rendering',
+ 'vector-effect',
+ 'clip-path',
+ 'mask',
+] as const;
+
+type WorkflowImageDimensions = {
+ width: number;
+ height: number;
+ canvasWidth: number;
+ canvasHeight: number;
+};
+
+const getPaddedWorkflowBounds = (bounds: Rect): Rect => ({
+ x: bounds.x - EXPORT_PADDING,
+ y: bounds.y - EXPORT_PADDING,
+ width: bounds.width + EXPORT_PADDING * 2,
+ height: bounds.height + EXPORT_PADDING * 2,
+});
+
+type WorkflowContentBoundsOptions = {
+ includeInputFieldLabels?: boolean;
+};
+
+export const getWorkflowContentBounds = (
+ flowElement: HTMLElement,
+ nodeBounds: Rect,
+ { includeInputFieldLabels = true }: WorkflowContentBoundsOptions = {}
+): Rect => {
+ let minX = nodeBounds.x;
+ let minY = nodeBounds.y;
+ let maxX = nodeBounds.x + nodeBounds.width;
+ let maxY = nodeBounds.y + nodeBounds.height;
+
+ flowElement.querySelectorAll<SVGGraphicsElement>('.react-flow__edge-path').forEach((path) => {
+ let pathBounds: DOMRect;
+ try {
+ pathBounds = path.getBBox();
+ } catch {
+ return;
+ }
+ if (
+ !Number.isFinite(pathBounds.x) ||
+ !Number.isFinite(pathBounds.y) ||
+ !Number.isFinite(pathBounds.width) ||
+ !Number.isFinite(pathBounds.height)
+ ) {
+ return;
+ }
+
+ minX = Math.min(minX, pathBounds.x);
+ minY = Math.min(minY, pathBounds.y);
+ maxX = Math.max(maxX, pathBounds.x + pathBounds.width);
+ maxY = Math.max(maxY, pathBounds.y + pathBounds.height);
+ });
+
+ if (includeInputFieldLabels) {
+ const flowRect = flowElement.getBoundingClientRect();
+ const viewport = flowElement.querySelector<HTMLElement>('.react-flow__viewport');
+ const viewportRect = viewport?.getBoundingClientRect() ?? flowRect;
+ const transform = viewport ? (getComputedStyle(viewport).transform ?? 'none') : 'none';
+ const matrix = transform
+ .match(/^matrix\(([^)]+)\)$/)?.[1]
+ ?.split(',')
+ .map(Number);
+ const zoom = matrix?.[0] && Number.isFinite(matrix[0]) && matrix[0] > 0 ? matrix[0] : 1;
+
+ flowElement.querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]').forEach((label) => {
+ const labelRect = label.getBoundingClientRect();
+ const intrinsicWidth = Math.max(labelRect.width, label.scrollWidth);
+ const intrinsicHeight = Math.max(labelRect.height, label.scrollHeight);
+ const overflowWidth = Math.max(0, intrinsicWidth - labelRect.width) / zoom;
+ const direction = getComputedStyle(label).direction;
+ const labelX = (labelRect.left - viewportRect.left) / zoom - (direction === 'rtl' ? overflowWidth : 0);
+ const labelY = (labelRect.top - viewportRect.top) / zoom;
+ const labelWidth = intrinsicWidth / zoom;
+ const labelHeight = intrinsicHeight / zoom;
+
+ minX = Math.min(minX, labelX);
+ minY = Math.min(minY, labelY);
+ maxX = Math.max(maxX, labelX + labelWidth);
+ maxY = Math.max(maxY, labelY + labelHeight);
+ });
+ }
+
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+};
+
+export const getWorkflowImageDimensions = (bounds: Rect): WorkflowImageDimensions => {
+ const paddedBounds = getPaddedWorkflowBounds(bounds);
+
+ const width = Math.max(1, Math.ceil(paddedBounds.width));
+ const height = Math.max(1, Math.ceil(paddedBounds.height));
+
+ const scale = Math.min(EXPORT_SCALE, EXPORT_MAX_CANVAS_DIMENSION / width, EXPORT_MAX_CANVAS_DIMENSION / height);
+ const canvasWidth = Math.max(1, Math.floor(width * scale));
+ const canvasHeight = Math.max(1, Math.floor(height * scale));
+
+ return { width, height, canvasWidth, canvasHeight };
+};
+
+export const getWorkflowExportCloneStyle = (dimensions: WorkflowImageDimensions) => ({
+ width: `${dimensions.width}px`,
+ height: `${dimensions.height}px`,
+ position: 'relative',
+ left: '0',
+ top: '0',
+ pointerEvents: 'none',
+});
+
+export const getWorkflowExportOptions = (dimensions: WorkflowImageDimensions, backgroundColor: string) => ({
+ width: dimensions.width,
+ height: dimensions.height,
+ canvasWidth: dimensions.canvasWidth,
+ canvasHeight: dimensions.canvasHeight,
+ backgroundColor,
+ pixelRatio: 1,
+ includeStyleProperties: [...EXPORT_STYLE_PROPERTIES],
+ imagePlaceholder: WORKFLOW_EXPORT_IMAGE_PLACEHOLDER,
+ onImageErrorHandler: () => WORKFLOW_EXPORT_IMAGE_PLACEHOLDER,
+ skipFonts: false,
+});
+
+export const getWorkflowSvgExportStyles = (computedStyle: Pick<CSSStyleDeclaration, 'getPropertyValue'>) =>
+ SVG_EXPORT_STYLE_PROPERTIES.reduce<Record<string, string>>((styles, property) => {
+ const value = computedStyle.getPropertyValue(property);
+ if (value) {
+ styles[property] = value;
+ }
+ return styles;
+ }, {});
+
+export const sanitizeWorkflowImageFilename = (workflowName: string, fallbackWorkflowName: string): string => {
+ const sanitizedName = workflowName
+ .replace(/[<>:"/\\|?*]/g, '-')
+ .split('')
+ .map((character) => (character.charCodeAt(0) < 32 ? '-' : character))
+ .join('')
+ .trim()
+ .replace(/[. ]+$/g, '');
+
+ return sanitizedName || fallbackWorkflowName;
+};
+
+const setExportElementStyle = (element: HTMLElement | SVGElement, property: string, value: string) => {
+ element.style.setProperty(property, value, 'important');
+};
+
+export const getWorkflowExportStagingStyle = (dimensions: WorkflowImageDimensions) => ({
+ position: 'fixed',
+ left: '-100000px',
+ top: '0',
+ width: `${dimensions.width}px`,
+ height: `${dimensions.height}px`,
+ pointerEvents: 'none',
+});
+
+const setBackgroundGridForExport = (root: HTMLElement, translation: { x: number; y: number }) => {
+ const background = root.querySelector<SVGSVGElement>('.react-flow__background');
+ const pattern = background?.querySelector<SVGPatternElement>('pattern');
+ if (!background || !pattern) {
+ return;
+ }
+
+ const patternId = pattern.id.endsWith('-export') ? pattern.id : `${pattern.id}-export`;
+ pattern.id = patternId;
+ pattern.setAttribute('width', `${WORKFLOW_GRID_SIZE}`);
+ pattern.setAttribute('height', `${WORKFLOW_GRID_SIZE}`);
+ pattern.setAttribute('x', `${((translation.x % WORKFLOW_GRID_SIZE) + WORKFLOW_GRID_SIZE) % WORKFLOW_GRID_SIZE}`);
+ pattern.setAttribute('y', `${((translation.y % WORKFLOW_GRID_SIZE) + WORKFLOW_GRID_SIZE) % WORKFLOW_GRID_SIZE}`);
+ pattern.setAttribute('patternTransform', `translate(-${WORKFLOW_GRID_SIZE},-${WORKFLOW_GRID_SIZE})`);
+
+ const patternReference = `url(#${patternId})`;
+ background.querySelector('rect')?.setAttribute('fill', patternReference);
+
+ const dot = pattern.querySelector('circle');
+ dot?.setAttribute('cx', '0.5');
+ dot?.setAttribute('cy', '0.5');
+ dot?.setAttribute('r', '0.5');
+};
+
+const inlineSvgStylesForExport = (root: HTMLElement) => {
+ root
+ .querySelectorAll<SVGElement>(
+ '.react-flow__edges svg, .react-flow__edges svg *, .react-flow__background, .react-flow__background *'
+ )
+ .forEach((element) => {
+ const styles = getWorkflowSvgExportStyles(getComputedStyle(element));
+ Object.entries(styles).forEach(([property, value]) => {
+ element.style.setProperty(property, value, 'important');
+ });
+ });
+};
+
+export const setWorkflowExportNodeOpacity = (root: HTMLElement) => {
+ root.querySelectorAll<HTMLElement>('.react-flow__node > [data-is-selected]').forEach((element) => {
+ setExportElementStyle(element, 'opacity', '1');
+ });
+ root.querySelectorAll<HTMLElement>('.react-flow__node').forEach((element) => {
+ setExportElementStyle(element, 'opacity', '1');
+ });
+};
+
+export const hideWorkflowExportStatusIndicators = (root: HTMLElement) => {
+ root.querySelectorAll<HTMLElement>('[data-node-status-indicator="true"]').forEach((element) => {
+ setExportElementStyle(element, 'display', 'none');
+ });
+};
+
+export const hideWorkflowExportInfoIcons = (root: HTMLElement) => {
+ root.querySelectorAll<SVGElement>('[data-node-info-icon="true"]').forEach((element) => {
+ setExportElementStyle(element, 'display', 'none');
+ });
+};
+
+export const setWorkflowExportInputFieldTitleStyles = (root: HTMLElement) => {
+ root.querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]').forEach((element) => {
+ setExportElementStyle(element, 'display', 'block');
+ setExportElementStyle(element, 'white-space', 'nowrap');
+ setExportElementStyle(element, 'overflow', 'visible');
+ setExportElementStyle(element, 'text-overflow', 'clip');
+ });
+};
+
+const namespaceWorkflowExportIds = (clone: HTMLElement) => {
+ const elements = [clone, ...clone.querySelectorAll<HTMLElement | SVGElement>('*')];
+ const ids = new Map<string, string>();
+
+ elements.forEach((element) => {
+ if (element.id) {
+ ids.set(element.id, `${element.id}-workflow-export`);
+ }
+ });
+
+ elements.forEach((element) => {
+ const id = element.id;
+ if (id) {
+ element.id = ids.get(id) ?? id;
+ }
+ });
+
+ const sortedIds = [...ids.entries()].sort(([first], [second]) => second.length - first.length);
+ const rewriteReferences = (value: string) =>
+ sortedIds.reduce((rewritten, [id, namespacedId]) => rewritten.split(`#${id}`).join(`#${namespacedId}`), value);
+
+ elements.forEach((element) => {
+ Array.from(element.attributes).forEach((attribute) => {
+ const rewritten = rewriteReferences(attribute.value);
+ if (rewritten !== attribute.value) {
+ element.setAttribute(attribute.name, rewritten);
+ }
+ });
+ });
+};
+
+const prepareExportClone = (clone: HTMLElement, bounds: Rect, dimensions: WorkflowImageDimensions) => {
+ const root = clone.matches('.react-flow') ? clone : clone.querySelector<HTMLElement>('.react-flow');
+ const viewport = clone.querySelector<HTMLElement>('.react-flow__viewport');
+ if (!root || !viewport) {
+ throw new Error('Workflow editor DOM is missing React Flow viewport');
+ }
+
+ const translation = {
+ x: EXPORT_PADDING - bounds.x,
+ y: EXPORT_PADDING - bounds.y,
+ };
+
+ Object.assign(clone.style, getWorkflowExportCloneStyle(dimensions));
+
+ root.style.width = `${dimensions.width}px`;
+ root.style.height = `${dimensions.height}px`;
+ setExportElementStyle(root, 'background-color', 'var(--xy-background-color)');
+ viewport.style.transform = `translate(${translation.x}px, ${translation.y}px) scale(1)`;
+ setBackgroundGridForExport(root, translation);
+
+ clone
+ .querySelectorAll<HTMLElement>('[data-is-selected], [data-selected], [data-are-connected-nodes-selected]')
+ .forEach((element) => {
+ if (element.hasAttribute('data-is-selected')) {
+ element.setAttribute('data-is-selected', 'false');
+ }
+ if (element.hasAttribute('data-selected')) {
+ element.setAttribute('data-selected', 'false');
+ }
+ if (element.hasAttribute('data-are-connected-nodes-selected')) {
+ element.setAttribute('data-are-connected-nodes-selected', 'false');
+ }
+ });
+ clone.querySelectorAll('.react-flow__node.selected, .react-flow__edge.selected').forEach((element) => {
+ element.classList.remove('selected');
+ });
+ clone.querySelectorAll('.react-flow__edge.workflow-selected-node-edge').forEach((element) => {
+ element.classList.remove('workflow-selected-node-edge');
+ });
+ clone
+ .querySelectorAll<HTMLElement>(
+ '[data-workflow-export-control="true"], .react-flow__controls, .react-flow__minimap, .react-flow__panel'
+ )
+ .forEach((element) => {
+ setExportElementStyle(element, 'display', 'none');
+ });
+ clone.querySelectorAll<HTMLElement>('[data-workflow-node-shell="true"]').forEach((element) => {
+ setExportElementStyle(element, 'border-color', 'var(--chakra-colors-border-emphasized)');
+ setExportElementStyle(element, 'box-shadow', 'var(--chakra-shadows-sm)');
+ });
+ clone.querySelectorAll<HTMLElement>('[data-connector-node-body="true"]').forEach((element) => {
+ setExportElementStyle(element, 'background-color', 'var(--chakra-colors-bg-emphasized)');
+ });
+ clone.querySelectorAll<HTMLElement>('[data-connector-node-icon="true"]').forEach((element) => {
+ setExportElementStyle(element, 'color', 'var(--chakra-colors-fg)');
+ });
+ setWorkflowExportNodeOpacity(clone);
+ hideWorkflowExportStatusIndicators(clone);
+ hideWorkflowExportInfoIcons(clone);
+ setWorkflowExportInputFieldTitleStyles(clone);
+
+ clone
+ .querySelectorAll<HTMLElement>('.react-flow__edges, .react-flow__edges > svg, .react-flow__edge')
+ .forEach((element) => {
+ setExportElementStyle(element, 'z-index', '0');
+ });
+ clone
+ .querySelectorAll<HTMLElement>('.react-flow__edgelabel-renderer, .react-flow__edgelabel-renderer *')
+ .forEach((element) => {
+ setExportElementStyle(element, 'z-index', '0');
+ });
+ clone.querySelectorAll<HTMLElement>('.react-flow__nodes, .react-flow__node').forEach((element) => {
+ setExportElementStyle(element, 'z-index', '1');
+ });
+ clone.querySelectorAll<HTMLElement>('.react-flow__selection, .react-flow__nodesselection').forEach((element) => {
+ setExportElementStyle(element, 'display', 'none');
+ });
+};
+
+const toBlobWithTimeout = async (clone: HTMLElement, options: ReturnType<typeof getWorkflowExportOptions>) => {
+ if (isWorkflowRasterizationPending) {
+ throw new Error('A previous workflow image export is still running');
+ }
+
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ let timedOut = false;
+ isWorkflowRasterizationPending = true;
+ const rasterize = import('html-to-image').then(({ toBlob }) => (timedOut ? null : toBlob(clone, options)));
+ void rasterize.then(
+ () => {
+ isWorkflowRasterizationPending = false;
+ },
+ () => {
+ isWorkflowRasterizationPending = false;
+ }
+ );
+
+ try {
+ return await Promise.race([
+ rasterize,
+ new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(() => {
+ timedOut = true;
+ reject(new Error(`Workflow image export timed out after ${WORKFLOW_EXPORT_TIMEOUT_MS} ms`));
+ }, WORKFLOW_EXPORT_TIMEOUT_MS);
+ }),
+ ]);
+ } finally {
+ if (timeoutId !== undefined) {
+ clearTimeout(timeoutId);
+ }
+ }
+};
+
+const downloadPng = (blob: Blob, workflowName: string, fallbackWorkflowName: string) => {
+ downloadBlob(blob, `${sanitizeWorkflowImageFilename(workflowName, fallbackWorkflowName)}.png`);
+};
+
+export const exportWorkflowAsPng = async ({
+ flowElement,
+ bounds,
+ workflowName,
+ fallbackWorkflowName,
+}: {
+ flowElement: HTMLElement;
+ bounds: Rect;
+ workflowName: string;
+ fallbackWorkflowName: string;
+}): Promise<void> => {
+ if (isWorkflowRasterizationPending) {
+ throw new Error('A previous workflow image export is still running');
+ }
+
+ const contentBounds = getWorkflowContentBounds(flowElement, bounds, { includeInputFieldLabels: false });
+ const dimensions = getWorkflowImageDimensions(contentBounds);
+ const clone = flowElement.cloneNode(true) as HTMLElement;
+ const stagingWrapper = document.createElement('div');
+
+ try {
+ namespaceWorkflowExportIds(clone);
+ prepareExportClone(clone, contentBounds, dimensions);
+ Object.assign(stagingWrapper.style, getWorkflowExportStagingStyle(dimensions));
+ stagingWrapper.appendChild(clone);
+ (flowElement.parentElement ?? document.body).appendChild(stagingWrapper);
+
+ const measuredContentBounds = getWorkflowContentBounds(clone, contentBounds);
+ const measuredDimensions = getWorkflowImageDimensions(measuredContentBounds);
+ if (
+ measuredContentBounds.x !== contentBounds.x ||
+ measuredContentBounds.y !== contentBounds.y ||
+ measuredDimensions.width !== dimensions.width ||
+ measuredDimensions.height !== dimensions.height
+ ) {
+ prepareExportClone(clone, measuredContentBounds, measuredDimensions);
+ Object.assign(stagingWrapper.style, getWorkflowExportStagingStyle(measuredDimensions));
+ }
+
+ inlineSvgStylesForExport(clone);
+ const blob = await toBlobWithTimeout(
+ clone,
+ getWorkflowExportOptions(measuredDimensions, getComputedStyle(clone).backgroundColor)
+ );
+ if (!blob) {
+ throw new Error('Workflow image export returned an empty Blob');
+ }
+ downloadPng(blob, workflowName, fallbackWorkflowName);
+ } finally {
+ stagingWrapper.remove();
+ }
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
index ad50e5ec61..b8fe917b9d 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
@@ -153,7 +153,7 @@ const INFO_TOOLTIP_POSITIONING = { placement: 'top-end' } as const;
/** The quiet header info affordance: a `fg.subtle` icon whose tooltip carries the node details. */
export const WorkflowNodeInfoIcon = ({ content, label }: { content: ReactNode; label: string }) => (
<Tooltip content={content} positioning={INFO_TOOLTIP_POSITIONING} showArrow>
- <Icon aria-label={label} as={InfoIcon} boxSize="3.5" color="fg.subtle" />
+ <Icon aria-label={label} as={InfoIcon} boxSize="3.5" color="fg.subtle" data-node-info-icon="true" />
</Tooltip>
);
@@ -173,6 +173,7 @@ export const WorkflowNodeOutcomeIcon = ({
as={outcome === 'completed' ? CircleCheckIcon : CircleAlertIcon}
boxSize="3.5"
color={outcome === 'completed' ? 'fg.success' : 'fg.error'}
+ data-node-status-indicator="true"
flexShrink={0}
role="img"
/>