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): direct input for image collection fields

Josh Corbettda61a7d563dc
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 83ffdbea23..20a39f1118 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1442,6 +1442,8 @@
"forLoopBodyBoundary": "For loop body",
"forLoopBodyBoundaryStatus": {
"missing_linkage": "missing loop linkage",
+ "imageCollectionCount_one": "{{count}} image",
+ "imageCollectionCount_other": "{{count}} images",
"invalid_linkage": "invalid loop linkage",
"duplicate_linkage": "duplicate loop linkage",
"missing_return": "missing ForReturn",
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index be8bd869b8..c43d9a3416 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -55,14 +55,14 @@ describe('workflow field validation', () => {
);
});
- it('treats connected required fields as valid', () => {
- expect(
it('accepts an empty string as a required string value', () => {
expect(getWorkflowFieldInvalidReason({ isConnected: false, template: input(), value: '' })).toBe(null);
expect(isWorkflowFieldValueValid(input(), '')).toBe(true);
expect(isWorkflowFieldValueValid(input({ options: ['a'], type: single('EnumField') }), '')).toBe(false);
});
+ it('treats connected required fields as valid', () => {
+ expect(
getWorkflowFieldInvalidReason({ isConnected: true, template: input({ input: 'connection' }), value: '' })
).toBe(null);
});
@@ -113,13 +113,28 @@ describe('workflow field validation', () => {
expect(isWorkflowFieldValueValid(input({ type: single('VideoField') }), {})).toBe(false);
});
- it('keeps COLLECTION media values on the generic non-null check (persisted arrays stay valid)', () => {
+ it('validates image collections as lists of image refs and keeps video collections on the non-null check', () => {
const videos = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'VideoField' } });
const images = input({ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' } });
expect(isWorkflowFieldValueValid(videos, [{ video_name: 'a.mp4' }, { video_name: 'b.mp4' }])).toBe(true);
expect(isWorkflowFieldValueValid(videos, undefined)).toBe(false);
expect(isWorkflowFieldValueValid(images, [{ image_name: 'a.png' }])).toBe(true);
+ expect(isWorkflowFieldValueValid(images, [])).toBe(true);
+ expect(isWorkflowFieldValueValid(images, [{ image_name: '' }])).toBe(false);
+ expect(isWorkflowFieldValueValid(images, { image_name: 'a.png' })).toBe(false);
+ });
+
+ it('exposes image collections as direct inputs but keeps other collections connection-only', () => {
+ expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' } }))).toBe(
+ true
+ );
+ expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'VideoField' } }))).toBe(
+ false
+ );
+ expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'StringField' } }))).toBe(
+ false
+ );
});
it('accepts a LoRA collection as a list, a bare entry, or an empty list', () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index 595ebcf63c..061a469acd 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -40,18 +40,18 @@ const MODEL_FIELD_TYPE_NAMES = new Set([
export const isModelFieldType = (type: FieldType): boolean => MODEL_FIELD_TYPE_NAMES.has(type.name);
+/** Collection field types with a direct-input list widget; other collections are connection-only. */
+const DIRECT_COLLECTION_FIELD_TYPE_NAMES = new Set(['ImageField']);
+
/** True when the field renders an editable control on the node / linear form. */
export const isDirectInputField = (template: FieldInputTemplate): boolean =>
- template.input !== 'connection' && isStatefulFieldType(template.type) && template.type.cardinality !== 'COLLECTION';
+ template.input !== 'connection' &&
+ isStatefulFieldType(template.type) &&
+ (template.type.cardinality !== 'COLLECTION' || DIRECT_COLLECTION_FIELD_TYPE_NAMES.has(template.type.name));
/** A field can be exposed to the Linear UI when it can be edited directly. */
export const isExposableField = (template: FieldInputTemplate): boolean => isDirectInputField(template);
-export const cloneWorkflowFieldDefault = (template: FieldInputTemplate): unknown =>
- template.default === undefined ? undefined : structuredClone(template.default);
-
-export const isWorkflowFieldValueDefault = (template: FieldInputTemplate, value: unknown): boolean => {
- if (value === template.default) {
/** Numeric fields whose linear-form element can show a randomize button. */
export const isShuffleableField = (template: FieldInputTemplate): boolean =>
(template.type.name === 'IntegerField' || template.type.name === 'FloatField') && isDirectInputField(template);
@@ -95,6 +95,11 @@ export const getRandomWorkflowFieldValue = (template: FieldInputTemplate, random
return Number((Math.min(last, index) * step).toFixed(decimals));
};
+export const cloneWorkflowFieldDefault = (template: FieldInputTemplate): unknown =>
+ template.default === undefined ? undefined : structuredClone(template.default);
+
+export const isWorkflowFieldValueDefault = (template: FieldInputTemplate, value: unknown): boolean => {
+ if (value === template.default) {
return true;
}
@@ -209,7 +214,8 @@ const isColorValueValid = (value: unknown): boolean => {
export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {
switch (template.type.name) {
case 'StringField':
- return isNonEmptyString(value);
+ // An empty string is a legitimate string value (e.g. a blank negative prompt).
+ return typeof value === 'string';
case 'IntegerField':
case 'FloatField':
return isNumberFieldValueValid(template, value);
@@ -224,8 +230,7 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
// models through untouched.
return Array.isArray(value) ? value.every(isLoraFieldCollectionEntry) : isLoraFieldCollectionEntry(value);
case 'SchedulerField':
- // An empty string is a legitimate string value (e.g. a blank negative prompt).
- return typeof value === 'string';
+ return isNonEmptyString(value);
case 'BoardField':
return (
value === undefined ||
@@ -235,15 +240,14 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
hasNonEmptyStringProp(value, 'board_id')
);
case 'ImageField':
- // COLLECTION media values are arrays the direct-input widget never
- // authors; keep the generic non-null check for them so persisted array
- // values (imported workflows) stay exactly as valid as before.
if (template.type.cardinality === 'COLLECTION') {
- return value !== undefined && value !== null;
+ return Array.isArray(value) && value.every((item) => hasNonEmptyStringProp(item, 'image_name'));
}
return hasNonEmptyStringProp(value, 'image_name');
case 'VideoField':
+ // COLLECTION video values are arrays no direct-input widget authors; keep the
+ // generic non-null check so persisted values (imported workflows) stay valid.
if (template.type.cardinality === 'COLLECTION') {
return value !== undefined && value !== null;
}
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.tsx
index a0affc8b21..8f27424335 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
@@ -2,6 +2,7 @@ import type { FieldInputTemplate } from '@features/workflow/contracts';
import { ChakraProvider, Field } from '@chakra-ui/react';
import { DndContext } from '@dnd-kit/core';
+import { toaster } from '@platform/ui';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act, cloneElement, useCallback, useState } from 'react';
@@ -262,7 +263,6 @@ const findButton = (label: string): HTMLButtonElement => {
return button;
};
-describe('WorkflowFieldInput textarea', () => {
const BOOLEAN_TEMPLATE = {
name: 'enabled',
title: 'Enabled',
@@ -297,6 +297,7 @@ describe('WorkflowFieldInput boolean', () => {
});
});
+describe('WorkflowFieldInput textarea', () => {
it('uses the accessible unbounded resizable textarea for prompt-like string fields', async () => {
await renderField(TEXTAREA_TEMPLATE, 'hello', vi.fn());
@@ -343,7 +344,81 @@ describe('WorkflowFieldInput media inputs', () => {
expect(onChange).toHaveBeenCalledWith(undefined);
});
- it('keeps COLLECTION media fields connection-only (the widget would write a bare object into a list)', async () => {
+ it('edits image collections as a list: picks append, remove drops one, clear empties', async () => {
+ const onChange = vi.fn();
+ const collectionTemplate = {
+ name: 'images',
+ title: 'Images',
+ type: { cardinality: 'COLLECTION', name: 'ImageField' },
+ } as unknown as FieldInputTemplate;
+
+ await renderField(collectionTemplate, [{ image_name: 'a.png' }, { image_name: 'b.png' }], onChange);
+
+ expect(host.textContent).not.toContain('Connection only');
+ expect(host.querySelectorAll('img')).toHaveLength(2);
+ expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.multiple).toBe(true);
+
+ await act(() => findButton('common.add').click());
+ expect(onChange).toHaveBeenLastCalledWith([
+ { image_name: 'a.png' },
+ { image_name: 'b.png' },
+ { image_name: SELECTED_GALLERY_VIDEO.name },
+ ]);
+
+ await act(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove a.png"]')!.click());
+ expect(onChange).toHaveBeenLastCalledWith([{ image_name: 'b.png' }]);
+
+ await act(() => findButton('Clear').click());
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ });
+
+ it('keeps an empty image collection droppable and pickable', async () => {
+ const onChange = vi.fn();
+ const collectionTemplate = {
+ name: 'images',
+ title: 'Images',
+ type: { cardinality: 'COLLECTION', name: 'ImageField' },
+ } as unknown as FieldInputTemplate;
+
+ await renderField(collectionTemplate, [], onChange);
+
+ const emptyState = findButton('widgets.gallery.picker.chooseImage');
+
+ expect(emptyState.getBoundingClientRect().height).toBeGreaterThanOrEqual(64);
+ await act(() => emptyState.click());
+ expect(onChange).toHaveBeenLastCalledWith([{ image_name: SELECTED_GALLERY_VIDEO.name }]);
+ });
+
+ it('adopts the files that uploaded when one of a multi-file batch fails', async () => {
+ uploadImageMock.mockResolvedValueOnce({ imageName: 'first.png' }).mockRejectedValueOnce(new Error('413'));
+ const createToast = vi.spyOn(toaster, 'create').mockImplementation(() => '');
+ const onChange = vi.fn();
+ const collectionTemplate = {
+ name: 'images',
+ title: 'Images',
+ type: { cardinality: 'COLLECTION', name: 'ImageField' },
+ } as unknown as FieldInputTemplate;
+
+ await renderField(collectionTemplate, [{ image_name: 'a.png' }], onChange);
+
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+ const transfer = new DataTransfer();
+
+ transfer.items.add(new File(['1'], 'one.png', { type: 'image/png' }));
+ transfer.items.add(new File(['2'], 'two.png', { type: 'image/png' }));
+ fileInput.files = transfer.files;
+ await act(() => fileInput.dispatchEvent(new Event('change', { bubbles: true })));
+
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith([{ image_name: 'a.png' }, { image_name: 'first.png' }]);
+ });
+ await vi.waitFor(() => {
+ expect(createToast).toHaveBeenCalledWith(expect.objectContaining({ description: 'two.png', type: 'error' }));
+ });
+ createToast.mockRestore();
+ });
+
+ it('keeps video COLLECTION fields connection-only (the widget would write a bare object into a list)', async () => {
const collectionTemplate = {
name: 'videos',
title: 'Videos',
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index af57e5d7c4..d769522d5c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -13,6 +13,7 @@ import {
Image,
Input,
NumberInput,
+ SimpleGrid,
Stack,
Switch,
Text,
@@ -27,8 +28,8 @@ import {
type GalleryBoard,
type GalleryItem,
} from '@features/gallery';
-import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
-import { GalleryPickerPopover } from '@features/gallery/picker';
+import { getSelectedGalleryImageFromValues, toGalleryItemKey } from '@features/gallery/contracts';
+import { GalleryPickerPopover, type GalleryPickerSelection } from '@features/gallery/picker';
import { invalidateGallery } from '@features/gallery/queries';
import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';
import { DEFAULT_LORA_WEIGHT_CONFIG, sanitizeBatchCount, SCHEDULER_OPTIONS } from '@features/generation/settings';
@@ -37,6 +38,7 @@ import { isSeedInputField } from '@features/workflow/graph';
import {
getWorkflowMediaFieldDropId,
getWorkflowMediaFieldDropItem,
+ getWorkflowMediaFieldDropItems,
type WorkflowMediaKind,
} from '@features/workflow/ui/fields/mediaFieldDnd';
import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
@@ -46,6 +48,7 @@ import {
toLoraFieldCollectionList,
} from '@features/workflow/utility';
import { planSeedSubmission, type SeedMode, wrapSeed } from '@platform/core/seed';
+import { useMountEffect } from '@platform/react/useMountEffect';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -172,12 +175,12 @@ const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldIn
);
};
-const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
- const isInteger = template.type.name === 'IntegerField';
- const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';
/** A double-click anywhere in the box selects the whole value, not just the word under the pointer. */
const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTarget.select();
+const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
+ const isInteger = template.type.name === 'IntegerField';
+ const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';
const min = template.minimum ?? template.exclusiveMinimum ?? undefined;
const max = template.maximum ?? template.exclusiveMaximum ?? undefined;
const onInputChange = useCallback(
@@ -205,10 +208,10 @@ const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTa
w="full"
{...invalidProps(invalid)}
onChange={onInputChange}
+ onDoubleClick={selectInputText}
/>
);
};
- onDoubleClick={selectInputText}
/**
* The shared seed control under a workflow row. The workflow owns the value
@@ -273,11 +276,15 @@ const SWITCH_CHECKED_PROPS = { bg: 'accent.solid' };
const BooleanInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
const onCheckedChange = useCallback((event: { checked: boolean }) => onChange(event.checked), [onChange]);
+ // The host id goes through zag's id map: the root is a `<label for>` pointing at zag's hidden-input
+ // id, so an `id` set on the element itself would leave the label pointing at nothing (an inert switch).
+ const switchIds = useMemo(() => (id ? { hiddenInput: `${id}-switch-input` } : undefined), [id]);
return (
<Switch.Root
checked={value === true}
className="nodrag"
+ ids={switchIds}
invalid={invalid}
size="sm"
onCheckedChange={onCheckedChange}
@@ -287,15 +294,11 @@ const BooleanInput = ({ id, invalid, onChange, template, value }: WorkflowFieldI
<Switch.Thumb />
</Switch.Control>
</Switch.Root>
- // The host id goes through zag's id map: the root is a `<label for>` pointing at zag's hidden-input
- // id, so an `id` set on the element itself would leave the label pointing at nothing (an inert switch).
- const switchIds = useMemo(() => (id ? { hiddenInput: `${id}-switch-input` } : undefined), [id]);
);
};
const SELECT_VALUE_TEXT_PROPS = { placeholder: 'Select…' };
- ids={switchIds}
const SelectInput = ({
id,
invalid,
@@ -539,82 +542,55 @@ const VIDEO_ONLY = ['video'] as const;
const MEDIA_INPUT_FOCUS_PROPS = { outline: '2px solid {colors.accent.focusRing}', outlineOffset: '2px' } as const;
/**
- * Direct input for `ImageField` / `VideoField`: shows the current item with a
- * thumbnail, opens the gallery picker, accepts a single-item gallery drag
- * onto the row, and uploads a local file to the gallery's selected board.
+ * Upload: file picker -> gallery upload -> adopt the uploaded items. The
+ * adoption is pinned to this widget instance AND the project it started in:
+ * `onUploaded` dispatches into the *active* project, so a completion arriving
+ * after a project switch (or after this node was deleted, which unmounts the
+ * widget) must not be applied - the upload itself still succeeded, so the
+ * gallery is refreshed and the user is pointed there instead.
*/
-const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputProps & { kind: WorkflowMediaKind }) => {
- const { t } = useTranslation();
+const useMediaUpload = ({
+ kind,
+ multiple = false,
+ onUploaded,
+}: {
+ kind: WorkflowMediaKind;
+ multiple?: boolean;
+ onUploaded: (names: string[]) => void;
+}) => {
const config = MEDIA_FIELD_CONFIG[kind];
const uploadBoardId = useWorkflowProjectSelector((project) =>
typeof project.galleryValues.selectedBoardId === 'string' ? project.galleryValues.selectedBoardId : 'none'
);
- const mediaName =
- typeof (value as Record<string, unknown> | null | undefined)?.[config.nameKey] === 'string'
- ? ((value as Record<string, string>)[config.nameKey] ?? null)
- : null;
- const invalidAriaProps = useMemo(() => (invalid ? { 'aria-invalid': true } : {}), [invalid]);
-
- // dnd: the whole input row is a drop target for a single gallery item of the
- // matching kind. The instance-unique suffix keeps ids distinct when the node
- // editor and the Linear UI panel render the same field at once.
- const instanceId = useId();
- const dropId = getWorkflowMediaFieldDropId(`${id ?? 'field'}:${instanceId}`);
- const { active } = useDndContext();
- const acceptsActiveDrag = getWorkflowMediaFieldDropItem(active?.data.current, kind) !== null;
- const { isOver, setNodeRef } = useDroppable({ disabled: !acceptsActiveDrag, id: dropId });
- const onDragEnd = useCallback(
- (event: DragEndEvent) => {
- if (event.over?.id !== dropId) {
- return;
- }
-
- const item = getWorkflowMediaFieldDropItem(event.active.data.current, kind);
-
- if (item) {
- onChange({ [config.nameKey]: item.name });
- }
- },
- [config.nameKey, dropId, kind, onChange]
- );
-
- useDndMonitor({ onDragEnd });
-
- // Upload: file picker -> gallery upload -> adopt the uploaded item. The
- // adoption is pinned to this widget instance AND the project it started in:
- // `onChange` dispatches into the *active* project, so a completion arriving
- // after a project switch (or after this node was deleted, which unmounts the
- // widget) must not be applied - the upload itself still succeeded, so the
- // gallery is refreshed and the user is pointed there instead.
const { project } = useWorkflowUi();
const queryClient = useQueryClient();
const isMountedRef = useRef(true);
- useEffect(
- () => () => {
- isMountedRef.current = false;
- },
- []
- );
+ useMountEffect(() => () => {
+ isMountedRef.current = false;
+ });
const fileInputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);
const onUploadClick = useCallback(() => fileInputRef.current?.click(), []);
const onFileChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
+ const files = Array.from(event.currentTarget.files ?? []).slice(0, multiple ? undefined : 1);
// Reset so picking the same file again re-fires the change event.
event.currentTarget.value = '';
- if (!file) {
+ if (files.length === 0) {
return;
}
// `accept` on the input is advisory only ("All Files" bypasses it); an
// unknown type (empty string) is left for the server to judge.
- if (file.type && !file.type.startsWith(`${kind}/`)) {
- toaster.create({ title: `Please choose a ${config.noun} file`, type: 'error' });
+ if (files.some((file) => file.type && !file.type.startsWith(`${kind}/`))) {
+ toaster.create({
+ title: `Please choose ${multiple ? `${config.noun} files` : `a ${config.noun} file`}`,
+ type: 'error',
+ });
return;
}
@@ -624,37 +600,324 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr
setIsUploading(true);
void (async () => {
- try {
- const name =
- kind === 'image'
- ? (await galleryTransfers.upload(file, uploadBoardId, { signal: owner.signal })).imageName
- : (await galleryTransfers.uploadVideo(file, uploadBoardId, { signal: owner.signal })).name;
+ const names: string[] = [];
+ const failedFiles: string[] = [];
+
+ // Each file lands or fails on its own; what landed is adopted either way.
+ for (const file of files) {
+ try {
+ names.push(
+ kind === 'image'
+ ? (await galleryTransfers.upload(file, uploadBoardId, { signal: owner.signal })).imageName
+ : (await galleryTransfers.uploadVideo(file, uploadBoardId, { signal: owner.signal })).name
+ );
+ } catch {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ failedFiles.push(file.name);
+ }
+ }
- assertAccountScopeCurrent(owner);
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ if (names.length > 0) {
void invalidateGallery(queryClient, owner);
if (isMountedRef.current && project.getSnapshot().id === projectId) {
- onChange({ [config.nameKey]: name });
+ onUploaded(names);
} else {
toaster.create({
- description: `The workflow changed while ${name} uploaded - find it in the gallery.`,
+ description: `The workflow changed while ${names.join(', ')} uploaded - find it in the gallery.`,
title: 'Upload finished',
type: 'info',
});
}
- } catch {
- if (isAccountScopeCurrent(owner)) {
- toaster.create({ title: `Failed to upload ${config.noun}`, type: 'error' });
- }
- } finally {
- if (isAccountScopeCurrent(owner) && isMountedRef.current) {
- setIsUploading(false);
- }
+ }
+
+ if (failedFiles.length > 0) {
+ toaster.create({
+ description: failedFiles.join(', '),
+ title: `Failed to upload ${failedFiles.length === 1 ? config.noun : `${failedFiles.length} ${config.noun}s`}`,
+ type: 'error',
+ });
+ }
+
+ if (isMountedRef.current) {
+ setIsUploading(false);
}
})();
},
- [config.nameKey, config.noun, kind, onChange, project, queryClient, uploadBoardId]
+ [config.noun, kind, multiple, onUploaded, project, queryClient, uploadBoardId]
+ );
+
+ return { fileInputRef, isUploading, onFileChange, onUploadClick };
+};
+
+const getImageCollectionNames = (value: unknown): string[] =>
+ Array.isArray(value)
+ ? [
+ ...new Set(
+ value.flatMap((item) =>
+ typeof (item as Record<string, unknown> | null)?.image_name === 'string'
+ ? [(item as { image_name: string }).image_name]
+ : []
+ )
+ ),
+ ]
+ : [];
+
+const IMAGE_COLLECTION_REMOVE_PROPS = { opacity: 1 } as const;
+
+const ImageCollectionTile = ({
+ index,
+ name,
+ onRemove,
+}: {
+ index: number;
+ name: string;
+ onRemove: (index: number) => void;
+}) => {
+ const onRemoveClick = useCallback(() => onRemove(index), [index, onRemove]);
+
+ return (
+ <Box aspectRatio="1" bg="bg.subtle" className="group" position="relative" rounded="xs">
+ <Image
+ alt=""
+ h="full"
+ objectFit="cover"
+ rounded="xs"
+ src={MEDIA_FIELD_CONFIG.image.getThumbnailUrl(name)}
+ title={name}
+ w="full"
+ />
+ <IconButton
+ aria-label={`Remove ${name}`}
+ bg="bg.panel"
+ insetInlineEnd="0.5"
+ opacity={0}
+ position="absolute"
+ size="2xs"
+ top="0.5"
+ transition="opacity var(--wb-motion-duration-fast) ease"
+ variant="subtle"
+ _focusVisible={IMAGE_COLLECTION_REMOVE_PROPS}
+ _groupHover={IMAGE_COLLECTION_REMOVE_PROPS}
+ onClick={onRemoveClick}
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </Box>
+ );
+};
+
+/**
+ * Direct input for `ImageField` collections (Image Collection primitive, Image
+ * Batch): a thumbnail grid with per-item removal, a multi-select gallery
+ * picker, a multi-item gallery drop target, and multi-file upload.
+ */
+const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value }: WorkflowFieldInputProps) => {
+ const { t } = useTranslation();
+ const { project } = useWorkflowUi();
+ const names = useMemo(() => getImageCollectionNames(value), [value]);
+ const invalidAriaProps = useMemo(() => (invalid ? { 'aria-invalid': true } : {}), [invalid]);
+ // An upload finishing later appends to the field as it stands then, read from the document, not
+ // to the list this render saw.
+ const appendNames = useCallback(
+ (added: string[]) => {
+ const node = project.getSnapshot().projectGraph.nodes.find((candidate) => candidate.id === nodeId);
+ const current = getImageCollectionNames(
+ node && isInvocationNode(node) ? node.data.inputs[template.name]?.value : value
+ );
+ const next = [...current, ...added.filter((name) => !current.includes(name))];
+
+ if (next.length !== current.length) {
+ onChange(next.map((image_name) => ({ image_name })));
+ }
+ },
+ [nodeId, onChange, project, template.name, value]
+ );
+ const removeAt = useCallback(
+ (index: number) => onChange(names.filter((_, i) => i !== index).map((image_name) => ({ image_name }))),
+ [names, onChange]
+ );
+ const onClearClick = useCallback(() => onChange([]), [onChange]);
+
+ const instanceId = useId();
+ const dropId = getWorkflowMediaFieldDropId(`${id ?? 'field'}:${instanceId}`);
+ const { active } = useDndContext();
+ const acceptsActiveDrag = getWorkflowMediaFieldDropItems(active?.data.current, 'image').length > 0;
+ const { isOver, setNodeRef } = useDroppable({ disabled: !acceptsActiveDrag, id: dropId });
+ const onDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ if (event.over?.id === dropId) {
+ appendNames(getWorkflowMediaFieldDropItems(event.active.data.current, 'image').map((item) => item.name));
+ }
+ },
+ [appendNames, dropId]
+ );
+
+ useDndMonitor({ onDragEnd });
+
+ const { fileInputRef, isUploading, onFileChange, onUploadClick } = useMediaUpload({
+ kind: 'image',
+ multiple: true,
+ onUploaded: appendNames,
+ });
+ const pickerSelection = useMemo<GalleryPickerSelection>(
+ () => ({
+ addedKeys: new Set(names.map((name) => toGalleryItemKey({ kind: 'image', name }))),
+ mode: 'multiple',
+ remaining: {},
+ }),
+ [names]
+ );
+ const onPick = useCallback((item: GalleryItem) => appendNames([item.name]), [appendNames]);
+ const pickerLabel = t('widgets.gallery.picker.chooseImage');
+
+ return (
+ <Box position="relative" w="full" {...invalidAriaProps}>
+ <Box
+ ref={setNodeRef}
+ boxShadow={invalid ? '0 0 0 1px {colors.red.solid}' : undefined}
+ className="nodrag"
+ position="relative"
+ rounded="sm"
+ w="full"
+ >
+ {names.length > 0 ? (
+ <SimpleGrid
+ borderWidth="1px"
+ className="nowheel"
+ columns={3}
+ gap="1"
+ maxH="48"
+ overflowY="auto"
+ p="1"
+ rounded="sm"
+ >
+ {names.map((name, index) => (
+ <ImageCollectionTile key={name} index={index} name={name} onRemove={removeAt} />
+ ))}
+ </SimpleGrid>
+ ) : (
+ // The empty state keeps the drop target tall enough to hit and doubles as the picker trigger.
+ <GalleryPickerPopover accept={IMAGE_ONLY} label={pickerLabel} selection={pickerSelection} onPick={onPick}>
+ <chakra.button
+ aria-label={pickerLabel}
+ className="nodrag"
+ display="block"
+ h="20"
+ type="button"
+ w="full"
+ _focusVisible={MEDIA_INPUT_FOCUS_PROPS}
+ >
+ <Flex
+ alignItems="center"
+ borderStyle="dashed"
+ borderWidth="1px"
+ direction="column"
+ gap="1"
+ h="full"
+ justifyContent="center"
+ rounded="sm"
+ transition="border-color var(--wb-motion-duration-fast) ease"
+ w="full"
+ _hover={MEDIA_INPUT_HOVER_PROPS}
+ >
+ <Text as="span" color="fg" fontSize="xs" fontWeight="600">
+ {pickerLabel}
+ </Text>
+ <Text as="span" color="fg.subtle" fontSize="2xs">
+ {t('widgets.gallery.picker.dropHint')}
+ </Text>
+ </Flex>
+ </chakra.button>
+ </GalleryPickerPopover>
+ )}
+ <DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label="Drop images" />
+ </Box>
+ <HStack gap="1.5" mt="1" w="full">
+ <GalleryPickerPopover accept={IMAGE_ONLY} label={pickerLabel} selection={pickerSelection} onPick={onPick}>
+ <Button className="nodrag" size="2xs" variant="outline">
+ <Icon as={ImagePlusIcon} boxSize="3" />
+ {t('common.add')}
+ </Button>
+ </GalleryPickerPopover>
+ <Button className="nodrag" disabled={isUploading} size="2xs" variant="outline" onClick={onUploadClick}>
+ {isUploading ? 'Uploading…' : 'Upload'}
+ </Button>
+ {names.length > 0 ? (
+ <Button className="nodrag" size="2xs" variant="ghost" onClick={onClearClick}>
+ Clear
+ </Button>
+ ) : null}
+ {names.length > 0 ? (
+ <Text color="fg.subtle" fontSize="2xs" ms="auto">
+ {t('nodes.imageCollectionCount', { count: names.length })}
+ </Text>
+ ) : null}
+ <input
+ ref={fileInputRef}
+ accept={MEDIA_FIELD_CONFIG.image.fileAccept}
+ aria-label="Upload image files"
+ multiple
+ style={HIDDEN_FILE_INPUT_STYLE}
+ type="file"
+ onChange={onFileChange}
+ />
+ </HStack>
+ </Box>
+ );
+};
+
+/**
+ * Direct input for `ImageField` / `VideoField`: shows the current item with a
+ * thumbnail, opens the gallery picker, accepts a single-item gallery drag
+ * onto the row, and uploads a local file to the gallery's selected board.
+ */
+const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputProps & { kind: WorkflowMediaKind }) => {
+ const { t } = useTranslation();
+ const config = MEDIA_FIELD_CONFIG[kind];
+ const mediaName =
+ typeof (value as Record<string, unknown> | null | undefined)?.[config.nameKey] === 'string'
+ ? ((value as Record<string, string>)[config.nameKey] ?? null)
+ : null;
+ const invalidAriaProps = useMemo(() => (invalid ? { 'aria-invalid': true } : {}), [invalid]);
+
+ // dnd: the whole input row is a drop target for a single gallery item of the
+ // matching kind. The instance-unique suffix keeps ids distinct when the node
+ // editor and the Linear UI panel render the same field at once.
+ const instanceId = useId();
+ const dropId = getWorkflowMediaFieldDropId(`${id ?? 'field'}:${instanceId}`);
+ const { active } = useDndContext();
+ const acceptsActiveDrag = getWorkflowMediaFieldDropItem(active?.data.current, kind) !== null;
+ const { isOver, setNodeRef } = useDroppable({ disabled: !acceptsActiveDrag, id: dropId });
+ const onDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ if (event.over?.id !== dropId) {
+ return;
+ }
+
+ const item = getWorkflowMediaFieldDropItem(event.active.data.current, kind);
+
+ if (item) {
+ onChange({ [config.nameKey]: item.name });
+ }
+ },
+ [config.nameKey, dropId, kind, onChange]
+ );
+
+ useDndMonitor({ onDragEnd });
+
+ const onUploaded = useCallback(
+ (names: string[]) => onChange({ [config.nameKey]: names[0] }),
+ [config.nameKey, onChange]
);
+ const { fileInputRef, isUploading, onFileChange, onUploadClick } = useMediaUpload({ kind, onUploaded });
const onPick = useCallback(
(item: GalleryItem) => onChange({ [config.nameKey]: item.name }),
@@ -1221,15 +1484,11 @@ const CONNECTION_ONLY_FALLBACK = (
);
export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
- // COLLECTION media fields (e.g. Concatenate Videos' list input) hold arrays;
- // the single-value media widget would write a bare object into them. The
- // node editor never shows a control for COLLECTION fields, but linear-form
- // elements migrated from legacy `exposedFields` can reach here directly.
- if (
- (props.template.type.name === 'ImageField' || props.template.type.name === 'VideoField') &&
- props.template.type.cardinality === 'COLLECTION'
- ) {
- return CONNECTION_ONLY_FALLBACK;
+ // COLLECTION fields hold arrays; only image lists have a list widget. Other
+ // collections stay connection-only even when a migrated linear-form element
+ // points at them, since the single-value widget would write a bare value.
+ if (props.template.type.cardinality === 'COLLECTION') {
+ return props.template.type.name === 'ImageField' ? <ImageCollectionInput {...props} /> : CONNECTION_ONLY_FALLBACK;
}
switch (props.template.type.name) {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts
index b594f1b117..a91ceca378 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { getWorkflowMediaFieldDropId, getWorkflowMediaFieldDropItem } from './mediaFieldDnd';
+import {
+ getWorkflowMediaFieldDropId,
+ getWorkflowMediaFieldDropItem,
+ getWorkflowMediaFieldDropItems,
+} from './mediaFieldDnd';
const drag = (items: { kind: string; name: string }[]) => ({ items, kind: 'gallery-item' });
@@ -45,3 +49,33 @@ describe('getWorkflowMediaFieldDropId', () => {
expect(getWorkflowMediaFieldDropId('node-1-video:r1')).toBe('workflow-media-field:node-1-video:r1');
});
});
+
+describe('getWorkflowMediaFieldDropItems', () => {
+ it('returns every dragged item of the kind, in drag order', () => {
+ expect(
+ getWorkflowMediaFieldDropItems(
+ drag([
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ ]),
+ 'image'
+ )
+ ).toEqual([
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ ]);
+ });
+
+ it('rejects mixed-kind drags and non-gallery payloads', () => {
+ expect(
+ getWorkflowMediaFieldDropItems(
+ drag([
+ { kind: 'image', name: 'a.png' },
+ { kind: 'video', name: 'b.mp4' },
+ ]),
+ 'image'
+ )
+ ).toEqual([]);
+ expect(getWorkflowMediaFieldDropItems({ kind: 'gallery-board' }, 'image')).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts
index d7e97f602e..5f001589cd 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts
@@ -14,6 +14,15 @@ export interface WorkflowMediaDropItem {
export const getWorkflowMediaFieldDropId = (fieldKey: string): string => `workflow-media-field:${fieldKey}`;
+/** Every dragged gallery item of `kind`; empty when the drag carries anything else. */
+export const getWorkflowMediaFieldDropItems = (
+ activeData: unknown,
+ kind: WorkflowMediaKind
+): WorkflowMediaDropItem[] =>
+ isGalleryItemDragData(activeData) && activeData.items.every((item) => item.kind === kind)
+ ? activeData.items.map((item) => ({ kind, name: item.name }))
+ : [];
+
/**
* Resolves a gallery drag payload to the single item a media field can accept,
* or null. Multi-item drags are rejected outright: a single-value field
@@ -24,11 +33,7 @@ export const getWorkflowMediaFieldDropItem = (
activeData: unknown,
kind: WorkflowMediaKind
): WorkflowMediaDropItem | null => {
- if (!isGalleryItemDragData(activeData) || activeData.items.length !== 1) {
- return null;
- }
-
- const item = activeData.items[0];
+ const items = getWorkflowMediaFieldDropItems(activeData, kind);
- return item && item.kind === kind ? { kind: item.kind, name: item.name } : null;
+ return items.length === 1 ? (items[0] ?? null) : null;
};