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(webv2): pointer-true drop edges, innermost-wins nesting, keyboard drag for the form builder

joshistoast142e345ce90b
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 70a768dedb..553b89115f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx
@@ -3,6 +3,7 @@ import { Box, HStack, Icon, Input, Menu, Portal, Separator, Stack, Text, Textare
import {
DndContext,
DragOverlay,
+ KeyboardSensor,
MeasuringStrategy,
PointerSensor,
pointerWithin,
@@ -45,13 +46,15 @@ import {
TextIcon,
XIcon,
} from 'lucide-react';
-import { createContext, use, useCallback, useMemo, useState, type ChangeEvent, type ReactNode } from 'react';
+import { createContext, use, useCallback, useMemo, useRef, useState, type ChangeEvent, type ReactNode } from 'react';
import {
formEdgeDroppableId,
formIntoDroppableId,
+ getFormDropEdge,
isFormDescendantOrSelf,
parseFormDroppableId,
+ pickInnermostFormCollision,
resolveFormDrop,
type FormDropTarget,
} from './formBuilderDnd';
@@ -137,7 +140,21 @@ const BuilderCard = ({
}) => {
const { editGraph } = useProjectGraphCommands();
const { activeElementId, dropTarget, form } = use(BuilderDndContext);
- const { attributes, listeners, setNodeRef: setDragRef } = useDraggable({ id: element.id });
+ 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`
+ // enforce `event.target === activator` (dnd-kit's `KeyboardSensor.activators`
+ // check) — without it, `Space`/`Enter` bubbling up from the action buttons
+ // this title bar contains (Remove, Zoom to node, etc.) would also lift the
+ // card, the keyboard equivalent of the `onPointerDown` `stopPropagation`
+ // guard those buttons already carry for pointer drags.
+ const setDragHandleRef = useCallback(
+ (node: HTMLElement | null) => {
+ setDragRef(node);
+ setActivatorNodeRef(node);
+ },
+ [setActivatorNodeRef, setDragRef]
+ );
const { setNodeRef: setDropRef } = useDroppable({
disabled: activeElementId !== null && isFormDescendantOrSelf(form, activeElementId, element.id),
id: formEdgeDroppableId(element.id),
@@ -166,7 +183,7 @@ const BuilderCard = ({
{...getWorkflowNodeChromeProps({ invalid: Boolean(isInvalid), selected: Boolean(isHovered || isSelected) })}
>
<HStack
- ref={setDragRef}
+ ref={setDragHandleRef}
bg="bg.muted"
borderBottomWidth="1px"
borderColor="border.subtle"
@@ -505,14 +522,36 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta
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 } }));
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(KeyboardSensor)
+ );
// 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 form = projectGraph.form;
+ // `DragMoveEvent.delta` is scroll-adjusted (translate + the panel's scroll
+ // offset baked in), so `activatorEvent.clientY + delta.y` overshoots the
+ // real pointer once the panel auto-scrolls while `over.rect` stays in
+ // fresh viewport coordinates. `collisionDetection`'s `args.pointerCoordinates`
+ // is the one place dnd-kit hands back the true (already scroll-correct)
+ // pointer position, so it's captured here and read in `handleDragMove`.
+ const pointerYRef = useRef<number | null>(null);
+ const collisionDetection: CollisionDetection = useCallback(
+ (args) => {
+ pointerYRef.current = args.pointerCoordinates?.y ?? null;
+
+ const within = pointerWithin(args);
+ const candidates = within.length > 0 ? within : rectIntersection(args);
+ const picked = pickInnermostFormCollision(
+ candidates.map((collision) => ({ id: String(collision.id) })),
+ form
+ );
+
+ return picked === null ? candidates : candidates.filter((collision) => String(collision.id) === picked);
+ },
+ [form]
+ );
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveElementId(String(event.active.id));
@@ -537,11 +576,15 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta
return;
}
+ // The true (scroll-correct) pointer position when the drag has one
+ // (`PointerSensor`, captured from `collisionDetection`'s
+ // `pointerCoordinates`); a `KeyboardSensor` drag has no pointer, so fall
+ // back to the dragged card's translated center.
const activeRect = active.rect.current.translated;
- const pointerY = activeRect ? activeRect.top + activeRect.height / 2 : over.rect.top;
+ const referenceY = pointerYRef.current ?? (activeRect ? activeRect.top + activeRect.height / 2 : over.rect.top);
setDropTarget({
- edge: pointerY < over.rect.top + over.rect.height / 2 ? 'above' : 'below',
+ edge: getFormDropEdge(referenceY, over.rect.top, over.rect.height),
elementId: parsed.elementId,
kind: 'edge',
});
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 ba0bd6bc24..5a94c29a08 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
@@ -186,6 +186,10 @@ describe('Form builder drag and drop (dnd-kit)', () => {
);
};
+ const key = (target: EventTarget, code: string): void => {
+ target.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code }));
+ };
+
// 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
@@ -217,6 +221,41 @@ describe('Form builder drag and drop (dnd-kit)', () => {
await interact(() => pointer('pointerup', handle.ownerDocument, x, y + 1));
};
+ /**
+ * Drags `sourceTitle`'s title bar to vertical position `targetCenterY` via
+ * the keyboard: `Space` lifts, `ArrowDown`/`ArrowUp` steps 25px at a time
+ * toward the target (dnd-kit's `defaultKeyboardCoordinateGetter`), `Space`
+ * drops. Ends with a net-zero nudge in the same direction as the last real
+ * step — the keyboard analogue of `dragTo`'s no-op settle move:
+ * `MeasuringStrategy.Always`'s remeasure lands one tick after the arrow
+ * press that triggered it, so the last press's own `onDragMove` can still
+ * report a stale `over`.
+ */
+ const dragToWithKeyboard = async (sourceTitle: string, targetCenterY: number): Promise<void> => {
+ const handle = titleBarFor(sourceTitle);
+ const startRect = handle.getBoundingClientRect();
+ const startCenterY = startRect.top + startRect.height / 2;
+ const direction = targetCenterY >= startCenterY ? 'ArrowDown' : 'ArrowUp';
+ const opposite = direction === 'ArrowDown' ? 'ArrowUp' : 'ArrowDown';
+ const steps = Math.round(Math.abs(targetCenterY - startCenterY) / 25);
+
+ handle.focus();
+ expect(handle.ownerDocument.activeElement).toBe(handle);
+
+ // Space lifts (dnd-kit's `KeyboardSensor` start code).
+ await interact(() => key(handle, 'Space'));
+
+ for (let step = 0; step < steps; step++) {
+ await interact(() => key(handle, direction));
+ }
+ await interact(() => key(handle, direction));
+ await interact(() => key(handle, opposite));
+
+ // Space drops, resolving the move through the same `onDragEnd` ->
+ // `moveFormElementTo` path the pointer drag uses.
+ await interact(() => key(handle, 'Space'));
+ };
+
it('keeps dragging alive after a field is dropped into a container', async () => {
await renderHarness();
@@ -257,4 +296,62 @@ describe('Form builder drag and drop (dnd-kit)', () => {
expect(opacities).not.toContain('0.4');
});
+
+ /**
+ * Regression coverage for the "keyboard drag" finding: the drag handle
+ * spreads dnd-kit's `attributes` (`role="button"`, `tabIndex=0`), which
+ * promises "press space to lift, arrows to move" — a promise only true
+ * once a `KeyboardSensor` is registered alongside the `PointerSensor`.
+ * There's no pointer during a keyboard drag, so `KeyboardSensor` moves the
+ * dragged card's tracked rect by a fixed 25px step per arrow press
+ * (dnd-kit's `defaultKeyboardCoordinateGetter`) and collision detection
+ * falls through to `rectIntersection` (`pointerWithin` needs real pointer
+ * coordinates, which a keyboard drag never has).
+ */
+ it('moves a form element into a container with the keyboard', async () => {
+ await renderHarness();
+
+ const emptyHint = [...host.querySelectorAll<HTMLElement>('*')].find(
+ (element) => element.textContent === 'Empty container — drag elements here'
+ );
+
+ expect(emptyHint).toBeDefined();
+
+ const dropZoneRect = emptyHint!.getBoundingClientRect();
+
+ await dragToWithKeyboard('Heading', dropZoneRect.top + dropZoneRect.height / 2);
+
+ const containerContent = cardContentFor('Container (column layout)');
+
+ expect(containerContent.textContent).toContain('Heading');
+ expect(containerContent.textContent).not.toContain('Empty container');
+ });
+
+ /**
+ * Coverage for the keyboard *edge* path specifically: the "into a
+ * container" case above never reaches `getFormDropEdge`'s card-center
+ * fallback (`handleDragMove` returns early for `into` targets before
+ * `referenceY` is even computed) — a keyboard drag has no
+ * `pointerCoordinates`, so this is the only path that exercises the
+ * fallback dnd-kit needs for a real "arrows move the card" keyboard drag.
+ * Moves "Divider" (root sibling, after "Heading") up onto the upper
+ * quarter of "Heading"'s card, landing 'above' it and reordering it first.
+ */
+ it('reorders a form element above a sibling with the keyboard', async () => {
+ await renderHarness();
+
+ const headingCardRect = titleBarFor('Heading').parentElement!.getBoundingClientRect();
+
+ await dragToWithKeyboard('Divider', headingCardRect.top + headingCardRect.height * 0.25);
+
+ const leafElements = [...host.querySelectorAll<HTMLElement>('*')].filter(
+ (element) => element.children.length === 0
+ );
+ const dividerIndex = leafElements.findIndex((element) => element.textContent?.trim() === 'Divider');
+ const headingIndex = leafElements.findIndex((element) => element.textContent?.trim() === 'Heading');
+
+ expect(dividerIndex).toBeGreaterThanOrEqual(0);
+ expect(headingIndex).toBeGreaterThanOrEqual(0);
+ expect(dividerIndex).toBeLessThan(headingIndex);
+ });
});
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.ts
index 5312743ced..9b5c0dc9f7 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts
@@ -2,7 +2,15 @@ import type { WorkflowForm } from '@features/workflow/contracts';
import { describe, expect, it } from 'vitest';
-import { findFormParentId, isFormDescendantOrSelf, resolveFormDrop } from './formBuilderDnd';
+import {
+ findFormParentId,
+ formEdgeDroppableId,
+ formIntoDroppableId,
+ getFormDropEdge,
+ isFormDescendantOrSelf,
+ pickInnermostFormCollision,
+ resolveFormDrop,
+} from './formBuilderDnd';
/**
* root -> [fieldA, container1 -> [fieldB], fieldC]
@@ -78,3 +86,99 @@ describe('findFormParentId', () => {
expect(findFormParentId(form, form.rootElementId)).toBeNull();
});
});
+
+describe('getFormDropEdge', () => {
+ it('splits at the midline of the hovered card', () => {
+ expect(getFormDropEdge(10, 0, 40)).toBe('above');
+ expect(getFormDropEdge(30, 0, 40)).toBe('below');
+ });
+});
+
+/**
+ * root -> [container A -> [container B -> [fieldD], fieldC]]
+ * Mirrors a nested-container layout the way the builder renders it: A's own
+ * body holds both B (another container) and a plain field.
+ */
+const buildNestedFormFixture = (): WorkflowForm => ({
+ elements: {
+ A: { data: { children: ['B', 'fieldC'], layout: 'column' }, id: 'A', parentId: 'root', type: 'container' },
+ B: { data: { children: ['fieldD'], layout: 'column' }, id: 'B', parentId: 'A', type: 'container' },
+ fieldC: { data: { content: '' }, id: 'fieldC', parentId: 'A', type: 'heading' },
+ fieldD: { data: { content: '' }, id: 'fieldD', parentId: 'B', type: 'heading' },
+ root: { data: { children: ['A'], layout: 'column' }, id: 'root', type: 'container' },
+ },
+ rootElementId: 'root',
+});
+
+describe('pickInnermostFormCollision', () => {
+ const nestedForm = buildNestedFormFixture();
+
+ it('returns null when there are no collisions', () => {
+ expect(pickInnermostFormCollision([], nestedForm)).toBeNull();
+ });
+
+ it('prefers the deepest container when nested droppables overlap', () => {
+ const collisions = [{ id: formIntoDroppableId('A') }, { id: formIntoDroppableId('B') }];
+
+ expect(pickInnermostFormCollision(collisions, nestedForm)).toBe(formIntoDroppableId('B'));
+ });
+
+ it('is order-independent for nested containers', () => {
+ const collisions = [{ id: formIntoDroppableId('B') }, { id: formIntoDroppableId('A') }];
+
+ expect(pickInnermostFormCollision(collisions, nestedForm)).toBe(formIntoDroppableId('B'));
+ });
+
+ it('prefers an edge target over its enclosing container', () => {
+ const collisions = [{ id: formIntoDroppableId('A') }, { id: formEdgeDroppableId('fieldC') }];
+
+ expect(pickInnermostFormCollision(collisions, nestedForm)).toBe(formEdgeDroppableId('fieldC'));
+ });
+
+ /**
+ * A container's own `into:X` dropzone is DOM-nested inside its own
+ * `edge:X` box (the whole card), so hovering the dropzone always matches
+ * both — not just when a *different*, deeper element's edge is involved.
+ * `into:X` (lands inside X) must win over `edge:X` (lands inside X's
+ * parent): dropping onto a container's own empty-state hint has to append
+ * into it, not reorder it as a sibling.
+ */
+ it('prefers a container over its own edge when both match the same element', () => {
+ const collisions = [{ id: formEdgeDroppableId('A') }, { id: formIntoDroppableId('A') }];
+
+ expect(pickInnermostFormCollision(collisions, nestedForm)).toBe(formIntoDroppableId('A'));
+ expect(pickInnermostFormCollision([...collisions].reverse(), nestedForm)).toBe(formIntoDroppableId('A'));
+ });
+
+ /**
+ * root -> [C, B -> [D]]. C and B are incomparable siblings (neither is an
+ * ancestor of the other); D is nested under B. A greedy "compare each new
+ * candidate only against the current winner" pass can get stuck on C: C
+ * isn't D's ancestor, so a pairwise check never promotes D once C already
+ * won. Depth is computed independently per candidate specifically to avoid
+ * this, so the deepest (`D`) must win regardless of arrival order.
+ */
+ it('is order-independent for incomparable siblings plus a nested descendant', () => {
+ const siblingForm: WorkflowForm = {
+ elements: {
+ B: { data: { children: ['D'], layout: 'column' }, id: 'B', parentId: 'root', type: 'container' },
+ C: { data: { children: [], layout: 'column' }, id: 'C', parentId: 'root', type: 'container' },
+ D: { data: { children: [], layout: 'column' }, id: 'D', parentId: 'B', type: 'container' },
+ root: { data: { children: ['C', 'B'], layout: 'column' }, id: 'root', type: 'container' },
+ },
+ rootElementId: 'root',
+ };
+ const collisions = [
+ { id: formIntoDroppableId('C') },
+ { id: formIntoDroppableId('B') },
+ { id: formIntoDroppableId('D') },
+ ];
+
+ expect(pickInnermostFormCollision(collisions, siblingForm)).toBe(formIntoDroppableId('D'));
+ expect(pickInnermostFormCollision([...collisions].reverse(), siblingForm)).toBe(formIntoDroppableId('D'));
+ });
+
+ it('falls back to the first collision when nothing parses as a form droppable', () => {
+ expect(pickInnermostFormCollision([{ id: 'not-a-form-id' }], nestedForm)).toBe('not-a-form-id');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts
index 4f591758a6..fe12f9e6d2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts
@@ -49,6 +49,103 @@ export const isFormDescendantOrSelf = (form: WorkflowForm, ancestorId: string, c
return ancestor.data.children.some((childId) => isFormDescendantOrSelf(form, childId, candidateId));
};
+/** Above/below split at the hovered card's midline. `referenceY` is the pointer when available, else the dragged card's center. */
+export const getFormDropEdge = (referenceY: number, overTop: number, overHeight: number): 'above' | 'below' =>
+ referenceY < overTop + overHeight / 2 ? 'above' : 'below';
+
+/**
+ * The container a droppable would actually land the dragged element inside:
+ * `into:X` lands inside `X` itself; `edge:X` lands inside `X`'s own parent
+ * (it resolves to a sibling reorder around `X`). Unifying both kinds onto
+ * this one axis is what makes the tiebreak below a single "deepest wins"
+ * comparison instead of two separate rules.
+ */
+const formDropLandingContainerId = (form: WorkflowForm, droppableId: string): string | null => {
+ const parsed = parseFormDroppableId(droppableId);
+
+ if (!parsed) {
+ return null;
+ }
+
+ return parsed.kind === 'into' ? parsed.containerId : findFormParentId(form, parsed.elementId);
+};
+
+/** How many containers separate `containerId` from the form root — 0 for the root itself, +1 per level of nesting. */
+const formContainerDepth = (form: WorkflowForm, containerId: string): number => {
+ let depth = 0;
+ let currentId = containerId;
+
+ while (currentId !== form.rootElementId) {
+ const parentId = findFormParentId(form, currentId);
+
+ if (parentId === null) {
+ break;
+ }
+ currentId = parentId;
+ depth += 1;
+ }
+
+ return depth;
+};
+
+/**
+ * Innermost-wins tiebreak for overlapping droppables — restores the native-DnD
+ * `stopPropagation` semantics the port lost. A container's own `edge:X` and
+ * `into:X` are the same ambiguity dnd-kit's rect-based collision can't avoid:
+ * `into:X` is DOM-nested inside `edge:X`'s box, so hovering its dropzone
+ * always matches both. Comparing by landing container resolves it the same
+ * way as any other nesting — the deeper one wins, so `into:X` (lands inside
+ * `X`) beats `edge:X` (lands inside `X`'s parent).
+ *
+ * The rule, precisely: every candidate's landing container has a *depth*
+ * (its distance from the form root); the candidate with the greatest depth
+ * wins outright, and among candidates tied on depth, an edge wins over an
+ * into (a specific insertion point next to a sibling is a more precise
+ * intent than "append to this container"). Depth is computed independently
+ * per candidate — not by comparing each new candidate only against the
+ * current winner — so the result doesn't depend on the order `collisions`
+ * arrives in: two incomparable siblings (say containers `C` and `B`, neither
+ * nested under the other) plus a deeper `D` nested under `B` must still pick
+ * `D`, even if `C` happened to be evaluated first.
+ */
+export const pickInnermostFormCollision = (collisions: { id: string }[], form: WorkflowForm): string | null => {
+ if (collisions.length === 0) {
+ return null;
+ }
+
+ let winner: string | null = null;
+ let winnerDepth = -1;
+ let winnerIsEdge = false;
+
+ for (const collision of collisions) {
+ const id = String(collision.id);
+ const parsed = parseFormDroppableId(id);
+
+ if (!parsed) {
+ continue;
+ }
+
+ const landingId = formDropLandingContainerId(form, id);
+
+ if (landingId === null) {
+ continue;
+ }
+
+ const isEdge = parsed.kind === 'edge';
+ const depth = formContainerDepth(form, landingId);
+ const isDeeper = depth > winnerDepth;
+ const winsTie = depth === winnerDepth && isEdge && !winnerIsEdge;
+
+ if (winner === null || isDeeper || winsTie) {
+ winner = id;
+ winnerDepth = depth;
+ winnerIsEdge = isEdge;
+ }
+ }
+
+ return winner ?? String(collisions[0]!.id);
+};
+
/**
* Resolves a drop target to a `moveFormElementTo` call, or null when the move
* is disallowed (dropping onto self, into own subtree, or an unresolvable