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(generate): template preview image uses the shared media slot

Josh Corbettd4af961e58f1
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 6688d8f8fa..86b593b1ed 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2168,7 +2168,6 @@
"addImage": "Add an image",
"replaceImage": "Replace image",
"removeImage": "Remove image",
- "chooseFromGallery": "Choose from gallery",
"couldNotLoadImage": "Could not load that image",
"import": "Import",
"importHelp": "Import templates from a CSV or JSON file with name, prompt and negative_prompt.",
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
index bbbb5f0379..aa9a65ad13 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
@@ -324,6 +324,23 @@ describe('GalleryMediaSlot', () => {
expect(alertText()).toBe('widgets.gallery.picker.uploadFailed');
});
+ it('hands an uploaded file to the consumer instead of the gallery and shows a custom thumbnail', async () => {
+ const onUploadFile = vi.fn();
+ const value: GalleryMediaSlotValue = { kind: 'image', name: 'stored preview' };
+
+ await renderSlot({ onUploadFile, thumbnail: <span data-testid="custom-thumb" />, value });
+
+ expect(host?.querySelector('[data-testid="custom-thumb"]')).not.toBeNull();
+ expect(host?.querySelector('img')).toBeNull();
+
+ const file = new File(['image'], 'local.png', { type: 'image/png' });
+ await changeFile(file);
+
+ expect(onUploadFile).toHaveBeenCalledExactlyOnceWith(file);
+ expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
it('shows the current value with a replace hint and clears it', async () => {
const value: GalleryMediaSlotValue = { height: 96, kind: 'image', name: 'chosen.png', width: 128 };
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
index 282b6bba68..26b44eb339 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
@@ -22,7 +22,7 @@ import { DropZone } from '@platform/ui/DropZone';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { useQuery } from '@tanstack/react-query';
import { ChevronDownIcon, ImagePlusIcon, RefreshCwIcon, UploadIcon, XIcon } from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { GalleryPickerAccept } from './galleryPicker';
@@ -72,7 +72,9 @@ const getThumbnailUrl = (value: GalleryMediaSlotValue): string =>
* A single-item media field: click opens the gallery picker, a gallery drag
* can be dropped on it, and a file can be uploaded from its action row. Owns
* the async resolve/upload work and its busy and error states; the consumer
- * only sees `onChange` with a full item (or null when cleared).
+ * only sees `onChange` with a full item (or null when cleared). A consumer
+ * that stores the file itself takes it through `onUploadFile` instead of the
+ * gallery, and can show its own `thumbnail` for a value the gallery lacks.
*/
export const GalleryMediaSlot = ({
accept,
@@ -80,9 +82,11 @@ export const GalleryMediaSlot = ({
disabledReason,
dropId,
labels: labelOverrides,
- uploadBoardId,
+ thumbnail,
+ uploadBoardId = 'none',
value,
onChange,
+ onUploadFile,
}: {
accept: GalleryPickerAccept;
disabled?: boolean;
@@ -91,10 +95,14 @@ export const GalleryMediaSlot = ({
/** Unique droppable id; sibling slots must not share one. */
dropId: string;
labels?: Partial<GalleryMediaSlotLabels>;
+ /** Replaces the gallery thumbnail of `value`, for media the gallery does not hold. */
+ thumbnail?: ReactNode;
/** Where a file uploaded from the action row lands; a getter is read when the upload starts. */
- uploadBoardId: string | (() => string);
+ uploadBoardId?: string | (() => string);
value: GalleryMediaSlotValue | null;
onChange: (item: GalleryItem | null) => void;
+ /** Takes an uploaded file directly instead of sending it to the gallery. */
+ onUploadFile?: (file: File) => void;
}) => {
const { t } = useTranslation();
const { notifications } = useGalleryUi();
@@ -185,6 +193,10 @@ export const GalleryMediaSlot = ({
);
return;
}
+ if (onUploadFile) {
+ onUploadFile(file);
+ return;
+ }
setIsBusy(true);
void uploadFiles([file])
@@ -199,7 +211,7 @@ export const GalleryMediaSlot = ({
})
.finally(() => setIsBusy(false));
},
- [accept, onChange, t, uploadFiles]
+ [accept, onChange, onUploadFile, t, uploadFiles]
);
const { inputProps: uploadInputProps, openPicker: openUploadPicker } = useGalleryUploadInput(
handleUpload,
@@ -238,16 +250,18 @@ export const GalleryMediaSlot = ({
{value ? (
<HStack align="stretch" gap="3" h="20" p="2">
<Box bg="blackAlpha.300" boxSize="16" flexShrink="0" overflow="hidden" rounded="sm">
- <Image
- alt=""
- boxSize="full"
- objectFit="contain"
- outline="1px solid"
- outlineColor="border.image"
- outlineOffset="-1px"
- rounded="sm"
- src={getThumbnailUrl(value)}
- />
+ {thumbnail ?? (
+ <Image
+ alt=""
+ boxSize="full"
+ objectFit="contain"
+ outline="1px solid"
+ outlineColor="border.image"
+ outlineOffset="-1px"
+ rounded="sm"
+ src={getThumbnailUrl(value)}
+ />
+ )}
</Box>
<Stack align="start" flex="1" gap="1" justify="center" minW="0">
<MiddleTruncate color="fg" fontSize="xs" fontWeight="semibold" text={value.name} />
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
index 2c2f5d122c..9efcf17514 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx
@@ -1,4 +1,5 @@
import type { GalleryItem } from '@features/gallery';
+import type { GalleryMediaSlotLabels, GalleryMediaSlotValue } from '@features/gallery/mediaSlot';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import type {
PromptTemplateCreateDraft,
@@ -10,8 +11,8 @@ import type { PendingPromptTemplateDraft } from '@features/generation/ui/promptT
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import type { ChangeEvent } from 'react';
-import { Box, HStack, Input, Stack, Text } from '@chakra-ui/react';
-import { GalleryPickerPopover } from '@features/gallery/picker';
+import { HStack, Input, Stack, Text } from '@chakra-ui/react';
+import { GalleryMediaSlot } from '@features/gallery/mediaSlot';
import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
@@ -20,11 +21,10 @@ import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTexta
import { useMountEffect } from '@platform/react/useMountEffect';
import { captureAccountScope } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
-import { Button, IconButton } from '@platform/ui/Button';
-import { DropZone } from '@platform/ui/DropZone';
+import { Button } from '@platform/ui/Button';
import { Field } from '@platform/ui/Field';
import { Tooltip } from '@platform/ui/Tooltip';
-import { CheckIcon, ImageUpIcon, ImagesIcon, XIcon } from 'lucide-react';
+import { CheckIcon, XIcon } from 'lucide-react';
import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -46,11 +46,14 @@ interface EditorDraft {
image: PromptTemplateImageUpdate;
/** Undefined keeps the stored image, a URL previews a replacement, null removes it. */
imagePreviewUrl?: string | null;
+ /** What the slot names the replacement: the picked item or file. */
+ imageName?: string;
}
const MAX_NAME_LENGTH = 128;
const NEW_TEMPLATE_IMAGE = { hasImage: false, id: 'new' } as const;
const IMAGE_ONLY = ['image'] as const;
+const IMAGE_DROP_ID = 'prompt-template-image';
export const PromptTemplateEditor = ({
catalog,
@@ -63,7 +66,6 @@ export const PromptTemplateEditor = ({
const { t } = useTranslation();
const { notifications } = useGenerationUi();
const nameFieldId = useId();
- const fileInputRef = useRef<HTMLInputElement | null>(null);
const [draft, setDraft] = useState<EditorDraft>({
image: { kind: 'preserve' },
name: template?.name ?? '',
@@ -155,8 +157,6 @@ export const PromptTemplateEditor = ({
[]
);
- const pickImage = useCallback(() => fileInputRef.current?.click(), []);
-
// The value has to be read before `setDraft`, not inside the updater: React
// nulls `currentTarget` once the handler returns, and an updater can run after
// that.
@@ -174,10 +174,10 @@ export const PromptTemplateEditor = ({
}, []);
const setImageBlob = useCallback(
- (blob: Blob) => {
+ (blob: Blob, imageName: string) => {
const imagePreviewUrl = takeObjectUrl(blob);
- setDraft((current) => ({ ...current, image: { blob, kind: 'replace' }, imagePreviewUrl }));
+ setDraft((current) => ({ ...current, image: { blob, kind: 'replace' }, imageName, imagePreviewUrl }));
},
[takeObjectUrl]
);
@@ -200,7 +200,7 @@ export const PromptTemplateEditor = ({
})
.then((blob) => {
if (!signal.aborted) {
- setImageBlob(blob);
+ setImageBlob(blob, item.name);
}
})
.catch(() => {
@@ -212,17 +212,10 @@ export const PromptTemplateEditor = ({
[abortGalleryFetch, setImageBlob, t]
);
- const handleImageChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
-
- if (file) {
- abortGalleryFetch();
- setImageBlob(file);
- }
-
- // Reset so re-picking the same file still fires a change.
- event.currentTarget.value = '';
+ const handleUploadFile = useCallback(
+ (file: File) => {
+ abortGalleryFetch();
+ setImageBlob(file, file.name);
},
[abortGalleryFetch, setImageBlob]
);
@@ -230,9 +223,49 @@ export const PromptTemplateEditor = ({
const clearImage = useCallback(() => {
abortGalleryFetch();
takeObjectUrl(null);
- setDraft((current) => ({ ...current, image: { kind: 'remove' }, imagePreviewUrl: null }));
+ setDraft((current) => ({ ...current, image: { kind: 'remove' }, imageName: undefined, imagePreviewUrl: null }));
}, [abortGalleryFetch, takeObjectUrl]);
+ const handleSlotChange = useCallback(
+ (item: GalleryItem | null) => {
+ if (item === null) {
+ clearImage();
+ } else if (item.kind === 'image') {
+ handleGalleryPick(item);
+ }
+ },
+ [clearImage, handleGalleryPick]
+ );
+ const slotLabels = useMemo<Partial<GalleryMediaSlotLabels>>(
+ () => ({
+ choose: t('widgets.generate.promptTemplates.addImage'),
+ remove: t('widgets.generate.promptTemplates.removeImage'),
+ replace: t('widgets.generate.promptTemplates.replaceImage'),
+ }),
+ [t]
+ );
+ const slotThumbnail = useMemo(
+ () => (
+ <PromptTemplateImage
+ alt=""
+ boxSize="full"
+ fallback={null}
+ localPreviewUrl={draft.imagePreviewUrl}
+ objectFit="contain"
+ rounded="sm"
+ template={template ?? NEW_TEMPLATE_IMAGE}
+ />
+ ),
+ [draft.imagePreviewUrl, template]
+ );
+ const slotValue = useMemo<GalleryMediaSlotValue | null>(
+ () =>
+ hasImage
+ ? { kind: 'image', name: draft.imageName ?? template?.name ?? t('widgets.generate.promptTemplates.image') }
+ : null,
+ [draft.imageName, hasImage, t, template?.name]
+ );
+
const reportSaveError = useCallback(
(caught: unknown) =>
notifications.reportError({
@@ -328,75 +361,15 @@ export const PromptTemplateEditor = ({
</Field>
<Field label={t('widgets.generate.promptTemplates.image')}>
- <HStack gap="2">
- {template ? (
- <PromptTemplateImage
- alt=""
- boxSize="12"
- flexShrink="0"
- fallback={null}
- localPreviewUrl={draft.imagePreviewUrl}
- objectFit="cover"
- rounded="md"
- template={template}
- />
- ) : draft.imagePreviewUrl ? (
- <PromptTemplateImage
- alt=""
- boxSize="12"
- fallback={null}
- localPreviewUrl={draft.imagePreviewUrl}
- objectFit="cover"
- rounded="md"
- template={NEW_TEMPLATE_IMAGE}
- />
- ) : null}
- <DropZone
- alignItems="center"
- as="button"
- display="flex"
- flex="1"
- gap="1.5"
- justifyContent="center"
- px="2"
- py="2.5"
- onClick={pickImage}
- >
- <ImageUpIcon size={14} />
- <Text as="span" fontSize="2xs">
- {hasImage
- ? t('widgets.generate.promptTemplates.replaceImage')
- : t('widgets.generate.promptTemplates.addImage')}
- </Text>
- </DropZone>
- <GalleryPickerPopover
- accept={IMAGE_ONLY}
- label={t('widgets.generate.promptTemplates.chooseFromGallery')}
- onPick={handleGalleryPick}
- >
- <IconButton aria-label={t('widgets.generate.promptTemplates.chooseFromGallery')} size="2xs" variant="ghost">
- {/* The tooltip sits inside the trigger so it cannot replace the popover trigger's id. */}
- <Tooltip content={t('widgets.generate.promptTemplates.chooseFromGallery')}>
- <Box alignItems="center" display="flex" h="full" justifyContent="center" w="full">
- <ImagesIcon />
- </Box>
- </Tooltip>
- </IconButton>
- </GalleryPickerPopover>
- {hasImage ? (
- <Tooltip content={t('widgets.generate.promptTemplates.removeImage')}>
- <IconButton
- aria-label={t('widgets.generate.promptTemplates.removeImage')}
- size="2xs"
- variant="ghost"
- onClick={clearImage}
- >
- <XIcon />
- </IconButton>
- </Tooltip>
- ) : null}
- <input accept="image/*" hidden ref={fileInputRef} type="file" onChange={handleImageChange} />
- </HStack>
+ <GalleryMediaSlot
+ accept={IMAGE_ONLY}
+ dropId={IMAGE_DROP_ID}
+ labels={slotLabels}
+ thumbnail={slotThumbnail}
+ value={slotValue}
+ onChange={handleSlotChange}
+ onUploadFile={handleUploadFile}
+ />
</Field>
{error ? (
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
index d463ca1a6d..2c1d477e51 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
@@ -1,7 +1,10 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { GalleryUiProvider } from '@features/gallery/react';
import { exportPromptTemplates } from '@features/generation/data/promptTemplates';
import { PromptTemplateEditor } from '@features/generation/ui/promptFields/PromptTemplateEditor';
import { PromptTemplatesPanel } from '@features/generation/ui/promptFields/PromptTemplatesPanel';
@@ -152,6 +155,15 @@ const createCatalog = (overrides: Partial<PromptTemplateCatalog> = {}): PromptTe
...overrides,
});
+// The editor's image slot needs the gallery UI port and a drag context.
+const galleryAdapter = {
+ gallery: { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() },
+ galleryValues: { galleryView: 'images', selectedBoardId: 'none' },
+ notifications: { add: vi.fn(), reportError: vi.fn() },
+ projectName: 'Project',
+ widgets: { openGallery: () => true, patchGalleryValues: vi.fn() },
+} as unknown as GalleryUiAdapter;
+
const render = async (element: React.ReactNode) => {
host = document.createElement('div');
host.style.width = '400px';
@@ -162,7 +174,11 @@ const render = async (element: React.ReactNode) => {
const contents = (
<I18nextProvider i18n={i18n}>
<QueryClientProvider client={queryClient}>
- <ChakraProvider value={system}>{element}</ChakraProvider>
+ <ChakraProvider value={system}>
+ <GalleryUiProvider adapter={galleryAdapter}>
+ <DndContext>{element}</DndContext>
+ </GalleryUiProvider>
+ </ChakraProvider>
</QueryClientProvider>
</I18nextProvider>
);