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): fit selected nodes in the editor (#10225)

rnshine02e3ee0e5b44
diff --git a/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx b/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx
index c5a4a1a1f1..8c484ae888 100644
--- a/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx
+++ b/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx
@@ -25,6 +25,8 @@ To connect two nodes, drag from an output on the right of one node to an input o
Right-click a node to **Copy**, **Paste**, **Duplicate**, **Collapse** or **Delete** it, and double-click its title to rename it. The chevron in a node's title bar collapses it to keep a large graph tidy. Pasted nodes land at the pointer when the editor has focus and the pointer is over it, at the click point when you right-click empty space and choose **Paste**, and otherwise in the center of the visible view.
+Right-click an unselected node and choose **Fit selection** to frame that node. To frame several nodes, select them, then right-click a selected node or the selection outline and choose **Fit selection**. Use **Fit view** in the editor toolbar to frame the whole workflow.
+
The picker's **Utility** group has three special nodes:
* **Notes** — a sticky note for explaining a workflow to others, or to yourself later.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index cda26652ec..c13139e1a0 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2173,6 +2173,7 @@
"contextPasteWithConnections": "Paste with connections",
"contextCollapse": "Collapse",
"contextExpand": "Expand",
+ "contextFitSelection": "Fit selection",
"contextAddConnector": "Add connector",
"arithmeticSequence": "Arithmetic sequence",
"linearDistribution": "Linear distribution",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx
index 9525c22d70..5e027c646a 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx
@@ -50,6 +50,7 @@ describe('NodeContextMenu', () => {
onCopy={vi.fn()}
onDelete={vi.fn()}
onDuplicate={vi.fn()}
+ onFitSelection={vi.fn()}
onPaste={vi.fn()}
onToggleOpen={vi.fn()}
onUpdate={onUpdate}
@@ -84,6 +85,7 @@ describe('NodeContextMenu', () => {
expect(hint('delete')).toBe('workflows.deleteSelection');
expect(hint('duplicate')).toBe('workflows.duplicateSelection');
expect(hint('toggle-open')).toBeNull();
+ expect(hint('fit-selection')).toBeNull();
});
it('offers both pastes on empty canvas, disabled with an empty clipboard, anchored where the menu opened', async () => {
@@ -101,6 +103,7 @@ describe('NodeContextMenu', () => {
onCopy={vi.fn()}
onDelete={vi.fn()}
onDuplicate={vi.fn()}
+ onFitSelection={vi.fn()}
onPaste={onPaste}
onToggleOpen={vi.fn()}
onUpdate={vi.fn()}
@@ -112,6 +115,7 @@ describe('NodeContextMenu', () => {
const item = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`)!;
await renderPane(false);
+ expect(item('fit-selection')).toBeNull();
expect(item('paste').getAttribute('aria-disabled')).toBe('true');
expect(item('paste-with-connections').getAttribute('aria-disabled')).toBe('true');
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx
index a316a69fc9..360ada4e54 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx
@@ -11,6 +11,7 @@ import {
CopyIcon,
Link2Icon,
CopyPlusIcon,
+ MaximizeIcon,
PlusIcon,
Trash2Icon,
} from 'lucide-react';
@@ -48,6 +49,7 @@ export const NodeContextMenu = ({
onCopy,
onDelete,
onDuplicate,
+ onFitSelection,
onPaste,
onToggleOpen,
onUpdate,
@@ -59,6 +61,7 @@ export const NodeContextMenu = ({
onCopy: () => void;
onDelete: () => void;
onDuplicate: () => void;
+ onFitSelection: () => void;
onPaste: WorkflowContextMenuPaste;
onToggleOpen: () => void;
onUpdate: () => void;
@@ -109,6 +112,10 @@ export const NodeContextMenu = ({
<CommandShortcut commandId="workflows.duplicateSelection" />
</Menu.ItemCommand>
</Menu.Item>
+ <Menu.Item value="fit-selection" onClick={onFitSelection}>
+ <Icon as={MaximizeIcon} boxSize="3.5" />
+ <Menu.ItemText>{t('nodes.contextFitSelection')}</Menu.ItemText>
+ </Menu.Item>
{menuState.isNodeOpen !== null ? (
<Menu.Item value="toggle-open" onClick={onToggleOpen}>
<Icon as={menuState.isNodeOpen ? ChevronsDownUpIcon : ChevronsUpDownIcon} boxSize="3.5" />
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx
index 2821d3b564..b4ab35924a 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx
@@ -358,6 +358,97 @@ describe('WorkflowEditorView first open', () => {
});
});
+describe('WorkflowEditorView fit selection', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ const nodeIds = ['node-a', 'node-b', 'outside'];
+ const graph = {
+ ...createProjectGraph('fit-selection'),
+ nodes: [addNode('node-a', 0, 0), addNode('node-b', 360, 0), addNode('outside', 1300, 0)],
+ } satisfies ProjectGraphState;
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ host.style.cssText = 'width: 480px; height: 520px;';
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ clearWorkflowViewports();
+ });
+
+ const getNode = (id: string) => host.querySelector<HTMLElement>(`.react-flow__node[data-id="${id}"]`)!;
+ const getFullyVisibleNodes = () => {
+ const viewport = host.getBoundingClientRect();
+ return nodeIds.filter((id) => {
+ const node = getNode(id)?.getBoundingClientRect();
+ return (
+ node &&
+ node.left >= viewport.left - 1 &&
+ node.right <= viewport.right + 1 &&
+ node.top >= viewport.top - 1 &&
+ node.bottom <= viewport.bottom + 1
+ );
+ });
+ };
+ const getSelectedNodes = () =>
+ getWorkflowFlowInstance()
+ ?.getNodes()
+ .filter((node) => node.selected)
+ .map(({ id }) => id);
+
+ it.each([
+ ['the selection rectangle', ['node-a', 'node-b']],
+ ['a selected node', ['node-a', 'node-b']],
+ ['an unselected node', ['outside']],
+ ])('fits the nodes targeted by the menu on %s without editing the graph', async (target, expectedNodes) => {
+ const adapter = await renderEditor(root, createProjectStore(graph));
+ await expect
+ .poll(() => getWorkflowViewport(getWorkflowViewportKey(PROJECT_ID, graph.id, INSTANCE_ID)))
+ .not.toBeNull();
+ expect(getFullyVisibleNodes()).toEqual(nodeIds);
+
+ await userEvent.click(host.querySelector<HTMLElement>('button[aria-label="widgets.workflow.toolbar.boxSelect"]')!);
+ const pane = host.querySelector<HTMLElement>('.react-flow__pane')!;
+ const paneRect = pane.getBoundingClientRect();
+ const first = getNode('node-a').getBoundingClientRect();
+ const last = getNode('node-b').getBoundingClientRect();
+ await userEvent.dragAndDrop(pane, pane, {
+ sourcePosition: { x: first.left - paneRect.left - 4, y: first.top - paneRect.top - 4 },
+ targetPosition: { x: last.right - paneRect.left + 4, y: last.bottom - paneRect.top + 4 },
+ });
+ await expect.poll(getSelectedNodes).toEqual(['node-a', 'node-b']);
+
+ const element =
+ target === 'the selection rectangle'
+ ? host.querySelector<HTMLElement>('.react-flow__nodesselection-rect')!
+ : getNode(target === 'a selected node' ? 'node-a' : 'outside');
+ const rect = element.getBoundingClientRect();
+ await act(() =>
+ element.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + 10,
+ clientY: rect.top + 10,
+ })
+ )
+ );
+ const menuItem = document.querySelector<HTMLElement>('[role="menuitem"][data-value="fit-selection"]')!;
+ await userEvent.click(menuItem);
+
+ await expect.poll(getFullyVisibleNodes).toEqual(expectedNodes);
+ expect(getSelectedNodes()).toEqual(['node-a', 'node-b']);
+ expect(adapter.commands.editGraph).not.toHaveBeenCalled();
+
+ await userEvent.click(host.querySelector<HTMLElement>('button[aria-label="widgets.workflow.toolbar.fitView"]')!);
+ await expect.poll(getFullyVisibleNodes).toEqual(nodeIds);
+ });
+});
+
describe('WorkflowEditorView paste', () => {
let host: HTMLDivElement;
let outside: HTMLButtonElement;
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 e46d53e8a0..f492baa20c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -103,6 +103,7 @@ import { NodeContextMenu, type WorkflowContextMenuPaste, type WorkflowContextMen
import { NotesFlowNode } from './NotesFlowNode';
import {
isLargeWorkflowGraph,
+ UNMEASURED_WORKFLOW_NODE_SIZE,
WORKFLOW_INITIAL_RENDER_NODE_COUNT,
WORKFLOW_MINIMAP_DELAY_MS,
} from './performanceConstants';
@@ -1272,6 +1273,32 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
duplicateNodes(contextMenu?.kind === 'node' ? contextMenu.nodeId : undefined);
setContextMenu(null);
}, [contextMenu, duplicateNodes]);
+ const onContextMenuFitSelection = useCallback(() => {
+ setContextMenu(null);
+ if (!flowInstance || contextMenu?.kind !== 'node') {
+ return;
+ }
+
+ const nodes = getActionNodeIds(contextMenu.nodeId).flatMap((id) => {
+ const node = flowInstance.getInternalNode(id);
+ if (!node) {
+ return [];
+ }
+
+ // A selection can include offscreen nodes that XYFlow has never rendered or measured.
+ return [
+ node.measured.width && node.measured.height ? node : { ...node, measured: UNMEASURED_WORKFLOW_NODE_SIZE },
+ ];
+ });
+ if (nodes.length > 0) {
+ void fitWorkflowBounds(
+ flowInstance,
+ flowInstance.getNodesBounds(nodes),
+ flowStore.getState(),
+ reduceMotion ? 0 : 300
+ );
+ }
+ }, [contextMenu, flowInstance, flowStore, getActionNodeIds, reduceMotion]);
// Only the empty-canvas menu names a point; a node or selection menu pastes like any other menu, centered in the
// view, so the copy never lands on the nodes it was opened on.
const onContextMenuPaste = useCallback<WorkflowContextMenuPaste>(
@@ -1462,6 +1489,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
onCopy={onContextMenuCopy}
onDelete={onContextMenuDelete}
onDuplicate={onContextMenuDuplicate}
+ onFitSelection={onContextMenuFitSelection}
onPaste={onContextMenuPaste}
onToggleOpen={onContextMenuToggleOpen}
onUpdate={onContextMenuUpdate}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
index a24769d986..3bd80e45d2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
@@ -16,11 +16,9 @@ import {
type WorkflowFitViewTarget,
type WorkflowFlowInstance,
} from './flowInstanceStore';
+import { UNMEASURED_WORKFLOW_NODE_SIZE } from './performanceConstants';
import { clearNodeSelectionRequest, workflowSelectionStore } from './selectionStore';
-// A large graph renders only visible nodes, so xyflow never measures the rest; they count at a typical node size.
-const UNMEASURED_NODE_SIZE = { height: 160, width: 288 };
-
/** A node whose template exists renders as a placeholder card until its rebuilt data carries that template. */
const isAwaitingTemplate = (internal: InternalNode<WorkflowFlowNode>, templates: InvocationTemplates): boolean => {
const { userNode } = internal.internals;
@@ -70,8 +68,8 @@ const getWorkflowFitBounds = (
return null;
}
- const width = isMeasured ? internal.measured.width! : UNMEASURED_NODE_SIZE.width;
- const height = isMeasured ? internal.measured.height! : UNMEASURED_NODE_SIZE.height;
+ const width = isMeasured ? internal.measured.width! : UNMEASURED_WORKFLOW_NODE_SIZE.width;
+ const height = isMeasured ? internal.measured.height! : UNMEASURED_WORKFLOW_NODE_SIZE.height;
minX = Math.min(minX, position.x);
minY = Math.min(minY, position.y);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.ts
index 55b4c87e90..6c51964a99 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.ts
@@ -4,5 +4,8 @@ export const WORKFLOW_LARGE_GRAPH_EDGE_COUNT = 500;
export const WORKFLOW_MINIMAP_DELAY_MS = 450;
export const WORKFLOW_INITIAL_RENDER_NODE_COUNT = 120;
+/** Large graphs render only visible nodes. Use a typical size until an offscreen node is measured. */
+export const UNMEASURED_WORKFLOW_NODE_SIZE = { height: 160, width: 288 };
+
export const isLargeWorkflowGraph = ({ edgeCount, nodeCount }: { edgeCount: number; nodeCount: number }): boolean =>
nodeCount >= WORKFLOW_LARGE_GRAPH_NODE_COUNT || edgeCount >= WORKFLOW_LARGE_GRAPH_EDGE_COUNT;