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): ack preset press on pointerdown

joshistoast0eb15dfdfbb0
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
index f9b1113afe..ab20c31ec4 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
@@ -1,7 +1,7 @@
import type { DragEndEvent } from '@dnd-kit/core';
import type { LayoutPreset, LayoutPresetId } from '@workbench/layoutContracts';
import type { Project } from '@workbench/projectContracts';
-import type { KeyboardEvent, MouseEvent } from 'react';
+import type { KeyboardEvent, MouseEvent, PointerEvent } from 'react';
import { Box, HStack, Icon, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';
import {
@@ -49,10 +49,17 @@ import { LayoutPresetDialog } from './LayoutPresetDialog';
import { resolveLayoutPresetIcon } from './layoutPresetIcons';
import { openLayoutPresetDelete, openLayoutPresetEdit, openLayoutPresetManager } from './layoutPresetManagerStore';
import { HIDE_BELOW_PRESET_LABEL_WIDTH } from './topbarBreakpoints';
-import { useLayoutDrift } from './useLayoutDrift';
+import { useActiveLayoutPresetId, useLayoutDrift } from './useLayoutDrift';
import { useTopbarShortcut } from './useTopbarShortcut';
const PRESET_MENU_ATTRIBUTE = 'data-preset-menu';
+// The selected paint is ours, not the tabs machine's: React writes this
+// attribute in the same commit as the press, so the tab cannot lag the press
+// even by a machine transition. Same tokens the `subtle` tabs recipe emits for
+// `_selected`, so the tab is pixel-identical to the one it replaces.
+const PRESET_TAB_ACTIVE_CSS = {
+ '&[data-preset-active]': { bg: 'colorPalette.subtle', color: 'colorPalette.fg' },
+} as const;
const PRESET_SCROLL_CSS = { '&::-webkit-scrollbar': { display: 'none' }, scrollbarWidth: 'none' } as const;
const PRESET_TAB_KEYS_BLOCKED_DURING_DRAG = new Set(['ArrowDown', 'ArrowLeft', 'ArrowRight', 'End', 'Home']);
const DND_MODIFIERS = [restrictToHorizontalAxis, restrictToParentElement];
@@ -74,7 +81,6 @@ const selectPlacedGraphWidgetSources = (project: Project) => {
export const LayoutPresetStrip = () => {
const { t } = useTranslation();
- const { activePreset, hasDrifted } = useLayoutDrift();
const { layout } = useWorkbenchCommands();
const [isSaveAsOpen, setIsSaveAsOpen] = useState(false);
const [menuTarget, setMenuTarget] = useState<{ anchor: DOMRect; preset: LayoutPreset } | null>(null);
@@ -84,6 +90,20 @@ export const LayoutPresetStrip = () => {
const sourceOptions = useActiveProjectSelector(selectPlacedGraphWidgetSources);
const presets = useMemo(() => getOrderedLayoutPresets(account), [account]);
const presetIds = useMemo(() => presets.map(({ id }) => id), [presets]);
+ const { hasDrifted } = useLayoutDrift();
+ const activePresetId = useActiveLayoutPresetId();
+ const [pendingPresetId, setPendingPresetId] = useState<LayoutPresetId | null>(null);
+
+ // The store caught up; stop overriding it.
+ if (pendingPresetId !== null && pendingPresetId === activePresetId) {
+ setPendingPresetId(null);
+ }
+
+ const selectedPresetId = pendingPresetId ?? activePresetId;
+ const activePreset = useMemo(
+ () => presets.find(({ id }) => id === selectedPresetId) ?? presets[0]!,
+ [presets, selectedPresetId]
+ );
const dndAccessibility = useMemo(
() => ({ screenReaderInstructions: { draggable: t('topbar.presets.reorderInstructions') } }),
[t]
@@ -97,13 +117,28 @@ export const LayoutPresetStrip = () => {
() => ({ destination: invocation.destination, sourceId: invocation.sourceId }),
[invocation.destination, invocation.sourceId]
);
+ /**
+ * Desktop semantics: the control acknowledges the press on its own frame,
+ * then the workspace rearranges. Activating inside the handler put a
+ * ~100ms blocking React commit between the click and any pixel changing,
+ * and the tab itself did not repaint for ~330ms.
+ */
+ const requestPreset = useCallback(
+ (presetId: LayoutPresetId) => {
+ setPendingPresetId(presetId);
+ requestAnimationFrame(() => {
+ void layout.activatePreset(presetId);
+ });
+ },
+ [layout]
+ );
const applyPreset = useCallback(
(preset: LayoutPreset) => {
- if (preset.id !== activePreset.id) {
- void layout.activatePreset(preset.id);
+ if (preset.id !== selectedPresetId) {
+ requestPreset(preset.id);
}
},
- [activePreset.id, layout]
+ [requestPreset, selectedPresetId]
);
const handleValueChange = useCallback(
(event: { value: string }) => {
@@ -151,7 +186,7 @@ export const LayoutPresetStrip = () => {
<Tabs.Root
minW="max-content"
size="xs"
- value={activePreset.id}
+ value={selectedPresetId}
variant="subtle"
onValueChange={handleValueChange}
>
@@ -163,9 +198,10 @@ export const LayoutPresetStrip = () => {
<PresetTab
key={preset.id}
hasDrifted={hasDrifted}
- isActive={preset.id === activePreset.id}
+ isActive={preset.id === selectedPresetId}
preset={preset}
onOpenMenu={setMenuTarget}
+ onRequest={requestPreset}
/>
))}
</Tabs.List>
@@ -196,7 +232,7 @@ export const LayoutPresetStrip = () => {
</HStack>
<PresetMenu
- isActive={menuTarget?.preset.id === activePreset.id}
+ isActive={menuTarget?.preset.id === selectedPresetId}
hasDrifted={hasDrifted}
target={menuTarget}
onApply={applyPreset}
@@ -225,12 +261,14 @@ const PresetTab = ({
hasDrifted,
isActive,
onOpenMenu,
+ onRequest,
preset,
}: {
hasDrifted: boolean;
isActive: boolean;
preset: LayoutPreset;
onOpenMenu: (target: { anchor: DOMRect; preset: LayoutPreset }) => void;
+ onRequest: (presetId: LayoutPresetId) => void;
}) => {
const { t } = useTranslation();
const icon = resolveLayoutPresetIcon(preset.iconId);
@@ -268,6 +306,23 @@ const PresetTab = ({
[onOpenMenu, preset]
);
+ // The press, not the click, is what the user is waiting on. Chakra's tabs
+ // machine would still land the selection correctly, but only after the click
+ // it never sees until the button is released.
+ const handlePointerDown = useCallback(
+ (event: PointerEvent<HTMLButtonElement>) => {
+ // dnd-kit owns the drag gesture; chain rather than replace.
+ (listeners as { onPointerDown?: (value: unknown) => void } | undefined)?.onPointerDown?.(event);
+
+ const trigger = event.target instanceof Element ? event.target.closest(`[${PRESET_MENU_ATTRIBUTE}]`) : null;
+
+ if (!trigger && !isActive) {
+ onRequest(preset.id);
+ }
+ },
+ [isActive, listeners, onRequest, preset.id]
+ );
+
const handleContextMenu = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
@@ -308,8 +363,10 @@ const PresetTab = ({
{...listeners}
aria-label={showDrift ? `${preset.label}, ${t('topbar.presets.unsaved')}` : preset.label}
aria-keyshortcuts={isActive ? 'ArrowDown' : undefined}
+ css={PRESET_TAB_ACTIVE_CSS}
cursor={isDragging ? 'grabbing' : 'pointer'}
data-layout-preset-id={preset.id}
+ data-preset-active={isActive ? '' : undefined}
gap="1.5"
style={dndStyle}
touchAction="pan-x"
@@ -318,6 +375,7 @@ const PresetTab = ({
onContextMenu={handleContextMenu}
onFocus={handlePreload}
onKeyDown={handleKeyDown}
+ onPointerDown={handlePointerDown}
onPointerEnter={handlePreload}
>
<Icon as={icon} boxSize="3.5" flexShrink={0} />
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx
new file mode 100644
index 0000000000..c89555b244
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx
@@ -0,0 +1,176 @@
+import type { LayoutPresetId } from '@workbench/layoutContracts';
+import type * as LayoutPresetActivationModule from '@workbench/layoutPresetActivation';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createWorkbenchStore, type WorkbenchInternalStore } 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, describe, expect, it, vi } from 'vitest';
+
+// The store is read for real but never written: `activatePreset` is a stub the
+// test can freeze outright, which is the point of the suite. If the tab only
+// acknowledges the press once the store has caught up, nothing here passes.
+let store: WorkbenchInternalStore;
+let activatePreset: (presetId: LayoutPresetId) => Promise<void> = () => Promise.resolve();
+
+vi.mock('@workbench/WorkbenchContext', () => {
+ const useSnapshot = () => useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
+ const noop = () => undefined;
+
+ return {
+ shallowEqual: Object.is,
+ useActiveProjectSelector: <Selected,>(
+ selector: (project: ReturnType<typeof useSnapshot>['activeProject']) => Selected
+ ) => selector(useSnapshot().activeProject),
+ useDebouncedWorkbenchSelector: <Selected,>(selector: (snapshot: ReturnType<typeof useSnapshot>) => Selected) =>
+ selector(useSnapshot()),
+ useWorkbenchCommands: () => ({
+ layout: {
+ activatePreset: (presetId: LayoutPresetId) => activatePreset(presetId),
+ createPreset: noop,
+ reorderPresets: noop,
+ reset: noop,
+ savePreset: noop,
+ },
+ }),
+ useWorkbenchSelector: <Selected,>(selector: (snapshot: ReturnType<typeof useSnapshot>) => Selected) =>
+ selector(useSnapshot()),
+ };
+});
+
+vi.mock('@workbench/layoutPresetActivation', async (importOriginal) => ({
+ ...(await importOriginal<typeof LayoutPresetActivationModule>()),
+ preloadLayoutPresetWidgets: () => undefined,
+}));
+vi.mock('./useTopbarShortcut', () => ({ useTopbarShortcut: () => null }));
+
+import { LayoutPresetStrip } from './LayoutPresetStrip';
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+
+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 render = async (options: {
+ activatePreset: (presetId: LayoutPresetId) => Promise<void>;
+ activePresetId: LayoutPresetId;
+}) => {
+ activatePreset = options.activatePreset;
+ store = createWorkbenchStore();
+ store.commands.layout.applyPreset(options.activePresetId);
+ host = document.createElement('div');
+ host.style.width = '900px';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <LayoutPresetStrip />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await Promise.resolve();
+ });
+};
+
+const presetTab = (id: string): HTMLElement => {
+ const tab = document.querySelector<HTMLElement>(`[role="tab"][data-layout-preset-id="${id}"]`);
+
+ if (!tab) {
+ throw new Error(`No preset tab rendered for ${id}.`);
+ }
+
+ return tab;
+};
+
+const press = (element: Element): Promise<void> =>
+ act(async () => {
+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true }));
+ await Promise.resolve();
+ });
+
+const nextFrame = (): Promise<void> =>
+ act(async () => {
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => resolve(null));
+ });
+ });
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ activatePreset = () => Promise.resolve();
+});
+
+describe('LayoutPresetStrip acknowledgment', () => {
+ it('marks the pressed tab active on pointerdown, before any store update', async () => {
+ // activatePreset never resolves: the store is deliberately frozen.
+ const activate = vi.fn(() => new Promise<void>(() => {}));
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ const editTab = presetTab('edit');
+
+ expect(editTab.hasAttribute('data-preset-active')).toBe(false);
+
+ await press(editTab);
+
+ expect(presetTab('edit').hasAttribute('data-preset-active')).toBe(true);
+ expect(presetTab('compose').hasAttribute('data-preset-active')).toBe(false);
+ expect(store.getSnapshot().activeProject.layout.presetId).toBe('compose');
+ });
+
+ // The performance gate watches `aria-selected`, and assistive technology reads
+ // it: the acknowledgment is only real if the tabs machine moves with it.
+ it('moves the tabs machine selection in the same commit as the acknowledgment', async () => {
+ const activate = vi.fn(() => new Promise<void>(() => {}));
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ await press(presetTab('edit'));
+
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('true');
+ expect(presetTab('compose').getAttribute('aria-selected')).toBe('false');
+ expect(presetTab('compose').hasAttribute('data-selected')).toBe(false);
+ });
+
+ it('activates on the frame after the acknowledgment, not inside the handler', async () => {
+ const activate = vi.fn(() => Promise.resolve());
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ const editTab = presetTab('edit');
+
+ await act(async () => {
+ editTab.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true }));
+
+ // Checked before yielding: the handler itself must not have dispatched.
+ expect(activate).not.toHaveBeenCalled();
+ await Promise.resolve();
+ });
+
+ await nextFrame();
+
+ expect(activate).toHaveBeenCalledWith('edit');
+ });
+
+ it('does not re-activate the preset that is already active', async () => {
+ const activate = vi.fn(() => Promise.resolve());
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ await press(presetTab('compose'));
+ await nextFrame();
+
+ expect(activate).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts
index 8074e95648..831bcb1036 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts
@@ -1,4 +1,4 @@
-import type { LayoutPreset } from '@workbench/layoutContracts';
+import type { LayoutPresetId } from '@workbench/layoutContracts';
import type { WorkbenchSnapshot } from '@workbench/workbenchStore';
import {
@@ -6,36 +6,38 @@ import {
createLayoutPresetSnapshot,
resolveSavedLayoutPreset,
} from '@workbench/layoutPresetSnapshots';
-import { useDebouncedWorkbenchSelector } from '@workbench/WorkbenchContext';
+import { useDebouncedWorkbenchSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';
/** How long the live layout must hold still before the drift dot reacts. */
const DRIFT_SETTLE_MS = 250;
export interface LayoutDriftState {
- activePreset: LayoutPreset;
hasDrifted: boolean;
}
-const areDriftStatesEqual = (left: LayoutDriftState, right: LayoutDriftState): boolean =>
- left.hasDrifted === right.hasDrifted &&
- left.activePreset.id === right.activePreset.id &&
- left.activePreset.label === right.activePreset.label;
+// Module scope, not inline closures: a selector whose identity changed every
+// render would defeat `useSyncExternalStoreWithSelector`'s memoization and
+// re-run it on each one — and the drift comparison serialises the whole
+// arrangement.
+const selectActiveLayoutPresetId = (snapshot: WorkbenchSnapshot): LayoutPresetId =>
+ snapshot.activeProject.layout.presetId;
-// Module scope, not an inline closure: the comparison serialises the whole
-// arrangement, and a selector whose identity changed every render would defeat
-// `useSyncExternalStoreWithSelector`'s memoization and re-run it on each one.
-const selectLayoutDrift = (snapshot: WorkbenchSnapshot): LayoutDriftState => {
+const selectHasDrifted = (snapshot: WorkbenchSnapshot): boolean => {
const activePreset = resolveSavedLayoutPreset(snapshot.account, snapshot.activeProject.layout.presetId);
- return {
- activePreset,
- hasDrifted: !areLayoutPresetSnapshotsEqual(
- createLayoutPresetSnapshot(snapshot.activeProject),
- activePreset.snapshot
- ),
- };
+ return !areLayoutPresetSnapshotsEqual(createLayoutPresetSnapshot(snapshot.activeProject), activePreset.snapshot);
};
+/**
+ * Which preset the active project is on, read live.
+ *
+ * Deliberately not routed through the drift debounce below: the strip renders
+ * the selected tab from this, and a debounced read meant the control the user
+ * pressed was the last thing on screen to acknowledge the press.
+ */
+export const useActiveLayoutPresetId = (): LayoutPresetId =>
+ useWorkbenchSelector(selectActiveLayoutPresetId, Object.is);
+
/**
* Whether the live dock layout has diverged from the preset it was loaded from.
*
@@ -44,5 +46,6 @@ const selectLayoutDrift = (snapshot: WorkbenchSnapshot): LayoutDriftState => {
* blinks part-way through a gesture reads as a glitch rather than as
* information. Settling first means the user only ever sees the resting answer.
*/
-export const useLayoutDrift = (): LayoutDriftState =>
- useDebouncedWorkbenchSelector(selectLayoutDrift, DRIFT_SETTLE_MS, areDriftStatesEqual);
+export const useLayoutDrift = (): LayoutDriftState => ({
+ hasDrifted: useDebouncedWorkbenchSelector(selectHasDrifted, DRIFT_SETTLE_MS),
+});