Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): add legacy gallery image drop zones

joshistoast3c93f5d335d3
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index caab451537..9c0e064d40 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -974,6 +974,11 @@
"import": {
"blocked": "Finish the current canvas operation before adding images.",
"control": "Control Layer",
+ "dropControl": "Add as Control Layer",
+ "dropInpaintMask": "Add as Inpaint Mask",
+ "dropRaster": "Add as Raster Layer",
+ "dropRegionalReference": "Add as Regional Reference Image",
+ "dropResizedControl": "Add as Resized Control Layer",
"empty": "No gallery images were available to add.",
"failed": "Couldn't add images to canvas",
"inpaintMask": "Inpaint Mask",
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx
new file mode 100644
index 0000000000..d51caba9b4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx
@@ -0,0 +1,61 @@
+import { Grid } from '@chakra-ui/react';
+import { useDndContext } from '@dnd-kit/core';
+import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';
+
+import { getCanvasImageDropData, getCanvasImageDropId } from './canvasImageDnd';
+import { CanvasImageDropZone, type CanvasImageDropZoneProps } from './CanvasImageDropZone';
+
+export const CANVAS_IMAGE_DROP_LAYOUT = [
+ { destination: 'raster', colSpan: 3, row: 1 },
+ { destination: 'control', colSpan: 3, row: 1 },
+ { destination: 'regional-reference', colSpan: 2, row: 2 },
+ { destination: 'inpaint-mask', colSpan: 2, row: 2 },
+ { destination: 'control-resized', colSpan: 2, row: 2 },
+] as const;
+
+export const CANVAS_IMAGE_DROP_GRID_LAYOUT = {
+ gap: '0',
+ padding: '0',
+ templateColumns: 'repeat(6, minmax(0, 1fr))',
+ templateRows: 'repeat(2, minmax(0, 1fr))',
+} as const;
+
+const LABEL_KEYS = {
+ control: 'widgets.canvas.import.dropControl',
+ 'control-resized': 'widgets.canvas.import.dropResizedControl',
+ 'inpaint-mask': 'widgets.canvas.import.dropInpaintMask',
+ raster: 'widgets.canvas.import.dropRaster',
+ 'regional-reference': 'widgets.canvas.import.dropRegionalReference',
+} as const satisfies Record<
+ (typeof CANVAS_IMAGE_DROP_LAYOUT)[number]['destination'],
+ CanvasImageDropZoneProps['labelKey']
+>;
+
+const CANVAS_IMAGE_DROP_ZONES = CANVAS_IMAGE_DROP_LAYOUT.map((zone) => ({
+ ...zone,
+ data: getCanvasImageDropData(zone.destination),
+ id: getCanvasImageDropId(zone.destination),
+ labelKey: LABEL_KEYS[zone.destination],
+})) satisfies readonly CanvasImageDropZoneProps[];
+
+export const CanvasImageDropOverlay = ({
+ isDocumentEditingLocked,
+ isInteractionLocked,
+}: {
+ isDocumentEditingLocked: boolean;
+ isInteractionLocked: boolean;
+}) => {
+ const { active } = useDndContext();
+
+ if (isDocumentEditingLocked || isInteractionLocked || !isGalleryImageDragData(active?.data.current)) {
+ return null;
+ }
+
+ return (
+ <Grid {...CANVAS_IMAGE_DROP_GRID_LAYOUT} inset="0" pointerEvents="none" position="absolute" zIndex="2">
+ {CANVAS_IMAGE_DROP_ZONES.map((zone) => (
+ <CanvasImageDropZone key={zone.id} {...zone} />
+ ))}
+ </Grid>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx
new file mode 100644
index 0000000000..dfe16ec31f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx
@@ -0,0 +1,46 @@
+import { Flex, GridItem, Text } from '@chakra-ui/react';
+import { useDroppable } from '@dnd-kit/core';
+import { useTranslation } from 'react-i18next';
+
+import type { CanvasImageDropData } from './canvasImageDnd';
+
+export interface CanvasImageDropZoneProps {
+ colSpan: number;
+ data: CanvasImageDropData;
+ id: string;
+ labelKey:
+ | 'widgets.canvas.import.dropControl'
+ | 'widgets.canvas.import.dropInpaintMask'
+ | 'widgets.canvas.import.dropRaster'
+ | 'widgets.canvas.import.dropRegionalReference'
+ | 'widgets.canvas.import.dropResizedControl';
+ row: number;
+}
+
+export const CanvasImageDropZone = ({ colSpan, data, id, labelKey, row }: CanvasImageDropZoneProps) => {
+ const { t } = useTranslation();
+ const { isOver, setNodeRef } = useDroppable({ data, id });
+
+ return (
+ <GridItem ref={setNodeRef} colSpan={colSpan} gridRow={row} position="relative">
+ <Flex
+ alignItems="center"
+ bg={isOver ? 'accent.subtle' : 'bg.muted'}
+ borderColor={isOver ? 'accent.solid' : 'border.emphasized'}
+ borderStyle="dashed"
+ borderWidth="2px"
+ inset="0.5"
+ justifyContent="center"
+ opacity={isOver ? 0.98 : 0.88}
+ position="absolute"
+ rounded="md"
+ shadow={isOver ? '0 0 0 1px {colors.accent.solid}' : undefined}
+ transition="background var(--wb-motion-duration-fast) ease, border-color var(--wb-motion-duration-fast) ease, opacity var(--wb-motion-duration-fast) ease, box-shadow var(--wb-motion-duration-fast) ease"
+ >
+ <Text color="fg" fontSize="sm" fontWeight="700" textAlign="center">
+ {t(labelKey)}
+ </Text>
+ </Flex>
+ </GridItem>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index a8c428efbc..f66e0de08d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -3,7 +3,9 @@ import type { WidgetViewProps } from '@workbench/types';
import type { MouseEvent as ReactMouseEvent } from 'react';
import { Box } from '@chakra-ui/react';
+import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';
import { useQueueItemProgressImage } from '@workbench/backend/progressImageStore';
+import { getCanvasImportNotice } from '@workbench/canvas-operations/canvasImportNotice';
import {
createLayerId,
deleteLayerActions,
@@ -13,11 +15,12 @@ import {
reorderLayerActions,
} from '@workbench/canvasLayerOps';
import { getCanvasStagingSlots } from '@workbench/canvasStagingView';
+import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';
import { useWorkbenchSettingsSelector } from '@workbench/settings/store';
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 { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,6 +33,8 @@ import {
type CanvasContextMenuTarget,
} from './canvasContextMenu';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
+import { resolveCanvasImageDrop } from './canvasImageDnd';
+import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';
import { getCanvasInteractionCapabilities } from './canvasInteractionLock';
import { CanvasSaveToGallerySubmenu } from './CanvasSaveToGallerySubmenu';
import {
@@ -42,6 +47,7 @@ import { CanvasSurface } from './CanvasSurface';
import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';
import { resolveCheckerColors } from './checkerColors';
import { useCanvasOperation } from './engineStoreHooks';
+import { executeCanvasImageDropImport } from './executeCanvasImageDropImport';
import { StagingBar } from './StagingBar';
import { selectStagedPreviewSource, stagedPreviewKey } from './stagingPreview';
import { INLINE_EDIT_SELECTOR } from './surfaceFocus';
@@ -79,6 +85,7 @@ const REORDER_KINDS: Record<string, LayerReorderKind> = {
export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
const { t } = useTranslation();
const dispatch = useWorkbenchDispatch();
+ const store = useWorkbenchStore();
const engine = useCanvasEngine();
const canvas = useActiveProjectSelector((project) => project.canvas);
const queueItems = useActiveProjectSelector((project) => project.queue.items);
@@ -180,6 +187,47 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
});
const isInteractionLocked = interactionCapabilities.isSurfaceInteractionLocked;
+ const handleCanvasImageDrop = useCallback(
+ (event: DragEndEvent) => {
+ const resolution = resolveCanvasImageDrop(event.active.data.current, event.over?.data.current);
+ if (!resolution) {
+ return;
+ }
+
+ // Capture the destination project and mounted engine before any network
+ // work so a project switch cannot retarget this import mid-flight.
+ const project = store.getSnapshot().activeProject;
+ const mountedEngine = engine;
+
+ const execute = async (): Promise<void> => {
+ try {
+ const result = await executeCanvasImageDropImport({
+ destination: resolution.destination,
+ dispatch,
+ engine: mountedEngine,
+ getState: store.getState,
+ imageNames: resolution.imageNames,
+ project,
+ });
+ const notice = getCanvasImportNotice(result);
+ dispatch({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}), type: 'recordNotice' });
+ } catch (error: unknown) {
+ recordCanvasImportError({
+ dispatch,
+ error,
+ localizedMessage: t('widgets.canvas.import.failed'),
+ projectId: project.id,
+ });
+ }
+ };
+
+ void execute();
+ },
+ [dispatch, engine, store, t]
+ );
+
+ useDndMonitor({ onDragEnd: handleCanvasImageDrop });
+
useLayoutEffect(() => {
engine?.tools.setInteractionLocked(isInteractionLocked);
return () => engine?.tools.setInteractionLocked(false);
@@ -417,6 +465,10 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
return (
<Box aria-label={t('widgets.canvas.surface')} bg="bg.inset" h="full" overflow="hidden" position="relative" w="full">
<CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>
+ <CanvasImageDropOverlay
+ isDocumentEditingLocked={interactionCapabilities.isDocumentEditingLocked}
+ isInteractionLocked={isInteractionLocked}
+ />
{engine ? (
<>
<ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts
index 790416e4cf..6f376aadfd 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts
@@ -1,4 +1,7 @@
import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
+import type { GalleryImage } from '@workbench/gallery/api';
+
+import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';
export interface CanvasImageDropData {
kind: 'canvas-image-target';
@@ -13,6 +16,36 @@ export const getCanvasImageDropData = (destination: CanvasImageDropData['destina
kind: 'canvas-image-target',
});
+export const getCanvasImageDropId = (destination: CanvasImageDropData['destination']): string =>
+ `canvas-image-target:${destination}`;
+
+export interface CanvasImageDropResolution {
+ destination: CanvasImageDropData['destination'];
+ imageNames: string[];
+}
+
+export const resolveCanvasImageDrop = (activeData: unknown, overData: unknown): CanvasImageDropResolution | null => {
+ if (!isGalleryImageDragData(activeData) || !isCanvasImageDropData(overData)) {
+ return null;
+ }
+
+ return {
+ destination: overData.destination,
+ imageNames: activeData.images.map((image) => image.imageName),
+ };
+};
+
+export const orderCanvasImageDropImages = (
+ imageNames: readonly string[],
+ images: readonly GalleryImage[]
+): GalleryImage[] => {
+ const imagesByName = new Map(images.map((image) => [image.imageName, image]));
+ return imageNames.flatMap((imageName) => {
+ const image = imagesByName.get(imageName);
+ return image ? [image] : [];
+ });
+};
+
const canvasImageDropDestinations = {
control: true,
'control-resized': true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts
new file mode 100644
index 0000000000..1d27f2d79e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts
@@ -0,0 +1,132 @@
+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { GalleryImage } from '@workbench/gallery/api';
+import type { Project, WorkbenchState } from '@workbench/types';
+
+import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';
+import { describe, expect, it } from 'vitest';
+
+import {
+ getCanvasImageDropData,
+ getCanvasImageDropId,
+ orderCanvasImageDropImages,
+ resolveCanvasImageDrop,
+} from './canvasImageDnd';
+import { CANVAS_IMAGE_DROP_GRID_LAYOUT, CANVAS_IMAGE_DROP_LAYOUT } from './CanvasImageDropOverlay';
+import { executeCanvasImageDropImport } from './executeCanvasImageDropImport';
+
+describe('canvas image drop layout', () => {
+ it('covers the full surface with the legacy six-column, two-row grid', () => {
+ expect(CANVAS_IMAGE_DROP_GRID_LAYOUT).toEqual({
+ gap: '0',
+ padding: '0',
+ templateColumns: 'repeat(6, minmax(0, 1fr))',
+ templateRows: 'repeat(2, minmax(0, 1fr))',
+ });
+ });
+
+ it('occupies exactly six columns in each of two rows', () => {
+ expect(CANVAS_IMAGE_DROP_LAYOUT).toEqual([
+ { colSpan: 3, destination: 'raster', row: 1 },
+ { colSpan: 3, destination: 'control', row: 1 },
+ { colSpan: 2, destination: 'regional-reference', row: 2 },
+ { colSpan: 2, destination: 'inpaint-mask', row: 2 },
+ { colSpan: 2, destination: 'control-resized', row: 2 },
+ ]);
+
+ expect(
+ CANVAS_IMAGE_DROP_LAYOUT.reduce<Record<number, number>>((columnsByRow, zone) => {
+ columnsByRow[zone.row] = (columnsByRow[zone.row] ?? 0) + zone.colSpan;
+ return columnsByRow;
+ }, {})
+ ).toEqual({ 1: 6, 2: 6 });
+ });
+
+ it('has unique destinations and stable unique droppable ids', () => {
+ const destinations = CANVAS_IMAGE_DROP_LAYOUT.map((zone) => zone.destination);
+ const firstIds = destinations.map(getCanvasImageDropId);
+ const secondIds = destinations.map(getCanvasImageDropId);
+
+ expect(new Set(destinations).size).toBe(CANVAS_IMAGE_DROP_LAYOUT.length);
+ expect(new Set(firstIds).size).toBe(CANVAS_IMAGE_DROP_LAYOUT.length);
+ expect(secondIds).toEqual(firstIds);
+ });
+});
+
+describe('resolveCanvasImageDrop', () => {
+ const galleryDrag = getGalleryImageDragData([
+ { boardId: 'board-a', imageName: 'third.png' },
+ { boardId: 'board-b', imageName: 'first.png' },
+ { boardId: 'board-a', imageName: 'second.png' },
+ ]);
+
+ it('accepts a gallery-image to canvas-image-target pair and preserves requested order', () => {
+ expect(resolveCanvasImageDrop(galleryDrag, getCanvasImageDropData('control-resized'))).toEqual({
+ destination: 'control-resized',
+ imageNames: ['third.png', 'first.png', 'second.png'],
+ });
+ });
+
+ it.each([
+ [null, getCanvasImageDropData('raster')],
+ [{ kind: 'widget-instance' }, getCanvasImageDropData('raster')],
+ [galleryDrag, null],
+ [galleryDrag, { destination: 'raster', kind: 'widget-region' }],
+ [galleryDrag, { destination: 'regional-guidance', kind: 'canvas-image-target' }],
+ ])('rejects a non gallery-image to canvas-image-target pair', (activeData, overData) => {
+ expect(resolveCanvasImageDrop(activeData, overData)).toBeNull();
+ });
+});
+
+describe('orderCanvasImageDropImages', () => {
+ it('restores requested order and omits backend results that were not requested', () => {
+ const first = { imageName: 'first.png' } as GalleryImage;
+ const second = { imageName: 'second.png' } as GalleryImage;
+ const extra = { imageName: 'extra.png' } as GalleryImage;
+
+ expect(orderCanvasImageDropImages(['first.png', 'missing.png', 'second.png'], [extra, second, first])).toEqual([
+ first,
+ second,
+ ]);
+ });
+});
+
+describe('executeCanvasImageDropImport', () => {
+ it('looks up all names once, restores requested order, and calls the shared service once', async () => {
+ const first = { imageName: 'first.png' } as GalleryImage;
+ const second = { imageName: 'second.png' } as GalleryImage;
+ const extra = { imageName: 'extra.png' } as GalleryImage;
+ const project = { id: 'captured-project' } as Project;
+ const engine = { projectId: project.id } as CanvasEngine;
+ const getState = () => ({ activeProjectId: project.id }) as WorkbenchState;
+ const lookupCalls: string[][] = [];
+ const importCalls: unknown[] = [];
+
+ const result = await executeCanvasImageDropImport({
+ destination: 'control',
+ dispatch: () => undefined,
+ engine,
+ getGalleryImages: (imageNames) => {
+ lookupCalls.push([...imageNames]);
+ return Promise.resolve([second, extra, first]);
+ },
+ getState,
+ imageNames: ['first.png', 'second.png'],
+ importGalleryImages: (options) => {
+ importCalls.push(options);
+ return Promise.resolve({ failedImageNames: [], layerIds: ['layer-1', 'layer-2'], status: 'imported' });
+ },
+ project,
+ });
+
+ expect(lookupCalls).toEqual([['first.png', 'second.png']]);
+ expect(importCalls).toHaveLength(1);
+ expect(importCalls[0]).toMatchObject({
+ destination: 'control',
+ engine,
+ getState,
+ images: [first, second],
+ project,
+ });
+ expect(result).toEqual({ failedImageNames: [], layerIds: ['layer-1', 'layer-2'], status: 'imported' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts
new file mode 100644
index 0000000000..a8be2ee2c8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts
@@ -0,0 +1,38 @@
+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { Project, WorkbenchState } from '@workbench/types';
+import type { WorkbenchAction } from '@workbench/workbenchState';
+import type { Dispatch } from 'react';
+
+import {
+ importGalleryImagesToCanvas,
+ type GalleryCanvasImportDestination,
+ type ImportGalleryImagesResult,
+} from '@workbench/canvas-operations/api';
+import { getGalleryImagesByNames } from '@workbench/gallery/api';
+
+import { orderCanvasImageDropImages } from './canvasImageDnd';
+
+export const executeCanvasImageDropImport = async ({
+ destination,
+ dispatch,
+ engine,
+ getGalleryImages = getGalleryImagesByNames,
+ getState,
+ imageNames,
+ importGalleryImages = importGalleryImagesToCanvas,
+ project,
+}: {
+ destination: GalleryCanvasImportDestination;
+ dispatch: Dispatch<WorkbenchAction>;
+ engine: CanvasEngine | null;
+ getGalleryImages?: typeof getGalleryImagesByNames;
+ getState: () => WorkbenchState;
+ imageNames: readonly string[];
+ importGalleryImages?: typeof importGalleryImagesToCanvas;
+ project: Project;
+}): Promise<ImportGalleryImagesResult> => {
+ const fetchedImages = await getGalleryImages([...imageNames]);
+ const images = orderCanvasImageDropImages(imageNames, fetchedImages);
+
+ return importGalleryImages({ destination, dispatch, engine, getState, images, project });
+};