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.

refactor(gallery): build the video clip field on the media slot

Josh Corbette6c60c6a58f7
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 0825a3fffc..7c4bc37cdf 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3715,7 +3715,6 @@
"unsupportedImage": "Images can't be used here",
"unsupportedVideo": "Videos can't be used here",
"upload": "Upload",
- "uploadFailed": "The upload didn't go through. Check the notifications for details.",
"windowLimit": "Showing the first {{count}} items. Narrow the search to reach the rest.",
"working": "Working…"
},
@@ -3853,7 +3852,6 @@
"lastFrameHelp": "Optional: the video ends on this image (interpolates from the first frame).",
"pauseSelection": "Pause selection in Preview",
"playSelection": "Play selection in Preview",
- "removeClip": "Remove video",
"sampleLength": "Sample Length (Frames)",
"sampleLengthWithSeconds": "Sample Length · {{seconds}}s",
"trim": "Trim",
@@ -3862,9 +3860,7 @@
"trimHelp": "The kept range of the source clip. The extension continues from the end frame.",
"trimStart": "Start Frame",
"trimStartShort": "Start",
- "unsupportedVideoFile": "Please choose a video file.",
"uploadImageReference": "Upload image",
- "uploadingClip": "Uploading video…",
"clearStaleMedia": "Clear",
"staleFirstFrame": "A first frame is set, but this model does not support starting from one.",
"staleLastFrame": "A last frame is set, but this model does not support ending on one.",
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 6e4d241793..6bde943ee8 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
@@ -159,14 +159,7 @@ const renderSlot = async (props: Partial<Parameters<typeof GalleryMediaSlot>[0]>
testId="multi-thumb"
/>
<div data-testid="slot" style={{ left: 200, position: 'fixed', top: 200, width: 320 }}>
- <GalleryMediaSlot
- accept={['image']}
- dropId="test-slot"
- uploadBoardId="none"
- value={null}
- onChange={onChange}
- {...props}
- />
+ <GalleryMediaSlot accept={['image']} dropId="test-slot" value={null} onChange={onChange} {...props} />
</div>
</DndContext>
</GalleryUiProvider>
@@ -284,44 +277,21 @@ describe('GalleryMediaSlot', () => {
expect(onChange).not.toHaveBeenCalled();
});
- it('uploads into the given board and adopts the result', async () => {
- mocks.uploadGalleryImage.mockResolvedValue({
- boardId: 'none',
- createdAt: '2026-09-09T00:00:00.000Z',
- height: 96,
- imageCategory: 'user',
- imageName: 'fresh.png',
- imageUrl: '/full/fresh.png',
- queuedAt: '2026-09-09T00:00:00.000Z',
- sourceQueueItemId: 'queue-1',
- starred: false,
- thumbnailUrl: '/thumb/fresh.png',
- width: 128,
- });
+ it('offers no file action of its own — the picker carries the gallery upload', async () => {
await renderSlot();
- expect(host?.querySelector<HTMLInputElement>('input[type="file"]')?.multiple).toBe(false);
- await changeFile(new File(['image'], 'fresh.png', { type: 'image/png' }));
-
- expect(mocks.uploadGalleryImage).toHaveBeenCalledExactlyOnceWith(expect.any(File), 'none', expect.anything());
- expect(onChange).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'image', name: 'fresh.png' }));
- expect(alertText()).toBeNull();
+ expect(actionButton('widgets.gallery.picker.upload')).toBeUndefined();
+ expect(host?.querySelector('input[type="file"]')).toBeNull();
});
- it('refuses a file of a kind the slot cannot take and reports an upload that yields nothing', async () => {
- mocks.uploadGalleryImage.mockRejectedValue(new Error('storage offline'));
- await renderSlot();
+ it('refuses a file of a kind the consumer-owned upload cannot take', async () => {
+ const onUploadFile = vi.fn();
+ await renderSlot({ onUploadFile });
await changeFile(new File(['video'], 'clip.mp4', { type: 'video/mp4' }));
- expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
+ expect(onUploadFile).not.toHaveBeenCalled();
expect(alertText()).toBe('widgets.gallery.picker.unsupportedVideo');
-
- await changeFile(new File(['image'], 'photo.png', { type: 'image/png' }));
-
- expect(mocks.uploadGalleryImage).toHaveBeenCalledOnce();
- expect(onChange).not.toHaveBeenCalled();
- 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 () => {
@@ -337,7 +307,6 @@ describe('GalleryMediaSlot', () => {
await changeFile(file);
expect(onUploadFile).toHaveBeenCalledExactlyOnceWith(file);
- expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
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 ec05d24ecb..13896b7c1a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
@@ -5,12 +5,10 @@ import { Box, HStack, Icon, Image, Spinner, Stack, Text } from '@chakra-ui/react
import { useDndMonitor } from '@dnd-kit/core';
import { classifyGalleryUpload, getGalleryItemByRef } from '@features/gallery/data/backend';
import { getGalleryImageThumbnailUrl } from '@features/gallery/data/imageUrls';
-import { galleryBoardsOptions } from '@features/gallery/data/queries';
import { getGalleryVideoThumbnailUrl } from '@features/gallery/data/videoUrls';
import { FindInGalleryThumbnailButton } from '@features/gallery/ui/FindInGalleryButton';
import { isGalleryItemDragData, useGalleryItemDroppable } from '@features/gallery/ui/galleryDnd';
import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';
-import { useGalleryUploadAction } from '@features/gallery/ui/useGalleryUploadAction';
import { getGalleryUploadAccept, useGalleryUploadInput } from '@features/gallery/ui/useGalleryUploadInput';
import {
assertAccountScopeCurrent,
@@ -21,7 +19,6 @@ import { Button } from '@platform/ui/Button';
import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';
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, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,7 +27,6 @@ import type { GalleryPickerAccept } from './galleryPicker';
import { GalleryPickerPopover } from './GalleryPickerPopover';
-const EMPTY_BOARDS: never[] = [];
const DROP_ZONE_FOCUS_PROPS = {
outlineColor: 'accent.focusRing',
outlineOffset: '2px',
@@ -70,12 +66,13 @@ const getThumbnailUrl = (value: GalleryMediaSlotValue): string =>
value.kind === 'video' ? getGalleryVideoThumbnailUrl(value.name) : getGalleryImageThumbnailUrl(value.name);
/**
- * 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). 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.
+ * A single-item media field: click opens the gallery picker (which carries the
+ * gallery upload), and a gallery drag can be dropped on it. Owns the async
+ * resolve work and its busy and error states; the consumer only sees
+ * `onChange` with a full item (or null when cleared). A consumer that stores
+ * the file itself — media the gallery does not hold — takes it through
+ * `onUploadFile`, which adds a file action to the row, and can show its own
+ * `thumbnail` for such a value.
*/
export const GalleryMediaSlot = ({
accept,
@@ -84,7 +81,6 @@ export const GalleryMediaSlot = ({
dropId,
labels: labelOverrides,
thumbnail,
- uploadBoardId = 'none',
value,
onChange,
onFind,
@@ -99,8 +95,6 @@ export const GalleryMediaSlot = ({
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);
value: GalleryMediaSlotValue | null;
onChange: (item: GalleryItem | null) => void;
/**
@@ -109,12 +103,11 @@ export const GalleryMediaSlot = ({
* media the gallery does not own has nothing to reveal.
*/
onFind?: () => void;
- /** Takes an uploaded file directly instead of sending it to the gallery. */
+ /** Takes a file the consumer stores itself; gallery-backed slots upload through the picker instead. */
onUploadFile?: (file: File) => void;
}) => {
const { t } = useTranslation();
const { notifications } = useGalleryUi();
- const { data: boards } = useQuery(galleryBoardsOptions());
const [isBusy, setIsBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const isInert = disabled || isBusy;
@@ -185,7 +178,6 @@ export const GalleryMediaSlot = ({
useDndMonitor({ onDragEnd: handleDragEnd });
- const uploadFiles = useGalleryUploadAction({ boards: boards ?? EMPTY_BOARDS, selectedBoardId: uploadBoardId });
const uploadOptions = useMemo(() => ({ accept: getGalleryUploadAccept(accept), multiple: false }), [accept]);
const handleUpload = useCallback(
([file]: File[]) => {
@@ -194,32 +186,17 @@ export const GalleryMediaSlot = ({
setErrorMessage(null);
// The input's `accept` is advisory ("All files" bypasses it); a kind the
- // slot cannot take must not be uploaded only to be dropped on the floor.
+ // slot cannot take must not be handed on only to be dropped on the floor.
if (!file || (kind && !accept.includes(kind))) {
setErrorMessage(
t(kind === 'video' ? 'widgets.gallery.picker.unsupportedVideo' : 'widgets.gallery.picker.unsupportedImage')
);
return;
}
- if (onUploadFile) {
- onUploadFile(file);
- return;
- }
-
- setIsBusy(true);
- void uploadFiles([file])
- .then((uploaded) => {
- const item = uploaded.find((candidate) => accept.includes(candidate.kind));
- if (item) {
- onChange(item);
- } else {
- setErrorMessage(t('widgets.gallery.picker.uploadFailed'));
- }
- })
- .finally(() => setIsBusy(false));
+ onUploadFile?.(file);
},
- [accept, onChange, onUploadFile, t, uploadFiles]
+ [accept, onUploadFile, t]
);
const { inputProps: uploadInputProps, openPicker: openUploadPicker } = useGalleryUploadInput(
handleUpload,
@@ -327,26 +304,28 @@ export const GalleryMediaSlot = ({
) : null}
<DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={labels.drop} />
</Box>
- <HStack justify="end">
- {disabled ? null : (
- <Button disabled={isBusy} size="xs" variant="ghost" onClick={openUploadPicker}>
- <Icon as={UploadIcon} boxSize="3" />
- {t('widgets.gallery.picker.upload')}
- </Button>
- )}
- {value ? (
- <Button disabled={isBusy} size="xs" variant="ghost" onClick={handleClear}>
- <Icon as={XIcon} boxSize="3" />
- {labels.remove}
- </Button>
- ) : null}
- </HStack>
+ {(onUploadFile && !disabled) || value ? (
+ <HStack justify="end">
+ {onUploadFile && !disabled ? (
+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={openUploadPicker}>
+ <Icon as={UploadIcon} boxSize="3" />
+ {t('widgets.gallery.picker.upload')}
+ </Button>
+ ) : null}
+ {value ? (
+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={handleClear}>
+ <Icon as={XIcon} boxSize="3" />
+ {labels.remove}
+ </Button>
+ ) : null}
+ </HStack>
+ ) : null}
{errorMessage ? (
<Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">
{errorMessage}
</Text>
) : null}
- <input {...uploadInputProps} />
+ {onUploadFile ? <input {...uploadInputProps} /> : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
index 57b3928d1f..f8c9366073 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
@@ -8,11 +8,10 @@ import type {
GenerateSettings,
} from '@features/generation/core/types';
import type { GenerateSettingsUpdate } from '@features/generation/ui/generateDebounce';
-import type { ChangeEvent } from 'react';
-import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { HStack, Icon, Stack, Text } from '@chakra-ui/react';
import { useDndMonitor } from '@dnd-kit/core';
-import { galleryImages, galleryTransfers, toGalleryItemKey } from '@features/gallery';
+import { galleryImages, toGalleryItemKey } from '@features/gallery';
import { GalleryPickerPopover } from '@features/gallery/picker';
import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';
import {
@@ -25,14 +24,9 @@ import {
import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@features/generation/core/referenceImage';
import { clampDimension, deriveAspectRatioId, moveReferenceImage } from '@features/generation/core/settings';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
import { Button, DropTargetOverlay, DropZone } from '@platform/ui';
-import { ChevronDownIcon, ImagePlusIcon, UploadIcon } from 'lucide-react';
-import { useCallback, useMemo, useRef } from 'react';
+import { ChevronDownIcon, ImagePlusIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ReferenceImageCard } from './ReferenceImageCard';
@@ -60,8 +54,7 @@ export const GenerateReferenceImagesContent = ({
settings,
}: GenerateReferenceImagesContentProps) => {
const { t } = useTranslation();
- const { gallery, notifications } = useGenerationUi();
- const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const { gallery } = useGenerationUi();
const referenceImages = settings.referenceImages;
const isSupported = isReferenceImageSupported(selectedModel);
const maxReferenceImages = getMaxReferenceImages(selectedModel);
@@ -191,53 +184,6 @@ export const GenerateReferenceImagesContent = ({
[onCommitImmediate, selectedModel]
);
- const uploadFiles = useCallback(
- async (files: File[]) => {
- if (!canAdd || files.length === 0) {
- return;
- }
-
- const owner = captureAccountScope();
-
- try {
- const uploaded = await Promise.all(
- files
- .slice(0, maxReferenceImages - referenceImageCount)
- .map((file) => galleryTransfers.upload(file, 'none', { signal: owner.signal }))
- );
-
- assertAccountScopeCurrent(owner);
- appendReferenceImages(uploaded.map(generatedImageToReferenceImage));
- gallery.touchImages();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notifications.reportError({
- area: 'reference-images',
- message: error instanceof Error ? error.message : String(error),
- namespace: 'generation',
- });
- }
- },
- [appendReferenceImages, canAdd, gallery, maxReferenceImages, notifications, referenceImageCount]
- );
-
- const handleUploadZoneClick = useCallback(() => {
- if (canAdd) {
- fileInputRef.current?.click();
- }
- }, [canAdd]);
-
- const handleFileInputChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- void uploadFiles(Array.from(event.currentTarget.files ?? []));
- event.currentTarget.value = '';
- },
- [uploadFiles]
- );
-
const addGalleryImages = async (imageNames: string[]) => {
if (!canAdd || imageNames.length === 0) {
return;
@@ -323,12 +269,6 @@ export const GenerateReferenceImagesContent = ({
</Text>
</DropZone>
</GalleryPickerPopover>
- <HStack justify="end">
- <Button disabled={!canAdd} size="xs" variant="ghost" onClick={handleUploadZoneClick}>
- <Icon as={UploadIcon} boxSize="3" />
- {t('widgets.gallery.picker.upload')}
- </Button>
- </HStack>
{referenceImageCount > 0 ? (
<Stack gap="2">
@@ -348,8 +288,6 @@ export const GenerateReferenceImagesContent = ({
))}
</Stack>
) : null}
-
- <Input ref={fileInputRef} accept="image/*" display="none" multiple type="file" onChange={handleFileInputChange} />
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx
index 7fb9d2d45b..8b26124c90 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleImageField.tsx
@@ -32,9 +32,7 @@ export const UpscaleImageField = memo(
[onChange]
);
- return (
- <GalleryMediaSlot accept={ACCEPT} dropId={DROP_ID} uploadBoardId="none" value={value} onChange={handleChange} />
- );
+ return <GalleryMediaSlot accept={ACCEPT} dropId={DROP_ID} value={value} onChange={handleChange} />;
},
(previous, next) =>
previous.onChange === next.onChange && areInputImagesEquivalent(previous.inputImage, next.inputImage)
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
index 1eb467fb42..c124ff20b8 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
@@ -32,7 +32,7 @@ export const VideoFrameImageField = memo(
image: ImageWithDims | null;
onChange: (image: ImageWithDims | null) => void;
}) {
- const { findInGallery, getUploadBoardId } = useVideoUiActions();
+ const { findInGallery } = useVideoUiActions();
const value = useMemo<GalleryMediaSlotValue | null>(
() => (image ? { height: image.height, kind: 'image', name: image.image_name, width: image.width } : null),
[image]
@@ -57,7 +57,6 @@ export const VideoFrameImageField = memo(
disabledReason={disabledReason}
dropId={dropId}
labels={labels}
- uploadBoardId={getUploadBoardId}
value={value}
onChange={handleChange}
onFind={handleFind}
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
index 34de095a17..bd643d0d94 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
@@ -1,26 +1,13 @@
-import type { DragEndEvent } from '@dnd-kit/core';
+import type { GalleryItem } from '@features/gallery';
import type { VideoSourceClip } from '@features/video/core/types';
-import type { ChangeEvent } from 'react';
-import { HStack, Icon, Input, Spinner, Stack, Text } from '@chakra-ui/react';
-import { useDndContext, useDndMonitor, useDroppable } from '@dnd-kit/core';
-import { galleryItems, galleryTransfers, type GalleryItem } from '@features/gallery';
-import { GalleryPickerPopover } from '@features/gallery/picker';
-import { galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';
+import { HStack, Stack, Text } from '@chakra-ui/react';
+import { GalleryMediaSlot, type GalleryMediaSlotLabels, type GalleryMediaSlotValue } from '@features/gallery/mediaSlot';
+import { galleryVideoUrls } from '@features/gallery/utility';
import { createVideoSourceClip } from '@features/video/core/settings';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
import { Field } from '@platform/ui';
-import { Button } from '@platform/ui/Button';
-import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';
-import { DropZone } from '@platform/ui/DropZone';
-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { ScrubberField } from '@platform/ui/ScrubberField';
-import { ChevronDownIcon, FilmIcon, UploadIcon, XIcon } from 'lucide-react';
-import { memo, useCallback, useRef, useState } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { PlayClipSpanButton } from './PlayClipSpanButton';
@@ -28,32 +15,13 @@ import { TrimBoundThumb } from './TrimBoundThumb';
import { useVideoUiActions } from './VideoUiContext';
/**
- * The clip to extend: gallery drop target, file upload, and the trim bounds —
- * one compact row per bound, the bound's live frame at left and its slider at
- * right (see TrimBoundThumb for the seek technique). The rows are the only
- * preview; the drop zone itself is a slim header with the clip's identity.
+ * The clip to extend: the shared media slot (picker, gallery drop, upload) and
+ * the trim bounds — one compact row per bound, the bound's live frame at left
+ * and its slider at right (see TrimBoundThumb for the seek technique).
*/
const DROP_ID = 'video-source-clip';
const VIDEO_ONLY = ['video'] as const;
-const DROP_ZONE_FOCUS_PROPS = {
- outlineColor: 'accent.focusRing',
- outlineOffset: '2px',
- outlineStyle: 'solid',
- outlineWidth: '2px',
-};
-const DROP_ZONE_DISABLED_PROPS = { cursor: 'not-allowed', opacity: 0.6 };
-const DROP_ZONE_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };
-
-const getSingleVideoDragName = (data: unknown): string | null => {
- if (!isGalleryItemDragData(data) || data.items.length !== 1) {
- return null;
- }
-
- const item = data.items[0];
-
- return item?.kind === 'video' ? item.name : null;
-};
const areSourceClipsEquivalent = (left: VideoSourceClip | null, right: VideoSourceClip | null): boolean =>
(left === null && right === null) ||
@@ -78,123 +46,23 @@ export const VideoSourceClipField = memo(
sourceVideo: VideoSourceClip | null;
}) {
const { t } = useTranslation();
- const { findInGallery, getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();
- const fileInputRef = useRef<HTMLInputElement | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [errorMessage, setErrorMessage] = useState<string | null>(null);
- const isInert = disabled || isLoading;
-
- const { active } = useDndContext();
- const acceptsActiveDrag = !isInert && getSingleVideoDragName(active?.data.current) !== null;
- const { isOver, setNodeRef } = useDroppable({ disabled: !acceptsActiveDrag, id: DROP_ID });
-
- const adoptVideo = useCallback(
- async (videoName: string) => {
- setErrorMessage(null);
- setIsLoading(true);
-
- try {
- const item = await galleryItems.resolve({ kind: 'video', name: videoName });
-
- if (item?.kind === 'video') {
- onChange(
- createVideoSourceClip({
- durationSeconds: item.durationSeconds,
- fps: item.fps,
- height: item.height,
- name: item.name,
- width: item.width,
- })
- );
- }
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- setErrorMessage(message);
- reportError(message);
- } finally {
- setIsLoading(false);
- }
- },
- [onChange, reportError]
- );
-
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- const videoName = getSingleVideoDragName(event.active.data.current);
-
- if (!isInert && event.over?.id === DROP_ID && videoName) {
- void adoptVideo(videoName);
- }
- },
- [adoptVideo, isInert]
- );
-
- useDndMonitor({ onDragEnd: handleDragEnd });
-
- const uploadFile = useCallback(
- async (file: File) => {
- setErrorMessage(null);
-
- // `accept` is advisory; an unknown type (empty string) is the server's call.
- if (file.type && !file.type.startsWith('video/')) {
- setErrorMessage(t('widgets.video.unsupportedVideoFile'));
- reportError(t('widgets.video.unsupportedVideoFile'));
- return;
- }
-
- const owner = captureAccountScope();
- setIsLoading(true);
-
- try {
- const uploaded = await galleryTransfers.uploadVideo(file, getUploadBoardId(), { signal: owner.signal });
-
- assertAccountScopeCurrent(owner);
- onChange(
- createVideoSourceClip({
- durationSeconds: uploaded.durationSeconds,
- fps: uploaded.fps,
- height: uploaded.height,
- name: uploaded.name,
- width: uploaded.width,
- })
- );
- touchGalleryImages();
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- const message = error instanceof Error ? error.message : String(error);
- setErrorMessage(message);
- reportError(message);
- } finally {
- setIsLoading(false);
- }
- },
- [getUploadBoardId, onChange, reportError, t, touchGalleryImages]
+ const { findInGallery } = useVideoUiActions();
+ const slotLabels = useMemo<Partial<GalleryMediaSlotLabels>>(
+ () => ({ drop: t('widgets.video.dropInitialVideo') }),
+ [t]
);
-
- const handleFileChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
-
- if (file) {
- void uploadFile(file);
- }
- event.currentTarget.value = '';
- },
- [uploadFile]
+ const slotValue = useMemo<GalleryMediaSlotValue | null>(
+ () =>
+ sourceVideo
+ ? { height: sourceVideo.height, kind: 'video', name: sourceVideo.video_name, width: sourceVideo.width }
+ : null,
+ [sourceVideo]
);
- const handlePickFile = useCallback(() => {
- if (!isInert) {
- fileInputRef.current?.click();
- }
- }, [isInert]);
- const handleClear = useCallback(() => onChange(null), [onChange]);
- const handlePick = useCallback(
- (item: GalleryItem) => {
- if (item.kind === 'video') {
- setErrorMessage(null);
+ const handleSlotChange = useCallback(
+ (item: GalleryItem | null) => {
+ if (item === null) {
+ onChange(null);
+ } else if (item.kind === 'video') {
onChange(createVideoSourceClip(item));
}
},
@@ -242,74 +110,15 @@ export const VideoSourceClipField = memo(
return (
<Stack gap="2">
- <GalleryPickerPopover
+ <GalleryMediaSlot
accept={VIDEO_ONLY}
- label={t(sourceVideo ? 'widgets.gallery.picker.replaceVideo' : 'widgets.gallery.picker.chooseVideo')}
- onPick={handlePick}
- >
- <DropZone
- ref={setNodeRef}
- as="button"
- aria-busy={isLoading}
- aria-disabled={disabled}
- aria-label={t(sourceVideo ? 'widgets.gallery.picker.replaceVideo' : 'widgets.gallery.picker.chooseVideo')}
- cursor={disabled ? 'not-allowed' : undefined}
- disabled={isInert}
- isDisabled={isInert}
- isOver={isOver}
- minH="24"
- overflow="hidden"
- position="relative"
- textAlign="start"
- w="full"
- _focusVisible={DROP_ZONE_FOCUS_PROPS}
- _disabled={DROP_ZONE_DISABLED_PROPS}
- _hover={isInert ? undefined : DROP_ZONE_HOVER_PROPS}
- opacity={disabled ? 0.6 : undefined}
- >
- {sourceVideo && previewSrc ? (
- <HStack gap="2" minW="0" p="2">
- <FilmIcon aria-hidden="true" size={14} />
- <MiddleTruncate color="fg" flex="1" fontSize="xs" fontWeight="semibold" text={sourceVideo.video_name} />
- <Text color="fg.muted" flexShrink="0" fontSize="2xs" fontVariantNumeric="tabular-nums">
- {sourceVideo.width} × {sourceVideo.height} · {sourceVideo.fps} fps
- </Text>
- </HStack>
- ) : (
- <Stack align="center" color="fg.muted" gap="1.5" justify="center" minH="24" px="4">
- {isLoading ? (
- <Spinner size="sm" />
- ) : (
- <HStack color="fg" fontSize="xs" fontWeight="600" gap="1.5">
- <Icon as={FilmIcon} boxSize="4" />
- {t('widgets.gallery.picker.chooseVideo')}
- <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />
- </HStack>
- )}
- <Text color="fg.subtle" fontSize="2xs" textAlign="center">
- {disabled && disabledReason
- ? disabledReason
- : isLoading
- ? t('widgets.video.uploadingClip')
- : t('widgets.gallery.picker.dropHint')}
- </Text>
- </Stack>
- )}
- <DropTargetOverlay
- isActive={acceptsActiveDrag}
- isOver={isOver}
- label={t('widgets.video.dropInitialVideo')}
- />
- </DropZone>
- </GalleryPickerPopover>
- {disabled ? null : (
- <HStack justify="end">
- <Button disabled={isLoading} size="xs" variant="ghost" onClick={handlePickFile}>
- <Icon as={UploadIcon} boxSize="3" />
- {t('widgets.gallery.picker.upload')}
- </Button>
- </HStack>
- )}
+ disabled={disabled}
+ disabledReason={disabledReason}
+ dropId={DROP_ID}
+ labels={slotLabels}
+ value={slotValue}
+ onChange={handleSlotChange}
+ />
{sourceVideo && previewSrc ? (
<Stack gap="2">
{/* The empty-state slot shows the reason when no clip is set; with
@@ -364,28 +173,8 @@ export const VideoSourceClipField = memo(
</Stack>
</HStack>
</Field>
- <HStack justify="end">
- <Button disabled={isLoading} size="xs" variant="ghost" onClick={handleClear}>
- <XIcon aria-hidden="true" size="12" />
- {t('widgets.video.removeClip')}
- </Button>
- </HStack>
</Stack>
) : null}
- {errorMessage ? (
- <Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">
- {errorMessage}
- </Text>
- ) : null}
- <Input
- ref={fileInputRef}
- accept="video/*"
- aria-hidden="true"
- display="none"
- tabIndex={-1}
- type="file"
- onChange={handleFileChange}
- />
</Stack>
);
},
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx
index eb7d49aa07..6a9cfefbbd 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx
@@ -45,7 +45,6 @@ await i18n.use(initReactI18next).init({
},
video: {
playSelection: 'Play selection in Preview',
- removeClip: 'Remove clip',
trim: 'Trim',
trimEnd: 'Trim end',
trimEndShort: 'End',
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx
index 6994f8a4f2..bf91ce3465 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx
@@ -1,8 +1,10 @@
import type { GalleryVideoItem } from '@features/gallery';
+import type { GalleryUiAdapter } from '@features/gallery/react';
import type { VideoReferenceItem, VideoSourceClip } from '@features/video/core/types';
import { ChakraProvider } from '@chakra-ui/react';
import { DndContext } from '@dnd-kit/core';
+import { GalleryUiProvider } from '@features/gallery/react';
import { system } from '@theme/system';
import i18next from 'i18next';
import { act, useCallback, useEffect, useState, type ReactNode } from 'react';
@@ -52,7 +54,6 @@ await i18n.use(initReactI18next).init({
referencesHelp: 'help',
removeReference: 'Remove reference',
sampleLength: 'Sample Length',
- removeClip: 'Remove video',
trim: 'Trim',
trimEnd: 'End Frame',
trimEndShort: 'End',
@@ -188,14 +189,25 @@ const RetrimmableHarness = () => {
);
};
+// The source clip field is built on the gallery media slot, which reads the
+// gallery UI port for its picker and error reporting.
+const galleryAdapter = {
+ gallery: { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() },
+ galleryValues: {},
+ notifications: { add: vi.fn(), reportError: vi.fn() },
+ widgets: { openGallery: () => true, patchGalleryValues: vi.fn() },
+} as unknown as GalleryUiAdapter;
+
const renderTree = async (element: ReactNode): Promise<void> => {
await act(() =>
root.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <DndContext>
- <VideoUiProvider adapter={adapter}>{element}</VideoUiProvider>
- </DndContext>
+ <GalleryUiProvider adapter={galleryAdapter}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>{element}</VideoUiProvider>
+ </DndContext>
+ </GalleryUiProvider>
</ChakraProvider>
</I18nextProvider>
)