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.

fix(workflows): isolate snapshot rendering from editor

JPPhoto7b62fed1931b
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 c623095bff..ab4bd151df 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
@@ -15,7 +15,8 @@ const toolbarMocks = vi.hoisted(() => ({
getNodes: vi.fn(() => [{ id: 'seed' }]),
getNodesBounds: vi.fn(() => ({ x: 12, y: 34, width: 56, height: 78 })),
info: vi.fn(),
- onExportPendingChange: vi.fn(),
+ onExportPrepare: vi.fn(),
+ onExportComplete: vi.fn(),
success: vi.fn(),
zoomIn: vi.fn(),
zoomOut: vi.fn(),
@@ -72,6 +73,7 @@ const render = async (nodeOpacity: number) => {
host.style.cssText = 'height:520px;position:relative;width:320px';
document.body.append(host);
root = createRoot(host);
+ toolbarMocks.onExportPrepare.mockResolvedValue(host);
await settle(() => {
root?.render(
@@ -80,7 +82,8 @@ const render = async (nodeOpacity: number) => {
<EditorToolbar
nodeOpacity={nodeOpacity}
tool="pan"
- onExportPendingChange={toolbarMocks.onExportPendingChange}
+ onExportPrepare={toolbarMocks.onExportPrepare}
+ onExportComplete={toolbarMocks.onExportComplete}
onNodeOpacityChange={vi.fn()}
onToolChange={vi.fn()}
/>
@@ -137,6 +140,8 @@ describe('editor toolbar', () => {
nodeOpacity={1}
tool="pan"
updatableNodeCount={2}
+ onExportPrepare={toolbarMocks.onExportPrepare}
+ onExportComplete={toolbarMocks.onExportComplete}
onNodeOpacityChange={vi.fn()}
onToolChange={vi.fn()}
onUpdateNodes={onUpdateNodes}
@@ -169,9 +174,17 @@ describe('editor toolbar', () => {
expect(new Set(buttonBoxes())).toEqual(new Set(['28x28']));
});
- it('offers a camera action for exporting the workflow image', async () => {
- toolbarMocks.exportWorkflowAsPng.mockResolvedValue(undefined);
+ it('captures the prepared export view and keeps the camera pending until rasterization finishes', async () => {
+ let finish: () => void = () => {};
+ toolbarMocks.exportWorkflowAsPng.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ })
+ );
await render(1);
+ const exportElement = document.createElement('div');
+ toolbarMocks.onExportPrepare.mockResolvedValueOnce(exportElement);
const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!;
@@ -182,10 +195,13 @@ describe('editor toolbar', () => {
expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledWith({
bounds: { x: 12, y: 34, width: 56, height: 78 },
fallbackWorkflowName: 'Untitled Workflow',
- flowElement: host,
+ flowElement: exportElement,
workflowName: 'Test workflow',
});
- expect(toolbarMocks.onExportPendingChange.mock.calls).toEqual([[true], [false]]);
+ expect(camera.disabled).toBe(true);
+ expect(toolbarMocks.onExportComplete).not.toHaveBeenCalled();
+ finish();
+ await vi.waitFor(() => expect(toolbarMocks.onExportComplete).toHaveBeenCalledOnce());
expect(camera.disabled).toBe(false);
});
@@ -207,16 +223,18 @@ describe('editor toolbar', () => {
expect(tooltip).not.toBeUndefined();
});
- it('reports an export failure and releases the camera action', async () => {
- toolbarMocks.exportWorkflowAsPng.mockRejectedValueOnce(new Error('rasterization failed'));
+ it.each(['prepare', 'rasterize'])('reports a %s failure and releases the camera action', async (stage) => {
await render(1);
+ (stage === 'prepare' ? toolbarMocks.onExportPrepare : toolbarMocks.exportWorkflowAsPng).mockRejectedValueOnce(
+ new Error('export failed')
+ );
const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!;
await settle(() => camera.click());
await vi.waitFor(() => expect(toolbarMocks.error).toHaveBeenCalledWith('Could not export workflow image.'));
expect(toolbarMocks.error).toHaveBeenCalledWith('Could not export workflow image.');
- expect(toolbarMocks.onExportPendingChange.mock.calls).toEqual([[true], [false]]);
+ expect(toolbarMocks.onExportComplete).toHaveBeenCalledOnce();
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 e153e61d39..8d1c55fda4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
@@ -57,7 +57,8 @@ export const EditorToolbar = ({
nodeOpacity,
tool,
updatableNodeCount = 0,
- onExportPendingChange,
+ onExportPrepare,
+ onExportComplete,
onNodeOpacityChange,
onToolChange,
onUpdateNodes,
@@ -67,7 +68,8 @@ 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;
+ onExportPrepare: () => Promise<HTMLElement>;
+ onExportComplete: () => void;
onToolChange: (tool: EditorTool) => void;
onUpdateNodes?: () => void;
}) => {
@@ -77,7 +79,6 @@ export const EditorToolbar = ({
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;
@@ -93,17 +94,11 @@ export const EditorToolbar = ({
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 {
+ const flowElement = await onExportPrepare();
await waitForExportFrame();
await waitForExportFrame();
const { exportWorkflowAsPng } = await import('./workflowImageExport');
@@ -118,7 +113,7 @@ export const EditorToolbar = ({
} finally {
isExportingWorkflowRef.current = false;
setIsExportingWorkflow(false);
- onExportPendingChange?.(false);
+ onExportComplete();
}
})();
}, [
@@ -127,7 +122,8 @@ export const EditorToolbar = ({
getNodes,
getNodesBounds,
notifications,
- onExportPendingChange,
+ onExportPrepare,
+ onExportComplete,
workflowName,
]);
const fitViewRef = useRef<HTMLButtonElement>(null);
@@ -142,14 +138,7 @@ export const EditorToolbar = ({
);
return (
- <Box
- ref={toolbarRef}
- data-workflow-export-control="true"
- left="2"
- position="absolute"
- top={EDITOR_TOOLBAR_TOP}
- zIndex="5"
- >
+ <Box data-workflow-export-control="true" left="2" position="absolute" top={EDITOR_TOOLBAR_TOP} zIndex="5">
<Toolbar>
{TOOLS.map(({ icon, id, label }) => (
<EditorToolButton
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 0e81b5f886..4fdf956083 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
@@ -11,7 +11,7 @@ import { buildCurrentImageNode, createProjectGraph, projectGraphReducer } from '
import { system } from '@theme/system';
import { applyNodeChanges, ReactFlow, type NodeChange } from '@xyflow/react';
import { createInstance } from 'i18next';
-import { act, startTransition, useCallback, useEffect, useState, useSyncExternalStore } from 'react';
+import { act, createRef, startTransition, useCallback, useEffect, useState, useSyncExternalStore } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { page, userEvent } from 'vitest/browser';
@@ -21,6 +21,7 @@ import { CurrentImageFlowNode } from './CurrentImageFlowNode';
import { toFlowEdges, toFlowNodes } from './flowAdapters';
import { InvocationFlowNode, WorkflowImageExportProvider } from './InvocationFlowNode';
import { exportWorkflowAsPng, WORKFLOW_EXPORT_TIMEOUT_MS } from './workflowImageExport';
+import { WorkflowImageExportView } from './WorkflowImageExportView';
import '@xyflow/react/dist/style.css';
@@ -550,6 +551,93 @@ describe('InvocationFlowNode output preview', () => {
expect(capturedClone?.textContent).toContain('Failed: Child workflow error: Child node failed');
});
+ it('keeps the visible collapsed node unchanged while an expanded offscreen snapshot is rasterizing', async () => {
+ const node = { ...documentNode, data: { ...documentNode.data, isOpen: false, notes: 'Snapshot metadata' } };
+ const directNode = { ...documentNode, id: 'direct-node', position: { x: 20, y: 100 } };
+ const graph = { ...projectGraph, nodes: [node, directNode] };
+ const directTemplate = { ...template, inputs: { a: { ...template.inputs.a!, input: 'direct' as const } } };
+ const nodes = toFlowNodes(graph, [], { preview: directTemplate });
+ const adapter = createAdapter(createExecutionPort().port, projectSnapshotFor(graph));
+ const exportRef = createRef<HTMLDivElement>();
+ host.style.position = 'relative';
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <WorkflowUiProvider adapter={adapter}>
+ <div data-visible-editor style={{ height: '100%', width: '100%' }}>
+ <ReactFlow nodes={nodes} edges={[]} nodeTypes={nodeTypes} />
+ </div>
+ <WorkflowImageExportView containerRef={exportRef} nodes={nodes} edges={[]} nodeTypes={nodeTypes} />
+ </WorkflowUiProvider>
+ </ChakraProvider>
+ )
+ );
+ const visible = host.querySelector<HTMLElement>('[data-visible-editor]')!;
+ const visibleNode = visible.querySelector<HTMLElement>('.react-flow__node')!;
+ const beforeHeight = visibleNode.getBoundingClientRect().height;
+ expect(beforeHeight).toBeGreaterThan(0);
+ let finish: (blob: Blob) => void = () => {};
+ let capturedClone: HTMLElement | undefined;
+ exportMocks.toBlob.mockImplementation((clone: HTMLElement) => {
+ capturedClone = clone;
+ return new Promise<Blob>((resolve) => {
+ finish = resolve;
+ });
+ });
+ const capture = exportWorkflowAsPng({
+ bounds: { x: 20, y: 20, width: 300, height: 260 },
+ fallbackWorkflowName: 'Untitled Workflow',
+ flowElement: exportRef.current!.querySelector<HTMLElement>('.react-flow')!,
+ workflowName: 'Isolated snapshot',
+ });
+ await vi.waitFor(() => expect(capturedClone).toBeDefined());
+ expect(visible.textContent).not.toContain('Snapshot metadata');
+ expect(visible.querySelector('button[aria-label="Expand node"]')).not.toBeNull();
+ expect(visibleNode.getBoundingClientRect().height).toBe(beforeHeight);
+ const visibleInput = visible.querySelector<HTMLInputElement>('input');
+ const offscreenInput = exportRef.current!.querySelector<HTMLInputElement>('input');
+ expect(visibleInput).not.toBeNull();
+ expect(offscreenInput).not.toBeNull();
+ expect(visibleInput?.id).not.toBe(offscreenInput?.id);
+ expect(capturedClone?.textContent).toContain('Snapshot metadata');
+ await page.screenshot({ path: '../../../../../artifacts/workflow-export-pending.png' });
+ finish(new Blob(['png'], { type: 'image/png' }));
+ await capture;
+ });
+
+ it.each(['running', 'failed'] as const)('omits retained results from a %s retry snapshot', async (status) => {
+ const execution = createExecutionPort();
+ const completed = {
+ error: null,
+ latestOutput: { value: 'previous result' },
+ outputImageUrl: 'data:image/png;base64,cHJldmlvdXM=',
+ progress: null,
+ progressMessage: null,
+ status: 'completed' as const,
+ };
+ execution.set(completed);
+ const adapter = createAdapter(execution.port);
+ await render(adapter, 1, true);
+ expect(host.textContent).toContain('previous result');
+ await act(() => execution.set({ ...completed, status }));
+ let capturedClone: HTMLElement | undefined;
+ exportMocks.toBlob.mockImplementation((clone: HTMLElement) => {
+ capturedClone = clone;
+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));
+ });
+ await exportWorkflowAsPng({
+ bounds: { x: 20, y: 20, width: 300, height: 260 },
+ fallbackWorkflowName: 'Untitled Workflow',
+ flowElement: host.querySelector<HTMLElement>('.react-flow')!,
+ workflowName: 'Retry',
+ });
+ expect(capturedClone?.textContent).not.toContain('previous result');
+ expect(capturedClone?.querySelector('img')).toBeNull();
+ if (status === 'failed') {
+ expect(capturedClone?.textContent).toContain('Failed');
+ }
+ });
+
it('blocks a third capture after two timeouts and recovers when one rasterization settles', async () => {
vi.useFakeTimers();
exportMocks.toBlob.mockClear();
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 548e3853ec..2df670f8ed 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -391,7 +391,7 @@ const NodeUpdateIcon = ({
};
const NodeInfoTooltipContent = ({
- executionError,
+ executionError = null,
node,
template,
}: {
@@ -413,9 +413,10 @@ const NodeInfoTooltipContent = ({
{updateStatusText ? <Text color="fg.warning">{updateStatusText}</Text> : null}
<Text color="fg.subtle">{t('nodes.nodeClassification', { classification: template.classification })}</Text>
<Text color="fg.subtle">{t('nodes.nodeCategory', { category: template.category })}</Text>
- {executionError ? (
+ {executionError !== null ? (
<Text color="fg.error">
- {t('nodes.executionFailed')}: {executionError}
+ {t('nodes.executionFailed')}
+ {executionError ? `: ${executionError}` : null}
</Text>
) : null}
{template.description ? <Text fontStyle="italic">{template.description}</Text> : null}
@@ -729,7 +730,7 @@ const InputFieldRow = ({
{showsControl ? (
<Box mt="0.5" w="full">
<WorkflowFieldInput
- id={`${node.id}-${template.name}-value`}
+ id={`${isWorkflowImageExport ? 'export-' : ''}${node.id}-${template.name}-value`}
invalid={isInvalid}
nodeId={node.id}
seedMode={getWorkflowFieldSeedMode(instance)}
@@ -1018,8 +1019,9 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
const isMissingRequiredInput = hasMissingRequiredInputs(node, inputTemplates, connectedFieldNames);
const isCompact = data.isCompact && !selected && !isWorkflowImageExport;
const withFooter = !isZoomedOut && templateView.isExecutable && templateView.hasImageOutput;
- const withOutputPreview = Boolean(execution?.outputImageUrl);
- const latestResult = execution?.latestOutput;
+ const resultExecution = isWorkflowImageExport && execution?.status !== 'completed' ? null : execution;
+ const withOutputPreview = Boolean(resultExecution?.outputImageUrl);
+ const latestResult = resultExecution?.latestOutput;
return (
<NodeShell
@@ -1056,7 +1058,9 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
{isWorkflowImageExport ? (
<Box data-workflow-export-content="true" maxW="full" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">
<NodeInfoTooltipContent
- executionError={execution?.status === 'failed' ? getNodeExecutionError(node, execution.error, t) : null}
+ executionError={
+ execution?.status === 'failed' ? (getNodeExecutionError(node, execution.error, t) ?? '') : null
+ }
node={node}
template={template}
/>
@@ -1105,9 +1109,9 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
) : (
<HiddenHandles inputTemplates={inputTemplates} outputTemplates={outputTemplates} />
)}
- {isOpen && execution?.outputImageUrl ? (
+ {isOpen && resultExecution?.outputImageUrl ? (
<NodeOutputPreview
- imageUrl={execution.outputImageUrl}
+ imageUrl={resultExecution.outputImageUrl}
isSkeleton={isZoomedOut}
nodeId={node.id}
roundedBottom={!withFooter}
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 cb620b20f1..ab50080721 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
@@ -49,7 +49,7 @@ describe('getInitialRenderFlowModel', () => {
expect(windowed.edges.map((edge) => edge.id)).toEqual(['inside']);
});
- it('renders the full graph during image export, even before the large-graph window expands', () => {
+ it('keeps the visible large graph windowed until its initial mount completes', () => {
const nodes = Array.from({ length: WORKFLOW_INITIAL_RENDER_NODE_COUNT + 2 }, (_, index) =>
createNode(`node-${index}`, index)
);
@@ -65,13 +65,12 @@ describe('getInitialRenderFlowModel', () => {
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']);
+ expect(rendered?.nodes).toHaveLength(WORKFLOW_INITIAL_RENDER_NODE_COUNT);
+ expect(rendered?.edges.map((edge) => edge.id)).toEqual(['inside']);
});
});
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 1736a7f7bc..97d5acce05 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -2,8 +2,8 @@ import type { ProjectGraphState, WorkflowEdge as WorkflowDocumentEdge, XYPositio
import type { WorkflowPerfSource, WorkflowRuntimeApi } from '@features/workflow/ui/contracts';
import { Box, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react';
-import '@xyflow/react/dist/style.css';
import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@features/workflow/react';
+import '@xyflow/react/dist/style.css';
import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@features/workflow/ui/graph-preview';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import {
@@ -58,6 +58,9 @@ import {
startTransition,
type MouseEvent as ReactMouseEvent,
} from 'react';
+import { flushSync } from 'react-dom';
+
+import type { WorkflowImageExportView } from './WorkflowImageExportView';
import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, useHasClipboardNodes } from './clipboard';
import { ConnectorFlowNode } from './ConnectorFlowNode';
@@ -76,7 +79,7 @@ import {
releaseWorkflowFlowInstance,
type WorkflowFlowInstance,
} from './flowInstanceStore';
-import { InvocationFlowNode, WorkflowImageExportProvider } from './InvocationFlowNode';
+import { InvocationFlowNode } from './InvocationFlowNode';
import LoopBodyBoundaryOverlay from './LoopBodyBoundaryOverlay';
import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';
import { NotesFlowNode } from './NotesFlowNode';
@@ -242,15 +245,9 @@ export const getInitialRenderFlowModel = (model: WorkflowFlowModel, viewport: Vi
export const getRenderedFlowModel = (
model: WorkflowFlowModel | null,
viewport: Viewport,
- {
- isExportingWorkflow,
- isFullGraphMounted,
- isLargeGraph,
- }: { isExportingWorkflow: boolean; isFullGraphMounted: boolean; isLargeGraph: boolean }
+ { isFullGraphMounted, isLargeGraph }: { isFullGraphMounted: boolean; isLargeGraph: boolean }
): WorkflowFlowModel | null =>
- model && isLargeGraph && !isExportingWorkflow && !isFullGraphMounted
- ? getInitialRenderFlowModel(model, viewport)
- : model;
+ model && isLargeGraph && !isFullGraphMounted ? getInitialRenderFlowModel(model, viewport) : model;
const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);
@@ -324,7 +321,18 @@ 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 [ExportView, setExportView] = useState<typeof WorkflowImageExportView | null>(null);
+ const exportRef = useRef<HTMLDivElement>(null);
+ const onExportPrepare = useCallback(async () => {
+ const { WorkflowImageExportView } = await import('./WorkflowImageExportView');
+ flushSync(() => setExportView(() => WorkflowImageExportView));
+ const element = exportRef.current?.querySelector<HTMLElement>('.react-flow');
+ if (!element) {
+ throw new Error('Workflow export view did not mount');
+ }
+ return element;
+ }, []);
+ const onExportComplete = useCallback(() => setExportView(null), []);
const [tool, setTool] = useState<EditorTool>('pan');
const [nodeOpacity, setNodeOpacity] = useState(1);
const [isMinimapReady, setIsMinimapReady] = useState(!isLargeGraph);
@@ -411,8 +419,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
});
const pointerToolHandlers = tool === 'lasso' ? lassoHandlers : tool === 'eraser' ? eraserHandlers : {};
const renderedFlowModel = useMemo(
- () => getRenderedFlowModel(flowModel, defaultViewport, { isExportingWorkflow, isFullGraphMounted, isLargeGraph }),
- [defaultViewport, flowModel, isExportingWorkflow, isFullGraphMounted, isLargeGraph]
+ () => getRenderedFlowModel(flowModel, defaultViewport, { isFullGraphMounted, isLargeGraph }),
+ [defaultViewport, flowModel, isFullGraphMounted, isLargeGraph]
);
const renderedFlowNodes = renderedFlowModel?.nodes ?? EMPTY_FLOW_NODES;
const renderedFlowEdges = renderedFlowModel?.edges ?? EMPTY_FLOW_EDGES;
@@ -1149,68 +1157,81 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
onContextMenuCapture={onEditorContextMenuCapture}
{...pointerToolHandlers}
>
- <WorkflowImageExportProvider isExporting={isExportingWorkflow}>
- <ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>
- key={viewportKey}
+ <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}
+ onExportPrepare={onExportPrepare}
+ onExportComplete={onExportComplete}
+ onNodeOpacityChange={setNodeOpacity}
+ onToolChange={setTool}
+ onUpdateNodes={onUpdateNodes}
+ />
+ {workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}
+ </ReactFlow>
+ {ExportView ? (
+ <ExportView
+ containerRef={exportRef}
colorMode={getFlowColorMode(themeId)}
- connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}
defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
- defaultViewport={defaultViewport}
- deleteKeyCode={DELETE_KEY_CODES}
- elevateEdgesOnSelect={!workflowEdgesBehindNodes}
- edges={renderedFlowEdges}
+ edges={flowEdges}
edgeTypes={edgeTypes}
- isValidConnection={isValidConnection}
- maxZoom={2}
- minZoom={0.1}
- nodes={renderedFlowNodes}
+ nodes={flowNodes}
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>
+ </ExportView>
+ ) : null}
{flowInstance ? (
<WorkflowSelectionRequestRuntime
flowInstance={flowInstance}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx
new file mode 100644
index 0000000000..d721107ab6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx
@@ -0,0 +1,41 @@
+import { Box } from '@chakra-ui/react';
+import { Background, BackgroundVariant, ReactFlow, ReactFlowProvider, type ReactFlowProps } from '@xyflow/react';
+import { useId, type RefObject } from 'react';
+
+import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';
+
+import { WorkflowImageExportProvider } from './InvocationFlowNode';
+
+/** A separate flow store keeps export measurements and expanded nodes out of the editor. */
+export const WorkflowImageExportView = ({
+ containerRef,
+ ...props
+}: ReactFlowProps<WorkflowFlowNode, WorkflowFlowEdge> & { containerRef: RefObject<HTMLDivElement | null> }) => {
+ const gridId = useId();
+
+ return (
+ <Box ref={containerRef} aria-hidden inert h="full" left="-100000px" position="absolute" top="0" w="full">
+ <ReactFlowProvider>
+ <WorkflowImageExportProvider isExporting>
+ <ReactFlow
+ {...props}
+ id={`workflow-export-${gridId}`}
+ elementsSelectable={false}
+ nodesConnectable={false}
+ nodesDraggable={false}
+ >
+ <Background
+ bgColor="var(--xy-background-color)"
+ color="var(--wb-flow-grid)"
+ gap={25}
+ id={gridId}
+ size={1.5}
+ variant={BackgroundVariant.Dots}
+ />
+ {props.children}
+ </ReactFlow>
+ </WorkflowImageExportProvider>
+ </ReactFlowProvider>
+ </Box>
+ );
+};