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.

perf(webv2): isolate form-builder drop-target churn in its own context

joshistoastb03479150ee2
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx
index 553b89115f..50a1f8ceb2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx
@@ -46,7 +46,17 @@ import {
TextIcon,
XIcon,
} from 'lucide-react';
-import { createContext, use, useCallback, useMemo, useRef, useState, type ChangeEvent, type ReactNode } from 'react';
+import {
+ createContext,
+ memo,
+ use,
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+ type ChangeEvent,
+ type ReactNode,
+} from 'react';
import {
formEdgeDroppableId,
@@ -73,16 +83,25 @@ import { NodeFieldControl, useNodeFieldBinding } from './NodeFieldControl';
interface BuilderDndContextValue {
activeElementId: string | null;
- dropTarget: FormDropTarget | null;
form: WorkflowForm;
}
const BuilderDndContext = createContext<BuilderDndContextValue>({
activeElementId: null,
- dropTarget: null,
form: { elements: {}, rootElementId: '' },
});
+/**
+ * Split out from `BuilderDndContext`: `dropTarget` changes on every
+ * `onDragMove` frame while a drag is in flight, while `activeElementId`/
+ * `form` only change at drag start/end. Bundling them would force every
+ * card to re-render per pointer move (cards read `BuilderDndContext` for
+ * opacity/disabled state); only the drop-indicator components below read
+ * this one, so a move re-renders just the indicator for the affected card
+ * or container.
+ */
+const BuilderDropTargetContext = createContext<FormDropTarget | null>(null);
+
/** Title shown in a card's title bar and the drag ghost. Shared so the two never drift. */
const getFormElementTitle = (element: WorkflowFormElement): string => {
switch (element.type) {
@@ -120,8 +139,36 @@ const BuilderDragGhost = ({ element }: { element: WorkflowFormElement }) => (
</HStack>
);
+/**
+ * The edge drop-indicator line above/below a card. The only piece of a card
+ * that needs to know `dropTarget` — isolated into its own component so it's
+ * also the only piece that re-renders on every drag-move frame.
+ */
+const CardDropEdgeIndicator = ({ elementId }: { elementId: string }) => {
+ const dropTarget = use(BuilderDropTargetContext);
+ const edge = dropTarget?.kind === 'edge' && dropTarget.elementId === elementId ? dropTarget.edge : null;
+
+ if (!edge) {
+ return null;
+ }
+
+ return (
+ <Box
+ bg="accent.solid"
+ h="2px"
+ left="0"
+ pointerEvents="none"
+ position="absolute"
+ right="0"
+ rounded="full"
+ zIndex="1"
+ {...(edge === 'above' ? { top: '-1px' } : { bottom: '-1px' })}
+ />
+ );
+};
+
/** A builder card: typed title bar (drag handle + actions) over the element's content. */
-const BuilderCard = ({
+const BuilderCardBase = ({
children,
element,
extraActions,
@@ -139,7 +186,7 @@ const BuilderCard = ({
title: string;
}) => {
const { editGraph } = useProjectGraphCommands();
- const { activeElementId, dropTarget, form } = use(BuilderDndContext);
+ const { activeElementId, form } = use(BuilderDndContext);
const { attributes, listeners, setActivatorNodeRef, setNodeRef: setDragRef } = useDraggable({ id: element.id });
// The title bar is both the draggable node and its own drag handle, so it
// needs both refs: `setActivatorNodeRef` is what makes `KeyboardSensor`
@@ -159,23 +206,10 @@ const BuilderCard = ({
disabled: activeElementId !== null && isFormDescendantOrSelf(form, activeElementId, element.id),
id: formEdgeDroppableId(element.id),
});
- const edgeForThisCard = dropTarget?.kind === 'edge' && dropTarget.elementId === element.id ? dropTarget.edge : null;
return (
<Box ref={setDropRef} flex="1" minW="0" opacity={activeElementId === element.id ? 0.4 : 1} position="relative">
- {edgeForThisCard ? (
- <Box
- bg="accent.solid"
- h="2px"
- left="0"
- pointerEvents="none"
- position="absolute"
- right="0"
- rounded="full"
- zIndex="1"
- {...(edgeForThisCard === 'above' ? { top: '-1px' } : { bottom: '-1px' })}
- />
- ) : null}
+ <CardDropEdgeIndicator elementId={element.id} />
<Box
overflow="hidden"
position="relative"
@@ -222,19 +256,33 @@ const BuilderCard = ({
);
};
-/** Drop zone covering a container's body, appending at the end. Doubles as the empty-container hint. */
-const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElement; isEmpty: boolean }) => {
- const { activeElementId, dropTarget, form } = use(BuilderDndContext);
- const canDrop = activeElementId !== null && !isFormDescendantOrSelf(form, activeElementId, container.id);
- const { setNodeRef } = useDroppable({
- disabled: activeElementId === null || isFormDescendantOrSelf(form, activeElementId, container.id),
- id: formIntoDroppableId(container.id),
- });
- const isActive = dropTarget?.kind === 'into' && dropTarget.containerId === container.id;
+/**
+ * Memoized so a `dropTarget` change elsewhere in the form (a context update
+ * that only its parent `BuilderElement` would otherwise re-render for)
+ * doesn't cascade into every card — `BuilderCard` itself only reads
+ * `BuilderDndContext`, which changes solely at drag start/end.
+ */
+const BuilderCard = memo(BuilderCardBase);
- if (!canDrop && !isEmpty) {
- return null;
- }
+/**
+ * The container drop-zone's hover styling and "drop here" vs. "empty" copy.
+ * The only piece of `ContainerDropZone` that needs `dropTarget` — isolated
+ * into its own component so it's also the only piece that re-renders on
+ * every drag-move frame.
+ */
+const ContainerDropZoneBody = ({
+ canDrop,
+ containerId,
+ isEmpty,
+ setNodeRef,
+}: {
+ canDrop: boolean;
+ containerId: string;
+ isEmpty: boolean;
+ setNodeRef: (node: HTMLElement | null) => void;
+}) => {
+ const dropTarget = use(BuilderDropTargetContext);
+ const isActive = dropTarget?.kind === 'into' && dropTarget.containerId === containerId;
return (
<DropZone
@@ -252,6 +300,26 @@ const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormEle
);
};
+/** Drop zone covering a container's body, appending at the end. Doubles as the empty-container hint. */
+const ContainerDropZoneBase = ({ container, isEmpty }: { container: ContainerFormElement; isEmpty: boolean }) => {
+ const { activeElementId, form } = use(BuilderDndContext);
+ const canDrop = activeElementId !== null && !isFormDescendantOrSelf(form, activeElementId, container.id);
+ const { setNodeRef } = useDroppable({
+ disabled: activeElementId === null || isFormDescendantOrSelf(form, activeElementId, container.id),
+ id: formIntoDroppableId(container.id),
+ });
+
+ if (!canDrop && !isEmpty) {
+ return null;
+ }
+
+ return (
+ <ContainerDropZoneBody canDrop={canDrop} containerId={container.id} isEmpty={isEmpty} setNodeRef={setNodeRef} />
+ );
+};
+
+const ContainerDropZone = memo(ContainerDropZoneBase);
+
/** The shared description popover, bound through the form element. */
const FieldDescriptionAction = ({
element,
@@ -276,7 +344,7 @@ const FieldDescriptionAction = ({
);
};
-const BuilderElement = ({
+const BuilderElementBase = ({
element,
hoveredNodeId,
invalidElementIds,
@@ -424,6 +492,18 @@ const BuilderElement = ({
}
};
+/**
+ * Memoized so `FormBuilderTab`'s per-drag-move `dropTarget` state update
+ * (a plain `useState` re-render, unrelated to any of this component's own
+ * props) doesn't re-invoke every card's render function on every pointer
+ * move — none of `element`/`hoveredNodeId`/`invalidElementIds`/
+ * `projectGraph`/`selectedNodeIds` change mid-drag, so this bails and the
+ * `dropTarget` update only reaches the drop-indicator components that
+ * subscribe to `BuilderDropTargetContext` directly (context updates reach
+ * their consumers regardless of memoized ancestors in between).
+ */
+const BuilderElement = memo(BuilderElementBase);
+
const AddElementMenu = () => {
const { editGraph } = useProjectGraphCommands();
const add = (elementType: 'divider' | 'heading' | 'text' | 'container', layout?: 'row' | 'column') =>
@@ -616,8 +696,8 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta
);
const dndContextValue = useMemo<BuilderDndContextValue>(
- () => ({ activeElementId, dropTarget, form: projectGraph.form }),
- [activeElementId, dropTarget, projectGraph.form]
+ () => ({ activeElementId, form: projectGraph.form }),
+ [activeElementId, projectGraph.form]
);
const selectedNodeIdSet = useMemo(() => new Set(selectedNodeIds), [selectedNodeIds]);
const invalidElementIds = useMemo(
@@ -638,25 +718,27 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta
onDragStart={handleDragStart}
>
<BuilderDndContext value={dndContextValue}>
- <Stack gap="2" p="3" w="full">
- {rootChildren.length === 0 ? (
- <Text color="fg.subtle" fontSize="2xs">
- The form is empty. Pin fields from the Workflow editor's nodes, then arrange them here — drag card title
- bars to reorder, drop them into containers, and add headings or dividers below.
- </Text>
- ) : null}
- {rootChildren.map((element) => (
- <BuilderElement
- key={element.id}
- element={element}
- hoveredNodeId={hoveredNodeId}
- invalidElementIds={invalidElementIds}
- projectGraph={projectGraph}
- selectedNodeIds={selectedNodeIdSet}
- />
- ))}
- <AddElementMenu />
- </Stack>
+ <BuilderDropTargetContext value={dropTarget}>
+ <Stack gap="2" p="3" w="full">
+ {rootChildren.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ The form is empty. Pin fields from the Workflow editor's nodes, then arrange them here — drag card title
+ bars to reorder, drop them into containers, and add headings or dividers below.
+ </Text>
+ ) : null}
+ {rootChildren.map((element) => (
+ <BuilderElement
+ key={element.id}
+ element={element}
+ hoveredNodeId={hoveredNodeId}
+ invalidElementIds={invalidElementIds}
+ projectGraph={projectGraph}
+ selectedNodeIds={selectedNodeIdSet}
+ />
+ ))}
+ <AddElementMenu />
+ </Stack>
+ </BuilderDropTargetContext>
</BuilderDndContext>
<DragOverlay dropAnimation={null}>
{activeElement ? <BuilderDragGhost element={activeElement} /> : null}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx
index 5a94c29a08..7a7b14ae4b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx
@@ -1,21 +1,39 @@
+import type * as DndKitCoreModule from '@dnd-kit/core';
import type { ProjectGraphState } from '@features/workflow/contracts';
import type { WorkflowUiAdapter } from '@features/workflow/react';
import type { ProjectGraphAction } from '@features/workflow/utility';
import { ChakraProvider } from '@chakra-ui/react';
+import { useDroppable } from '@dnd-kit/core';
import { WorkflowUiProvider } from '@features/workflow/react';
import { createProjectGraph, projectGraphReducer } from '@features/workflow/utility';
import { system } from '@theme/system';
import { act, useCallback, useMemo, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
+import { formEdgeDroppableId } from './formBuilderDnd';
import { FormBuilderTab } from './FormBuilderTab';
import { PanelModeToggle } from './WorkflowLinearPanel';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+// This app is built with the React Compiler (`vite.config.mts`), which
+// auto-memoizes plain value computations inside components based on their
+// detected dependencies — so a spy on a pure helper a card's render calls
+// (e.g. `isFormDescendantOrSelf`) can't be trusted as a "did this card's
+// render function run" probe: the compiler can (and does) skip re-running
+// such a call even when the surrounding component *was* invoked. `dnd-kit`'s
+// `useDroppable` is a hook, and hook calls can never be skipped by the
+// compiler (they must run unconditionally, in order, every render), so a
+// real passthrough spy on it is a reliable per-card render probe instead.
+vi.mock('@dnd-kit/core', async (importOriginal) => {
+ const actual = await importOriginal<typeof DndKitCoreModule>();
+
+ return { ...actual, useDroppable: vi.fn(actual.useDroppable) };
+});
+
describe('Workflow Linear panel mode toggle', () => {
let host: HTMLDivElement;
let root: Root;
@@ -116,8 +134,8 @@ describe('Form builder drag and drop (dnd-kit)', () => {
return doc;
};
- const Harness = () => {
- const [projectGraph, setProjectGraph] = useState(buildInitialGraph);
+ const Harness = ({ initialGraph }: { initialGraph: ProjectGraphState }) => {
+ const [projectGraph, setProjectGraph] = useState(initialGraph);
const editGraph = useCallback((action: ProjectGraphAction) => {
setProjectGraph((current) => projectGraphReducer(current, action));
}, []);
@@ -145,11 +163,11 @@ describe('Form builder drag and drop (dnd-kit)', () => {
);
};
- const renderHarness = async () => {
+ const renderHarness = async (initialGraph: ProjectGraphState = buildInitialGraph()): Promise<void> => {
await act(() => {
root.render(
<ChakraProvider value={system}>
- <Harness />
+ <Harness initialGraph={initialGraph} />
</ChakraProvider>
);
});
@@ -354,4 +372,73 @@ describe('Form builder drag and drop (dnd-kit)', () => {
expect(headingIndex).toBeGreaterThanOrEqual(0);
expect(dividerIndex).toBeLessThan(headingIndex);
});
+
+ /**
+ * Perf isolation for `BuilderDropTargetContext`: `dropTarget` (per-move
+ * churn) lives apart from `BuilderDndContext`'s `activeElementId`/`form`
+ * (drag start/end only), and `BuilderElement` is memoized on props that
+ * don't change mid-drag — so a move that never targets "Divider" should
+ * never re-invoke its `BuilderCard`. Probed via the `useDroppable`
+ * passthrough spy (mocked at module scope above): `BuilderCard` calls it
+ * exactly once per render with `formEdgeDroppableId(element.id)`, and hook
+ * calls (unlike plain helper calls) can't be optimized away by the React
+ * Compiler, so a call carrying "Divider"'s edge-droppable id is direct,
+ * compiler-proof evidence its `BuilderCard` re-rendered.
+ */
+ it('does not re-render an unrelated card on a drag-move that only changes the drop target', async () => {
+ const initialGraph = buildInitialGraph();
+ const dividerId = Object.values(initialGraph.form.elements).find((element) => element.type === 'divider')!.id;
+ const dividerDroppableId = formEdgeDroppableId(dividerId);
+
+ await renderHarness(initialGraph);
+
+ // The empty-container hint's rect, captured *before* the drag starts —
+ // once a drag is active this card's `canDrop` flips true and its own
+ // text changes from "Empty container..." to "Drop here", so the text
+ // selector below would no longer match if read mid-drag.
+ const emptyHint = [...host.querySelectorAll<HTMLElement>('*')].find(
+ (element) => element.textContent === 'Empty container — drag elements here'
+ );
+
+ expect(emptyHint).toBeDefined();
+
+ const dropZoneRect = emptyHint!.getBoundingClientRect();
+ const midX = dropZoneRect.left + dropZoneRect.width / 2;
+ const midY = dropZoneRect.top + dropZoneRect.height / 2;
+
+ const handle = titleBarFor('Heading');
+ const startRect = handle.getBoundingClientRect();
+ const startX = startRect.left + startRect.width / 2;
+ const startY = startRect.top + startRect.height / 2;
+
+ // Arm the `PointerSensor` (>4px activation constraint), then settle onto
+ // the container's drop zone the same way `dragTo` does (a same-target
+ // no-op nudge — `MeasuringStrategy.Always`'s remeasure lands one tick
+ // after the move that triggered it, so a single move can still report a
+ // stale `over`). This establishes a real `into` `dropTarget`; only the
+ // moves *after* this point, which don't change the logical target, are
+ // under test.
+ await interact(() => pointer('pointerdown', handle, startX, startY));
+ await interact(() => pointer('pointermove', handle.ownerDocument, startX + 8, startY));
+ await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY));
+ await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 1));
+ vi.mocked(useDroppable).mockClear();
+
+ // Two more moves inside the same drop zone: `over` (and therefore the
+ // *logical* `dropTarget`) doesn't change, but `handleDragMove` still
+ // calls `setDropTarget` with a fresh object every time `onDragMove`
+ // fires — that per-frame churn, not touching "Divider" at all, is
+ // exactly what's under test.
+ await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 2));
+ await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 3));
+
+ const dividerCardRerendered = vi
+ .mocked(useDroppable)
+ .mock.calls.some(([options]) => options.id === dividerDroppableId);
+
+ expect(dividerCardRerendered).toBe(false);
+
+ // End the drag cleanly so it doesn't leak into other tests.
+ await interact(() => pointer('pointerup', handle.ownerDocument, midX, midY + 3));
+ });
});