Skip to content

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

refactor(workflow): isolate selection request runtime

joshistoast4f50f4f6dfb3
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 9e62793e20..8ceee95405 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -80,15 +80,11 @@ import {
WORKFLOW_INITIAL_RENDER_NODE_COUNT,
WORKFLOW_MINIMAP_DELAY_MS,
} from './performanceConstants';
-import {
- clearNodeSelectionRequest,
- reportNodeHover,
- reportNodeSelection,
- workflowSelectionStore,
-} from './selectionStore';
+import { reportNodeHover, reportNodeSelection, workflowSelectionStore } from './selectionStore';
import { useEraser } from './useEraser';
import { useLasso } from './useLasso';
import { WorkflowEdge } from './WorkflowEdge';
+import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';
import { getWorkflowViewport, getWorkflowViewportKey, setWorkflowViewport } from './workflowViewportStore';
const nodeTypes: NodeTypes = {
@@ -523,35 +519,6 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
};
}, [flowInstance]);
- const applyRequestedSelection = useEffectEvent(() => {
- const selectionRequest = workflowSelectionStore.getSnapshot().selectionRequest;
-
- if (!selectionRequest || !flowInstance) {
- return;
- }
-
- selectNodes(selectionRequest.nodeIds);
- void flowInstance.fitView({
- duration: reduceMotion ? 0 : 300,
- maxZoom: 1.25,
- nodes: selectionRequest.nodeIds.map((id) => ({ id })),
- });
- clearNodeSelectionRequest();
- });
-
- // Outside surfaces publish selection requests through an external store.
- // Subscribe at that seam so the request does not need an intermediate
- // render-and-effect cycle before it reaches the flow instance.
- useEffect(() => {
- const pendingRequestTimer = window.setTimeout(applyRequestedSelection, 0);
- const unsubscribe = workflowSelectionStore.subscribe(applyRequestedSelection);
-
- return () => {
- window.clearTimeout(pendingRequestTimer);
- unsubscribe();
- };
- }, [flowInstance]);
-
/** The context-menu node acts alone unless it is part of the current selection. */
const getActionNodeIds = useCallback(
(nodeId?: string): string[] => {
@@ -1115,6 +1082,13 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
/>
{workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}
</ReactFlow>
+ {flowInstance ? (
+ <WorkflowSelectionRequestRuntime
+ flowInstance={flowInstance}
+ reduceMotion={reduceMotion}
+ selectNodes={selectNodes}
+ />
+ ) : null}
{lassoOverlay}
{eraserOverlay}
<NodeContextMenu
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx
new file mode 100644
index 0000000000..c29c523b2a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx
@@ -0,0 +1,73 @@
+/* eslint-disable react-perf/jsx-no-new-object-as-prop -- test injects stable fakes into the runtime */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WorkflowFlowInstance } from './flowInstanceStore';
+
+import { requestNodeSelection, workflowSelectionStore } from './selectionStore';
+import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const waitForPendingSelection = () =>
+ new Promise<void>((resolve) => {
+ window.setTimeout(resolve, 0);
+ });
+
+describe('WorkflowSelectionRequestRuntime', () => {
+ let host: HTMLDivElement;
+ let root: Root | null;
+
+ beforeEach(() => {
+ workflowSelectionStore.patchSnapshot({ hoveredNodeId: null, selectedNodeIds: [], selectionRequest: null });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ if (root) {
+ await act(() => root?.unmount());
+ }
+ host.remove();
+ });
+
+ it('applies pending and later requests with current motion preferences, then unsubscribes', async () => {
+ const fitView = vi.fn(() => Promise.resolve(true));
+ const flowInstance = { fitView } as unknown as WorkflowFlowInstance;
+ const selectNodes = vi.fn();
+ requestNodeSelection(['pending-node']);
+
+ await act(() => {
+ root?.render(
+ <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion={false} selectNodes={selectNodes} />
+ );
+ });
+ await act(waitForPendingSelection);
+
+ expect(selectNodes).toHaveBeenLastCalledWith(['pending-node']);
+ expect(fitView).toHaveBeenLastCalledWith({
+ duration: 300,
+ maxZoom: 1.25,
+ nodes: [{ id: 'pending-node' }],
+ });
+
+ await act(() => {
+ root?.render(
+ <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={selectNodes} />
+ );
+ });
+ act(() => requestNodeSelection(['later-node']));
+
+ expect(selectNodes).toHaveBeenLastCalledWith(['later-node']);
+ expect(fitView).toHaveBeenLastCalledWith({ duration: 0, maxZoom: 1.25, nodes: [{ id: 'later-node' }] });
+
+ await act(() => root?.unmount());
+ root = null;
+ act(() => requestNodeSelection(['after-unmount']));
+
+ expect(selectNodes).toHaveBeenCalledTimes(2);
+ expect(fitView).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
new file mode 100644
index 0000000000..4b79ee3764
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
@@ -0,0 +1,49 @@
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { useEffectEvent } from 'react';
+
+import type { WorkflowFlowInstance } from './flowInstanceStore';
+
+import { clearNodeSelectionRequest, workflowSelectionStore } from './selectionStore';
+
+interface WorkflowSelectionRequestRuntimeProps {
+ flowInstance: WorkflowFlowInstance;
+ reduceMotion: boolean;
+ selectNodes: (nodeIds: string[]) => void;
+}
+
+/** Applies outside selection requests while a workflow flow instance is mounted. */
+export const WorkflowSelectionRequestRuntime = ({
+ flowInstance,
+ reduceMotion,
+ selectNodes,
+}: WorkflowSelectionRequestRuntimeProps) => {
+ const applyRequestedSelection = useEffectEvent(() => {
+ const selectionRequest = workflowSelectionStore.getSnapshot().selectionRequest;
+
+ if (!selectionRequest) {
+ return;
+ }
+
+ selectNodes(selectionRequest.nodeIds);
+ void flowInstance.fitView({
+ duration: reduceMotion ? 0 : 300,
+ maxZoom: 1.25,
+ nodes: selectionRequest.nodeIds.map((id) => ({ id })),
+ });
+ clearNodeSelectionRequest();
+ });
+
+ /* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */
+ useMountEffect(() => {
+ const pendingRequestTimer = window.setTimeout(applyRequestedSelection, 0);
+ const unsubscribe = workflowSelectionStore.subscribe(applyRequestedSelection);
+
+ return () => {
+ window.clearTimeout(pendingRequestTimer);
+ unsubscribe();
+ };
+ });
+ /* eslint-enable react-hooks/rules-of-hooks */
+
+ return null;
+};