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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): form builder dnd-kit port
joshistoast735760ddb3db
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsxindex 8ae630c327..70a768dedb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx@@ -1,11 +1,28 @@import { Box, HStack, Icon, Input, Menu, Portal, Separator, Stack, Text, Textarea } from '@chakra-ui/react';/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */+import {+ DndContext,+ DragOverlay,+ MeasuringStrategy,+ PointerSensor,+ pointerWithin,+ rectIntersection,+ useDraggable,+ useDroppable,+ useSensor,+ useSensors,+ type CollisionDetection,+ type DragEndEvent,+ type DragMoveEvent,+ type DragStartEvent,+} from '@dnd-kit/core';import {isInvocationNode,type ContainerFormElement,type InvocationTemplates,type NodeFieldFormElement,type ProjectGraphState,+ type WorkflowForm,type WorkflowFormElement,} from '@features/workflow/contracts';import { useInvocationTemplatesSelector, type InvocationTemplatesSnapshot } from '@features/workflow/react';@@ -28,8 +45,16 @@ import {TextIcon,XIcon,} from 'lucide-react';-import { createContext, use, useMemo, useState, type ChangeEvent, type DragEvent, type ReactNode } from 'react';+import { createContext, use, useCallback, useMemo, useState, type ChangeEvent, type ReactNode } from 'react';+import {+ formEdgeDroppableId,+ formIntoDroppableId,+ isFormDescendantOrSelf,+ parseFormDroppableId,+ resolveFormDrop,+ type FormDropTarget,+} from './formBuilderDnd';import { NodeFieldControl, useNodeFieldBinding } from './NodeFieldControl';/**@@ -37,100 +62,91 @@ import { NodeFieldControl, useNodeFieldBinding } from './NodeFieldControl';* card with its own title bar — type label on the left, actions on the right,* content below — mirroring the legacy builder. Cards reorder and reparent by* dragging their title bar (drop indicators above/below, containers accept- * drops into their body). All edits go through the project graph document- * reducer.+ * drops into their body) via dnd-kit: moves happen only at `onDragEnd`, which+ * fires at the `DndContext` level regardless of whether the drop reparents+ * (and therefore remounts) the dragged card. All edits go through the+ * project graph document reducer.*/interface BuilderDndContextValue {- draggingElementId: string | null;- setDraggingElementId: (elementId: string | null) => void;+ activeElementId: string | null;+ dropTarget: FormDropTarget | null;+ form: WorkflowForm;}const BuilderDndContext = createContext<BuilderDndContextValue>({- draggingElementId: null,- setDraggingElementId: () => undefined,+ activeElementId: null,+ dropTarget: null,+ form: { elements: {}, rootElementId: '' },});-type DropEdge = 'above' | 'below';+/** 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) {+ case 'container':+ return `Container (${element.data.layout} layout)`;+ case 'node-field':+ return 'Node Field';+ case 'heading':+ return 'Heading';+ case 'text':+ return 'Text';+ case 'divider':+ return 'Divider';+ }+};++/** The dragged card's `DragOverlay` ghost: a compact title bar following the pointer. */+const BuilderDragGhost = ({ element }: { element: WorkflowFormElement }) => (+ <HStack+ bg="bg.muted"+ borderColor="border.subtle"+ borderWidth="1px"+ cursor="grabbing"+ gap="1"+ opacity={0.85}+ px="1.5"+ py="0.5"+ rounded="md"+ shadow="md"+ >+ <Icon as={GripVerticalIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ <Text color="fg.muted" fontSize="2xs" fontWeight="600" minW="0" truncate>+ {getFormElementTitle(element)}+ </Text>+ </HStack>+);/** A builder card: typed title bar (drag handle + actions) over the element's content. */const BuilderCard = ({children,element,extraActions,- index,isHovered,isInvalid,isSelected,- parentId,title,}: {children: ReactNode;element: WorkflowFormElement;extraActions?: ReactNode;- index: number;isHovered?: boolean;isInvalid?: boolean;isSelected?: boolean;- parentId: string;title: string;}) => {const { editGraph } = useProjectGraphCommands();- const { draggingElementId, setDraggingElementId } = use(BuilderDndContext);- const [isDragArmed, setIsDragArmed] = useState(false);- const [dropEdge, setDropEdge] = useState<DropEdge | null>(null);- const isDropTarget = draggingElementId !== null && draggingElementId !== element.id;-- const onDragOver = (event: DragEvent<HTMLDivElement>) => {- if (!isDropTarget) {- return;- }-- event.preventDefault();- event.stopPropagation();-- const bounds = event.currentTarget.getBoundingClientRect();-- setDropEdge(event.clientY < bounds.top + bounds.height / 2 ? 'above' : 'below');- };-- const onDrop = (event: DragEvent<HTMLDivElement>) => {- if (!isDropTarget || !draggingElementId || !dropEdge) {- return;- }-- event.preventDefault();- event.stopPropagation();- editGraph({- elementId: draggingElementId,- index: dropEdge === 'above' ? index : index + 1,- parentId,- type: 'moveFormElementTo',- });- setDropEdge(null);- };+ const { activeElementId, dropTarget, form } = use(BuilderDndContext);+ const { attributes, listeners, setNodeRef: setDragRef } = useDraggable({ id: element.id });+ const { setNodeRef: setDropRef } = useDroppable({+ 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- draggable={isDragArmed}- flex="1"- minW="0"- opacity={draggingElementId === element.id ? 0.4 : 1}- position="relative"- onDragEnd={() => {- setDraggingElementId(null);- setIsDragArmed(false);- }}- onDragLeave={() => setDropEdge(null)}- onDragOver={onDragOver}- onDragStart={(event: DragEvent<HTMLDivElement>) => {- event.stopPropagation();- event.dataTransfer.effectAllowed = 'move';- setDraggingElementId(element.id);- }}- onDrop={onDrop}- >- {dropEdge ? (+ <Box ref={setDropRef} flex="1" minW="0" opacity={activeElementId === element.id ? 0.4 : 1} position="relative">+ {edgeForThisCard ? (<Boxbg="accent.solid"h="2px"@@ -140,7 +156,7 @@ const BuilderCard = ({right="0"rounded="full"zIndex="1"- {...(dropEdge === 'above' ? { top: '-1px' } : { bottom: '-1px' })}+ {...(edgeForThisCard === 'above' ? { top: '-1px' } : { bottom: '-1px' })}/>) : null}<Box@@ -150,6 +166,7 @@ const BuilderCard = ({{...getWorkflowNodeChromeProps({ invalid: Boolean(isInvalid), selected: Boolean(isHovered || isSelected) })}><HStack+ ref={setDragRef}bg="bg.muted"borderBottomWidth="1px"borderColor="border.subtle"@@ -160,8 +177,8 @@ const BuilderCard = ({position="relative"zIndex="2"_active={{ cursor: 'grabbing' }}- onPointerDown={() => setIsDragArmed(true)}- onPointerUp={() => setIsDragArmed(false)}+ {...attributes}+ {...listeners}><Icon as={GripVerticalIcon} boxSize="3" color="fg.subtle" flexShrink={0} /><Text color="fg.muted" fontSize="2xs" fontWeight="600" minW="0" truncate>@@ -190,10 +207,13 @@ 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 { editGraph } = useProjectGraphCommands();- const { draggingElementId } = use(BuilderDndContext);- const [isActive, setIsActive] = useState(false);- const canDrop = draggingElementId !== null && draggingElementId !== container.id;+ 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;if (!canDrop && !isEmpty) {return null;@@ -201,6 +221,7 @@ const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElereturn (<DropZone+ ref={setNodeRef}alignSelf="stretch"flex={isEmpty ? '1' : undefined}fontSize="2xs"@@ -208,29 +229,6 @@ const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElepx="2"py="1.5"textAlign="center"- onDragLeave={() => setIsActive(false)}- onDragOver={(event: DragEvent<HTMLDivElement>) => {- if (canDrop) {- event.preventDefault();- event.stopPropagation();- setIsActive(true);- }- }}- onDrop={(event: DragEvent<HTMLDivElement>) => {- if (!canDrop || !draggingElementId) {- return;- }-- event.preventDefault();- event.stopPropagation();- editGraph({- elementId: draggingElementId,- index: container.data.children.length,- parentId: container.id,- type: 'moveFormElementTo',- });- setIsActive(false);- }}>{canDrop ? 'Drop here' : 'Empty container — drag elements here'}</DropZone>@@ -263,18 +261,14 @@ const FieldDescriptionAction = ({const BuilderElement = ({element,- index,hoveredNodeId,- parentId,- projectGraph,invalidElementIds,+ projectGraph,selectedNodeIds,}: {element: WorkflowFormElement;- index: number;hoveredNodeId: string | null;invalidElementIds: Set<string>;- parentId: string;projectGraph: ProjectGraphState;selectedNodeIds: Set<string>;}) => {@@ -301,19 +295,15 @@ const BuilderElement = ({<Icon as={isRow ? Rows2Icon : Columns2Icon} boxSize="3" /></IconButton>}- index={index}- parentId={parentId}- title={`Container (${element.data.layout} layout)`}+ title={getFormElementTitle(element)}><Stack align={isRow ? 'stretch' : undefined} direction={isRow ? 'row' : 'column'} gap="2" w="full">- {getFormChildren(projectGraph.form, element.id).map((child, childIndex) => (+ {getFormChildren(projectGraph.form, element.id).map((child) => (<BuilderElementkey={child.id}element={child}hoveredNodeId={hoveredNodeId}invalidElementIds={invalidElementIds}- index={childIndex}- parentId={element.id}projectGraph={projectGraph}selectedNodeIds={selectedNodeIds}/>@@ -360,12 +350,10 @@ const BuilderElement = ({</IconButton></>}- index={index}isHovered={element.data.fieldIdentifier.nodeId === hoveredNodeId}isInvalid={invalidElementIds.has(element.id)}isSelected={selectedNodeIds.has(element.data.fieldIdentifier.nodeId)}- parentId={parentId}- title="Node Field"+ title={getFormElementTitle(element)}><NodeFieldControl element={element} isLabelEditable projectGraph={projectGraph} /></BuilderCard>@@ -373,7 +361,7 @@ const BuilderElement = ({}case 'heading': {return (- <BuilderCard element={element} index={index} parentId={parentId} title="Heading">+ <BuilderCard element={element} title={getFormElementTitle(element)}><Inputaria-label="Form heading"fontSize="sm"@@ -391,7 +379,7 @@ const BuilderElement = ({}case 'text': {return (- <BuilderCard element={element} index={index} parentId={parentId} title="Text">+ <BuilderCard element={element} title={getFormElementTitle(element)}><Textareaaria-label="Form text"color="fg.muted"@@ -411,7 +399,7 @@ const BuilderElement = ({}case 'divider': {return (- <BuilderCard element={element} index={index} parentId={parentId} title="Divider">+ <BuilderCard element={element} title={getFormElementTitle(element)}><Separator borderColor="border.subtle" /></BuilderCard>);@@ -514,10 +502,79 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphStaconst templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const hoveredNodeId = workflowSelectionStore.useSelector((snapshot) => snapshot.hoveredNodeId);const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);- const [draggingElementId, setDraggingElementId] = useState<string | null>(null);+ const { editGraph } = useProjectGraphCommands();+ const [activeElementId, setActiveElementId] = useState<string | null>(null);+ const [dropTarget, setDropTarget] = useState<FormDropTarget | null>(null);+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));+ // Droppable rects freeze at drag start by default; the builder's drop+ // indicators and container hints appear mid-drag, so re-measure continuously.+ const measuring = useMemo(() => ({ droppable: { strategy: MeasuringStrategy.Always } }), []);+ const collisionDetection: CollisionDetection = useCallback((args) => {+ const within = pointerWithin(args);+ return within.length > 0 ? within : rectIntersection(args);+ }, []);++ const handleDragStart = useCallback((event: DragStartEvent) => {+ setActiveElementId(String(event.active.id));+ }, []);+ const handleDragMove = useCallback((event: DragMoveEvent) => {+ const { active, over } = event;++ if (!over) {+ setDropTarget(null);+ return;+ }++ const parsed = parseFormDroppableId(String(over.id));++ if (!parsed) {+ setDropTarget(null);+ return;+ }++ if (parsed.kind === 'into') {+ setDropTarget({ containerId: parsed.containerId, kind: 'into' });+ return;+ }++ const activeRect = active.rect.current.translated;+ const pointerY = activeRect ? activeRect.top + activeRect.height / 2 : over.rect.top;++ setDropTarget({+ edge: pointerY < over.rect.top + over.rect.height / 2 ? 'above' : 'below',+ elementId: parsed.elementId,+ kind: 'edge',+ });+ }, []);+ const clearDrag = useCallback(() => {+ setActiveElementId(null);+ setDropTarget(null);+ }, []);+ const handleDragEnd = useCallback(+ (event: DragEndEvent) => {+ const activeId = String(event.active.id);++ if (dropTarget) {+ const resolved = resolveFormDrop(projectGraph.form, activeId, dropTarget);++ if (resolved) {+ editGraph({+ elementId: activeId,+ index: resolved.index,+ parentId: resolved.parentId,+ type: 'moveFormElementTo',+ });+ }+ }++ clearDrag();+ },+ [clearDrag, dropTarget, editGraph, projectGraph.form]+ );+const dndContextValue = useMemo<BuilderDndContextValue>(- () => ({ draggingElementId, setDraggingElementId }),- [draggingElementId]+ () => ({ activeElementId, dropTarget, form: projectGraph.form }),+ [activeElementId, dropTarget, projectGraph.form]);const selectedNodeIdSet = useMemo(() => new Set(selectedNodeIds), [selectedNodeIds]);const invalidElementIds = useMemo(@@ -525,30 +582,42 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta[projectGraph, templatesStatus, templates]);const rootChildren = getFormChildren(projectGraph.form);+ const activeElement = activeElementId ? projectGraph.form.elements[activeElementId] : undefined;return (- <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, index) => (- <BuilderElement- key={element.id}- element={element}- hoveredNodeId={hoveredNodeId}- invalidElementIds={invalidElementIds}- index={index}- parentId={projectGraph.form.rootElementId}- projectGraph={projectGraph}- selectedNodeIds={selectedNodeIdSet}- />- ))}- <AddElementMenu />- </Stack>- </BuilderDndContext>+ <DndContext+ collisionDetection={collisionDetection}+ measuring={measuring}+ sensors={sensors}+ onDragCancel={clearDrag}+ onDragEnd={handleDragEnd}+ onDragMove={handleDragMove}+ 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>+ </BuilderDndContext>+ <DragOverlay dropAnimation={null}>+ {activeElement ? <BuilderDragGhost element={activeElement} /> : null}+ </DragOverlay>+ </DndContext>);};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.tsxindex 03bd98f17e..ba0bd6bc24 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,10 +1,17 @@+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 { WorkflowUiProvider } from '@features/workflow/react';+import { createProjectGraph, projectGraphReducer } from '@features/workflow/utility';import { system } from '@theme/system';-import { act, useState } from 'react';+import { act, useCallback, useMemo, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { userEvent } from 'vitest/browser';+import { FormBuilderTab } from './FormBuilderTab';import { PanelModeToggle } from './WorkflowLinearPanel';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -72,3 +79,182 @@ describe('Workflow Linear panel mode toggle', () => {expect(selection(tabs)).toEqual(['false', 'true']);});});++/**+ * Regression coverage for the native-DnD bug: dropping a card into a+ * container reparents it, React remounts the card under its new parent, and+ * the native `dragend` event (bound to the old node) never fires — leaving+ * the module's dragging state stuck and killing every drag after it. The+ * dnd-kit port resolves moves only in `onDragEnd` at the `DndContext` level,+ * which fires regardless of node unmounts, so a second drag right after a+ * reparenting drop must still work.+ */+describe('Form builder drag and drop (dnd-kit)', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.width = '480px';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ /** root -> [heading "Field A", divider, container(column, empty)] */+ const buildInitialGraph = (): ProjectGraphState => {+ let doc = createProjectGraph('form-dnd-test');++ doc = projectGraphReducer(doc, { content: 'Field A', elementType: 'heading', type: 'addFormElement' });+ doc = projectGraphReducer(doc, { elementType: 'divider', type: 'addFormElement' });+ doc = projectGraphReducer(doc, { elementType: 'container', layout: 'column', type: 'addFormElement' });++ return doc;+ };++ const Harness = () => {+ const [projectGraph, setProjectGraph] = useState(buildInitialGraph);+ const editGraph = useCallback((action: ProjectGraphAction) => {+ setProjectGraph((current) => projectGraphReducer(current, action));+ }, []);+ const adapter = useMemo(+ () =>+ ({+ commands: {+ bindLibraryWorkflow: () => undefined,+ editGraph,+ redo: () => undefined,+ replace: () => undefined,+ restoreSnapshot: () => undefined,+ saveSnapshot: () => undefined,+ undo: () => undefined,+ },+ widgets: { open: () => undefined, patchValues: () => undefined },+ }) as unknown as WorkflowUiAdapter,+ [editGraph]+ );++ return (+ <WorkflowUiProvider adapter={adapter}>+ <FormBuilderTab projectGraph={projectGraph} />+ </WorkflowUiProvider>+ );+ };++ const renderHarness = async () => {+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <Harness />+ </ChakraProvider>+ );+ });+ };++ /** The title-bar `HStack` is the drag handle: it's the direct DOM parent of its title `Text`. */+ const titleBarFor = (title: string): HTMLElement => {+ const leaf = [...host.querySelectorAll<HTMLElement>('*')].find(+ (element) => element.children.length === 0 && element.textContent?.trim() === title+ );++ if (!leaf?.parentElement) {+ throw new Error(`title bar not found for "${title}"`);+ }++ return leaf.parentElement;+ };++ /** The card's content `Box` — the title bar's rounded-chrome parent's second (and last) child. */+ const cardContentFor = (title: string): HTMLElement => {+ const chrome = titleBarFor(title).parentElement;+ const content = chrome?.lastElementChild;++ if (!(content instanceof HTMLElement)) {+ throw new Error(`card content not found for "${title}"`);+ }++ return content;+ };++ const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {+ target.dispatchEvent(+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })+ );+ };++ // dnd-kit's continuous droppable re-measuring (`MeasuringStrategy.Always`)+ // and sensor activation run on their own rAF-scheduled updates outside+ // React's synchronous event handling, so each step needs a real tick to+ // settle before the next one — a bare `act(() => pointer(...))` leaves+ // `over` stale and the drop resolves against the wrong (or no) target.+ const interact = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 50);+ });+ });++ /** Drags `sourceTitle`'s title bar to `(x, y)` with a >4px jitter move first to arm the PointerSensor. */+ const dragTo = async (sourceTitle: string, x: number, y: number): Promise<void> => {+ const handle = titleBarFor(sourceTitle);+ const startRect = handle.getBoundingClientRect();+ const startX = startRect.left + startRect.width / 2;+ const startY = startRect.top + startRect.height / 2;++ await interact(() => pointer('pointerdown', handle, startX, startY));+ await interact(() => pointer('pointermove', handle.ownerDocument, startX + 8, startY));+ await interact(() => pointer('pointermove', handle.ownerDocument, x, y));+ // A `MeasuringStrategy.Always` remeasure lands one tick after the move+ // that triggered it, so the move's own `onDragMove` can still report a+ // stale `over`. A no-op settle move re-runs collision detection against+ // the now-current rects before the drop.+ await interact(() => pointer('pointermove', handle.ownerDocument, x, y + 1));+ await interact(() => pointer('pointerup', handle.ownerDocument, x, y + 1));+ };++ it('keeps dragging alive after a field is dropped into a container', async () => {+ await renderHarness();++ // Drag 1: "Field A" (a heading) into the empty container's drop zone.+ const emptyHint = [...host.querySelectorAll<HTMLElement>('*')].find(+ (element) => element.textContent === 'Empty container — drag elements here'+ );++ expect(emptyHint).toBeDefined();++ const dropZoneRect = emptyHint!.getBoundingClientRect();++ await dragTo('Heading', dropZoneRect.left + dropZoneRect.width / 2, dropZoneRect.top + dropZoneRect.height / 2);++ // The container's card content now holds the heading card, and the+ // empty-state hint is gone.+ const containerContent = cardContentFor('Container (column layout)');++ expect(containerContent.textContent).toContain('Heading');+ expect(containerContent.textContent).not.toContain('Empty container');++ // Drag 2: THE REGRESSION ASSERTION. "Divider" (still at the root) drops+ // onto the now-nested "Heading" card's lower edge. Under the old native+ // DnD implementation, drag 1's reparent remount lost `dragend` and left+ // `draggingElementId` stuck — this second drag would never start.+ const headingCardRect = titleBarFor('Heading').parentElement!.getBoundingClientRect();++ await dragTo('Divider', headingCardRect.left + headingCardRect.width / 2, headingCardRect.bottom - 2);++ // The divider moved into the container, next to the heading.+ const containerContentAfter = cardContentFor('Container (column layout)');++ expect(containerContentAfter.textContent).toContain('Heading');+ expect(containerContentAfter.textContent).toContain('Divider');++ // No card is left stuck at the mid-drag 40% opacity.+ const opacities = [...host.querySelectorAll<HTMLElement>('*')].map((element) => getComputedStyle(element).opacity);++ expect(opacities).not.toContain('0.4');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.tsnew file mode 100644index 0000000000..5312743ced--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts@@ -0,0 +1,80 @@+import type { WorkflowForm } from '@features/workflow/contracts';++import { describe, expect, it } from 'vitest';++import { findFormParentId, isFormDescendantOrSelf, resolveFormDrop } from './formBuilderDnd';++/**+ * root -> [fieldA, container1 -> [fieldB], fieldC]+ * Mirrors the shape `getFormChildren` walks: a root container element in+ * `form.elements` whose `data.children` list the top-level elements, each+ * carrying its own `parentId` back to its container (exactly what+ * `moveFormElementTo` maintains in `core/document.ts`).+ */+const buildFormFixture = (): WorkflowForm => ({+ elements: {+ container1: {+ data: { children: ['fieldB'], layout: 'column' },+ id: 'container1',+ parentId: 'root',+ type: 'container',+ },+ fieldA: { data: { content: '' }, id: 'fieldA', parentId: 'root', type: 'heading' },+ fieldB: { data: { content: '' }, id: 'fieldB', parentId: 'container1', type: 'heading' },+ fieldC: { data: { content: '' }, id: 'fieldC', parentId: 'root', type: 'heading' },+ root: { data: { children: ['fieldA', 'container1', 'fieldC'], layout: 'column' }, id: 'root', type: 'container' },+ },+ rootElementId: 'root',+});++const form = buildFormFixture();++describe('resolveFormDrop', () => {+ it('drops above a root sibling at its index', () => {+ expect(resolveFormDrop(form, 'fieldC', { edge: 'above', elementId: 'fieldA', kind: 'edge' })).toEqual({+ index: 0,+ parentId: form.rootElementId,+ });+ });++ it('drops below a nested element inside its container', () => {+ expect(resolveFormDrop(form, 'fieldA', { edge: 'below', elementId: 'fieldB', kind: 'edge' })).toEqual({+ index: 1,+ parentId: 'container1',+ });+ });++ it('appends into a container body', () => {+ expect(resolveFormDrop(form, 'fieldA', { containerId: 'container1', kind: 'into' })).toEqual({+ index: 1,+ parentId: 'container1',+ });+ });++ it('rejects dropping a container into itself or a descendant', () => {+ expect(resolveFormDrop(form, 'container1', { containerId: 'container1', kind: 'into' })).toBeNull();+ expect(resolveFormDrop(form, 'container1', { edge: 'above', elementId: 'fieldB', kind: 'edge' })).toBeNull();+ });++ it('rejects dropping an element onto itself', () => {+ expect(resolveFormDrop(form, 'fieldA', { edge: 'above', elementId: 'fieldA', kind: 'edge' })).toBeNull();+ });+});++describe('isFormDescendantOrSelf', () => {+ it('sees a nested child as a descendant', () => {+ expect(isFormDescendantOrSelf(form, 'container1', 'fieldB')).toBe(true);+ expect(isFormDescendantOrSelf(form, 'container1', 'fieldA')).toBe(false);+ });+});++describe('findFormParentId', () => {+ it('finds root and container parents', () => {+ expect(findFormParentId(form, 'fieldA')).toBe(form.rootElementId);+ expect(findFormParentId(form, 'fieldB')).toBe('container1');+ });++ it('returns null for the root element itself', () => {+ expect(findFormParentId(form, form.rootElementId)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.tsnew file mode 100644index 0000000000..4f591758a6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts@@ -0,0 +1,88 @@+import type { WorkflowForm } from '@features/workflow/contracts';++/**+ * Pure dnd-kit plumbing for the form builder: droppable id encoding/decoding+ * and the drop-target -> reparent resolution the old native-DnD `onDrop`+ * handlers computed inline. Kept side-effect free so it can be unit tested+ * without mounting the builder; `FormBuilderTab` only wires this to+ * `editGraph({ type: 'moveFormElementTo', ... })` at `onDragEnd`.+ *+ * `WorkflowForm` elements each carry their own `parentId` (maintained by+ * `moveFormElementTo` in `core/document.ts`), so parent lookup is a direct+ * read rather than a scan over every container — mirrors how `getFormChildren`+ * resolves the root the same as any other container (`form.elements[id]`,+ * `type === 'container'`).+ */++export type FormDropTarget =+ | { kind: 'edge'; elementId: string; edge: 'above' | 'below' }+ | { kind: 'into'; containerId: string };++export const formEdgeDroppableId = (elementId: string): string => `edge:${elementId}`;+export const formIntoDroppableId = (containerId: string): string => `into:${containerId}`;++export const parseFormDroppableId = (+ id: string+): { kind: 'edge'; elementId: string } | { kind: 'into'; containerId: string } | null => {+ if (id.startsWith('edge:')) {+ return { elementId: id.slice(5), kind: 'edge' };+ }+ if (id.startsWith('into:')) {+ return { containerId: id.slice(5), kind: 'into' };+ }+ return null;+};++/** The id of `elementId`'s container, or null for the root element (which has no parent). */+export const findFormParentId = (form: WorkflowForm, elementId: string): string | null =>+ form.elements[elementId]?.parentId ?? null;++/** True when `candidateId` is `ancestorId` itself or nested anywhere under it. */+export const isFormDescendantOrSelf = (form: WorkflowForm, ancestorId: string, candidateId: string): boolean => {+ if (ancestorId === candidateId) {+ return true;+ }+ const ancestor = form.elements[ancestorId];+ if (ancestor?.type !== 'container') {+ return false;+ }+ return ancestor.data.children.some((childId) => isFormDescendantOrSelf(form, childId, candidateId));+};++/**+ * Resolves a drop target to a `moveFormElementTo` call, or null when the move+ * is disallowed (dropping onto self, into own subtree, or an unresolvable+ * target). The reducer re-validates and no-ops on any of these too — this is+ * the same guard duplicated at the droppable level so drop zones for invalid+ * targets don't render mid-drag.+ */+export const resolveFormDrop = (+ form: WorkflowForm,+ activeId: string,+ target: FormDropTarget+): { parentId: string; index: number } | null => {+ if (target.kind === 'into') {+ const container = form.elements[target.containerId];+ if (container?.type !== 'container' || isFormDescendantOrSelf(form, activeId, target.containerId)) {+ return null;+ }+ return { index: container.data.children.length, parentId: target.containerId };+ }++ if (target.elementId === activeId || isFormDescendantOrSelf(form, activeId, target.elementId)) {+ return null;+ }+ const parentId = findFormParentId(form, target.elementId);+ if (parentId === null) {+ return null;+ }+ const parent = form.elements[parentId];+ if (parent?.type !== 'container') {+ return null;+ }+ const index = parent.data.children.indexOf(target.elementId);+ if (index < 0) {+ return null;+ }+ return { index: target.edge === 'above' ? index : index + 1, parentId };+};