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
feat(canvas): add save-to-gallery context menu
joshistoast0502607ee850
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 7282246edb..9414db8c0d 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -948,6 +948,17 @@"selectViewTool": "Select view tool","undo": "Undo canvas edit"},+ "contextMenu": {+ "empty": "This region has no visible raster content.",+ "notReady": "The canvas is still preparing image data.",+ "saveBboxToGallery": "Save BBox to Gallery",+ "saveCanvasToGallery": "Save Canvas to Gallery",+ "saveError": "Couldn't save to gallery",+ "saveToGallery": "Save to Gallery",+ "saved": "Saved to gallery",+ "savedDescription": "{{name}} was added to your gallery.",+ "stale": "The canvas changed while saving. Try again."+ },"controls": {"fitBboxToLayers": "Fit frame to layers","fitBboxToMasks": "Fit frame to masks",diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsxnew file mode 100644index 0000000000..2153ea2ba3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx@@ -0,0 +1,45 @@+import type { ReactNode } from 'react';++import { Menu, Portal } from '@chakra-ui/react';+import { MenuContent } from '@workbench/components/ui';+import { useCallback, useMemo } from 'react';++import type { CanvasContextMenuTarget } from './canvasContextMenu';++export const CanvasGlobalContextMenu = ({+ children,+ onClose,+ target,+}: {+ children: ReactNode;+ onClose: () => void;+ target: CanvasContextMenuTarget;+}) => {+ const positioning = useMemo(+ () => ({+ getAnchorRect: () => ({ height: 1, width: 1, x: target.x, y: target.y }),+ placement: 'bottom-start' as const,+ }),+ [target.x, target.y]+ );+ const onOpenChange = useCallback(+ (details: { open: boolean }) => {+ if (!details.open) {+ onClose();+ }+ },+ [onClose]+ );++ return (+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={onOpenChange}>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="14rem" py="1">+ {children}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsxnew file mode 100644index 0000000000..6b21996119--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx@@ -0,0 +1,59 @@+import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/saveCanvasToGallery';++import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { MenuContent } from '@workbench/components/ui';+import { ChevronRightIcon, SaveIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++const SUBMENU_POSITIONING = { placement: 'right-start' } as const;++export const CanvasSaveToGallerySubmenu = ({+ disabled,+ onSave,+}: {+ disabled: boolean;+ onSave: (region: CanvasGallerySaveRegion) => void;+}) => {+ const { t } = useTranslation();+ const onSaveCanvas = useCallback(() => onSave('canvas'), [onSave]);+ const onSaveBbox = useCallback(() => onSave('bbox'), [onSave]);++ return (+ <Menu.Root positioning={SUBMENU_POSITIONING}>+ <Menu.TriggerItem asChild>+ <button disabled={disabled} type="button">+ <HStack gap="2" minW="0" w="full">+ <Icon as={SaveIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="xs">+ {t('widgets.canvas.contextMenu.saveToGallery')}+ </Text>+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ </HStack>+ </button>+ </Menu.TriggerItem>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="13rem" py="1">+ <Menu.Item disabled={disabled} value="save-canvas" onSelect={onSaveCanvas}>+ <HStack gap="2" minW="0" w="full">+ <Icon as={SaveIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="xs">+ {t('widgets.canvas.contextMenu.saveCanvasToGallery')}+ </Text>+ </HStack>+ </Menu.Item>+ <Menu.Item disabled={disabled} value="save-bbox" onSelect={onSaveBbox}>+ <HStack gap="2" minW="0" w="full">+ <Icon as={SaveIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="xs">+ {t('widgets.canvas.contextMenu.saveBboxToGallery')}+ </Text>+ </HStack>+ </Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 2bbb34b4d5..ec79a8f16e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -14,17 +14,20 @@ import {} from '@workbench/canvasLayerOps';import { getCanvasStagingSlots } from '@workbench/canvasStagingView';import { useWorkbenchSettingsSelector } from '@workbench/settings/store';-import { CanvasLayerContextMenu, type CanvasLayerContextMenuTarget } from '@workbench/widgets/layers/LayerContextMenu';+import { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useState } from 'react';+import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { gridSizeForModelBase } from './bboxGrid';import { CanvasBottomControls } from './CanvasBottomControls';import { CanvasBottomOverlay } from './CanvasBottomOverlay';+import { resolveCanvasContextMenu, type CanvasContextMenuTarget } from './canvasContextMenu';+import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';import { getCanvasInteractionCapabilities } from './canvasInteractionLock';+import { CanvasSaveToGallerySubmenu } from './CanvasSaveToGallerySubmenu';import {CANVAS_SETTINGS,CANVAS_SHOW_PROGRESS_KEY,@@ -39,6 +42,7 @@ import { selectStagedPreviewSource, stagedPreviewKey } from './stagingPreview';import { INLINE_EDIT_SELECTOR } from './surfaceFocus';import { ToolStrip } from './ToolStrip';import { useCanvasEngine } from './useCanvasEngine';+import { useCanvasGallerySave } from './useCanvasGallerySave';/** Command id → document-space nudge delta (shift variants are ×10). */const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {@@ -76,40 +80,34 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);const { document, stagingArea } = canvas;const operation = useCanvasOperation(engine);+ const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);- // Right-click on the canvas surface: hit-test the layer under the cursor, select- // it, and open the SAME per-layer context menu the layers panel uses — anchored- // at the pointer. `null` (empty space, or a mid-flight gesture/session the engine- // refuses) means "browser menu suppressed, no layer menu".- const [layerMenuTarget, setLayerMenuTarget] = useState<CanvasLayerContextMenuTarget | null>(null);- const closeLayerMenu = useCallback(() => setLayerMenuTarget(null), []);+ // Right-click on the canvas surface: hit-test the layer under the cursor and+ // open either the shared per-layer menu or the global empty-space menu at the+ // pointer. Locked interaction skips the hit-test but keeps global save visible.+ const [contextMenuTarget, setContextMenuTarget] = useState<CanvasContextMenuTarget | null>(null);+ const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);const handleSurfaceContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {// Keep the native menu inside inline editors (the text tool's contenteditable// overlay), consistent with the surface-focus INLINE_EDIT_SELECTOR.- if (event.target instanceof Element && event.target.closest(INLINE_EDIT_SELECTOR)) {+ const rect = event.currentTarget.getBoundingClientRect();+ const resolution = resolveCanvasContextMenu({+ clientX: event.clientX,+ clientY: event.clientY,+ hitTest: engine ? (point) => engine.tools.contextMenuLayerIdAt(point) : undefined,+ isInlineEditor: event.target instanceof Element && !!event.target.closest(INLINE_EDIT_SELECTOR),+ isInteractionLocked,+ surfaceLeft: rect.left,+ surfaceTop: rect.top,+ });+ if (!resolution.preventDefault) {return;}- // Suppress the browser context menu everywhere else on the surface.event.preventDefault();- if (isInteractionLocked) {- setLayerMenuTarget(null);- return;- }- if (!engine) {- setLayerMenuTarget(null);- return;+ if (resolution.target?.layerId) {+ dispatch({ id: resolution.target.layerId, type: 'setCanvasSelectedLayer' });}- // The container and the canvas targets share a top-left origin, so its rect- // gives the same screen coords the pointer pipeline feeds the viewport.- const rect = event.currentTarget.getBoundingClientRect();- const layerId = engine.tools.contextMenuLayerIdAt({ x: event.clientX - rect.left, y: event.clientY - rect.top });- if (!layerId) {- setLayerMenuTarget(null);- return;- }- // Select first (one dispatch, matching a left-click select), then open the menu.- dispatch({ id: layerId, type: 'setCanvasSelectedLayer' });- setLayerMenuTarget({ layerId, x: event.clientX, y: event.clientY });+ setContextMenuTarget(resolution.target);};// The bbox tool snaps to a model-dependent grid; the engine is model-agnostic,@@ -396,6 +394,19 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {};}, [runtime.commands, runtime.hotkeys, t]);+ const layerContextMenuTarget = useMemo(+ () =>+ contextMenuTarget?.layerId !== null && contextMenuTarget?.layerId !== undefined+ ? { layerId: contextMenuTarget.layerId, x: contextMenuTarget.x, y: contextMenuTarget.y }+ : null,+ [contextMenuTarget]+ );+ const isSaveToGalleryDisabled = isSaving || isInteractionLocked;+ const saveToGallerySubmenu = useMemo(+ () => <CanvasSaveToGallerySubmenu disabled={isSaveToGalleryDisabled} onSave={saveToGallery} />,+ [isSaveToGalleryDisabled, saveToGallery]+ );+return (<Box aria-label={t('widgets.canvas.surface')} bg="bg.inset" h="full" overflow="hidden" position="relative" w="full">{engine ? (@@ -403,12 +414,18 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {<CanvasSurface engine={engine} onContextMenu={handleSurfaceContextMenu} /><ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} /><CanvasLayerContextMenu+ additionalItems={saveToGallerySubmenu}dispatch={dispatch}engine={engine}layers={document.layers}- target={layerMenuTarget}- onClose={closeLayerMenu}+ target={layerContextMenuTarget}+ onClose={closeContextMenu}/>+ {contextMenuTarget && !layerContextMenuTarget ? (+ <CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>+ {saveToGallerySubmenu}+ </CanvasGlobalContextMenu>+ ) : null}</>) : null}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.tsnew file mode 100644index 0000000000..a71d756b9f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from 'vitest';++import { resolveCanvasContextMenu } from './canvasContextMenu';++const baseOptions = {+ clientX: 240,+ clientY: 160,+ isInlineEditor: false,+ isInteractionLocked: false,+ surfaceLeft: 40,+ surfaceTop: 20,+};++describe('resolveCanvasContextMenu', () => {+ it('leaves inline editors to the native context menu', () => {+ const hitTest = vi.fn(() => 'layer-1');++ expect(resolveCanvasContextMenu({ ...baseOptions, hitTest, isInlineEditor: true })).toEqual({+ preventDefault: false,+ target: null,+ });+ expect(hitTest).not.toHaveBeenCalled();+ });++ it('opens the global menu without hit-testing while interaction is locked', () => {+ const hitTest = vi.fn(() => 'layer-1');++ expect(resolveCanvasContextMenu({ ...baseOptions, hitTest, isInteractionLocked: true })).toEqual({+ preventDefault: true,+ target: { layerId: null, x: 240, y: 160 },+ });+ expect(hitTest).not.toHaveBeenCalled();+ });++ it('opens the layer menu at the pointer for a hit layer', () => {+ const hitTest = vi.fn(() => 'layer-1');++ expect(resolveCanvasContextMenu({ ...baseOptions, hitTest })).toEqual({+ preventDefault: true,+ target: { layerId: 'layer-1', x: 240, y: 160 },+ });+ expect(hitTest).toHaveBeenCalledWith({ x: 200, y: 140 });+ });++ it('opens the global menu when the pointer is over empty canvas', () => {+ expect(resolveCanvasContextMenu({ ...baseOptions, hitTest: () => null })).toEqual({+ preventDefault: true,+ target: { layerId: null, x: 240, y: 160 },+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.tsnew file mode 100644index 0000000000..435bbd7f8c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts@@ -0,0 +1,43 @@+export interface CanvasContextMenuTarget {+ x: number;+ y: number;+ layerId: string | null;+}++interface ResolveCanvasContextMenuOptions {+ clientX: number;+ clientY: number;+ hitTest?: (point: { x: number; y: number }) => string | null;+ isInlineEditor: boolean;+ isInteractionLocked: boolean;+ surfaceLeft: number;+ surfaceTop: number;+}++interface CanvasContextMenuResolution {+ preventDefault: boolean;+ target: CanvasContextMenuTarget | null;+}++export const resolveCanvasContextMenu = ({+ clientX,+ clientY,+ hitTest,+ isInlineEditor,+ isInteractionLocked,+ surfaceLeft,+ surfaceTop,+}: ResolveCanvasContextMenuOptions): CanvasContextMenuResolution => {+ if (isInlineEditor) {+ return { preventDefault: false, target: null };+ }++ const layerId = isInteractionLocked+ ? null+ : (hitTest?.({ x: clientX - surfaceLeft, y: clientY - surfaceTop }) ?? null);++ return {+ preventDefault: true,+ target: { layerId, x: clientX, y: clientY },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.tsnew file mode 100644index 0000000000..e67b4c4107--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts@@ -0,0 +1,65 @@+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';++import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/saveCanvasToGallery';+import { useNotify } from '@workbench/useNotify';+import { useWorkbenchStore } from '@workbench/WorkbenchContext';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));++export const useCanvasGallerySave = (+ engine: CanvasEngine | null+): { isSaving: boolean; save: (region: CanvasGallerySaveRegion) => Promise<void> } => {+ const { t } = useTranslation();+ const notify = useNotify();+ const store = useWorkbenchStore();+ const isSavingRef = useRef(false);+ const [isSaving, setIsSaving] = useState(false);++ const save = useCallback(+ async (region: CanvasGallerySaveRegion): Promise<void> => {+ if (!engine || isSavingRef.current) {+ return;+ }++ isSavingRef.current = true;+ setIsSaving(true);+ const project = store.getSnapshot().activeProject;++ try {+ const result = await saveCanvasToGallery({ engine, project, region });++ if (result.status === 'saved') {+ store.dispatch({ projectId: project.id, type: 'touchGalleryImagesRefresh' });+ notify.success(+ t('widgets.canvas.contextMenu.saved'),+ t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })+ );+ } else if (result.status === 'empty') {+ notify.info(t('widgets.canvas.contextMenu.empty'));+ } else if (result.status === 'stale') {+ notify.info(t('widgets.canvas.contextMenu.stale'));+ } else {+ notify.info(t('widgets.canvas.contextMenu.notReady'));+ }+ } catch (error: unknown) {+ const message = toErrorMessage(error);+ store.dispatch({+ area: 'canvas-save-to-gallery',+ message,+ namespace: 'canvas',+ projectId: project.id,+ type: 'recordError',+ });+ notify.error(t('widgets.canvas.contextMenu.saveError'), message);+ } finally {+ isSavingRef.current = false;+ setIsSaving(false);+ }+ },+ [engine, notify, store, t]+ );++ return { isSaving, save };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 27bf19dfb0..f35e1595c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -4,7 +4,7 @@ import type { GenerateReferenceImage } from '@workbench/generation/types';import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasMaskContract } from '@workbench/types';import type { WorkbenchAction } from '@workbench/workbenchState';import type { LucideIcon } from 'lucide-react';-import type { ComponentProps, Dispatch } from 'react';+import type { ComponentProps, Dispatch, ReactNode } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';@@ -141,6 +141,8 @@ interface LayerMenuProps {*/dialogKind?: LayerMenuDialogKind | null;onDialogKindChange?: (kind: LayerMenuDialogKind | null) => void;+ /** Additional canvas-only items composed after the shared layer actions. */+ additionalItems?: ReactNode;}/**@@ -172,6 +174,7 @@ const LayerMenu = ({unmountOnExit,dialogKind: controlledDialogKind,onDialogKindChange,+ additionalItems,}: LayerMenuProps) => {const { t } = useTranslation();const notify = useNotify();@@ -693,6 +696,12 @@ const LayerMenu = ({{menuLayout.map((section) => (<LayerMenuSection key={section.id} runAction={runAction} section={section} t={t} />))}+ {additionalItems ? (+ <>+ <Menu.Separator borderColor="border.subtle" />+ {additionalItems}+ </>+ ) : null}</MenuContent></Menu.Positioner></Portal>@@ -753,12 +762,14 @@ export interface CanvasLayerContextMenuTarget {* the last-known (sticky) target until the dialog closes (F1).*/export const CanvasLayerContextMenu = ({+ additionalItems,dispatch,engine,layers,target,onClose,}: {+ additionalItems?: ReactNode;dispatch: Dispatch<WorkbenchAction>;engine: CanvasEngine | null;layers: readonly CanvasLayerContract[];@@ -804,6 +815,7 @@ export const CanvasLayerContextMenu = ({return (<LayerMenukey={renderTarget.layerId}+ additionalItems={additionalItems}dispatch={dispatch}dialogKind={dialogState?.kind ?? null}engine={engine}