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 connector context menu handling (#9107)

Jonathan68ed0f96e976
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
index 2fc5e12384..e67330df59 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
@@ -69,6 +69,8 @@ import ConnectorNode from './nodes/Connector/ConnectorNode';
import CurrentImageNode from './nodes/CurrentImage/CurrentImageNode';
import InvocationNodeWrapper from './nodes/Invocation/InvocationNodeWrapper';
import NotesNode from './nodes/Notes/NotesNode';
+import type { WorkflowContextMenuState } from './workflowContextMenu';
+import { getWorkflowContextMenuState } from './workflowContextMenu';
import { isWorkflowHotkeyEnabled, shouldIgnoreWorkflowCopyHotkey } from './workflowHotkeys';
const edgeTypes = {
@@ -90,54 +92,6 @@ const snapGrid: [number, number] = [25, 25];
const selectCancelConnection = (state: ReactFlowState) => state.cancelConnection;
-type WorkflowContextMenuState =
- | {
- kind: 'pane';
- clientX: number;
- clientY: number;
- pageX: number;
- pageY: number;
- }
- | {
- kind: 'connector';
- connectorId: string;
- pageX: number;
- pageY: number;
- }
- | null;
-
-const getWorkflowContextMenuState = (
- event: globalThis.MouseEvent,
- flowWrapper: HTMLDivElement | null
-): WorkflowContextMenuState => {
- if (event.shiftKey || !(event.target instanceof Element) || !flowWrapper?.contains(event.target)) {
- return null;
- }
-
- const connectorId = event.target.closest<HTMLElement>('[data-connector-node-id]')?.dataset.connectorNodeId;
- if (connectorId) {
- return {
- kind: 'connector',
- connectorId,
- pageX: event.pageX,
- pageY: event.pageY,
- };
- }
-
- const paneTarget = event.target.closest('.react-flow__pane');
- if (paneTarget && flowWrapper.contains(paneTarget)) {
- return {
- kind: 'pane',
- clientX: event.clientX,
- clientY: event.clientY,
- pageX: event.pageX,
- pageY: event.pageY,
- };
- }
-
- return null;
-};
-
export const Flow = memo(() => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
@@ -265,20 +219,20 @@ export const Flow = memo(() => {
);
const deleteConnectorFromContextMenu = useCallback(() => {
- if (contextMenuState?.kind !== 'connector' || !connectorSpliceConnections) {
+ if (contextMenuState?.kind !== 'connector') {
return;
}
const connectorEdgeRemovals: EdgeChange<AnyEdge>[] = edges
.filter((edge) => edge.source === contextMenuState.connectorId || edge.target === contextMenuState.connectorId)
.map((edge) => ({ type: 'remove', id: edge.id }));
- const spliceEdgeAdditions: EdgeChange<AnyEdge>[] = connectorSpliceConnections.map((connection) => ({
+ const spliceEdgeAdditions: EdgeChange<AnyEdge>[] = (connectorSpliceConnections ?? []).map((connection) => ({
type: 'add',
item: connectionToEdge(connection),
}));
pendingNodeInternalsUpdateRef.current = [
contextMenuState.connectorId,
- ...connectorSpliceConnections.flatMap((connection) => [connection.source, connection.target]),
+ ...(connectorSpliceConnections?.flatMap((connection) => [connection.source, connection.target]) ?? []),
];
dispatch(edgesChanged([...connectorEdgeRemovals, ...spliceEdgeAdditions]));
dispatch(nodesChanged([{ type: 'remove', id: contextMenuState.connectorId }]));
@@ -318,12 +272,7 @@ export const Flow = memo(() => {
if (contextMenuState?.kind === 'connector') {
return (
<MenuList visibility="visible">
- <MenuItem
- icon={<PiTrashBold />}
- onClick={deleteConnectorFromContextMenu}
- isDisabled={!connectorSpliceConnections}
- isDestructive
- >
+ <MenuItem icon={<PiTrashBold />} onClick={deleteConnectorFromContextMenu} isDestructive>
{t('nodes.deleteConnector')}
</MenuItem>
</MenuList>
@@ -331,7 +280,7 @@ export const Flow = memo(() => {
}
return <MenuList visibility="visible" />;
- }, [addConnectorAtPaneMenuPosition, connectorSpliceConnections, contextMenuState, deleteConnectorFromContextMenu, t]);
+ }, [addConnectorAtPaneMenuPosition, contextMenuState, deleteConnectorFromContextMenu, t]);
const closeContextMenu = useCallback(() => {
setContextMenuState(null);
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.test.ts b/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.test.ts
new file mode 100644
index 0000000000..c102064fe5
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWorkflowContextMenuState } from './workflowContextMenu';
+
+class FakeElement {
+ readonly children: FakeElement[] = [];
+ readonly dataset: Record<string, string> = {};
+ parent: FakeElement | null = null;
+
+ constructor(
+ readonly tagName: string,
+ readonly options: { className?: string; attrs?: Record<string, string>; dataset?: Record<string, string> } = {}
+ ) {
+ if (options.dataset) {
+ Object.assign(this.dataset, options.dataset);
+ }
+ }
+
+ appendChild(child: FakeElement): FakeElement {
+ child.parent = this;
+ this.children.push(child);
+ return child;
+ }
+
+ contains(target: FakeElement): boolean {
+ return target === this || this.children.some((child) => child.contains(target));
+ }
+
+ closest(selector: string): FakeElement | null {
+ const selectors = selector.split(',').map((s) => s.trim());
+ let current: FakeElement | null = this.parent;
+ if (selectors.some((selector) => this.matches(selector))) {
+ return this;
+ }
+ while (current) {
+ if (selectors.some((selector) => current?.matches(selector))) {
+ return current;
+ }
+ current = current.parent;
+ }
+ return null;
+ }
+
+ private matches(selector: string): boolean {
+ if (selector.startsWith('.')) {
+ return this.options.className?.split(' ').includes(selector.slice(1)) ?? false;
+ }
+
+ if (selector === '[data-connector-node-id]') {
+ return typeof this.dataset.connectorNodeId === 'string';
+ }
+
+ if (selector === 'a[href]') {
+ return this.tagName === 'a' && typeof this.options.attrs?.href === 'string';
+ }
+
+ if (selector === '[contenteditable="true"]') {
+ return this.options.attrs?.contenteditable === 'true';
+ }
+
+ if (selector === '[contenteditable=""]') {
+ return this.options.attrs?.contenteditable === '';
+ }
+
+ if (selector === '[role="textbox"]') {
+ return this.options.attrs?.role === 'textbox';
+ }
+
+ return this.tagName === selector;
+ }
+}
+
+const buildEvent = (target: FakeElement, shiftKey = false) =>
+ ({
+ shiftKey,
+ target,
+ clientX: 10,
+ clientY: 20,
+ pageX: 30,
+ pageY: 40,
+ }) as unknown as MouseEvent;
+
+const buildFlow = () => {
+ const wrapper = new FakeElement('div');
+ const pane = wrapper.appendChild(new FakeElement('div', { className: 'react-flow__pane' }));
+ return { wrapper, pane };
+};
+
+describe('getWorkflowContextMenuState', () => {
+ it('opens the add connector menu for pane descendants', () => {
+ const { wrapper, pane } = buildFlow();
+ const background = pane.appendChild(new FakeElement('svg'));
+
+ expect(getWorkflowContextMenuState(buildEvent(background), wrapper as unknown as HTMLDivElement)).toEqual({
+ kind: 'pane',
+ clientX: 10,
+ clientY: 20,
+ pageX: 30,
+ pageY: 40,
+ });
+ });
+
+ it('opens the connector menu for connector nodes even though they are inside a ReactFlow node', () => {
+ const { wrapper, pane } = buildFlow();
+ const node = pane.appendChild(new FakeElement('div', { className: 'react-flow__node' }));
+ const connector = node.appendChild(
+ new FakeElement('div', { dataset: { connectorNodeId: 'connector-1' }, className: 'nodrag' })
+ );
+
+ expect(getWorkflowContextMenuState(buildEvent(connector), wrapper as unknown as HTMLDivElement)).toEqual({
+ kind: 'connector',
+ connectorId: 'connector-1',
+ pageX: 30,
+ pageY: 40,
+ });
+ });
+
+ it('does not open the add connector menu for interactive fields inside a node', () => {
+ const { wrapper, pane } = buildFlow();
+ const node = pane.appendChild(new FakeElement('div', { className: 'react-flow__node' }));
+ const input = node.appendChild(new FakeElement('input'));
+
+ expect(getWorkflowContextMenuState(buildEvent(input), wrapper as unknown as HTMLDivElement)).toBeNull();
+ });
+
+ it('does not open the add connector menu for image field areas inside a node', () => {
+ const { wrapper, pane } = buildFlow();
+ const node = pane.appendChild(new FakeElement('div', { className: 'react-flow__node' }));
+ const imageField = node.appendChild(new FakeElement('div', { className: 'nodrag' }));
+
+ expect(getWorkflowContextMenuState(buildEvent(imageField), wrapper as unknown as HTMLDivElement)).toBeNull();
+ });
+
+ it('allows the native context menu on shift right click', () => {
+ const { wrapper, pane } = buildFlow();
+
+ expect(getWorkflowContextMenuState(buildEvent(pane, true), wrapper as unknown as HTMLDivElement)).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.ts b/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.ts
new file mode 100644
index 0000000000..18d4933677
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/workflowContextMenu.ts
@@ -0,0 +1,75 @@
+import { NO_DRAG_CLASS, NO_PAN_CLASS, NO_WHEEL_CLASS } from 'features/nodes/types/constants';
+
+export type WorkflowContextMenuState =
+ | {
+ kind: 'pane';
+ clientX: number;
+ clientY: number;
+ pageX: number;
+ pageY: number;
+ }
+ | {
+ kind: 'connector';
+ connectorId: string;
+ pageX: number;
+ pageY: number;
+ }
+ | null;
+
+const INTERACTIVE_CONTEXT_MENU_SELECTOR = [
+ 'input',
+ 'textarea',
+ 'select',
+ 'option',
+ 'button',
+ 'a[href]',
+ '[contenteditable="true"]',
+ '[contenteditable=""]',
+ '[role="textbox"]',
+ `.${NO_DRAG_CLASS}`,
+ `.${NO_PAN_CLASS}`,
+ `.${NO_WHEEL_CLASS}`,
+ '.react-flow__node',
+].join(',');
+
+const isElementLike = (target: EventTarget | null): target is Element =>
+ typeof target === 'object' &&
+ target !== null &&
+ 'closest' in target &&
+ typeof (target as { closest?: unknown }).closest === 'function';
+
+export const getWorkflowContextMenuState = (
+ event: Pick<globalThis.MouseEvent, 'shiftKey' | 'target' | 'clientX' | 'clientY' | 'pageX' | 'pageY'>,
+ flowWrapper: Pick<HTMLDivElement, 'contains'> | null
+): WorkflowContextMenuState => {
+ if (event.shiftKey || !isElementLike(event.target) || !flowWrapper?.contains(event.target)) {
+ return null;
+ }
+
+ const connectorId = event.target.closest<HTMLElement>('[data-connector-node-id]')?.dataset.connectorNodeId;
+ if (connectorId) {
+ return {
+ kind: 'connector',
+ connectorId,
+ pageX: event.pageX,
+ pageY: event.pageY,
+ };
+ }
+
+ if (event.target.closest(INTERACTIVE_CONTEXT_MENU_SELECTOR)) {
+ return null;
+ }
+
+ const paneTarget = event.target.closest('.react-flow__pane');
+ if (paneTarget && flowWrapper.contains(paneTarget)) {
+ return {
+ kind: 'pane',
+ clientX: event.clientX,
+ clientY: event.clientY,
+ pageX: event.pageX,
+ pageY: event.pageY,
+ };
+ }
+
+ return null;
+};
diff --git a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts
index 5306347921..f331692b43 100644
--- a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts
@@ -19,6 +19,22 @@ const buildFixedConnectorNode = (id: string) => {
};
describe('nodesSlice connector actions', () => {
+ it('removes an unconnected connector', () => {
+ const connector = buildFixedConnectorNode('connector-1');
+
+ const initialState = deepClone(nodesSliceConfig.slice.reducer(undefined, { type: 'test/init' }));
+ initialState.nodes = [connector];
+ initialState.edges = [];
+
+ const nextState = nodesSliceConfig.slice.reducer(
+ initialState,
+ nodesChanged([{ type: 'remove', id: connector.id }])
+ );
+
+ expect(nextState.nodes).toEqual([]);
+ expect(nextState.edges).toEqual([]);
+ });
+
it('splits a direct edge into source -> connector -> target edges when inserting a connector', () => {
const source = buildNode(add);
const target = buildNode(sub);