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(widgets): make the panel resize handle actually grabbable
joshistoast514ddefa60ab
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsxnew file mode 100644index 0000000000..0ccb790a8d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx@@ -0,0 +1,170 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { FocusRegionProvider } from '@workbench/focusRegions';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import i18next from 'i18next';+import { act, useSyncExternalStore } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The drag-to-collapse gesture against the *real* store, reducer and shell+ * gating — the unit tests either side of this one mock the command layer, so+ * between them they cannot catch a break in the wiring itself.+ */++const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));++vi.mock('@workbench/WorkbenchContext', () => ({+ shallowEqual: Object.is,+ useActiveProjectSelector: (selector: (project: never) => unknown) => {+ const store = storeRef.current!;+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);++ return selector(snapshot.activeProject as never);+ },+ useWorkbenchCommands: () => storeRef.current!.commands,+}));++import { WidgetPanelFrame } from './WidgetFrames';++const i18n = i18next.createInstance();+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ lng: 'en',+ resources: { en: { translation: { widgets: { panelLabel: '{{region}} panel' } } } },+});++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const interact = (run: () => void): Promise<void> =>+ act(async () => {+ run();+ await Promise.resolve();+ });++/** Mirrors how `WorkbenchShell`/`BottomPanel` decide to mount a panel at all. */+const Shell = ({ region }: { region: 'bottom' | 'left' | 'right' }) => {+ const store = storeRef.current!;+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);+ const regionState = snapshot.activeProject.widgetRegions[region];+ const panels = snapshot.activeProject.layout.panels;+ const isOpen = region === 'left' ? panels.isLeftOpen : region === 'right' ? panels.isRightOpen : panels.isBottomOpen;++ if (!isOpen || regionState.isCollapsed) {+ return <div data-testid="collapsed" />;+ }++ return (+ <WidgetPanelFrame instanceId={regionState.activeInstanceId} region={region} typeId="gallery">+ <div />+ </WidgetPanelFrame>+ );+};++const renderShell = async (region: 'bottom' | 'left' | 'right') => {+ await interact(() =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <FocusRegionProvider>+ <Shell region={region} />+ </FocusRegionProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );++ const separator = host?.querySelector('[role="separator"]');++ if (!separator) {+ throw new Error('panel frame did not render a resize handle');+ }++ return separator;+};++const getRegion = (region: 'bottom' | 'left' | 'right') =>+ storeRef.current!.getSnapshot().activeProject.widgetRegions[region];++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'height:800px;width:1600px;';+ document.body.append(host);+ root = createRoot(host);+ storeRef.current = createWorkbenchStore();++ // Presets ship the bottom strip closed *and* collapsed, and `setRegionCollapsed`+ // deliberately does not touch `panels.isBottomOpen`. Open it the way the app+ // does — by selecting its active widget from the status rail.+ const bottom = storeRef.current.getSnapshot().activeProject.widgetRegions.bottom;++ storeRef.current.commands.widgets.select({+ projectId: storeRef.current.getSnapshot().activeProject.id,+ region: 'bottom',+ widgetId: bottom.activeInstanceId,+ });+});++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ storeRef.current = null;+});++describe('drag-to-collapse against the real aggregate', () => {+ it('collapses the left panel and unmounts it', async () => {+ const separator = await renderShell('left');+ const startSizePx = getRegion('left').sizePx;++ await interact(() => separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 260 - startSizePx })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientX: 260 - startSizePx })));++ expect(getRegion('left').isCollapsed).toBe(true);+ expect(getRegion('left').sizePx).toBe(startSizePx);+ expect(host?.querySelector('[data-testid="collapsed"]')).not.toBeNull();+ });++ it('collapses the right panel, whose axis runs the other way', async () => {+ const separator = await renderShell('right');+ const startSizePx = getRegion('right').sizePx;++ await interact(() => separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: startSizePx - 260 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientX: startSizePx - 260 })));++ expect(getRegion('right').isCollapsed).toBe(true);+ });++ it('collapses the bottom strip against its own floor', async () => {+ const separator = await renderShell('bottom');+ const startSizePx = getRegion('bottom').sizePx;++ await interact(() => separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientY: 0 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientY: startSizePx - 10 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientY: startSizePx - 10 })));++ expect(getRegion('bottom').isCollapsed).toBe(true);+ });++ it('resizes without collapsing when the drag stops at the floor', async () => {+ const separator = await renderShell('left');+ const startSizePx = getRegion('left').sizePx;++ await interact(() => separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0 })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: 340 - startSizePx })));+ await interact(() => window.dispatchEvent(new PointerEvent('pointerup', { clientX: 340 - startSizePx })));++ expect(getRegion('left').isCollapsed).toBe(false);+ expect(getRegion('left').sizePx).toBe(350);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsxindex 1ac916270e..19469f835e 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx@@ -36,11 +36,7 @@ import { WidgetSourceLockBadge } from './WidgetSourceLockBadge';const PANEL_SIZE_STEP_PX = 16;-/**- * A live resize drag. `sizePx` is what the panel renders at — always inside the- * region's bounds — while `isCollapseOvershoot` remembers that the pointer went- * far enough past the floor to mean "collapse", which clamping alone discards.- */+/** `sizePx` is the floored size the panel renders at; the flag survives the flooring. */interface PanelResizeDrag {isCollapseOvershoot: boolean;sizePx: number;@@ -64,9 +60,8 @@ export const WidgetPanelFrame = ({const regionState = useActiveProjectSelector((project) => project.widgetRegions[region]);const { layout } = useWorkbenchCommands();const [drag, setDrag] = useState<PanelResizeDrag | null>(null);- // The drag listens on `window`, so a frame that unmounts mid-gesture (a- // preset switch, a widget closing) would otherwise leave the listeners- // behind and commit a size to a region that is no longer on screen.+ // A frame unmounting mid-gesture would otherwise leave window listeners+ // behind and commit a size to a region no longer on screen.const pointerSessionRef = useRef<AbortController | null>(null);useMountEffect(() => () => pointerSessionRef.current?.abort());@@ -104,12 +99,21 @@ export const WidgetPanelFrame = ({let nextDrag: PanelResizeDrag = { isCollapseOvershoot: false, sizePx: clampPanelSize(region, startSizePx) };+ // Keeps the gesture alive when the pointer leaves the window, which is+ // where it goes when dragging the bottom strip shut. Throws if the+ // pointer is already gone; the window listeners still carry the drag.+ try {+ event.currentTarget.setPointerCapture(event.pointerId);+ } catch {+ // No capture available — fall through to the window listeners.+ }+const handlePointerMove = (moveEvent: PointerEvent) => {const deltaPx = isBottom ? startY - moveEvent.clientY : (moveEvent.clientX - startX) * direction;const rawSizePx = startSizePx + deltaPx;- // Recomputed from the live position every move, never latched, so- // dragging back inside the floor disarms the collapse.+ // Derived from the live position, never latched, so dragging back+ // inside the floor disarms the collapse.nextDrag = {isCollapseOvershoot: isPanelCollapseOvershoot(region, rawSizePx),sizePx: clampPanelSize(region, rawSizePx),@@ -122,10 +126,8 @@ export const WidgetPanelFrame = ({setDrag(null);if (nextDrag.isCollapseOvershoot) {- // Collapsing is a visibility change, not a resize: `sizePx` keeps the- // width the user chose, so the rail button reopens the panel where- // they left it — as collapsing from the rail already does. Committing- // the floor here would ratchet a 450px panel down to 350 every time.+ // Visibility change, not a resize — `sizePx` keeps the width the user+ // chose so the rail button reopens the panel where they left it.layout.setRegionCollapsed(region, true);return;@@ -134,8 +136,7 @@ export const WidgetPanelFrame = ({commitSize(nextDrag.sizePx);};- // A cancelled gesture is an interruption, not an instruction: it keeps- // the size the pointer reached but never collapses.+ // An interruption, not an instruction: keeps the size, never collapses.const handlePointerCancel = () => {pointerSession.abort();setDrag(null);@@ -153,7 +154,12 @@ export const WidgetPanelFrame = ({(event: ReactKeyboardEvent<HTMLDivElement>) => {const step = event.shiftKey ? PANEL_SIZE_STEP_PX * 2 : PANEL_SIZE_STEP_PX;const sizeChanges: Partial<Record<string, number>> = isBottom- ? { ArrowDown: -step, ArrowUp: step, End: maxPanelSizePx - displaySizePx, Home: minPanelSizePx - displaySizePx }+ ? {+ ArrowDown: -step,+ ArrowUp: step,+ End: maxPanelSizePx - displaySizePx,+ Home: minPanelSizePx - displaySizePx,+ }: {ArrowLeft: isLeft ? -step : step,ArrowRight: isLeft ? step : -step,@@ -175,12 +181,15 @@ export const WidgetPanelFrame = ({() => (isBottom ? { h: `${displaySizePx}px`, w: 'full' } : { h: 'full', w: `${displaySizePx}px` }),[displaySizePx, isBottom]);+ // Inside the panel's box, never straddling its edge: the frame clips its+ // overflow, so a handle hung outside loses that half and leaves a ~4px+ // target sitting behind the border people actually aim at.const resizeOrientationProps = useMemo(- () => (isBottom ? { h: '2', left: '0', right: '0', top: '-1' } : { bottom: '0', top: '0', w: '2' }),+ () => (isBottom ? { h: '2', left: '0', right: '0', top: '0' } : { bottom: '0', top: '0', w: '2' }),[isBottom]);const resizeSideProps = useMemo(- () => (!isBottom ? (isLeft ? { right: '-1' } : { left: '-1' }) : {}),+ () => (!isBottom ? (isLeft ? { right: '0' } : { left: '0' }) : {}),[isBottom, isLeft]);@@ -215,13 +224,10 @@ export const WidgetPanelFrame = ({position="absolute"role="separator"tabIndex={0}- // The handle is invisible at rest and only shows on hover, but an 8px- // strip loses hover the moment a drag starts — so while the drag is- // armed to collapse, it lights up on its own. Without it, overshooting- // is a gesture with no feedback until the panel vanishes.+ // Hover is lost the moment the drag starts, so the armed state paints itself.bg={isCollapseArmed ? 'accent.solid' : undefined}data-collapse-armed={isCollapseArmed ? '' : undefined}- opacity={isCollapseArmed ? '0.65' : '0'}+ opacity={isCollapseArmed ? '1' : '0'}transition="opacity var(--wb-motion-duration-fast) ease, background var(--wb-motion-duration-fast) ease"zIndex="1"{...resizeOrientationProps}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsxindex 65dac1f021..ee2610c6ab 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx@@ -156,6 +156,45 @@ describe('WidgetPanelFrame resize', () => {expect(separator.getAttribute('aria-valuemax')).toBe('720');});+ // The frame clips its overflow, so a handle hung outside the panel edge+ // loses that half — leaving a sliver behind the border people aim at, and a+ // gesture that silently does nothing.+ it.each(['left', 'right', 'bottom'] as const)('keeps the whole %s handle inside the clip', async (region) => {+ const separator = await renderFrame(region);+ const handle = separator.getBoundingClientRect();+ const panel = separator.parentElement!.getBoundingClientRect();++ expect(handle.left).toBeGreaterThanOrEqual(panel.left);+ expect(handle.right).toBeLessThanOrEqual(panel.right);+ expect(handle.top).toBeGreaterThanOrEqual(panel.top);+ expect(handle.bottom).toBeLessThanOrEqual(panel.bottom);+ });++ it('holds the panel at the floor while the drag keeps going', async () => {+ const separator = await renderFrame();+ // Chakra emits the width as a class rather than an inline style.+ const panelWidth = () => getComputedStyle(separator.parentElement!).width;++ await dragTo(separator, { end: 'none', widthPx: 300 });+ expect(panelWidth()).toBe('350px');+ expect(separator.hasAttribute('data-collapse-armed')).toBe(false);++ await interact(() => window.dispatchEvent(new PointerEvent('pointermove', { clientX: -400 })));+ expect(panelWidth()).toBe('350px');+ expect(separator.hasAttribute('data-collapse-armed')).toBe(true);+ });++ it('captures the pointer so the gesture survives leaving the window', async () => {+ const separator = await renderFrame();+ const setPointerCapture = vi.spyOn(separator as HTMLElement, 'setPointerCapture');++ await interact(() =>+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 0, pointerId: 7 }))+ );++ expect(setPointerCapture).toHaveBeenCalledWith(7);+ });+it('drops the window listeners when the frame unmounts mid-drag', async () => {const separator = await renderFrame();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 2a7a912a54..8cec3ebe2c 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -26,6 +26,7 @@ import { DEFAULT_PROJECT_SETTINGS } from './settings/store';import { getProjectWidgetValues } from './widgetState';import {clampPanelSize,+ getPanelCollapseThreshold,GRAPH_HISTORY_BYTE_BUDGET,isPanelCollapseOvershoot,normalizeGraphHistory,@@ -685,6 +686,11 @@ describe('workbench panel resize bounds', () => {expect(isPanelCollapseOvershoot('bottom', 16)).toBe(true);});+ it('exposes the collapse threshold as a size below the floor', () => {+ expect(getPanelCollapseThreshold('left')).toBe(270);+ expect(getPanelCollapseThreshold('bottom')).toBe(16);+ });+it('reopens a collapsed region at the size it was collapsed from', () => {let state = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex e69d2c3e25..d8095f047a 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -427,13 +427,13 @@ export const getPanelSizeBounds = (region: WidgetRegion): { max: number; min: nureturn { max: MAX_PANEL_SIZE_PX, min: MIN_PANEL_SIZE_PX };};-/**- * True once a resize drag has overshot the floor far enough to mean collapse.- * Takes the drag's raw, unclamped size — the whole point is the distance- * `clampPanelSize` throws away.- */+/** The size at or below which releasing a resize drag collapses the region. */+export const getPanelCollapseThreshold = (region: WidgetRegion): number =>+ getPanelSizeBounds(region).min - PANEL_COLLAPSE_OVERSHOOT_PX;++/** True once a drag has pushed past the floor far enough that releasing collapses. */export const isPanelCollapseOvershoot = (region: WidgetRegion, sizePx: number): boolean =>- sizePx <= getPanelSizeBounds(region).min - PANEL_COLLAPSE_OVERSHOOT_PX;+ sizePx <= getPanelCollapseThreshold(region);const now = (): string => new Date().toISOString();