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(webv2): improve workflow editor interactions

joshistoast9dbdeff7c5fd
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
index ec66fc33dd..888f04f81a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
@@ -14,6 +14,7 @@ import {
createWorkflowId,
} from '../../workflows/document';
import type { InvocationTemplate, XYPosition } from '../../workflows/types';
+import { getCompatibleInputTemplate } from '../../workflows/validation';
import { parseWorkflowJson } from '../../workflows/workflowJson';
import type { WidgetLabelProps, WidgetViewProps } from '../../types';
import { AddNodeDialog } from './editor/AddNodeDialog';
@@ -129,8 +130,15 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
const dispatch = useWorkbenchDispatch();
const notify = useNotify();
const fileInputRef = useRef<HTMLInputElement | null>(null);
- const { dialogHostId, importRequestCount, isAddNodeOpen, isLibraryOpen, isNewWorkflowConfirmOpen } =
- workflowUiStore.useSnapshot();
+ const {
+ addNodeConnection,
+ addNodePosition,
+ dialogHostId,
+ importRequestCount,
+ isAddNodeOpen,
+ isLibraryOpen,
+ isNewWorkflowConfirmOpen,
+ } = workflowUiStore.useSnapshot();
const restorableHistory = graphHistory.filter((entry) => entry.document);
// Both workflow surfaces can be mounted at once; exactly one (the first to
@@ -156,6 +164,10 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
}, [importRequestCount, isDialogHost]);
const getInsertPosition = (): XYPosition => {
+ if (addNodePosition) {
+ return addNodePosition;
+ }
+
const instance = getWorkflowFlowInstance();
const center = instance
? instance.screenToFlowPosition({ x: window.innerWidth / 2, y: window.innerHeight / 2 })
@@ -166,8 +178,39 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
};
const addNode = (template: InvocationTemplate) => {
+ const node = buildInvocationNode(template, getInsertPosition());
+
+ if (!addNodeConnection) {
+ dispatch({
+ action: { node, type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ return;
+ }
+
+ const targetInput = getCompatibleInputTemplate(template, addNodeConnection.sourceType);
+
+ if (!targetInput) {
+ dispatch({
+ action: { node, type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ return;
+ }
+
dispatch({
- action: { node: buildInvocationNode(template, getInsertPosition()), type: 'addNode' },
+ action: {
+ edge: {
+ id: createWorkflowId('edge'),
+ source: addNodeConnection.sourceNodeId,
+ sourceHandle: addNodeConnection.sourceHandle,
+ target: node.id,
+ targetHandle: targetInput.name,
+ type: 'default',
+ },
+ node,
+ type: 'addNodeAndEdge',
+ },
type: 'applyProjectGraphAction',
});
};
@@ -289,6 +332,7 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
}}
/>
<AddNodeDialog
+ connectionFilter={addNodeConnection}
isOpen={isAddNodeOpen}
onAddCurrentImage={addCurrentImage}
onAddNode={addNode}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx
index 3895f3aed7..b8c1c4fc18 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx
@@ -7,6 +7,8 @@ import { Scrollable } from '../../../components/ui/Scrollable';
import { Tooltip } from '../../../components/ui/Tooltip';
import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
import type { InvocationTemplate } from '../../../workflows/types';
+import { getCompatibleInputTemplate } from '../../../workflows/validation';
+import type { AddNodeConnectionFilter } from '../workflowUiStore';
/**
* Command-palette-style node picker: a centered search dialog whose results
@@ -80,12 +82,40 @@ const NodeResultRow = ({ row }: { row: NodeRow }) => (
);
export const AddNodeDialog = ({
+ connectionFilter,
isOpen,
onAddCurrentImage,
onAddNode,
onAddNote,
onOpenChange,
}: {
+ connectionFilter: AddNodeConnectionFilter | null;
+ isOpen: boolean;
+ onAddCurrentImage: () => void;
+ onAddNode: (template: InvocationTemplate) => void;
+ onAddNote: () => void;
+ onOpenChange: (isOpen: boolean) => void;
+}) =>
+ isOpen ? (
+ <AddNodeDialogContent
+ connectionFilter={connectionFilter}
+ isOpen={isOpen}
+ onAddCurrentImage={onAddCurrentImage}
+ onAddNode={onAddNode}
+ onAddNote={onAddNote}
+ onOpenChange={onOpenChange}
+ />
+ ) : null;
+
+const AddNodeDialogContent = ({
+ connectionFilter,
+ isOpen,
+ onAddCurrentImage,
+ onAddNode,
+ onAddNote,
+ onOpenChange,
+}: {
+ connectionFilter: AddNodeConnectionFilter | null;
isOpen: boolean;
onAddCurrentImage: () => void;
onAddNode: (template: InvocationTemplate) => void;
@@ -112,33 +142,39 @@ export const AddNodeDialog = ({
const groups = useMemo<CategoryGroup[]>(() => {
const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);
- const utilityRows: NodeRow[] = [
- {
- description: 'Annotate the workflow with a free-text note.',
- isBeta: false,
- nodePack: 'invokeai',
- onAdd: () => {
- onAddNote();
- close(true);
- },
- title: 'Notes',
- },
- {
- description: 'Show the latest generated image (and live progress) inside the graph.',
- isBeta: false,
- nodePack: 'invokeai',
- onAdd: () => {
- onAddCurrentImage();
- close(true);
- },
- title: 'Current Image',
- },
- ].filter((row) => terms.every((term) => row.title.toLowerCase().includes(term)));
+ const utilityRows: NodeRow[] = connectionFilter
+ ? []
+ : [
+ {
+ description: 'Annotate the workflow with a free-text note.',
+ isBeta: false,
+ nodePack: 'invokeai',
+ onAdd: () => {
+ onAddNote();
+ close(true);
+ },
+ title: 'Notes',
+ },
+ {
+ description: 'Show the latest generated image (and live progress) inside the graph.',
+ isBeta: false,
+ nodePack: 'invokeai',
+ onAdd: () => {
+ onAddCurrentImage();
+ close(true);
+ },
+ title: 'Current Image',
+ },
+ ].filter((row) => terms.every((term) => row.title.toLowerCase().includes(term)));
const byCategory = new Map<string, NodeRow[]>();
for (const template of Object.values(templates)) {
- if (template.classification === 'internal' || (terms.length > 0 && !matchesSearch(template, terms))) {
+ if (
+ template.classification === 'internal' ||
+ (terms.length > 0 && !matchesSearch(template, terms)) ||
+ (connectionFilter && !getCompatibleInputTemplate(template, connectionFilter.sourceType))
+ ) {
continue;
}
@@ -167,7 +203,7 @@ export const AddNodeDialog = ({
return utilityRows.length > 0
? [{ label: UTILITY_CATEGORY, rows: utilityRows }, ...categoryGroups]
: categoryGroups;
- }, [close, onAddCurrentImage, onAddNode, onAddNote, searchTerm, templates]);
+ }, [close, connectionFilter, onAddCurrentImage, onAddNode, onAddNote, searchTerm, templates]);
const totalCount = groups.reduce((sum, group) => sum + group.rows.length, 0);
const accordionValue = isSearching ? groups.map((group) => group.label) : expandedCategories;
@@ -183,7 +219,7 @@ export const AddNodeDialog = ({
} else if (totalCount === 0) {
body = (
<Text color="fg.subtle" fontSize="xs" px="1" py="4" textAlign="center">
- No nodes match your search.
+ {connectionFilter ? `No nodes accept ${connectionFilter.sourceType.name}.` : 'No nodes match your search.'}
</Text>
);
} else {
@@ -194,26 +230,32 @@ export const AddNodeDialog = ({
variant="plain"
onValueChange={(event) => setExpandedCategories(event.value)}
>
- {groups.map((group) => (
- <Accordion.Item key={group.label} value={group.label}>
- <Accordion.ItemTrigger cursor="pointer" px="1" py="1.5">
- <Accordion.ItemIndicator />
- <Text flex="1" fontSize="xs" fontWeight="700" textAlign="start">
- {group.label}
- </Text>
- <Badge size="sm" variant="surface">
- {group.rows.length}
- </Badge>
- </Accordion.ItemTrigger>
- <Accordion.ItemContent>
- <Stack gap="0.5" pb="2">
- {group.rows.map((row) => (
- <NodeResultRow key={`${group.label}:${row.title}`} row={row} />
- ))}
- </Stack>
- </Accordion.ItemContent>
- </Accordion.Item>
- ))}
+ {groups.map((group) => {
+ const isExpanded = accordionValue.includes(group.label);
+
+ return (
+ <Accordion.Item key={group.label} value={group.label}>
+ <Accordion.ItemTrigger cursor="pointer" px="1" py="1.5">
+ <Accordion.ItemIndicator />
+ <Text flex="1" fontSize="xs" fontWeight="700" textAlign="start">
+ {group.label}
+ </Text>
+ <Badge size="sm" variant="surface">
+ {group.rows.length}
+ </Badge>
+ </Accordion.ItemTrigger>
+ <Accordion.ItemContent>
+ {isExpanded ? (
+ <Stack gap="0.5" pb="2">
+ {group.rows.map((row) => (
+ <NodeResultRow key={`${group.label}:${row.title}`} row={row} />
+ ))}
+ </Stack>
+ ) : null}
+ </Accordion.ItemContent>
+ </Accordion.Item>
+ );
+ })}
</Accordion.Root>
);
}
@@ -239,7 +281,11 @@ export const AddNodeDialog = ({
<Input
autoFocus
aria-label="Search for nodes"
- placeholder="Search for nodes…"
+ placeholder={
+ connectionFilter
+ ? `Search compatible ${connectionFilter.sourceType.name} nodes…`
+ : 'Search for nodes…'
+ }
size="md"
value={searchTerm}
onChange={(event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value)}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx
index cbe359a381..a2ca87c603 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx
@@ -5,27 +5,40 @@ import {
ClipboardPasteIcon,
CopyIcon,
CopyPlusIcon,
+ PlusIcon,
Trash2Icon,
} from 'lucide-react';
+import type { XYPosition } from '../../../workflows/types';
+
/**
- * Right-click utilities for a flow node, anchored at the pointer. The menu is
- * fully controlled — the editor owns the open state and the actions, since
- * copy/paste/duplicate need the flow instance and selection context.
+ * Right-click utilities for the flow pane and nodes, anchored at the pointer.
+ * The menu is fully controlled because each action needs editor-local context.
*/
export interface NodeContextMenuState {
- nodeId: string;
+ kind: 'node';
+ nodeId?: string;
/** The node's `isOpen`; null for node types without a collapse toggle (notes). */
isNodeOpen: boolean | null;
x: number;
y: number;
}
+export interface PaneContextMenuState {
+ kind: 'pane';
+ position: XYPosition;
+ x: number;
+ y: number;
+}
+
+export type WorkflowContextMenuState = NodeContextMenuState | PaneContextMenuState;
+
export const NodeContextMenu = ({
canPaste,
menuState,
onClose,
+ onAddConnector,
onCopy,
onDelete,
onDuplicate,
@@ -33,8 +46,9 @@ export const NodeContextMenu = ({
onToggleOpen,
}: {
canPaste: boolean;
- menuState: NodeContextMenuState | null;
+ menuState: WorkflowContextMenuState | null;
onClose: () => void;
+ onAddConnector: (position: XYPosition) => void;
onCopy: () => void;
onDelete: () => void;
onDuplicate: () => void;
@@ -56,32 +70,41 @@ export const NodeContextMenu = ({
<Portal>
<Menu.Positioner>
<Menu.Content minW="11rem">
- <Menu.Item value="copy" onClick={onCopy}>
- <Icon as={CopyIcon} boxSize="3.5" />
- <Menu.ItemText>Copy</Menu.ItemText>
- <Menu.ItemCommand>Ctrl C</Menu.ItemCommand>
- </Menu.Item>
- <Menu.Item disabled={!canPaste} value="paste" _disabled={{ opacity: 0.4 }} onClick={onPaste}>
- <Icon as={ClipboardPasteIcon} boxSize="3.5" />
- <Menu.ItemText>Paste</Menu.ItemText>
- <Menu.ItemCommand>Ctrl V</Menu.ItemCommand>
- </Menu.Item>
- <Menu.Item value="duplicate" onClick={onDuplicate}>
- <Icon as={CopyPlusIcon} boxSize="3.5" />
- <Menu.ItemText>Duplicate</Menu.ItemText>
- </Menu.Item>
- {menuState?.isNodeOpen !== null ? (
- <Menu.Item value="toggle-open" onClick={onToggleOpen}>
- <Icon as={menuState?.isNodeOpen ? ChevronRightIcon : ChevronDownIcon} boxSize="3.5" />
- <Menu.ItemText>{menuState?.isNodeOpen ? 'Collapse' : 'Expand'}</Menu.ItemText>
+ {!menuState ? null : menuState.kind === 'pane' ? (
+ <Menu.Item value="add-connector" onClick={() => onAddConnector(menuState.position)}>
+ <Icon as={PlusIcon} boxSize="3.5" />
+ <Menu.ItemText>Add connector</Menu.ItemText>
</Menu.Item>
- ) : null}
- <Menu.Separator borderColor="border.subtle" />
- <Menu.Item color="fg.error" value="delete" onClick={onDelete}>
- <Icon as={Trash2Icon} boxSize="3.5" />
- <Menu.ItemText>Delete</Menu.ItemText>
- <Menu.ItemCommand>Del</Menu.ItemCommand>
- </Menu.Item>
+ ) : (
+ <>
+ <Menu.Item value="copy" onClick={onCopy}>
+ <Icon as={CopyIcon} boxSize="3.5" />
+ <Menu.ItemText>Copy</Menu.ItemText>
+ <Menu.ItemCommand>Ctrl C</Menu.ItemCommand>
+ </Menu.Item>
+ <Menu.Item disabled={!canPaste} value="paste" _disabled={{ opacity: 0.4 }} onClick={onPaste}>
+ <Icon as={ClipboardPasteIcon} boxSize="3.5" />
+ <Menu.ItemText>Paste</Menu.ItemText>
+ <Menu.ItemCommand>Ctrl V</Menu.ItemCommand>
+ </Menu.Item>
+ <Menu.Item value="duplicate" onClick={onDuplicate}>
+ <Icon as={CopyPlusIcon} boxSize="3.5" />
+ <Menu.ItemText>Duplicate</Menu.ItemText>
+ </Menu.Item>
+ {menuState.isNodeOpen !== null ? (
+ <Menu.Item value="toggle-open" onClick={onToggleOpen}>
+ <Icon as={menuState.isNodeOpen ? ChevronRightIcon : ChevronDownIcon} boxSize="3.5" />
+ <Menu.ItemText>{menuState.isNodeOpen ? 'Collapse' : 'Expand'}</Menu.ItemText>
+ </Menu.Item>
+ ) : null}
+ <Menu.Separator borderColor="border.subtle" />
+ <Menu.Item color="fg.error" value="delete" onClick={onDelete}>
+ <Icon as={Trash2Icon} boxSize="3.5" />
+ <Menu.ItemText>Delete</Menu.ItemText>
+ <Menu.ItemCommand>Del</Menu.ItemCommand>
+ </Menu.Item>
+ </>
+ )}
</Menu.Content>
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
index 0d6e724b05..2c02a3d769 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
@@ -14,8 +14,18 @@ import {
type IsValidConnection,
type NodeChange,
type NodeTypes,
+ type OnConnectEnd,
} from '@xyflow/react';
-import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react';
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent,
+ type MouseEvent as ReactMouseEvent,
+} from 'react';
import '@xyflow/react/dist/style.css';
@@ -25,9 +35,10 @@ import { useNotify } from '../../../useNotify';
import { useWorkbenchPreferences } from '../../../settings/store';
import { useActiveProjectSelector, useWorkbenchDispatch } from '../../../WorkbenchContext';
import { getProjectGraphReadiness } from '../../../workflows/buildGraph';
-import { createWorkflowId } from '../../../workflows/document';
+import { buildConnectorNode, createWorkflowId } from '../../../workflows/document';
import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '../../../workflows/templates';
-import { validateConnection } from '../../../workflows/validation';
+import type { XYPosition } from '../../../workflows/types';
+import { getWorkflowSourceFieldType, validateConnection } from '../../../workflows/validation';
import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, useHasClipboardNodes } from './clipboard';
import { CurrentImageFlowNode } from './CurrentImageFlowNode';
import { EditorToolbar, type EditorTool } from './EditorToolbar';
@@ -38,14 +49,17 @@ import {
type WorkflowFlowInstance,
} from './flowInstanceStore';
import { InvocationFlowNode } from './InvocationFlowNode';
-import { NodeContextMenu, type NodeContextMenuState } from './NodeContextMenu';
+import { ConnectorFlowNode } from './ConnectorFlowNode';
+import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';
import { NotesFlowNode } from './NotesFlowNode';
import { clearNodeSelectionRequest, reportNodeSelection, workflowSelectionStore } from './selectionStore';
import { useEraser } from './useEraser';
import { useLasso } from './useLasso';
import { useModifierHeld } from './useModifierHeld';
+import { setAddNodeOpen } from '../workflowUiStore';
const nodeTypes: NodeTypes = {
+ connector: ConnectorFlowNode,
current_image: CurrentImageFlowNode,
invocation: InvocationFlowNode,
notes: NotesFlowNode,
@@ -67,6 +81,16 @@ const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 1.5 } };
const isEditableTarget = (target: EventTarget | null): boolean =>
target instanceof HTMLElement && target.closest('input, textarea, select, [contenteditable="true"]') !== null;
+const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y: number } | null => {
+ if (event instanceof MouseEvent) {
+ return { x: event.clientX, y: event.clientY };
+ }
+
+ const touch = event.changedTouches[0];
+
+ return touch ? { x: touch.clientX, y: touch.clientY } : null;
+};
+
const WorkflowFlow = () => {
const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
const dispatch = useWorkbenchDispatch();
@@ -80,10 +104,11 @@ const WorkflowFlow = () => {
const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);
const [tool, setTool] = useState<EditorTool>('pan');
const [nodeOpacity, setNodeOpacity] = useState(1);
- const [contextMenu, setContextMenu] = useState<NodeContextMenuState | null>(null);
+ const [contextMenu, setContextMenu] = useState<WorkflowContextMenuState | null>(null);
const { selectionRequest } = workflowSelectionStore.useSnapshot();
const isSnapHeld = useModifierHeld('Control');
const hasClipboardNodes = useHasClipboardNodes();
+ const backgroundId = useId().replace(/:/g, '');
/** Node ids to select once the next document-driven rebuild lands (fresh paste/duplicate results). */
const pendingSelectionRef = useRef<string[] | null>(null);
@@ -174,15 +199,18 @@ const WorkflowFlow = () => {
}, [flowInstance, selectNodes, selectionRequest]);
/** The context-menu node acts alone unless it is part of the current selection. */
- const getActionNodeIds = (nodeId?: string): string[] => {
- const selectedIds = flowNodes.filter((node) => node.selected).map((node) => node.id);
+ const getActionNodeIds = useCallback(
+ (nodeId?: string): string[] => {
+ const selectedIds = flowNodes.filter((node) => node.selected).map((node) => node.id);
- if (nodeId && !selectedIds.includes(nodeId)) {
- return [nodeId];
- }
+ if (nodeId && !selectedIds.includes(nodeId)) {
+ return [nodeId];
+ }
- return selectedIds;
- };
+ return selectedIds;
+ },
+ [flowNodes]
+ );
const copyNodes = (nodeId?: string) => {
const copiedCount = copyNodesToClipboard(projectGraph, getActionNodeIds(nodeId));
@@ -222,6 +250,10 @@ const WorkflowFlow = () => {
}
};
+ const addConnector = (position: XYPosition) => {
+ dispatch({ action: { node: buildConnectorNode(position), type: 'addNode' }, type: 'applyProjectGraphAction' });
+ };
+
const onEditorKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (isEditableTarget(event.target) || !(event.ctrlKey || event.metaKey)) {
return;
@@ -325,9 +357,45 @@ const WorkflowFlow = () => {
[dispatch]
);
- const onNodeContextMenu = useCallback((event: MouseEvent, node: WorkflowFlowNode) => {
+ const onConnectEnd = useCallback<OnConnectEnd>(
+ (event, connectionState) => {
+ if (!flowInstance || !(event.target instanceof Element) || !event.target.closest('.react-flow__pane')) {
+ return;
+ }
+
+ const sourceHandle = connectionState.fromHandle?.id;
+ const sourceNodeId = connectionState.fromHandle?.nodeId ?? connectionState.fromNode?.id;
+
+ if (!sourceHandle || !sourceNodeId || connectionState.fromHandle?.type !== 'source') {
+ return;
+ }
+
+ const sourceType = getWorkflowSourceFieldType(
+ projectGraph,
+ templatesSnapshot.templates,
+ sourceNodeId,
+ sourceHandle
+ );
+
+ if (!sourceType) {
+ return;
+ }
+
+ const position = getEventClientPosition(event);
+
+ if (!position) {
+ return;
+ }
+
+ setAddNodeOpen(true, flowInstance.screenToFlowPosition(position), { sourceHandle, sourceNodeId, sourceType });
+ },
+ [flowInstance, projectGraph, templatesSnapshot.templates]
+ );
+
+ const onNodeContextMenu = useCallback((event: ReactMouseEvent, node: WorkflowFlowNode) => {
event.preventDefault();
setContextMenu({
+ kind: 'node',
isNodeOpen: node.type === 'invocation' ? node.data.documentNode.data.isOpen : null,
nodeId: node.id,
x: event.clientX,
@@ -335,8 +403,59 @@ const WorkflowFlow = () => {
});
}, []);
+ const onPaneContextMenu = useCallback(
+ (event: ReactMouseEvent | globalThis.MouseEvent) => {
+ if (!flowInstance) {
+ return;
+ }
+
+ event.preventDefault();
+ if (
+ event.target instanceof Element &&
+ event.target.closest('.react-flow__nodesselection') &&
+ getActionNodeIds().length > 0
+ ) {
+ setContextMenu({
+ kind: 'node',
+ isNodeOpen: null,
+ x: event.clientX,
+ y: event.clientY,
+ });
+ return;
+ }
+
+ setContextMenu({
+ kind: 'pane',
+ position: flowInstance.screenToFlowPosition({ x: event.clientX, y: event.clientY }),
+ x: event.clientX,
+ y: event.clientY,
+ });
+ },
+ [flowInstance, getActionNodeIds]
+ );
+
+ const onEditorContextMenuCapture = useCallback(
+ (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest('.react-flow__nodesselection') &&
+ getActionNodeIds().length > 0
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ setContextMenu({
+ kind: 'node',
+ isNodeOpen: null,
+ x: event.clientX,
+ y: event.clientY,
+ });
+ }
+ },
+ [getActionNodeIds]
+ );
+
const onNodeClick = useCallback(
- (_: MouseEvent, node: WorkflowFlowNode) => {
+ (_: ReactMouseEvent, node: WorkflowFlowNode) => {
if (tool === 'eraser') {
eraseElements({ edgeIds: [], nodeIds: [node.id] });
}
@@ -345,7 +464,7 @@ const WorkflowFlow = () => {
);
const onEdgeClick = useCallback(
- (_: MouseEvent, edge: FlowEdge) => {
+ (_: ReactMouseEvent, edge: FlowEdge) => {
if (tool === 'eraser') {
eraseElements({ edgeIds: [edge.id], nodeIds: [] });
}
@@ -377,6 +496,7 @@ const WorkflowFlow = () => {
h="full"
position="relative"
w="full"
+ onContextMenuCapture={onEditorContextMenuCapture}
onKeyDown={onEditorKeyDown}
{...pointerToolHandlers}
>
@@ -400,15 +520,24 @@ const WorkflowFlow = () => {
snapToGrid={workflowSnapToGrid || isSnapHeld}
style={{ background: 'transparent' }}
onConnect={onConnect}
+ onConnectEnd={onConnectEnd}
onEdgeClick={onEdgeClick}
onEdgesChange={onEdgesChange}
onInit={setFlowInstance}
onNodeClick={onNodeClick}
onNodeContextMenu={onNodeContextMenu}
onNodesChange={onNodesChange}
+ onPaneContextMenu={onPaneContextMenu}
onSelectionChange={onSelectionChange}
>
- <Background color="var(--wb-flow-grid)" gap={24} size={1.5} variant={BackgroundVariant.Dots} />
+ <Background
+ bgColor="var(--xy-background-color)"
+ color="var(--wb-flow-grid)"
+ gap={24}
+ id={`workflow-grid-${backgroundId}`}
+ size={1.5}
+ variant={BackgroundVariant.Dots}
+ />
<EditorToolbar
nodeOpacity={nodeOpacity}
tool={tool}
@@ -422,17 +551,21 @@ const WorkflowFlow = () => {
<NodeContextMenu
canPaste={hasClipboardNodes}
menuState={contextMenu}
+ onAddConnector={(position) => {
+ addConnector(position);
+ setContextMenu(null);
+ }}
onClose={() => setContextMenu(null)}
onCopy={() => {
- copyNodes(contextMenu?.nodeId);
+ copyNodes(contextMenu?.kind === 'node' ? contextMenu.nodeId : undefined);
setContextMenu(null);
}}
onDelete={() => {
- deleteNodes(contextMenu?.nodeId);
+ deleteNodes(contextMenu?.kind === 'node' ? contextMenu.nodeId : undefined);
setContextMenu(null);
}}
onDuplicate={() => {
- duplicateNodes(contextMenu?.nodeId);
+ duplicateNodes(contextMenu?.kind === 'node' ? contextMenu.nodeId : undefined);
setContextMenu(null);
}}
onPaste={() => {
@@ -440,7 +573,7 @@ const WorkflowFlow = () => {
setContextMenu(null);
}}
onToggleOpen={() => {
- if (contextMenu && contextMenu.isNodeOpen !== null) {
+ if (contextMenu?.kind === 'node' && contextMenu.nodeId && contextMenu.isNodeOpen !== null) {
dispatch({
action: { isOpen: !contextMenu.isNodeOpen, nodeId: contextMenu.nodeId, type: 'setNodeIsOpen' },
type: 'applyProjectGraphAction',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts
index fe1e8fd83d..d219bb04c7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts
@@ -1,4 +1,11 @@
import { createExternalStore } from '../../externalStore';
+import type { FieldType, XYPosition } from '../../workflows/types';
+
+export interface AddNodeConnectionFilter {
+ sourceHandle: string;
+ sourceNodeId: string;
+ sourceType: FieldType;
+}
/**
* Session-lived UI coordination for the workflow widget. Menu items live
@@ -8,6 +15,8 @@ import { createExternalStore } from '../../externalStore';
*/
export interface WorkflowUiSnapshot {
+ addNodeConnection: AddNodeConnectionFilter | null;
+ addNodePosition: XYPosition | null;
isAddNodeOpen: boolean;
isLibraryOpen: boolean;
isNewWorkflowConfirmOpen: boolean;
@@ -22,6 +31,8 @@ export interface WorkflowUiSnapshot {
}
export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({
+ addNodeConnection: null,
+ addNodePosition: null,
dialogHostId: null,
importRequestCount: 0,
isAddNodeOpen: false,
@@ -50,8 +61,16 @@ export const setWorkflowLibraryOpen = (isOpen: boolean): void => {
workflowUiStore.patchSnapshot({ isLibraryOpen: isOpen });
};
-export const setAddNodeOpen = (isOpen: boolean): void => {
- workflowUiStore.patchSnapshot({ isAddNodeOpen: isOpen });
+export const setAddNodeOpen = (
+ isOpen: boolean,
+ position: XYPosition | null = null,
+ connection: AddNodeConnectionFilter | null = null
+): void => {
+ workflowUiStore.patchSnapshot({
+ addNodeConnection: isOpen ? connection : null,
+ addNodePosition: isOpen ? position : null,
+ isAddNodeOpen: isOpen,
+ });
};
export const setNewWorkflowConfirmOpen = (isOpen: boolean): void => {