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(workflow): media context menus in fields, outputs and pickers; tooltips stay under menus (#10338)
Josh Corbett06e13e1e6ae9
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 7c85219365..7a85b192f9 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -115,6 +115,7 @@ Feature interfaces stay ordinary module interfaces unless two adapters add lever- Models owns the served architecture table and its VAE pairing question. Generation maps the table onto its own policy; the Generate VAE picker, validator and compiler and Related Models' VAE links ask the same question, so pairings change only in the backend's `VaeFacet`. Pure cores read it through `features/models/architectures`; it loads on demand, off the Launchpad startup graph ([features/models/README.md](src/features/models/README.md#architecture-table)).- Gallery, Generation, Workflow, Upscale keep compilation and UI seams internal until a feature ticket shows another independent adapter. Workbench image actions also stay internal, not a shallow Image Feature.- Gallery picker and media slots read a narrow `GalleryHost`: gallery scope, notifications, optional Gallery-widget reveal. Workbench derives it from the Gallery UI adapter. Launchpad's model manager has no workbench and supplies its own.+- Gallery media shown outside the Gallery widget (workflow fields, outputs, picker tiles) opens the shared item menu through `useGalleryItemContextMenu` (`features/gallery/react`), which calls the Gallery UI adapter's stable `openItemContextMenu`. App fetches the item only when the surface has none and loads the menu with the lazy image-actions bridge; only the newest request in the active project opens, and the user's next click or Escape drops one still loading. A `GalleryHost` host has no item menu and keeps the browser's.- Media slots accept dragged gallery items only inside `GalleryDragScope`, provided by the workbench shell with its drag context. Widget dialog hosts and the Launchpad sit outside it.| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 6df101103a..ddb22eed96 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -510,6 +510,7 @@"source:src/app/WorkflowCommandShortcut.tsx","source:src/app/WorkflowUiAdapter.tsx","source:src/app/accountLifecycle.ts",+ "source:src/app/galleryItemMenu.tsx","source:src/app/loggingRuntime.ts","source:src/app/main.tsx","source:src/app/queueStagedResults.ts",@@ -779,6 +780,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/contextMenuPoint.ts","source:src/platform/react/draftRegistry.ts","source:src/platform/react/isEventFromOwnDom.ts","source:src/platform/react/useDebouncedValue.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 8871ce66b3..e73ed8fc53 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -623,6 +623,7 @@"source:src/platform/performance/semanticReady.ts","source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts",+ "source:src/platform/react/contextMenuPoint.ts","source:src/platform/react/useExitRetainedValue.ts","source:src/platform/react/useMountEffect.ts","source:src/platform/react/usePreservedScrollOffset.ts",@@ -914,6 +915,7 @@"source:src/app/WorkflowCommandShortcut.tsx","source:src/app/WorkflowUiAdapter.tsx","source:src/app/accountLifecycle.ts",+ "source:src/app/galleryItemMenu.tsx","source:src/app/loggingRuntime.ts","source:src/app/main.tsx","source:src/app/queueStagedResults.ts",@@ -1322,6 +1324,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/contextMenuPoint.ts","source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",@@ -2090,6 +2093,7 @@"source:src/app/WorkflowCommandShortcut.tsx","source:src/app/WorkflowUiAdapter.tsx","source:src/app/accountLifecycle.ts",+ "source:src/app/galleryItemMenu.tsx","source:src/app/loggingRuntime.ts","source:src/app/main.tsx","source:src/app/queueStagedResults.ts",@@ -2506,6 +2510,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/contextMenuPoint.ts","source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",@@ -3454,6 +3459,7 @@"source:src/app/WorkflowCommandShortcut.tsx","source:src/app/WorkflowUiAdapter.tsx","source:src/app/accountLifecycle.ts",+ "source:src/app/galleryItemMenu.tsx","source:src/app/loggingRuntime.ts","source:src/app/main.tsx","source:src/app/queueStagedResults.ts",@@ -3928,6 +3934,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/contextMenuPoint.ts","source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 119a20b7c0..64bed010bf 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -6680,6 +6680,7 @@"imagesSelected_other": "{{count}} images selected","itemsSelected_one": "{{count}} item selected","itemsSelected_other": "{{count}} items selected",+ "loadFailed": "Couldn't open the menu for this image or video. Try again.","newProjectFromImageHint_one": "Starts a canvas project from this image","newProjectFromImageHint_other": "Starts a canvas project from these images","openInNewTab": "Open in new tab",@@ -6690,6 +6691,7 @@"reuseFromVideo": "Reuse from video","sendToVideo": "Send to Video","sendToVideoHint": "Uses it as the first frame in Video",+ "unavailable": "This image or video is no longer available to you.","upscaleHint": "Opens Upscale with this image","useAsConditioningClip": "Use as conditioning clip","useAsControlHint": "Guides the next generation's structure",diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsxindex 2a11c74e61..246a9c9621 100644--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx@@ -1,14 +1,20 @@+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';import type { GalleryItemActionsOptions, GalleryItemContextMenuProps } from '@features/gallery/react';import type { ReactNode } from 'react';-import { GalleryItemActionsProvider } from '@features/gallery/react';+import { galleryItems } from '@features/gallery';+import { galleryBoardsOptions } from '@features/gallery/queries';+import { GalleryItemActionsProvider, useHostGalleryBoards } from '@features/gallery/react';+import { useQuery } from '@tanstack/react-query';import {ImageContextMenu,useDeletionConfirmation,useImageActions,type ImageActions,} from '@workbench/image-actions';-import { createContext, use } from 'react';+import { createContext, use, useCallback } from 'react';++import type { GalleryItemMenuHostProps, LoadedGalleryItemMenu } from './galleryItemMenu';const GalleryAppActionsContext = createContext<ImageActions | null>(null);@@ -50,3 +56,34 @@ const GalleryItemActionsAdapterComponent = ({export const GalleryItemActionsAdapter = GalleryItemActionsAdapterComponent;export const GalleryImageContextMenu = GalleryImageContextMenuComponent;++/** Mounted from the first opening on, so a deletion confirmation the menu opened survives the menu closing. */+const GalleryItemMenuHost = ({ generateValues, projectId, view, onClose }: GalleryItemMenuHostProps) => {+ const boards = useHostGalleryBoards(useQuery({ ...galleryBoardsOptions(), enabled: view !== null }).data);+ const viewId = view?.id;+ const handleClose = useCallback(() => {+ if (viewId !== undefined) {+ onClose(viewId);+ }+ }, [onClose, viewId]);++ return (+ <GalleryItemActionsAdapterComponent boards={boards} generateValues={generateValues} projectId={projectId}>+ <GalleryImageContextMenuComponent+ key={viewId}+ boards={boards}+ target={view?.target ?? null}+ onClose={handleClose}+ />+ </GalleryItemActionsAdapterComponent>+ );+};++export const loadGalleryItemMenu = async (+ ref: GalleryItemRef,+ item: GalleryItem | undefined,+ signal: AbortSignal+): Promise<LoadedGalleryItemMenu> => ({+ Host: GalleryItemMenuHost,+ item: item ?? (await galleryItems.resolve(ref, signal)),+});diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 5cf7f25e54..641479500c 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -1,5 +1,5 @@-import type { GalleryItemRef } from '@features/gallery/contracts';-import type { GalleryProjectRef, GalleryUiAdapter } from '@features/gallery/react';+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';+import type { GalleryItemContextMenuRequest, GalleryProjectRef, GalleryUiAdapter } from '@features/gallery/react';import type { ProjectLibrarySnapshot } from '@workbench/projects/library';import type { ReactNode } from 'react';@@ -8,6 +8,7 @@ import { GalleryUiProvider } from '@features/gallery/react';import { useAuthSession } from '@features/identity';import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';import { useWorkbenchFocus } from '@workbench/focusRegions';import { useProjectLibrarySelector } from '@workbench/projects/library';import { getProjectSyncSnapshot } from '@workbench/projects/syncStore';@@ -30,9 +31,11 @@ import {useWorkbenchQueries,useWorkbenchSelector,} from '@workbench/WorkbenchContext';-import { lazy, useMemo } from 'react';+import { lazy, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { createGalleryItemMenu, GalleryItemMenuSlot } from './galleryItemMenu';+const EMPTY_WIDGET_VALUES: Record<string, unknown> = Object.freeze({});/** The Gallery's values as it reads them: the project's pins over the user's gallery defaults. */@@ -62,6 +65,8 @@ const GalleryItemActionsAdapter = lazy(() =>const GalleryImageContextMenu = lazy(() =>import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageContextMenu })));+const loadGalleryItemMenu = (ref: GalleryItemRef, item: GalleryItem | undefined, signal: AbortSignal) =>+ import('./GalleryImageActionsBridge').then((module) => module.loadGalleryItemMenu(ref, item, signal));export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {const { projectId, projectName, galleryValues, generateValues, liveFollowEnabled } = useWorkbenchSelector(@@ -78,7 +83,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const boardSharing = useAuthSession().multiuserEnabled;const { gallery, notifications, widgets } = useWorkbenchCommands();const notify = useNotify();- const { t } = useTranslation();+ const { i18n, t } = useTranslation();const queries = useWorkbenchQueries();const accountScope = captureAccountScope();const exportProject = useExportLibraryProject();@@ -89,9 +94,30 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const projects = useProjectLibrarySelector(selectGalleryProjects, areGalleryProjectsEqual);const store = useWorkbenchInternalStore();const persistence = useWorkbenchPersistenceService();+ const [itemMenu] = useState(() => createGalleryItemMenu({ load: loadGalleryItemMenu }));+ // Stable, unlike the adapter: media surfaces subscribe to the opener alone.+ const [openItemContextMenu] = useState(() => (request: GalleryItemContextMenuRequest) => {+ const requestProjectId = queries.getSnapshot().activeProject.id;++ itemMenu.open(request, {+ isCurrent: () => queries.isActiveProject(requestProjectId),+ onFailure: (error) =>+ notifications.reportError({+ area: 'gallery-item-menu',+ message: i18n.t(+ error instanceof ApiError && (error.status === 403 || error.status === 404)+ ? 'widgets.gallery.itemMenu.unavailable'+ : 'widgets.gallery.itemMenu.loadFailed'+ ),+ namespace: 'gallery',+ }),+ });+ });// Preload row dependencies here to avoid a second fetch wave after the gallery mounts.useMountEffect(() => {void import('./GalleryImageActionsBridge');++ return itemMenu.dispose;});const adapter = useMemo<GalleryUiAdapter>(() => ({@@ -199,6 +225,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })reportError: notifications.reportError,undoable: (title, notice) => notify.undoable(title, { ...notice, projectId }),},+ openItemContextMenu,projectId,projectName,projects,@@ -230,6 +257,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })livePreview,notifications,notify,+ openItemContextMenu,openWorkbenchWidget,persistence,projectId,@@ -242,5 +270,10 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })]);- return <GalleryUiProvider adapter={adapter}>{children}</GalleryUiProvider>;+ return (+ <GalleryUiProvider adapter={adapter}>+ {children}+ <GalleryItemMenuSlot generateValues={generateValues} menu={itemMenu} projectId={projectId} />+ </GalleryUiProvider>+ );};diff --git a/invokeai/frontend/webv2/src/app/galleryItemMenu.test.ts b/invokeai/frontend/webv2/src/app/galleryItemMenu.test.tsnew file mode 100644index 0000000000..8034d6261b--- /dev/null+++ b/invokeai/frontend/webv2/src/app/galleryItemMenu.test.ts@@ -0,0 +1,82 @@+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';++import { describe, expect, it, vi } from 'vitest';++import { createGalleryItemMenu, type LoadedGalleryItemMenu } from './galleryItemMenu';++const Host = () => null;+const first = { kind: 'image', name: 'first.png' } as const;+const second = { kind: 'video', name: 'second.mp4' } as const;+const third = { kind: 'image', name: 'third.png' } as const;++const createMenu = () => {+ const interactions = new EventTarget();+ const loads = new Map<string, { promise: Promise<LoadedGalleryItemMenu>; resolve: () => void }>();+ const menu = createGalleryItemMenu({+ interactions,+ load: (ref) => {+ let resolve = () => {};+ const promise = new Promise<LoadedGalleryItemMenu>((settle) => {+ resolve = () => settle({ Host, item: ref as unknown as GalleryItem });+ });+ loads.set(ref.name, { promise, resolve });+ return promise;+ },+ });+ const settle = async (ref: GalleryItemRef) => {+ const load = loads.get(ref.name)!;+ load.resolve();+ await load.promise;+ };++ return { interactions, menu, settle };+};++const options = (isCurrent = () => true) => ({ isCurrent, onFailure: vi.fn() });++describe('gallery item menu', () => {+ it('shows only the newest request, and ignores a late close from the menu it replaced', async () => {+ const { menu, settle } = createMenu();+ const onFailure = vi.fn();++ menu.open({ ref: first, x: 1, y: 1 }, { isCurrent: () => true, onFailure });+ menu.open({ ref: second, x: 2, y: 2 }, { isCurrent: () => true, onFailure });+ await settle(second);+ await settle(first);++ expect(menu.getSnapshot().view?.target).toMatchObject({ itemRefs: [second], items: [second], x: 2, y: 2 });++ const secondViewId = menu.getSnapshot().view!.id;+ menu.open({ ref: third, x: 3, y: 3 }, { isCurrent: () => true, onFailure });+ await settle(third);+ menu.close(secondViewId);++ expect(menu.getSnapshot().view?.target.itemRefs).toEqual([third]);+ expect(onFailure).not.toHaveBeenCalled();+ });++ it.each([+ ['a click', new Event('pointerdown')],+ ['Escape', Object.assign(new Event('keydown'), { key: 'Escape' })],+ ])('drops a request still loading when the user moves on with %s', async (_, interaction) => {+ const { interactions, menu, settle } = createMenu();++ menu.open({ ref: first, x: 1, y: 1 }, options());+ interactions.dispatchEvent(interaction);+ await settle(first);++ expect(menu.getSnapshot().view).toBeNull();+ });++ it('drops a request whose project is no longer the active one when it is ready', async () => {+ const { menu, settle } = createMenu();++ menu.open(+ { ref: first, x: 1, y: 1 },+ options(() => false)+ );+ await settle(first);++ expect(menu.getSnapshot().view).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/app/galleryItemMenu.tsx b/invokeai/frontend/webv2/src/app/galleryItemMenu.tsxnew file mode 100644index 0000000000..46d4f00b7d--- /dev/null+++ b/invokeai/frontend/webv2/src/app/galleryItemMenu.tsx@@ -0,0 +1,147 @@+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';+import type { GalleryItemContextMenuRequest, GalleryItemContextMenuTarget } from '@features/gallery/react';+import type { ComponentType } from 'react';++import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { createExternalStoreCore } from '@platform/state/externalStoreCore';+import { useSyncExternalStore } from 'react';++export interface GalleryItemMenuView {+ id: number;+ target: GalleryItemContextMenuTarget;+}++export interface GalleryItemMenuHostProps {+ generateValues: Record<string, unknown>;+ projectId: string;+ view: GalleryItemMenuView | null;+ /** A new view mounts a new menu, so a late close from the one it replaced names that one. */+ onClose(viewId: number): void;+}++export interface LoadedGalleryItemMenu {+ Host: ComponentType<GalleryItemMenuHostProps>;+ item: GalleryItem;+}++interface GalleryItemMenuSnapshot {+ /** Kept once loaded: a deletion confirmation the menu opened outlives the menu. */+ Host: ComponentType<GalleryItemMenuHostProps> | null;+ view: GalleryItemMenuView | null;+}++export type GalleryItemMenu = ReturnType<typeof createGalleryItemMenu>;++export interface GalleryItemMenuOpenOptions {+ /** Checked when the menu is ready: false (the project changed, say) drops the request. */+ isCurrent: () => boolean;+ onFailure: (error: unknown) => void;+}++/**+ * One item menu for media shown outside the Gallery widget; only the newest request in this account may open it. A+ * request still loading is dropped by the user's next click or Escape, so a menu never opens over what they did next.+ */+export const createGalleryItemMenu = ({+ interactions,+ load,+}: {+ /** Where the user's next click or Escape is heard; the window unless given. */+ interactions?: Pick<EventTarget, 'addEventListener'>;+ /** Fetches the item only when `item` is missing. */+ load: (ref: GalleryItemRef, item: GalleryItem | undefined, signal: AbortSignal) => Promise<LoadedGalleryItemMenu>;+}) => {+ const store = createExternalStoreCore<GalleryItemMenuSnapshot>({ Host: null, view: null });+ let pending: AbortController | null = null;+ let nextId = 1;+ const cancelPending = () => {+ pending?.abort();+ pending = null;+ };++ return {+ /** Closes `viewId` only: a menu dismissed by the right-click that opened the next one leaves that one be. */+ close: (viewId: number) => {+ const { view } = store.getSnapshot();++ if (view?.id !== viewId) {+ return;+ }+ // The menu opened at a point, with no trigger to take focus back; an action that moved focus on keeps it there.+ if (document.activeElement?.closest('[role="menu"]')) {+ view.target.returnFocus?.()?.focus({ preventScroll: true });+ }+ store.patchSnapshot({ view: null });+ },+ dispose: cancelPending,+ getSnapshot: store.getSnapshot,+ open: (request: GalleryItemContextMenuRequest, { isCurrent, onFailure }: GalleryItemMenuOpenOptions) => {+ cancelPending();+ const controller = new AbortController();+ const scope = captureAccountScope();+ const isLive = () => pending === controller && isAccountScopeCurrent(scope);+ const listenerOptions = { capture: true, signal: controller.signal };+ const target = interactions ?? window;+ pending = controller;+ // Registered after the pointerdown that opened this request, so only a later one cancels it.+ target.addEventListener('pointerdown', cancelPending, listenerOptions);+ target.addEventListener(+ 'keydown',+ (event) => {+ if ((event as KeyboardEvent).key === 'Escape') {+ cancelPending();+ }+ },+ listenerOptions+ );++ load(request.ref, request.item, AbortSignal.any([controller.signal, scope.signal])).then(+ ({ Host, item }) => {+ if (!isLive()) {+ return;+ }+ cancelPending();+ if (!isCurrent()) {+ return;+ }+ store.setSnapshot({+ Host,+ view: {+ id: nextId++,+ target: {+ itemRefs: [request.ref],+ items: [item],+ returnFocus: request.returnFocus,+ x: request.x,+ y: request.y,+ },+ },+ });+ },+ (error: unknown) => {+ if (isLive()) {+ cancelPending();+ if (isCurrent()) {+ onFailure(error);+ }+ }+ }+ );+ },+ subscribe: store.subscribe,+ };+};++export const GalleryItemMenuSlot = ({+ generateValues,+ menu,+ projectId,+}: {+ generateValues: Record<string, unknown>;+ menu: GalleryItemMenu;+ projectId: string;+}) => {+ const { Host, view } = useSyncExternalStore(menu.subscribe, menu.getSnapshot, menu.getSnapshot);++ return Host ? <Host generateValues={generateValues} projectId={projectId} view={view} onClose={menu.close} /> : null;+};diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.tsindex 74d31d82de..357e0726be 100644--- a/invokeai/frontend/webv2/src/features/gallery/react.ts+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts@@ -5,9 +5,11 @@ export {type GalleryItemActions,type GalleryItemActionsOptions,type GalleryItemContextMenuProps,+ type GalleryItemContextMenuRequest,type GalleryItemContextMenuTarget,type GalleryHostProjectContext,type GalleryUiAdapter,+ useGalleryItemContextMenu,useHostGalleryBoards,useOptionalGalleryHostProjectContext,} from './ui/GalleryUiContext';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex d1df1fc27a..2ceac2a051 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -80,6 +80,7 @@ const adapter: GalleryUiAdapter = {followedProgressSessionId: null,followProgressSession: noop,notifications: { add: notificationsAdd, reportError: noop },+ openItemContextMenu: noop,projectId: 'project-1',projectName: 'Project',projects: [],diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsxindex 8051cf18d6..d41c5b4bfd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx@@ -176,6 +176,7 @@ const Harness = ({getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,notifications: { add: noop, reportError: noop },+ openItemContextMenu: noop,pinnedProgressSessionId: null,progressSessions,projectId: 'project-1',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsxindex bc47520a13..db73d1fae9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx@@ -81,8 +81,11 @@ export const GallerySearchField = ({ariaLabel: string;describedById?: string;endElement?: ReactNode;- /** Listbox wiring (`aria-controls`, `aria-activedescendant`) for hosts that drive a list from the field. */- inputProps?: Pick<React.ComponentProps<typeof Input>, 'aria-activedescendant' | 'aria-controls' | 'role'>;+ /** Listbox wiring (`aria-controls`, `aria-activedescendant`, the highlight's menu) for hosts driving a list from it. */+ inputProps?: Pick<+ React.ComponentProps<typeof Input>,+ 'aria-activedescendant' | 'aria-controls' | 'onContextMenu' | 'onPointerDown' | 'role'+ >;isInvalid?: boolean;mode?: 'metadata' | 'semantic';placeholder: string;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 6bd4d09418..d8e34ecec4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -12,8 +12,18 @@ import type { QueueProgressSession } from '@features/queue/contracts';import type { ResolvedValues } from '@platform/core/resolvedValues';import { asSingleAccountBoards } from '@features/gallery/core/boardAccess';+import { getContextMenuPoint, getContextMenuPointBelow } from '@platform/react/contextMenuPoint';import { createKeyedTransientStore, type KeyedTransientStore } from '@platform/state/externalStore';-import { createContext, use, useMemo, useState, type ComponentType, type ReactNode } from 'react';+import {+ createContext,+ use,+ useCallback,+ useMemo,+ useState,+ type ComponentType,+ type MouseEvent,+ type ReactNode,+} from 'react';export interface GalleryItemActions {/**@@ -60,6 +70,16 @@ export interface GalleryItemContextMenuTarget {y: number;}+export interface GalleryItemContextMenuRequest {+ /** What the surface already holds; the menu fetches the item without it. */+ item?: GalleryItem;+ ref: GalleryItemRef;+ /** Resolved on close. */+ returnFocus?: () => HTMLElement | null;+ x: number;+ y: number;+}+export interface GalleryItemContextMenuProps {boards: GalleryBoard[];target: GalleryItemContextMenuTarget | null;@@ -130,6 +150,11 @@ export interface GalleryUiAdapter {noteBoardBrowsed?(boardId: string): void;getItemLabel(item: GalleryItemRef): Promise<string | null>;notifications: GalleryNotificationsPort;+ /**+ * The item menu for media shown outside the Gallery widget; a newer request replaces a pending or open one. Stable:+ * media surfaces read it alone, so adapter rebuilds do not re-render them.+ */+ openItemContextMenu(request: GalleryItemContextMenuRequest): void;projectId: string;projectName: string;/** The open project need not be among them. */@@ -153,6 +178,7 @@ export interface GalleryUiAdapter {}const GalleryUiContext = createContext<GalleryUiAdapter | null>(null);+const GalleryItemContextMenuContext = createContext<GalleryUiAdapter['openItemContextMenu'] | undefined>(undefined);const GalleryItemActionsContext = createContext<GalleryItemActions | null>(null);export const GalleryItemActionsProvider = ({@@ -186,7 +212,9 @@ export const GalleryUiProvider = ({ adapter, children }: { adapter: GalleryUiAdareturn (<GalleryUiContext value={adapter}>- <GalleryLayoutStoreContext value={layoutStore}>{children}</GalleryLayoutStoreContext>+ <GalleryItemContextMenuContext value={adapter.openItemContextMenu}>+ <GalleryLayoutStoreContext value={layoutStore}>{children}</GalleryLayoutStoreContext>+ </GalleryItemContextMenuContext></GalleryUiContext>);};@@ -284,3 +312,66 @@ export const useGalleryHost = (): GalleryHost => {return resolved;};++const getFocusedElement = (): HTMLElement | null => {+ const { activeElement } = document;++ return activeElement instanceof HTMLElement && activeElement !== document.body ? activeElement : null;+};++const isGalleryItem = (media: GalleryItem | GalleryItemRef): media is GalleryItem => 'fullUrl' in media;++/**+ * The item menu for gallery media: an `onContextMenu` handler for an element showing it (right-click or the context-menu+ * key), or an `onClick` handler for a button that opens it, below the button. Pass the item itself when the surface has+ * it, so the menu opens without a fetch. Undefined without media or outside the workbench (a `GalleryHostProvider`+ * host), where the browser's own menu stays.+ *+ * `anchor` opens the menu below what it returns, or else below the handler's element, whatever the event's position:+ * for an element that only highlights the media (a field driving `aria-activedescendant`).+ */+export const useGalleryItemContextMenu = (+ media: GalleryItem | GalleryItemRef | null,+ anchor?: () => Element | null+): ((event: MouseEvent<HTMLElement>) => void) | undefined => {+ const host = use(GalleryHostContext);+ const open = use(GalleryItemContextMenuContext);+ const item = media && isGalleryItem(media) ? media : undefined;+ const kind = media?.kind;+ const name = media?.name;+ const handleContextMenu = useCallback(+ (event: MouseEvent<HTMLElement>) => {+ const { currentTarget, target } = event;++ // Handled already by media nested inside this one. React also bubbles events up from portals: a popover opened+ // from the media (its picker) keeps its own menus.+ if (+ !open ||+ kind === undefined ||+ name === undefined ||+ event.defaultPrevented ||+ !(target instanceof Node && currentTarget.contains(target))+ ) {+ return;+ }++ // Not stopped: owners around the media (a workflow node) read `defaultPrevented`, and window listeners (a touch+ // hold disarming its drag) must still hear the event.+ event.preventDefault();+ // A pressed button is the opener even where a click does not focus it.+ const isPress = event.type !== 'contextmenu';+ const opener = isPress ? currentTarget : getFocusedElement();+ const below = anchor ? (anchor() ?? currentTarget) : isPress ? currentTarget : null;++ open({+ ...(below ? getContextMenuPointBelow(below) : getContextMenuPoint(event)),+ item,+ ref: { kind, name },+ returnFocus: () => (opener?.isConnected ? opener : null),+ });+ },+ [anchor, item, kind, name, open]+ );++ return host || !open || kind === undefined || name === undefined ? undefined : handleContextMenu;+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsxindex 4713b5bfa4..5c59327ee4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx@@ -133,6 +133,7 @@ const adapter: GalleryUiAdapter = {getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,notifications: { add: noop, reportError: noop },+ openItemContextMenu: noop,pinnedProgressSessionId: null,progressSessions: [],projectId: 'project-1',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsxindex effd36f6bf..2f9584bf74 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx@@ -1,13 +1,14 @@import type { SystemStyleObject } from '@chakra-ui/react';import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';import type { GallerySparsePageState } from '@features/gallery/ui/useGalleryData';-import type { CSSProperties, MouseEvent } from 'react';+import type { ComponentProps, CSSProperties, MouseEvent } from 'react';import { Box, Icon, Skeleton, Stack, Text } from '@chakra-ui/react';import { toGalleryItemKey } from '@features/gallery/core/items';import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';import { getGalleryColumnCountForCell } from '@features/gallery/ui/galleryGridLayout';import { GalleryTileFrame, GalleryTileMedia } from '@features/gallery/ui/GalleryTileFrame';+import { useGalleryItemContextMenu } from '@features/gallery/ui/GalleryUiContext';import { Button } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { CheckIcon } from 'lucide-react';@@ -53,6 +54,24 @@ const getTileCss = (state: GalleryPickerTileState, isActive: boolean): SystemStyexport const galleryPickerOptionId = (idBase: string, index: number): string => `${idBase}-slot-${index}`;+const VIEWPORT_PROPS: ComponentProps<typeof Scrollable>['viewportProps'] & { 'data-gallery-picker-viewport': '' } = {+ 'data-gallery-picker-viewport': '',+};++/** The option's tile while its bottom edge, where a menu anchors, is in view; overscan keeps hidden rows mounted. */+export const getShownGalleryPickerOption = (idBase: string, index: number): HTMLElement | null => {+ const tile = document.getElementById(galleryPickerOptionId(idBase, index));+ const viewport = tile?.closest('[data-gallery-picker-viewport]')?.getBoundingClientRect();++ if (!tile || !viewport) {+ return null;+ }++ const rect = tile.getBoundingClientRect();++ return rect.bottom > viewport.top && rect.bottom <= viewport.bottom ? tile : null;+};+const GalleryPickerTile = memo(function GalleryPickerTile({activeIndex,currentKey,@@ -75,6 +94,7 @@ const GalleryPickerTile = memo(function GalleryPickerTile({const { t } = useTranslation();const key = toGalleryItemKey(item);const css = useMemo(() => getTileCss(state, index === activeIndex), [activeIndex, index, state]);+ const onContextMenu = useGalleryItemContextMenu(item);const unsupportedLabel =state === 'unsupported'? t(item.kind === 'video' ? 'widgets.gallery.picker.unsupportedVideo' : 'widgets.gallery.picker.unsupportedImage')@@ -94,6 +114,7 @@ const GalleryPickerTile = memo(function GalleryPickerTile({item={item}role="option"title={unsupportedLabel}+ onContextMenu={onContextMenu}><GalleryTileMediafit="square"@@ -351,7 +372,7 @@ export const GalleryPickerGrid = ({);return (- <Scrollable flex="1" minH="0" viewportRef={viewportRef}>+ <Scrollable flex="1" minH="0" viewportProps={VIEWPORT_PROPS} viewportRef={viewportRef}><Boxref={measureRef}aria-busy={isStale || (total === null && !isInitialPageFailed) || isAnyPageLoading || undefined}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsxindex af36c6c163..7901b903ca 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx@@ -1,7 +1,7 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop */import type { GalleryItem } from '@features/gallery/core/items';import type { GalleryBoard } from '@features/gallery/core/types';-import type { GalleryUiAdapter } from '@features/gallery/react';+import type { GalleryItemContextMenuRequest, GalleryUiAdapter } from '@features/gallery/react';import type { GalleryHost } from '@features/gallery/ui/GalleryUiContext';import { ChakraProvider } from '@chakra-ui/react';@@ -14,6 +14,7 @@ import { system } from '@theme/system';import { act, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';import { getGalleryPickerSelectionAfterPick, type GalleryPickerSelection } from './galleryPicker';import { GalleryPickerPopover } from './GalleryPickerPopover';@@ -135,11 +136,13 @@ let queryClient: QueryClient | null = null;const galleryCommands = { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() };const openGallery = vi.fn(() => true);const notifications = { add: vi.fn(), reportError: vi.fn() };+const openItemContextMenu = vi.fn();const adapter = {gallery: galleryCommands,galleryValues: { galleryView: 'images', selectedBoardId: 'dogs', selectedImage: dogItems[1] },notifications,+ openItemContextMenu,projectName: 'Project',widgets: { openGallery, patchGalleryValues: vi.fn() },} as unknown as GalleryUiAdapter;@@ -424,6 +427,52 @@ describe('GalleryPickerPopover', () => {await vi.waitFor(() => expect(document.activeElement).toBe(trigger));});+ it("opens the highlighted item's menu from the keyboard in the search field, and leaves a right-click to the browser", async () => {+ const { dialog } = await openPicker();+ const input = getSearchInput(dialog);++ await vi.waitFor(() => expect(document.activeElement).toBe(input));+ await pressKey(input, 'ArrowLeft');+ await vi.waitFor(() => expect(getActiveOption(dialog)).toBe(getOption(dialog, 'image:a.png')));+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));++ const expectHighlightedItemMenu = () => {+ const request = openItemContextMenu.mock.lastCall?.[0] as GalleryItemContextMenuRequest;+ const tile = getOption(dialog, 'image:a.png').getBoundingClientRect();++ expect(request).toMatchObject({ item: dogItems[0], ref: { kind: 'image', name: 'a.png' } });+ expect(request.x).toBeGreaterThanOrEqual(tile.left);+ expect(request.x).toBeLessThanOrEqual(tile.right);+ expect(request.y).toBeGreaterThanOrEqual(tile.top);+ expect(request.y).toBeLessThanOrEqual(tile.bottom);+ expect(request.returnFocus?.()).toBe(input);+ };++ expectHighlightedItemMenu();++ await act(() => userEvent.click(input, { button: 'right' }));+ expect(openItemContextMenu).toHaveBeenCalledOnce();++ // A key-opened menu in an engine that reports it like a right-click: the key press came after the pointer's.+ const field = input.getBoundingClientRect();++ await act(() => userEvent.click(input));+ await pressKey(input, 'F10');+ await act(() =>+ input.dispatchEvent(+ new MouseEvent('contextmenu', {+ bubbles: true,+ button: 2,+ cancelable: true,+ clientX: field.left + field.width / 2,+ clientY: field.top + field.height / 2,+ })+ )+ );+ expect(openItemContextMenu).toHaveBeenCalledTimes(2);+ expectHighlightedItemMenu();+ });+it('dims tiles the slot cannot take and ignores clicks on them', async () => {const { dialog } = await openPicker();const videoTile = getOption(dialog, 'video:c.mp4');diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxindex c08da31e17..75d2e0baf2 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -1,6 +1,6 @@import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';import type { GallerySparseListing } from '@features/gallery/ui/useGalleryData';-import type { KeyboardEvent, RefObject } from 'react';+import type { KeyboardEvent, MouseEvent, RefObject } from 'react';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';@@ -12,12 +12,13 @@ import { GalleryAnnouncer, GalleryLoadNotice } from '@features/gallery/ui/Gallerimport { GallerySearchField } from '@features/gallery/ui/GallerySearchField';import { GallerySearchHelp } from '@features/gallery/ui/GallerySearchHelp';import { getGalleryProjectBoardId, getGallerySelectedBoardId } from '@features/gallery/ui/galleryStateView';-import { useGalleryHost } from '@features/gallery/ui/GalleryUiContext';+import { useGalleryHost, useGalleryItemContextMenu } from '@features/gallery/ui/GalleryUiContext';import { getGalleryUploadTargetLabel } from '@features/gallery/ui/GalleryUploadButton';import { GalleryViewSegmentTabs } from '@features/gallery/ui/GalleryViewTabs';import { useGalleryUploadAction } from '@features/gallery/ui/useGalleryUploadAction';import { useGalleryUploadInput } from '@features/gallery/ui/useGalleryUploadInput';import { isImeComposing } from '@platform/browser/imeComposition';+import { isKeyboardContextMenu } from '@platform/react/contextMenuPoint';import { getApiErrorMessage } from '@platform/transport/http';import { Button, CloseButton, IconButton } from '@platform/ui/Button';import { LoadError } from '@platform/ui/LoadError';@@ -42,7 +43,7 @@ import {type GalleryPickerSelection,} from './galleryPicker';import { GalleryPickerBoards, type GalleryPickerBoardGroup } from './GalleryPickerBoards';-import { galleryPickerOptionId, GalleryPickerGrid } from './GalleryPickerGrid';+import { galleryPickerOptionId, GalleryPickerGrid, getShownGalleryPickerOption } from './GalleryPickerGrid';import { useGalleryPickerScope, type GalleryPickerOpeningScope } from './useGalleryPickerScope';const BOARD_BUTTON_EXPANDED_PROPS = { bg: 'bg.hover' } as const;@@ -306,8 +307,16 @@ export const GalleryPickerView = ({[focusSearch, selectBoard]);+ // Whether the next `contextmenu` on the field follows a pointer press. Engines differ in how a key-opened one looks,+ // but only a pointer-opened one (mouse, Ctrl-click, touch hold) comes after a `pointerdown`.+ const searchPointerPressedRef = useRef(false);const handleSearchKeyDown = useCallback((event: KeyboardEvent<HTMLInputElement>) => {+ // Not a repeat: a modifier held through a right-click keeps repeating until the menu opens on release.+ if (!event.repeat) {+ searchPointerPressedRef.current = false;+ }+if (isImeComposing(event.nativeEvent)) {return;}@@ -453,6 +462,31 @@ export const GalleryPickerView = ({),[handleClearSearch, scope.pane, scope.searchTerm, t]);+ // Focus stays in the field, so the context-menu key reaches it rather than the highlighted tile.+ const getHighlightedTile = useCallback(+ () => getShownGalleryPickerOption(listboxId, resolvedActiveIndex),+ [listboxId, resolvedActiveIndex]+ );+ const openHighlightedItemMenu = useGalleryItemContextMenu(+ showsGrid && !isStale ? (activeItem ?? null) : null,+ getHighlightedTile+ );+ const handleSearchPointerDown = useCallback(() => {+ searchPointerPressedRef.current = true;+ }, []);+ // A right-click on the field keeps the browser's menu (paste); anything else opens the highlighted item's.+ const handleSearchContextMenu = useCallback(+ (event: MouseEvent<HTMLInputElement>) => {+ const fromPointer = searchPointerPressedRef.current && !isKeyboardContextMenu(event);++ searchPointerPressedRef.current = false;++ if (!fromPointer) {+ openHighlightedItemMenu?.(event);+ }+ },+ [openHighlightedItemMenu]+ );const searchInputProps = useMemo(() =>scope.pane === 'boards'@@ -464,9 +498,20 @@ export const GalleryPickerView = ({? galleryPickerOptionId(listboxId, resolvedActiveIndex): undefined,'aria-controls': listboxId,+ onContextMenu: handleSearchContextMenu,+ onPointerDown: handleSearchPointerDown,}: undefined,- [boardsId, isStale, listboxId, resolvedActiveIndex, scope.pane, showsGrid]+ [+ boardsId,+ handleSearchContextMenu,+ handleSearchPointerDown,+ isStale,+ listboxId,+ resolvedActiveIndex,+ scope.pane,+ showsGrid,+ ]);const searchLabel =scope.pane === 'boards'diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex bf9cf09e75..9a5273afb2 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -222,6 +222,7 @@ const adapter: GalleryUiAdapter = {reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),undoable: (...args: unknown[]) => mocks.notificationsUndoable(...args),},+ openItemContextMenu: vi.fn(),projectId: 'project-1',projectName: 'Project',projects: [],diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 1eda4f374e..e861835eef 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -111,6 +111,7 @@ const adapter: GalleryUiAdapter = {add: (...args: unknown[]) => mocks.notificationsAdd(...args),reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),},+ openItemContextMenu: noop,projectId: 'project-1',projectName: 'Project',projects: [],diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsxindex f51fbbfd3c..5a6dc2d5c8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx@@ -5,6 +5,7 @@ import type { KeyboardEvent, MouseEvent, ReactNode } from 'react';import { Box, Collapsible, Flex, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';import { canCopyText, copyText } from '@platform/browser/clipboard';+import { getContextMenuPoint } from '@platform/react/contextMenuPoint';import { MenuContent, MenuItem, useContextMenu } from '@platform/ui/Menu';import { ChevronRightIcon, CircleAlertIcon } from 'lucide-react';import { useCallback, useId, useState } from 'react';@@ -220,11 +221,6 @@ export const GenerateCollapsibleSection = ({const trigger = event.currentTarget;const root = trigger.parentElement!;const sections = panelSections();- // A keyboard-opened menu has no pointer position of its own (see `GenerateFieldContextMenu`).- const native = event.nativeEvent as Partial<PointerEvent>;- const fromKeyboard =- event.button === -1 || native.pointerType === '' || (event.clientX === 0 && event.clientY === 0);- const rect = trigger.getBoundingClientRect();setMenuFacts({anyFolded: sections.some((entry) => !isPanelSectionOpen(entry)),@@ -232,11 +228,10 @@ export const GenerateCollapsibleSection = ({root,});open({+ ...getContextMenuPoint(event),// A frame late: Zag focuses the menu a frame after a highlight, and a pick within that frame would otherwise land// focus back in the closing menu.restoreFocus: () => requestAnimationFrame(() => trigger.focus()),- x: fromKeyboard ? rect.left : event.clientX,- y: fromKeyboard ? rect.bottom : event.clientY,});};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsxindex ddf8f05b97..ca872415a1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx@@ -3,6 +3,7 @@ import type { MouseEvent, ReactNode } from 'react';import { Box, chakra, Menu, Portal } from '@chakra-ui/react';import { canCopyText, copyText } from '@platform/browser/clipboard';+import { getContextMenuPoint } from '@platform/react/contextMenuPoint';import { MenuContent, MenuItem, useContextMenu } from '@platform/ui/Menu';import { Tooltip } from '@platform/ui/Tooltip';import { useTranslation } from 'react-i18next';@@ -108,21 +109,9 @@ export const GenerateFieldContextMenu = ({const handleContextMenu = (event: MouseEvent<HTMLDivElement>) => {event.preventDefault();- // A keyboard-opened menu has no pointer position of its own: Chromium reports button -1 at wherever the mouse last- // was, other engines no pointer type or 0,0.- const native = event.nativeEvent as Partial<PointerEvent>;- const fromKeyboard =- event.button === -1 || native.pointerType === '' || (event.clientX === 0 && event.clientY === 0);const focused = document.activeElement instanceof HTMLElement ? document.activeElement : null;- const rect = (- focused && event.currentTarget.contains(focused) ? focused : event.currentTarget- ).getBoundingClientRect();- open({- restoreFocus: focused ? () => focused.focus() : undefined,- x: fromKeyboard ? rect.left : event.clientX,- y: fromKeyboard ? rect.bottom : event.clientY,- });+ open({ ...getContextMenuPoint(event), restoreFocus: focused ? () => focused.focus() : undefined });};return (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsxindex 9d3e54fa0f..bd35f2831f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx@@ -1,15 +1,19 @@import type { GeneratedImageContract } from '@features/gallery';+import type { GalleryItemRef } from '@features/gallery/contracts';import type { NodeProps } from '@xyflow/react';+import type { MouseEvent, ReactNode } from 'react';-import { Box, Flex, Text } from '@chakra-ui/react';+import { Box, Flex, Icon, Text } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';+import { useGalleryItemContextMenu } from '@features/gallery/react';import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { useProgressImage } from '@features/queue/react';import {getWorkflowNodeHeaderProps,getWorkflowNodeShellProps,useIsWorkflowImageExport,+ WorkflowNodeHeaderButton,} from '@features/workflow/ui/nodeChrome';import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';@@ -18,7 +22,8 @@ import {imageUrlToStreamingSource,progressImageToStreamingSource,} from '@platform/ui/streaming-image/streamingImageSource';-import { memo, useId, useMemo, type ReactNode } from 'react';+import { EllipsisVerticalIcon } from 'lucide-react';+import { memo, useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';@@ -57,24 +62,36 @@ const isSameImageView = (a: CurrentImageView | null, b: CurrentImageView | null)a.height === b.height);/** The image under the node's frame, draggable wherever gallery images can be dropped. */-const DraggableCurrentImage = ({ children, image }: { children: ReactNode; image: CurrentImageView | null }) => {+const DraggableCurrentImage = ({+ children,+ itemRef,+ onContextMenu,+}: {+ children: ReactNode;+ itemRef: GalleryItemRef | null;+ onContextMenu: ((event: MouseEvent<HTMLElement>) => void) | undefined;+}) => {const disabledId = useId();- const dragData = useMemo(- () => (image ? getGalleryItemDragData([{ kind: 'image', name: image.imageName }]) : undefined),- [image]- );- // Pointer drags only, as the Preview frame's: the image is no tab stop, so the canvas keeps its own keys.+ const dragData = useMemo(() => (itemRef ? getGalleryItemDragData([itemRef]) : undefined), [itemRef]);+ // Pointer drags only, as the Preview frame's: the image is no tab stop, so the canvas keeps its own keys. The header's+ // button is the keyboard's way to the item menu.const { listeners, setNodeRef } = useDraggable({data: dragData,- disabled: !image,- id: image- ? getGalleryItemDragId({ kind: 'image', name: image.imageName }, 'workflow-current-image', disabledId)+ disabled: !itemRef,+ id: itemRef+ ? getGalleryItemDragId(itemRef, 'workflow-current-image', disabledId): `workflow-current-image:disabled:${disabledId}`,});return (// `nodrag`: the canvas leaves the pointer to the image drag rather than moving the node.- <Box ref={setNodeRef} className="nodrag" cursor={image ? 'grab' : undefined} {...listeners}>+ <Box+ ref={setNodeRef}+ className="nodrag"+ cursor={itemRef ? 'grab' : undefined}+ onContextMenu={onContextMenu}+ {...listeners}+ >{children}</Box>);@@ -87,6 +104,13 @@ const CurrentImageEditorNode = ({ data, selected }: NodeProps<CurrentImageFlowNoconst progressImage = useProgressImage();const node = data.documentNode;const title = node.data.label || t('widgets.workflow.addNodeDialog.currentImageTitle');+ const shownImageName = progressImage ? null : image?.imageName;+ const itemRef = useMemo<GalleryItemRef | null>(+ () => (shownImageName ? { kind: 'image', name: shownImageName } : null),+ [shownImageName]+ );+ const openItemMenu = useGalleryItemContextMenu(itemRef);+ const imageActionsLabel = t('widgets.preview.imageActions');return (<Box@@ -96,15 +120,25 @@ const CurrentImageEditorNode = ({ data, selected }: NodeProps<CurrentImageFlowNow="20rem"{...getWorkflowNodeShellProps({ selected })}>- <Flex {...getWorkflowNodeHeaderProps()}>- <Text fontWeight="600">{title}</Text>+ <Flex {...getWorkflowNodeHeaderProps({ endsWithButton: openItemMenu !== undefined })}>+ <MiddleTruncate flex="1" fontWeight="600" minW="0" text={title} />{progressImage ? (- <Text color="brand.solid" data-node-status-indicator="true" fontSize="xs" ms="auto">+ <Text color="brand.solid" data-node-status-indicator="true" flexShrink={0} fontSize="xs">{t('widgets.workflow.generating')}</Text>+ ) : openItemMenu ? (+ <WorkflowNodeHeaderButton+ aria-haspopup="menu"+ aria-label={imageActionsLabel}+ className="nodrag"+ content={imageActionsLabel}+ onClick={openItemMenu}+ >+ <Icon as={EllipsisVerticalIcon} boxSize="3.5" />+ </WorkflowNodeHeaderButton>) : null}</Flex>- <DraggableCurrentImage image={progressImage ? null : image}>+ <DraggableCurrentImage itemRef={itemRef} onContextMenu={openItemMenu}><StreamingImageFramefallbackImage={imageUrlToStreamingSource({alt: image?.imageName ?? title,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex 834a2a9144..47d0146b49 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx@@ -12,6 +12,7 @@ import openapi from '@api/openapi.json';/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop -- each render mounts a fresh flow on purpose */import { Box, ChakraProvider } from '@chakra-ui/react';import { DndContext, type DragStartEvent } from '@dnd-kit/core';+import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';import { galleryImageUrls } from '@features/gallery/utility';import { parseOpenApiToTemplates } from '@features/workflow/data/templates';import { flowThemeCss } from '@features/workflow/ui/graph-preview/flowTheme';@@ -1413,8 +1414,11 @@ describe('InvocationFlowNode collapsed ports', () => {describe('CurrentImageFlowNode', () => {let host: HTMLDivElement;let root: Root;+ const openItemContextMenu = vi.fn();+ const galleryAdapter = { openItemContextMenu } as unknown as GalleryUiAdapter;beforeEach(() => {+ openItemContextMenu.mockClear();host = document.createElement('div');host.style.cssText = 'width: 480px; height: 520px;';document.body.append(host);@@ -1468,10 +1472,12 @@ describe('CurrentImageFlowNode', () => {{ ...createAdapter(createExecutionPort().port), project: project.port } as unknown as WorkflowUiAdapter}>- {/* Stands in for the shell's drag context, where gallery items are dragged. */}- <DndContext onDragStart={onDragStart}>- <ReactFlow edges={[]} nodes={currentImageNodes} nodeTypes={nodeTypes} />- </DndContext>+ <GalleryUiProvider adapter={galleryAdapter}>+ {/* Stands in for the shell's drag context, where gallery items are dragged. */}+ <DndContext onDragStart={onDragStart}>+ <ReactFlow edges={[]} nodes={currentImageNodes} nodeTypes={nodeTypes} />+ </DndContext>+ </GalleryUiProvider></WorkflowUiProvider></ChakraProvider>)@@ -1512,6 +1518,42 @@ describe('CurrentImageFlowNode', () => {expect(source!.getAttribute('role')).toBeNull();});+ it("opens the shown image's menu from a header button the keyboard reaches, only while an image is shown", async () => {+ const project = createGalleryProject({ recentImages: [recent] });+ const menuButton = () => host.querySelector<HTMLButtonElement>('button[aria-label="Image actions"]');+ await render(project);+ await vi.waitFor(() => expect(shownImage()).toBe(recent.imageUrl));++ const flowNode = host.querySelector<HTMLElement>('.react-flow__node')!;+ // The flow keeps a node hidden, so unfocusable, until it has measured it.+ await vi.waitFor(() => {+ flowNode.focus();+ expect(document.activeElement).toBe(flowNode);+ });+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(menuButton());+ await act(() => userEvent.keyboard('{Enter}'));++ const button = menuButton()!.getBoundingClientRect();+ expect(openItemContextMenu).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ ref: { kind: 'image', name: 'recent.png' }, x: button.left, y: button.bottom })+ );+ expect(openItemContextMenu.mock.lastCall![0].returnFocus()).toBe(menuButton());++ // A pointer press opens it below the button too, not at the pointer.+ await act(() => userEvent.click(menuButton()!));+ expect(openItemContextMenu.mock.lastCall![0]).toMatchObject({ x: button.left, y: button.bottom });++ exportMocks.progressImage = { dataUrl: outputImage(1, 1), height: 1, width: 1 };+ await act(() => project.setGalleryValues({ recentImages: [chosen] }));+ expect(host.textContent).toContain('Generating');+ expect(menuButton()).toBeNull();++ exportMocks.progressImage = null;+ await act(() => project.setGalleryValues({}));+ expect(menuButton()).toBeNull();+ });+it('does not render again for gallery changes that leave the shown image alone', async () => {const renders = vi.spyOn(exportMocks, 'progressImage', 'get');const project = createGalleryProject({ recentImages: [recent], selectedBoardId: 'a' });diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsxindex c696b0064f..af5de1359f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx@@ -496,6 +496,60 @@ describe('WorkflowEditorView fit selection', () => {});});+describe('WorkflowEditorView context menus', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ clearWorkflowViewports();+ });++ it('leaves a right-click inside a popover opened from a node to the browser', async () => {+ await renderEditor(root, createProjectStore({ ...createProjectGraph('portal'), nodes: [addNode('only', 0, 0)] }));+ const trigger = await vi.waitFor(() => {+ const element = host.querySelector<HTMLElement>('button[aria-label="nodes.editFieldDescription"]');+ expect(element).not.toBeNull();+ return element!;+ });+ await userEvent.click(trigger);+ const textarea = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>('textarea[aria-label="nodes.fieldDescription"]');+ expect(element).not.toBeNull();+ return element!;+ });+ expect(host.contains(textarea)).toBe(false);++ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true });+ await act(() => textarea.dispatchEvent(event));++ expect(event.defaultPrevented).toBe(false);+ expect(document.querySelector('[role="menu"]')).toBeNull();+ });++ it('opens no node menu over a right-click the node’s content handled, as its media does', async () => {+ await renderEditor(root, createProjectStore({ ...createProjectGraph('media'), nodes: [addNode('only', 0, 0)] }));+ const content = await vi.waitFor(() => {+ const element = host.querySelector<HTMLElement>('.react-flow__node[data-id="only"] input');+ expect(element).not.toBeNull();+ return element!;+ });+ content.addEventListener('contextmenu', (event) => event.preventDefault());++ await act(() => content.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })));++ expect(document.querySelector('[role="menu"]')).toBeNull();+ });+});+describe('WorkflowEditorView paste', () => {let host: HTMLDivElement;let outside: HTMLButtonElement;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex a150c30501..c84c7ef5cb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -1068,6 +1068,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {);const onNodeContextMenu = useCallback((event: ReactMouseEvent, node: WorkflowFlowNode) => {+ // Media inside the node handled it (with the item menu). React also bubbles events up from portals: a popover,+ // menu or dialog opened from the node keeps its own menu, and the browser's.+ if (event.defaultPrevented || !(event.target instanceof Node && event.currentTarget.contains(event.target))) {+ return;+ }+event.preventDefault();setContextMenu({kind: 'node',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsxindex e78a90fee0..38961935ed 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx@@ -4,7 +4,7 @@ import { Button, useUnavailableControl } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';import { VideoPlayer } from '@platform/ui/video-player/VideoPlayer';import { getFrameAtTime, getFrameTime } from '@platform/ui/video-player/videoTimeline';-import { useCallback, useMemo, useState, type SyntheticEvent } from 'react';+import { useCallback, useMemo, useState, type MouseEventHandler, type SyntheticEvent } from 'react';import { useTranslation } from 'react-i18next';export interface VideoFramePickerProps {@@ -13,6 +13,7 @@ export interface VideoFramePickerProps {fps: number;frameCount: number;onChange: (value: unknown) => void;+ onContextMenu?: MouseEventHandler<HTMLElement>;posterUrl: string;resolvedIndex: number;videoUrl: string;@@ -60,6 +61,7 @@ export const VideoFramePicker = ({fps,frameCount,onChange,+ onContextMenu,posterUrl,resolvedIndex,videoUrl,@@ -114,7 +116,7 @@ export const VideoFramePicker = ({return (// `nodrag` keeps pointer drags on the scrubber from moving the node; `nokey` keeps its arrow keys from nudging it.<Flex className="nodrag nokey" direction="column" gap="1" w="full">- <Box borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full">+ <Box borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full" onContextMenu={onContextMenu}><VideoPlayerref={setVideo}aria-label={t('nodes.framePreview')}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsxindex 956b4d1ae7..74c4154fd1 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx@@ -10,6 +10,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { createInstance, type i18n as I18nInstance } from 'i18next';import { act, cloneElement, startTransition, useCallback, useState } from 'react';+import { createPortal } from 'react-dom';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider } from 'react-i18next';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';@@ -29,7 +30,7 @@ const uploadImageMock = vi.fn();const uploadVideoMock = vi.fn();const resolveItemMock = vi.fn();-const pickerState = vi.hoisted(() => ({ accept: null as readonly string[] | null }));+const pickerState = vi.hoisted(() => ({ accept: null as readonly string[] | null, isOpen: false }));const workflowApiMock = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn() }));const workflowCommandsMock = vi.hoisted(() => ({ editGraph: vi.fn() }));const findInGalleryMock = vi.hoisted(() => vi.fn());@@ -52,7 +53,13 @@ vi.mock('@features/gallery/picker', () => ({}) => {pickerState.accept = accept;- return cloneElement(children, { onClick: () => onPick(SELECTED_GALLERY_VIDEO) });+ return (+ <>+ {cloneElement(children, { onClick: () => onPick(SELECTED_GALLERY_VIDEO) })}+ {/* The real picker's content is portaled out of the field, as here. */}+ {pickerState.isOpen ? createPortal(<input aria-label="Search the picker" />, document.body) : null}+ </>+ );},}));@@ -656,6 +663,93 @@ describe('WorkflowFieldInput media inputs', () => {expect(uploadVideoMock).toHaveBeenCalledTimes(1);expect(uploadVideoMock.mock.calls[0]?.[1]).toBe('none');});++ const renderMediaMenuField = async (onNodeContextMenu?: (event: React.MouseEvent) => void) => {+ const openItemContextMenu = vi.fn();+ const adapter = { openItemContextMenu } as unknown as GalleryUiAdapter;++ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <DndContext>+ <GalleryUiProvider adapter={adapter}>+ <div onContextMenu={onNodeContextMenu}>+ <WorkflowFieldInput template={VIDEO_TEMPLATE} value={{ video_name: 'clip.mp4' }} onChange={vi.fn()} />+ </div>+ </GalleryUiProvider>+ </DndContext>+ </QueryClientProvider>+ </ChakraProvider>+ );+ });+ await vi.waitFor(() => {+ expect(host.textContent).toContain('640x480 · 5s');+ });++ // The thumbnail itself errors in the test server; the well's picker button holds it.+ return {+ openItemContextMenu,+ well: host.querySelector<HTMLElement>('button[aria-label="widgets.gallery.picker.chooseVideo"]')!,+ };+ };++ it("opens the gallery's item menu for the field's media at the pointer, and leaves its picker's to the browser", async () => {+ const nodeMenu = vi.fn((event: React.MouseEvent) => event.defaultPrevented);+ pickerState.isOpen = true;++ try {+ const { openItemContextMenu, well } = await renderMediaMenuField(nodeMenu);+ const rightClick = async (element: Element) => {+ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 30, clientY: 40 });+ await act(() => element.dispatchEvent(event));+ return event;+ };++ expect((await rightClick(well)).defaultPrevented).toBe(true);+ // The node reads this to stay out of the way.+ expect(nodeMenu).toHaveLastReturnedWith(true);+ expect(openItemContextMenu).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ item: expect.objectContaining({ kind: 'video', name: 'clip.mp4' }),+ ref: { kind: 'video', name: 'clip.mp4' },+ x: 30,+ y: 40,+ })+ );++ expect(+ (await rightClick(document.querySelector('input[aria-label="Search the picker"]')!)).defaultPrevented+ ).toBe(false);+ expect(openItemContextMenu).toHaveBeenCalledOnce();+ } finally {+ pickerState.isOpen = false;+ }+ });++ it('anchors a keyboard-opened item menu below the start of the focused media, on screen, not at the pointer', async () => {+ const { openItemContextMenu, well } = await renderMediaMenuField();+ const elsewhere = document.createElement('div');+ const openFromKeyboard = async () => {+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));+ return openItemContextMenu.mock.lastCall?.[0] as { x: number; y: number };+ };++ elsewhere.style.cssText = 'position:fixed;right:0;bottom:0;width:20px;height:20px';+ host.append(elsewhere);+ await userEvent.hover(elsewhere);+ well.focus();+ const rect = well.getBoundingClientRect();++ expect(await openFromKeyboard()).toMatchObject({ x: rect.left, y: rect.bottom });++ // Media can run past the viewport where scrolling cannot reveal it, as a node on the transformed workflow canvas.+ host.style.cssText = `position:fixed;inset-inline:0;top:${window.innerHeight - rect.height / 2}px`;+ const moved = well.getBoundingClientRect();++ expect(moved.bottom).toBeGreaterThan(window.innerHeight);+ expect(await openFromKeyboard()).toMatchObject({ x: moved.left, y: window.innerHeight });+ });});describe('WorkflowFieldInput video frame picker', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex ae5f32c35d..f5c36e51fc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -45,7 +45,11 @@ import {getCachedGalleryBoard,invalidateGallery,} from '@features/gallery/queries';-import { useHostGalleryBoards, useOptionalGalleryHostProjectContext } from '@features/gallery/react';+import {+ useGalleryItemContextMenu,+ useHostGalleryBoards,+ useOptionalGalleryHostProjectContext,+} from '@features/gallery/react';import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';import { DEFAULT_LORA_WEIGHT_CONFIG, sanitizeBatchCount, SCHEDULER_OPTIONS } from '@features/generation/settings';import { isInvocationNode } from '@features/workflow/contracts';@@ -124,6 +128,7 @@ import {useState,useSyncExternalStore,type ChangeEvent,+ type MouseEventHandler,} from 'react';import { useTranslation } from 'react-i18next';@@ -791,9 +796,17 @@ const ImageCollectionTile = ({const { findInGallery } = useWorkflowUi();const onRemoveClick = useCallback(() => onRemove(index), [index, onRemove]);const onFind = useCallback(() => findInGallery({ kind: 'image', name }), [findInGallery, name]);+ const onContextMenu = useGalleryItemContextMenu({ kind: 'image', name });return (- <Box aspectRatio="1" bg="bg.subtle" className="group" position="relative" rounded="xs">+ <Box+ aspectRatio="1"+ bg="bg.subtle"+ className="group"+ position="relative"+ rounded="xs"+ onContextMenu={onContextMenu}+ ><Imagealt=""h="full"@@ -1064,6 +1077,8 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPrretry: false,staleTime: 60_000,});+ const shownItem = mediaItem?.kind === kind && mediaItem.name === mediaName ? mediaItem : null;+ const onContextMenu = useGalleryItemContextMenu(shownItem ?? (mediaName ? { kind, name: mediaName } : null));const badge =mediaItem && mediaItem.name === mediaName && mediaItem.width > 0? `${mediaItem.width}x${mediaItem.height}${@@ -1083,7 +1098,15 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr<Box position="relative" w="full" {...invalidAriaProps}><MediaDropMonitor dropId={dropId} kind={kind} onDrop={onMediaDrop} />{/* The whole preview area is the drop target. */}- <Box ref={setNodeRef} className="nodrag group" h="32" position="relative" rounded="sm" w="full">+ <Box+ ref={setNodeRef}+ className="nodrag group"+ h="32"+ position="relative"+ rounded="sm"+ w="full"+ onContextMenu={onContextMenu}+ ><GalleryPickerPopover accept={pickerAccept} label={pickerLabel} onPick={onPick}><chakra.buttonaria-label={mediaName ? pickerLabel : undefined}@@ -1199,12 +1222,18 @@ const VideoFramePicker = lazy(() =>);/** The picker's box and button row while its player loads, so the node does not change size. */-const VideoFramePickerFallback = ({ posterUrl }: { posterUrl: string }) => {+const VideoFramePickerFallback = ({+ onContextMenu,+ posterUrl,+}: {+ onContextMenu: MouseEventHandler<HTMLElement> | undefined;+ posterUrl: string;+}) => {const { t } = useTranslation();return (<Flex direction="column" gap="1" w="full">- <Box bg="black" borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full">+ <Box bg="black" borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full" onContextMenu={onContextMenu}><Image alt="" h="full" objectFit="contain" src={posterUrl} w="full" /></Box><Button alignSelf="flex-start" disabled size="sm" variant="outline">@@ -1268,9 +1297,11 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {: Math.max(0, Math.min(frameCount - 1, numericValue < 0 ? frameCount + numericValue : numericValue));const posterUrl = video?.thumbnailUrl ?? null;+ const onVideoContextMenu = useGalleryItemContextMenu(video);const pickerFallback = useMemo(- () => (posterUrl === null ? null : <VideoFramePickerFallback posterUrl={posterUrl} />),- [posterUrl]+ () =>+ posterUrl === null ? null : <VideoFramePickerFallback posterUrl={posterUrl} onContextMenu={onVideoContextMenu} />,+ [onVideoContextMenu, posterUrl]);return (@@ -1287,6 +1318,7 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {resolvedIndex={resolvedIndex}videoUrl={video.fullUrl}onChange={onChange}+ onContextMenu={onVideoContextMenu}/></Suspense>) : (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsxindex 0fde733cb6..444b75f6c8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx@@ -8,6 +8,7 @@ import type { ChangeEvent } from 'react';import { Box, Flex, HStack, Image, Stack, Text, Textarea } from '@chakra-ui/react';import { FindInGalleryThumbnailButton } from '@features/gallery/mediaSlot';+import { useGalleryItemContextMenu } from '@features/gallery/react';import { galleryImageUrls } from '@features/gallery/utility';import { useInvocationTemplatesSelector } from '@features/workflow/react';import { workflowSelectionStore } from '@features/workflow/ui/editor/selectionStore';@@ -144,9 +145,10 @@ const OutputImage = ({ imageName }: { imageName: string }) => {const { t } = useTranslation();const { findInGallery } = useWorkflowUi();const onFind = useCallback(() => findInGallery({ kind: 'image', name: imageName }), [findInGallery, imageName]);+ const onContextMenu = useGalleryItemContextMenu({ kind: 'image', name: imageName });return (- <Box className="group" position="relative">+ <Box className="group" position="relative" onContextMenu={onContextMenu}><Imagealt={t('widgets.workflow.outputImage')}bg="bg.muted"diff --git a/invokeai/frontend/webv2/src/platform/react/contextMenuPoint.ts b/invokeai/frontend/webv2/src/platform/react/contextMenuPoint.tsnew file mode 100644index 0000000000..bf2a5464a3--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/react/contextMenuPoint.ts@@ -0,0 +1,34 @@+import type { MouseEvent } from 'react';++/**+ * A context menu opened with the keyboard (the Context Menu key, Shift+F10) has no pointer position of its own: Chromium+ * reports button -1 at a point of its own choosing, other engines no pointer type or 0,0. A heuristic: engines vary.+ */+export const isKeyboardContextMenu = (event: MouseEvent<Element>): boolean => {+ const native = event.nativeEvent as Partial<PointerEvent>;++ return event.button === -1 || native.pointerType === '' || (event.clientX === 0 && event.clientY === 0);+};++const clamp = (value: number, max: number) => Math.min(Math.max(value, 0), max);++/** Below the left edge of `element`, clamped to the viewport, as a tall element can run off it. */+export const getContextMenuPointBelow = (element: Element): { x: number; y: number } => {+ const rect = element.getBoundingClientRect();++ return { x: clamp(rect.left, window.innerWidth), y: clamp(rect.bottom, window.innerHeight) };+};++/**+ * Where a context menu opens: at the pointer, or from the keyboard below the focused element inside the handler's own,+ * else below the handler's.+ */+export const getContextMenuPoint = (event: MouseEvent<Element>): { x: number; y: number } => {+ if (!isKeyboardContextMenu(event)) {+ return { x: event.clientX, y: event.clientY };+ }++ const focused = document.activeElement;++ return getContextMenuPointBelow(focused && event.currentTarget.contains(focused) ? focused : event.currentTarget);+};diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsxindex 53460d7d48..e0899671f3 100644--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx@@ -1,11 +1,13 @@-import { ChakraProvider } from '@chakra-ui/react';+import { ChakraProvider, Menu, Popover, Portal } from '@chakra-ui/react';import { system } from '@theme/system';import { CameraIcon } from 'lucide-react';-import { Activity, act, useCallback, useRef, useState } from 'react';+import { Activity, act, type ReactElement, useCallback, useRef, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';+import { MenuContent } from './Menu';+import { PopoverContent } from './Popover';import { Toolbar, ToolbarButton } from './Toolbar';import { ClippedTooltip, Tooltip } from './Tooltip';@@ -220,3 +222,111 @@ it('shows a tip again only when hovered after its section was hidden mid-fade',await userEvent.hover(trigger);await expect.poll(() => shownTip()?.textContent).toBe('Open the other section');});++const POPOVER_AT = { getAnchorRect: () => ({ height: 1, width: 1, x: 24, y: 24 }), placement: 'bottom-start' } as const;++// Shared by the tooltip and the menu, as `useTooltipTriggerIds` does: Zag finds each trigger by its id.+const FIELD_ID = 'media-field';+const TIP_IDS = { trigger: FIELD_ID };+const MENU_IDS = { contextTrigger: FIELD_ID };++interface MediaFieldProps {+ inPopover: boolean;+ /** Tooltip around the menu's trigger is the `useTooltipTriggerIds` order; dialogs need the menu's outside. */+ isMenuTriggerOutside: boolean;+}++/** A field that shows its name on hover and opens a context menu from the same element; the item's tip opens with it. */+const MediaFieldWithMenu = ({ inPopover, isMenuTriggerOutside }: MediaFieldProps) => {+ const [isNameShown, setIsNameShown] = useState(false);+ const [isMenuOpen, setIsMenuOpen] = useState(false);+ const showName = useCallback(() => setIsNameShown(true), []);+ const handleMenuOpenChange = useCallback((details: { open: boolean }) => setIsMenuOpen(details.open), []);+ const button = (+ <button type="button" onPointerEnter={showName}>+ Media+ </button>+ );+ const nameTip = (trigger: ReactElement) => (+ <Tooltip content="Media name" ids={TIP_IDS} open={isNameShown} placement="bottom">+ {trigger}+ </Tooltip>+ );+ const field = (+ <Menu.Root ids={MENU_IDS} open={isMenuOpen} onOpenChange={handleMenuOpenChange}>+ {isMenuTriggerOutside ? (+ <Menu.ContextTrigger asChild>{nameTip(button)}</Menu.ContextTrigger>+ ) : (+ nameTip(<Menu.ContextTrigger asChild>{button}</Menu.ContextTrigger>)+ )}+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <Menu.Item value="unavailable">+ <Tooltip content="Item reason" open={isMenuOpen} placement="bottom">+ <span>Unavailable action</span>+ </Tooltip>+ </Menu.Item>+ <Menu.Item value="second">Second action</Menu.Item>+ <Menu.Item value="third">Third action</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );++ return inPopover ? (+ <Popover.Root open positioning={POPOVER_AT}>+ <Portal>+ <Popover.Positioner>+ <PopoverContent>+ <div style={{ width: '120px' }}>{field}</div>+ {/* Room under the field, so its tip lies over the popover. */}+ <div style={{ height: '80px' }} />+ </PopoverContent>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ ) : (+ <div style={{ left: '24px', position: 'absolute', top: '40px' }}>{field}</div>+ );+};++/** What the browser paints on top at a tip's centre; tips let the pointer through, so the probe lets this one hit. */+const paintedAtCentreOf = (text: string) => {+ const tip = [...document.querySelectorAll<HTMLElement>('[role="tooltip"]')].find((each) => each.textContent === text);+ if (!tip) {+ return null;+ }+ tip.style.pointerEvents = 'auto';+ const rect = tip.getBoundingClientRect();+ return document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);+};++it.each([+ { where: 'on the page', inPopover: false, isMenuTriggerOutside: false },+ { where: 'in a popover', inPopover: true, isMenuTriggerOutside: false },+ { where: 'in a popover, inside its menu trigger', inPopover: true, isMenuTriggerOutside: true },+])("paints a tip $where beneath its menu, and a menu item's tip above the menu", async (props) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <MediaFieldWithMenu {...props} />+ </ChakraProvider>+ )+ );+ const field = document.getElementById(FIELD_ID)!;++ await userEvent.hover(field);+ await expect.poll(() => paintedAtCentreOf('Media name')?.textContent).toBe('Media name');++ // Near the corner, so the menu opens over the tip below the field.+ await userEvent.click(field, { button: 'right', position: { x: 4, y: 4 } });+ const menu = () => document.querySelector('[data-scope="menu"][data-part="content"]');++ await expect.poll(() => !!menu()?.contains(paintedAtCentreOf('Media name'))).toBe(true);+ await expect.poll(() => paintedAtCentreOf('Item reason')?.textContent).toBe('Item reason');+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsxindex f2d8086ca4..4922cc7c84 100644--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx@@ -35,7 +35,6 @@ const ROOT_PROP_NAMES = new Set(['onOpenChange','open','openDelay',- 'positioning','present','unmountOnExit',]);@@ -106,7 +105,28 @@ const POINTER_EVENTS = ['onPointerMove', 'onPointerOver'] as const;const ARRIVAL_EVENTS = ['onFocus', 'onPointerMove', 'onPointerOver'] as const;const alwaysHidden = () => true;-type TooltipPlacement = NonNullable<NonNullable<ChakraTooltip.RootProps['positioning']>['placement']>;+type TooltipPositioning = NonNullable<ChakraTooltip.RootProps['positioning']>;+type TooltipPlacement = NonNullable<TooltipPositioning['placement']>;+type UpdatePosition = NonNullable<TooltipPositioning['updatePosition']>;++/**+ * A tip takes the z-index of the overlay holding its trigger (the recipe's page value otherwise), plus one when it+ * precedes that overlay in the DOM. A placement can run before Zag assigns the overlay's layer index; autoUpdate's+ * first observer callback, a frame later, places it again with the final value.+ */+const stackInTriggerLayer = (tip: HTMLElement | null, tooltipId: string): void => {+ // Zag marks the trigger with its tooltip's id, ref or not; a shared menu or popover trigger lists both owners and may+ // carry the other's data-scope, so only the owner word is matched.+ const owned = `[data-ownedby~="${CSS.escape(tooltipId)}"]`;+ const layer = tip && (tip.getRootNode() as ParentNode).querySelector(owned)?.closest('[data-part="positioner"]');+ const layerContent = layer?.firstElementChild;+ const zIndex = layerContent ? Number(getComputedStyle(layerContent).zIndex) : Number.NaN;+ if (tip && layer && Number.isFinite(zIndex)) {+ const precedesLayer = layer.compareDocumentPosition(tip) & Node.DOCUMENT_POSITION_PRECEDING;+ // An inline value of its own keeps Zag from copying the content's.+ tip.style.zIndex = String(precedesLayer ? zIndex + 1 : zIndex);+ }+};export interface TooltipProps extends ChakraTooltip.RootProps {showArrow?: boolean;@@ -141,15 +161,24 @@ export const Tooltip = (props: TooltipProps) => {contentRef,placement,portalRef,+ positioning: callerPositioning,ref,triggerProps,...rest} = props;const { rootProps, triggerProps: triggerPassthroughProps } = splitTooltipProps(rest);-- if (placement) {- rootProps.positioning = { placement, ...(rootProps.positioning as object | undefined) };- }+ const tooltipId = useId();+ const updatePosition = useCallback<UpdatePosition>(+ (details) => {+ stackInTriggerLayer(details.floatingElement, tooltipId);+ return callerPositioning?.updatePosition ? callerPositioning.updatePosition(details) : details.updatePosition();+ },+ [callerPositioning, tooltipId]+ );+ const positioning = useMemo(+ () => ({ ...(placement ? { placement } : {}), ...callerPositioning, updatePosition }),+ [callerPositioning, placement, updatePosition]+ );const { ref: explicitTriggerRef, ...explicitTriggerProps } = triggerProps ?? {};const mergedTriggerProps = { ...triggerPassthroughProps, ...explicitTriggerProps };const hasTriggerPassthrough = ref || explicitTriggerRef || Object.keys(mergedTriggerProps).length > 0;@@ -179,7 +208,12 @@ export const Tooltip = (props: TooltipProps) => {// Shut through the controlled prop; the gate above keeps the pointer from opening around it.return (- <ChakraTooltip.Root {...(rootProps as ChakraTooltip.RootProps)} {...(isKeptShut ? { open: false } : {})}>+ <ChakraTooltip.Root+ {...(rootProps as ChakraTooltip.RootProps)}+ id={tooltipId}+ positioning={positioning}+ {...(isKeptShut ? { open: false } : {})}+ ><ChakraTooltip.Trigger asChild>{triggerChild}</ChakraTooltip.Trigger><Portal disabled={!portalled} container={portalRef}><ChakraTooltip.Positioner>@@ -300,6 +334,17 @@ const TooltipGroupRoot = ({}const ids = useMemo(() => ({ trigger: (triggerValue?: string) => getTriggerId(triggerValue ?? '') }), [getTriggerId]);+ const tooltipId = useId();+ // All triggers share one layer, so whichever the lookup finds places the tip.+ const positioning = useMemo<TooltipPositioning>(+ () => ({+ updatePosition: (details) => {+ stackInTriggerLayer(details.floatingElement, tooltipId);+ return details.updatePosition();+ },+ }),+ [tooltipId]+ );const handleOpenChange = useCallback((details: { open: boolean }) => dispatch({ type: details.open ? 'open' : 'close' }),[]@@ -314,8 +359,10 @@ const TooltipGroupRoot = ({return (<ChakraTooltip.RootcloseOnScroll={closeOnScroll}+ id={tooltipId}ids={ids}open={isShown}+ positioning={positioning}onOpenChange={handleOpenChange}onTriggerValueChange={handleTriggerValueChange}>diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.tsindex f12aef9a02..c4280c6645 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts@@ -77,6 +77,8 @@ export const tooltipSlotRecipe = defineSlotRecipe({borderWidth: '1px',boxShadow: 'lg',color: 'fg',+ // Page tips sit beneath overlays, dialog backdrops (modal - 1) and toasts; Tooltip raises tips inside overlays.+ zIndex: 'calc({zIndex.modal} - 2)',// Chakra's `fast` scale-fade drags on an annotation this small._open: { ...chakraSlotRecipes.tooltip.base?.content?._open, animationDuration: 'faster' },_closed: { ...chakraSlotRecipes.tooltip.base?.content?._closed, animationDuration: 'faster' },diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex e9f3427fe9..6f61b6a1be 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -351,6 +351,7 @@ const GALLERY_STATE_MODULES = ['/features/gallery/core/settings.ts','/features/gallery/react.ts','/features/gallery/ui/GalleryUiContext.tsx',+ '/platform/react/contextMenuPoint.ts','/features/gallery/ui/GalleryMediaUsagePanel.tsx','/features/gallery/ui/galleryStateView.ts','/features/queue/contracts.ts',