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(webv2): describe an image dropped on the positive prompt box

joshistoast138f08cb8179
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 583ec98184..f0ce49adfb 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 803542,
+ "brotliBytes": 803553,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 803372,
+ "gzipBytes": 803395,
"imageRawBytes": 156376,
- "initialRawBytes": 1845192,
+ "initialRawBytes": 1845221,
"largestAssetRawBytes": 738008,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57912,
+ "ownedRawBytes": 57941,
"requestCount": 31,
"scriptRequestCount": 15,
"sourceOwners": [
@@ -241,15 +241,15 @@
]
},
"limits": {
- "brotliBytes": 811578,
+ "brotliBytes": 811589,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 811406,
+ "gzipBytes": 811429,
"imageRawBytes": 157940,
- "initialRawBytes": 1863644,
+ "initialRawBytes": 1863674,
"largestAssetRawBytes": 745389,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57912,
+ "ownedRawBytes": 57941,
"requestCount": 31,
"scriptRequestCount": 15
},
@@ -259,17 +259,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 992040,
+ "brotliBytes": 992202,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 990650,
+ "gzipBytes": 990803,
"imageRawBytes": 156376,
- "initialRawBytes": 2423127,
+ "initialRawBytes": 2423190,
"largestAssetRawBytes": 738008,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 110881,
- "requestCount": 72,
- "scriptRequestCount": 56,
+ "ownedRawBytes": 110967,
+ "requestCount": 73,
+ "scriptRequestCount": 57,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -749,17 +749,17 @@
]
},
"limits": {
- "brotliBytes": 1001961,
+ "brotliBytes": 1002125,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1000557,
+ "gzipBytes": 1000712,
"imageRawBytes": 157940,
- "initialRawBytes": 2447359,
+ "initialRawBytes": 2447422,
"largestAssetRawBytes": 745389,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 110881,
- "requestCount": 72,
- "scriptRequestCount": 56
+ "ownedRawBytes": 110967,
+ "requestCount": 73,
+ "scriptRequestCount": 57
},
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f976d1d35e..21c7426128 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -875,6 +875,7 @@
"dimensions": "Dimensions",
"disableConcept": "Disable {{name}}",
"disableReferenceImage": "Disable reference image",
+ "dropImageToPrompt": "Describe this image",
"dynamicPrompts": {
"title": "Dynamic Prompts",
"showPrompts": "Show dynamic prompts",
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index 420de9d72b..1d7c7fca25 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -3,6 +3,7 @@ import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } fro
import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFields/DynamicPromptsPanel';
+import type { DroppedPromptImage } from '@features/generation/ui/promptFields/usePromptImageDrop';
import type { ChangeEvent, MouseEvent } from 'react';
import { HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } from '@chakra-ui/react';
@@ -35,7 +36,7 @@ import {
TrashIcon,
Undo2Icon,
} from 'lucide-react';
-import { useCallback, useId, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;
@@ -81,6 +82,8 @@ export interface PromptTemplateState {
interface PositivePromptActionsProps {
batchCount: number;
+ /** An image dropped on the prompt box, for the image-to-prompt popover to open on. */
+ droppedImage: DroppedPromptImage;
/** Absent on surfaces whose prompt is not batch-expanded (Upscale). */
dynamicPrompts: DynamicPromptsFieldConfig | null;
/** The authored prompt wrapped by the active template — what actually expands. */
@@ -100,6 +103,7 @@ interface PositivePromptActionsProps {
export const PositivePromptActions = ({
batchCount,
+ droppedImage,
dynamicPrompts,
effectivePositivePrompt,
isPromptTriggerPickerOpen,
@@ -141,6 +145,7 @@ export const PositivePromptActions = ({
onPositivePromptChange={onPositivePromptChangeImmediate}
/>
<ImageToPromptButton
+ droppedImage={droppedImage}
isDisabled={template.isViewMode}
projectId={projectId}
onPositivePromptChange={onPositivePromptChangeImmediate}
@@ -508,10 +513,12 @@ const ExpandPromptButton = ({
};
const ImageToPromptButton = ({
+ droppedImage,
isDisabled,
onPositivePromptChange,
projectId,
}: {
+ droppedImage: DroppedPromptImage;
isDisabled: boolean;
projectId: string;
onPositivePromptChange: (prompt: string) => void;
@@ -530,6 +537,11 @@ const ImageToPromptButton = ({
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const llavaModels = models.filter((model) => model.type === 'llava_onevision');
const selectedModel = selectedModelKey ? llavaModels.find((model) => model.key === selectedModelKey) : null;
+ // A drop names the image outright, which is the whole point of dropping one:
+ // it is how you describe something other than what the gallery has selected.
+ const image = droppedImage.image ?? selectedImage;
+ const droppedImageName = droppedImage.image?.imageName ?? null;
+ const clearDroppedImage = droppedImage.onClear;
activeProjectIdRef.current = activeProjectId;
@@ -537,21 +549,39 @@ const ImageToPromptButton = ({
void ensureModelsLoaded();
});
+ // Dropping onto the prompt box is the gesture that opens this popover. Keyed
+ // on the name rather than the object so a re-render cannot reopen a popover
+ // the user has just dismissed; closing clears the drop, so the same image
+ // dropped twice still reads as two separate gestures.
+ useEffect(() => {
+ if (droppedImageName !== null) {
+ setIsOpen(true);
+ }
+ }, [droppedImageName]);
+
+ // Closing hands the popover back to the gallery selection. Every close route
+ // goes through here, including the one after a successful run — a controlled
+ // `open` does not fire `onOpenChange` when it is the code that closes it.
+ const close = useCallback(() => {
+ setIsOpen(false);
+ clearDroppedImage();
+ }, [clearDroppedImage]);
+
const runImageToPrompt = useCallback(async () => {
- if (!selectedImage || !selectedModel) {
+ if (!image || !selectedModel) {
return;
}
setIsLoading(true);
try {
- const result = await imageToPrompt({ image_name: selectedImage.imageName, model_key: selectedModel.key });
+ const result = await imageToPrompt({ image_name: image.imageName, model_key: selectedModel.key });
if (result.prompt && activeProjectIdRef.current === projectId) {
onPositivePromptChange(result.prompt);
}
- setIsOpen(false);
+ close();
} catch (error) {
notifications.reportError({
area: 'image-to-prompt',
@@ -562,10 +592,10 @@ const ImageToPromptButton = ({
} finally {
setIsLoading(false);
}
- }, [notifications, onPositivePromptChange, projectId, selectedImage, selectedModel, t]);
+ }, [close, image, notifications, onPositivePromptChange, projectId, selectedModel, t]);
const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);
- const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);
+ const handleOpenChange = useCallback((event: { open: boolean }) => (event.open ? setIsOpen(true) : close()), [close]);
const handleModelChange = useCallback((model: ModelConfig | null) => setSelectedModelKey(model?.key ?? null), []);
const handleRunImageToPrompt = useCallback(() => void runImageToPrompt(), [runImageToPrompt]);
@@ -619,18 +649,18 @@ const ImageToPromptButton = ({
value={selectedModelKey}
onChange={handleModelChange}
/>
- {selectedImage ? (
+ {image ? (
<HStack gap="2">
<Image
- alt={selectedImage.imageName}
+ alt={image.imageName}
boxSize="10"
flexShrink="0"
objectFit="cover"
rounded="md"
- src={selectedImage.thumbnailUrl || selectedImage.imageUrl}
+ src={image.thumbnailUrl || image.imageUrl}
/>
<Text color="fg.subtle" fontSize="xs" truncate>
- {selectedImage.imageName}
+ {image.imageName}
</Text>
</HStack>
) : (
@@ -639,7 +669,7 @@ const ImageToPromptButton = ({
</Text>
)}
<Button
- disabled={!selectedImage || !selectedModel}
+ disabled={!image || !selectedModel}
loading={isLoading}
size="xs"
onClick={handleRunImageToPrompt}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
index f39c522d4a..3b27a84a48 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
@@ -1,5 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */
import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -53,18 +54,22 @@ it('keeps positive prompt actions enabled when stale view mode has no active tem
<I18nextProvider i18n={i18n}>
<QueryClientProvider client={new QueryClient()}>
<ChakraProvider value={system}>
- <PositivePromptField
- heightPx={96}
- isTemplateViewMode
- loras={[]}
- projectId="project-1"
- selectedModel={undefined}
- showSyntaxHighlighting={false}
- value="a cat"
- onChange={vi.fn()}
- onResizeEnd={vi.fn()}
- onUsePrompt={vi.fn()}
- />
+ {/* The prompt box is a gallery-image drop target, so it lives inside
+ the shell's DndContext wherever it is really rendered. */}
+ <DndContext>
+ <PositivePromptField
+ heightPx={96}
+ isTemplateViewMode
+ loras={[]}
+ projectId="project-1"
+ selectedModel={undefined}
+ showSyntaxHighlighting={false}
+ value="a cat"
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </DndContext>
</ChakraProvider>
</QueryClientProvider>
</I18nextProvider>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
index 02a86f5e4b..4be68063b3 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -3,11 +3,12 @@ import type { PromptTemplateSnapshot } from '@features/generation/core/promptTem
import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';
import type { ChangeEvent, KeyboardEvent } from 'react';
+import { Box, Text } from '@chakra-ui/react';
import { applyPromptTemplate, getPromptTemplateChunks } from '@features/generation/core/promptTemplates';
import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
import { useWildcards } from '@features/generation/ui/useWildcards';
-import { Field } from '@platform/ui';
+import { DropZone, Field } from '@platform/ui';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,6 +19,7 @@ import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';
import { insertPromptText, registerPositivePromptElement } from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
+import { usePromptImageDrop } from './usePromptImageDrop';
import { usePromptTriggerAutocomplete } from './usePromptTriggerAutocomplete';
import { usePromptTriggerPicker } from './usePromptTriggerPicker';
@@ -109,6 +111,19 @@ export const PositivePromptField = ({
// the user is still typing.
const isViewingMerged = isTemplateViewMode && promptTemplate !== null;
+ // View mode hides the authored prompt, and the actions that would rewrite it
+ // are out of reach there — so is the drop that opens one of them.
+ //
+ // Destructured rather than kept whole: passing `imageDrop.setNodeRef` straight
+ // to `ref` makes the compiler read the object it came from as a ref too, and
+ // every other field of it then counts as a ref access during render.
+ const {
+ droppedImage,
+ isDragActive: isImageDragActive,
+ isOver: isImageDropOver,
+ setNodeRef: setImageDropRef,
+ } = usePromptImageDrop({ disabled: isViewingMerged });
+
const autocomplete = usePromptTriggerAutocomplete({
isDisabled: isViewingMerged,
keys: POSITIVE_PROMPT_TRIGGER_KEYS,
@@ -193,6 +208,7 @@ export const PositivePromptField = ({
() => (
<PositivePromptActions
batchCount={batchCount}
+ droppedImage={droppedImage}
dynamicPrompts={dynamicPrompts}
isPromptTriggerPickerOpen={triggerPicker.isOpen}
showSyntaxHighlighting={showSyntaxHighlighting}
@@ -215,6 +231,7 @@ export const PositivePromptField = ({
dynamicPrompts,
effectivePositivePrompt,
handleUsePrompt,
+ droppedImage,
insertTextAtCaret,
loras,
projectId,
@@ -246,29 +263,52 @@ export const PositivePromptField = ({
return (
<Field label={t('common.prompt')} labelEnd={labelEnd}>
- <PromptTextarea
- {...PROMPT_ATTENTION_TARGET_PROPS}
- {...autocomplete.comboboxProps}
- aria-label={t('widgets.generate.positivePrompt')}
- defaultHeightPx={heightPx}
- minHeightPx={96}
- resizeHandleAriaLabel={t('widgets.generate.resizePositivePrompt')}
- size="xs"
- fontFamily="mono"
- highlightDynamicPrompts={dynamicPrompts !== null}
- knownWildcards={knownWildcards}
- readOnly={isViewingMerged}
- showSyntaxHighlighting={showSyntaxHighlighting}
- templateChunks={templateChunks}
- textareaRef={handleTextareaRef}
- title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
- value={isViewingMerged ? effectivePositivePrompt : draftValue}
- onBlur={autocomplete.close}
- onChange={handlePromptChange}
- onClick={isViewingMerged ? exitViewMode : handlePromptClick}
- onKeyDown={handlePromptKeyDown}
- onResizeEnd={onResizeEnd}
- />
+ <Box ref={setImageDropRef} position="relative">
+ <PromptTextarea
+ {...PROMPT_ATTENTION_TARGET_PROPS}
+ {...autocomplete.comboboxProps}
+ aria-label={t('widgets.generate.positivePrompt')}
+ defaultHeightPx={heightPx}
+ minHeightPx={96}
+ resizeHandleAriaLabel={t('widgets.generate.resizePositivePrompt')}
+ size="xs"
+ fontFamily="mono"
+ highlightDynamicPrompts={dynamicPrompts !== null}
+ knownWildcards={knownWildcards}
+ readOnly={isViewingMerged}
+ showSyntaxHighlighting={showSyntaxHighlighting}
+ templateChunks={templateChunks}
+ textareaRef={handleTextareaRef}
+ title={isViewingMerged ? t('widgets.generate.promptTemplates.editAuthored') : undefined}
+ value={isViewingMerged ? effectivePositivePrompt : draftValue}
+ onBlur={autocomplete.close}
+ onChange={handlePromptChange}
+ onClick={isViewingMerged ? exitViewMode : handlePromptClick}
+ onKeyDown={handlePromptKeyDown}
+ onResizeEnd={onResizeEnd}
+ />
+ {/* Only while a compatible drag is in flight — a prompt box wearing a
+ permanent dashed border would read as an upload area, not a field.
+ `pointerEvents` stays off so the textarea underneath is unaffected;
+ dnd-kit hit-tests the wrapper's rect, not this overlay. */}
+ {isImageDragActive ? (
+ <DropZone
+ alignItems="center"
+ display="flex"
+ inset="0"
+ isOver={isImageDropOver}
+ justifyContent="center"
+ pointerEvents="none"
+ position="absolute"
+ variant="overlay"
+ zIndex="2"
+ >
+ <Text color="fg" fontSize="sm" fontWeight="700" textAlign="center">
+ {t('widgets.generate.dropImageToPrompt')}
+ </Text>
+ </DropZone>
+ ) : null}
+ </Box>
{autocomplete.element}
{triggerPicker.dismissElement}
{triggerPicker.isOpen ? (
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx
index 438c417357..3dd045802a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx
@@ -1,5 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */
import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -49,18 +50,22 @@ const render = async (isTemplateViewMode = false) => {
root?.render(
<QueryClientProvider client={new QueryClient()}>
<ChakraProvider value={system}>
- <PositivePromptField
- heightPx={TEXTAREA_HEIGHT_PX}
- isTemplateViewMode={isTemplateViewMode}
- loras={[]}
- projectId="project-1"
- selectedModel={SELECTED_MODEL as never}
- showSyntaxHighlighting={false}
- value=""
- onChange={vi.fn()}
- onResizeEnd={vi.fn()}
- onUsePrompt={vi.fn()}
- />
+ {/* The prompt box is a gallery-image drop target, so it lives inside
+ the shell's DndContext wherever it is really rendered. */}
+ <DndContext>
+ <PositivePromptField
+ heightPx={TEXTAREA_HEIGHT_PX}
+ isTemplateViewMode={isTemplateViewMode}
+ loras={[]}
+ projectId="project-1"
+ selectedModel={SELECTED_MODEL as never}
+ showSyntaxHighlighting={false}
+ value=""
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </DndContext>
</ChakraProvider>
</QueryClientProvider>
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx
new file mode 100644
index 0000000000..20c43da236
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx
@@ -0,0 +1,192 @@
+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import { Box, ChakraProvider } from '@chakra-ui/react';
+import { DndContext, PointerSensor, useDraggable, useSensor, useSensors } from '@dnd-kit/core';
+import { getGalleryItemDragData } from '@features/gallery/utility';
+import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+const i18n = i18next.createInstance();
+
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+
+const stubs = vi.hoisted(() => ({
+ ModelSelect: () => null,
+ selectedImage: { imageName: 'selected.png', imageUrl: '/i/selected.png', thumbnailUrl: '/t/selected.png' },
+}));
+
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ // Stubbed alongside the hook: the real one reads the context from its own
+ // unmocked module instance, which no provider in this harness fills.
+ GenerationModelSelect: stubs.ModelSelect,
+ useGenerationUi: () => ({
+ gallery: { selectedImage: stubs.selectedImage },
+ models: {
+ catalog: [{ base: 'any', key: 'llava-1', name: 'LLaVA', type: 'llava_onevision' }],
+ ensureLoaded: vi.fn(),
+ },
+ notifications: { reportError: vi.fn() },
+ project: { activeProjectId: 'project-1' },
+ promptHistory: { clear: vi.fn(), items: [] },
+ }),
+}));
+
+vi.mock('@features/generation/data/wildcards', () => ({
+ createWildcard: vi.fn(),
+ deleteWildcard: vi.fn(),
+ invalidateWildcardDependents: vi.fn(),
+ updateWildcard: vi.fn(),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),
+}));
+
+const DROPPED_IMAGE_NAME = 'dropped.png';
+const dragData = getGalleryItemDragData([{ kind: 'image', name: DROPPED_IMAGE_NAME }]);
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const GalleryDragSource = () => {
+ const { listeners, setNodeRef } = useDraggable({ data: dragData, id: 'gallery-source' });
+
+ return (
+ <button
+ ref={setNodeRef}
+ {...listeners}
+ data-testid="drag-source"
+ style={{ height: 80, left: 20, position: 'fixed', top: 20, touchAction: 'none', width: 80 }}
+ type="button"
+ />
+ );
+};
+
+const Harness = () => {
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
+
+ return (
+ <DndContext sensors={sensors}>
+ <GalleryDragSource />
+ <Box left="300px" position="fixed" top="20px" w="400px">
+ <PositivePromptField
+ heightPx={120}
+ loras={[]}
+ projectId="project-1"
+ selectedModel={undefined}
+ showSyntaxHighlighting={false}
+ value=""
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </Box>
+ </DndContext>
+ );
+};
+
+const settle = (action: () => void, delay = 40): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, delay);
+ });
+ });
+
+const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {
+ target.dispatchEvent(
+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })
+ );
+};
+
+const dropImageOnPromptBox = async ({ release = true } = {}) => {
+ const source = host!.querySelector<HTMLElement>('[data-testid="drag-source"]')!;
+ const box = host!.querySelector('textarea')!.getBoundingClientRect();
+ const x = box.left + box.width / 2;
+ const y = box.top + box.height / 2;
+
+ await settle(() => pointer('pointerdown', source, 50, 50));
+ await settle(() => pointer('pointermove', source.ownerDocument, 90, 50));
+ await settle(() => pointer('pointermove', source.ownerDocument, x, y));
+
+ if (release) {
+ await settle(() => pointer('pointerup', source.ownerDocument, x, y));
+ }
+};
+
+const imageToPromptButton = () =>
+ host!.querySelector<HTMLButtonElement>('button[aria-label="widgets.generate.imageToPrompt"]')!;
+
+const popoverImageName = (): string | null => {
+ const image = document.querySelector<HTMLImageElement>('[data-scope="popover"][data-part="content"] img');
+
+ return image?.getAttribute('alt') ?? null;
+};
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await settle(() =>
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <Harness />
+ </ChakraProvider>
+ </QueryClientProvider>
+ </I18nextProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await settle(() => root?.unmount(), 0);
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('dropping a gallery image on the positive prompt box', () => {
+ it('offers the prompt box as a drop target only while an image is being dragged', async () => {
+ expect(host!.textContent).not.toContain('widgets.generate.dropImageToPrompt');
+
+ await dropImageOnPromptBox({ release: false });
+
+ expect(host!.textContent).toContain('widgets.generate.dropImageToPrompt');
+
+ await settle(() => pointer('pointerup', host!.ownerDocument, 0, 0));
+
+ expect(host!.textContent).not.toContain('widgets.generate.dropImageToPrompt');
+ });
+
+ it('opens the image-to-prompt popover on the image that was dropped', async () => {
+ await dropImageOnPromptBox();
+
+ expect(popoverImageName()).toBe(DROPPED_IMAGE_NAME);
+ });
+
+ it('hands the popover back to the gallery selection once it is dismissed', async () => {
+ await dropImageOnPromptBox();
+ expect(popoverImageName()).toBe(DROPPED_IMAGE_NAME);
+
+ await act(async () => {
+ await userEvent.keyboard('{Escape}');
+ });
+ await settle(() => imageToPromptButton().click());
+
+ expect(popoverImageName()).toBe(stubs.selectedImage.imageName);
+ });
+
+ it('describes the gallery selection when nothing has been dropped', async () => {
+ await settle(() => imageToPromptButton().click());
+
+ expect(popoverImageName()).toBe(stubs.selectedImage.imageName);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts
new file mode 100644
index 0000000000..6f342af248
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts
@@ -0,0 +1,68 @@
+import type { GenerationSelectedImage } from '@features/generation/ui/GenerationUiContext';
+
+import { useDndContext, useDndMonitor } from '@dnd-kit/core';
+import { galleryImageUrls, isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';
+import { useCallback, useId, useMemo, useState } from 'react';
+
+const DROP_DATA = { kind: 'prompt-image' } as const;
+
+/**
+ * An image handed to the prompt box by a drag, waiting for the image-to-prompt
+ * popover to pick it up.
+ */
+export interface DroppedPromptImage {
+ /** The dropped image, or null when the popover should follow the gallery selection. */
+ image: GenerationSelectedImage | null;
+ /** Hands the popover back to the gallery selection once it is done with the drop. */
+ onClear: () => void;
+}
+
+export interface PromptImageDrop {
+ droppedImage: DroppedPromptImage;
+ /** A gallery image is mid-drag, so the drop affordance should be showing. */
+ isDragActive: boolean;
+ isOver: boolean;
+ setNodeRef: (element: HTMLElement | null) => void;
+}
+
+/**
+ * Makes an element a drop target for a gallery image and holds what landed on
+ * it. Dropping is the direct way to describe an image that is not the gallery's
+ * current selection — the popover reads this in preference to that selection,
+ * until it is done and clears it.
+ */
+export const usePromptImageDrop = ({ disabled = false }: { disabled?: boolean } = {}): PromptImageDrop => {
+ const dropId = useId();
+ const [image, setImage] = useState<GenerationSelectedImage | null>(null);
+ const { active } = useDndContext();
+ const { isOver, setNodeRef } = useGalleryImageDroppable({ data: DROP_DATA, disabled, id: dropId });
+
+ useDndMonitor({
+ onDragEnd: (event) => {
+ const data = event.active.data.current;
+
+ if (event.over?.id !== dropId || !isGalleryImageDragData(data)) {
+ return;
+ }
+
+ // The popover describes one image, so a multi-image drag describes its first.
+ const [first] = data.items;
+
+ setImage({
+ imageName: first.name,
+ imageUrl: galleryImageUrls.full(first.name),
+ thumbnailUrl: galleryImageUrls.thumbnail(first.name),
+ });
+ },
+ });
+
+ const onClear = useCallback(() => setImage(null), []);
+ const droppedImage = useMemo(() => ({ image, onClear }), [image, onClear]);
+
+ return {
+ droppedImage,
+ isDragActive: !disabled && isGalleryImageDragData(active?.data.current),
+ isOver,
+ setNodeRef,
+ };
+};