Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(image): support drag-and-drop reference image upload (#16207)

YuTengjing66e0b3c46a74
diff --git a/locales/en-US/image.json b/locales/en-US/image.json
index 4c1106f4efe..dc5873073d7 100644
--- a/locales/en-US/image.json
+++ b/locales/en-US/image.json
@@ -7,6 +7,7 @@
"config.header.title": "Image",
"config.height.label": "Height",
"config.imageNum.label": "Number of Images",
+ "config.imageUpload.maxCountReached": "You can add up to {{count}} reference images",
"config.imageUrl.label": "Reference Image",
"config.imageUrls.label": "Reference Images",
"config.model.label": "Model",
diff --git a/locales/en-US/video.json b/locales/en-US/video.json
index 933e2ba2d06..dedab7d54b6 100644
--- a/locales/en-US/video.json
+++ b/locales/en-US/video.json
@@ -5,6 +5,7 @@
"config.endImageUrl.label": "End Frame",
"config.generateAudio.label": "Generate Audio",
"config.header.title": "Video",
+ "config.imageUpload.maxCountReached": "You can add up to {{count}} reference images",
"config.imageUrl.label": "Start Frame",
"config.prompt.placeholder": "Describe the video you want to generate",
"config.prompt.placeholderWithRef": "Describe the scene you want to generate with the image",
diff --git a/locales/zh-CN/image.json b/locales/zh-CN/image.json
index 805d731366c..d1bca99fcff 100644
--- a/locales/zh-CN/image.json
+++ b/locales/zh-CN/image.json
@@ -7,6 +7,7 @@
"config.header.title": "图片",
"config.height.label": "高度",
"config.imageNum.label": "图片数量",
+ "config.imageUpload.maxCountReached": "最多可添加 {{count}} 张参考图",
"config.imageUrl.label": "参考图",
"config.imageUrls.label": "参考图",
"config.model.label": "模型",
diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.json
index eafcc866c2a..f7d227930b4 100644
--- a/locales/zh-CN/video.json
+++ b/locales/zh-CN/video.json
@@ -5,6 +5,7 @@
"config.endImageUrl.label": "结束画面",
"config.generateAudio.label": "生成音频",
"config.header.title": "视频",
+ "config.imageUpload.maxCountReached": "最多可添加 {{count}} 张参考图",
"config.imageUrl.label": "起始画面",
"config.prompt.placeholder": "描述你想生成的视频内容",
"config.prompt.placeholderWithRef": "结合图片,描述你想生成的画面",
diff --git a/packages/locales/src/default/image.ts b/packages/locales/src/default/image.ts
index f484660b2a4..f304ac0800c 100644
--- a/packages/locales/src/default/image.ts
+++ b/packages/locales/src/default/image.ts
@@ -7,6 +7,7 @@ export default {
'config.header.title': 'Image',
'config.height.label': 'Height',
'config.imageNum.label': 'Number of Images',
+ 'config.imageUpload.maxCountReached': 'You can add up to {{count}} reference images',
'config.imageUrl.label': 'Reference Image',
'config.imageUrls.label': 'Reference Images',
'config.model.label': 'Model',
diff --git a/packages/locales/src/default/video.ts b/packages/locales/src/default/video.ts
index b262832d26f..aaf0093b9c9 100644
--- a/packages/locales/src/default/video.ts
+++ b/packages/locales/src/default/video.ts
@@ -5,6 +5,7 @@ export default {
'config.endImageUrl.label': 'End Frame',
'config.generateAudio.label': 'Generate Audio',
'config.header.title': 'Video',
+ 'config.imageUpload.maxCountReached': 'You can add up to {{count}} reference images',
'config.imageUrl.label': 'Start Frame',
'config.promptExtend.label': 'Prompt Extend',
'config.prompt.placeholder': 'Describe the video you want to generate',
diff --git a/src/features/ModelSwitchPanel/components/List/index.tsx b/src/features/ModelSwitchPanel/components/List/index.tsx
index 27e1edf5388..992b9f2e651 100644
--- a/src/features/ModelSwitchPanel/components/List/index.tsx
+++ b/src/features/ModelSwitchPanel/components/List/index.tsx
@@ -105,7 +105,9 @@ export const List: FC<ListProps> = ({
className={styles.list}
flex={1}
ref={listRef}
- style={{ height: listHeight }}
+ // No fixed height: flex-shrink within the height-capped panel so the list
+ // scrolls internally on short viewports while the toolbar stays pinned.
+ style={{ minHeight: 0 }}
onScroll={handleListScroll}
>
{listItems.map((item, index) => {
diff --git a/src/features/ModelSwitchPanel/components/PanelContent.tsx b/src/features/ModelSwitchPanel/components/PanelContent.tsx
index 6b6120e6d72..32120792178 100644
--- a/src/features/ModelSwitchPanel/components/PanelContent.tsx
+++ b/src/features/ModelSwitchPanel/components/PanelContent.tsx
@@ -72,11 +72,23 @@ export const PanelContent: FC<PanelContentProps> = ({
<Rnd
disableDragging
enableResizing={ENABLE_RESIZING}
+ // Rnd needs a numeric `size.height`, but a fixed height overflows the top
+ // edge when the upward-opening popup meets a short viewport. Pass the
+ // clamp through Rnd's own `maxHeight` (a `style.maxHeight` gets overridden
+ // by Rnd's internal default) so CSS caps the box to the space base-ui
+ // exposes via `--available-height`; the inner list then flex-shrinks and
+ // scrolls. Height resize is disabled, so this doesn't fight drag logic.
+ maxHeight={`min(${panelHeight}px, var(--available-height, ${panelHeight}px))`}
maxWidth={MAX_WIDTH}
minWidth={MIN_WIDTH}
position={{ x: 0, y: 0 }}
size={{ height: panelHeight, width: panelWidth }}
- style={{ display: 'flex', flexDirection: 'column', position: 'relative' }}
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ minHeight: 0,
+ position: 'relative',
+ }}
onResizeStop={(_e, _direction, ref) => {
handlePanelWidthChange(ref.offsetWidth);
}}
@@ -91,7 +103,13 @@ export const PanelContent: FC<PanelContentProps> = ({
style={{
display: 'flex',
flexDirection: 'column',
- height: panelHeight,
+ // Clamp the panel to the viewport space base-ui exposes via
+ // `--available-height` (falling back to the natural height before it's
+ // measured). The trigger usually sits at the page bottom and the popup
+ // opens upward; a fixed height would overflow the top edge and clip the
+ // search box + first items on short viewports. Keeping a *concrete*
+ // height (not max-height) lets the inner list flex-shrink and scroll.
+ height: `min(${panelHeight}px, var(--available-height, ${panelHeight}px))`,
position: 'relative',
width: DEFAULT_WIDTH,
}}
diff --git a/src/routes/(main)/(create)/features/CreateGenerationPage.tsx b/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
index 8e38dab3b01..445d6b6dc4d 100644
--- a/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
+++ b/src/routes/(main)/(create)/features/CreateGenerationPage.tsx
@@ -2,44 +2,46 @@
import { Flexbox } from '@lobehub/ui';
import { AnimatePresence, m as motion } from 'motion/react';
-import type { ComponentType } from 'react';
+import type { ComponentType, CSSProperties } from 'react';
import { memo } from 'react';
import { useMatch } from 'react-router';
+import DragUploadZone from '@/components/DragUploadZone';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
import { useQueryState } from '@/hooks/useQueryParam';
+const dropZoneStyle: CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ width: '100%',
+};
+
interface CreateGenerationPageProps {
+ /** Disable the drop zone overlay/handling (e.g. model has no reference support). */
+ dragDisabled?: boolean;
+ /**
+ * When provided, the whole creation area becomes a drag-and-drop upload zone.
+ * Files dropped anywhere below the nav header are routed here.
+ */
+ onUploadFiles?: (files: File[]) => void | Promise<void>;
path: string;
PromptInput: ComponentType<{ disableAnimation?: boolean; showTitle?: boolean }>;
Workspace: ComponentType<{ embedInput?: boolean }>;
}
-const CreateGenerationPage = memo<CreateGenerationPageProps>(({ path, Workspace, PromptInput }) => {
- const isPersonalPath = useMatch({ end: true, path });
- const isWorkspacePath = useMatch({ end: true, path: `/:workspaceSlug${path}` });
- const [topic] = useQueryState('topic');
- const isHome = !topic;
+const CreateGenerationPage = memo<CreateGenerationPageProps>(
+ ({ path, Workspace, PromptInput, dragDisabled, onUploadFiles }) => {
+ const isPersonalPath = useMatch({ end: true, path });
+ const isWorkspacePath = useMatch({ end: true, path: `/:workspaceSlug${path}` });
+ const [topic] = useQueryState('topic');
+ const isHome = !topic;
- if (!isPersonalPath && !isWorkspacePath) return null;
+ if (!isPersonalPath && !isWorkspacePath) return null;
- return (
- <>
- <NavHeader
- right={<WideScreenButton />}
- styles={{
- center: {
- alignItems: 'center',
- display: 'flex',
- justifyContent: 'center',
- minWidth: 0,
- },
- left: { flex: 1, minWidth: 0 },
- right: { flex: 1, minWidth: 0 },
- }}
- />
+ const content = (
<Flexbox
height={'100%'}
style={{ flexDirection: 'column', overflow: 'hidden', position: 'relative' }}
@@ -95,9 +97,41 @@ const CreateGenerationPage = memo<CreateGenerationPageProps>(({ path, Workspace,
)}
</AnimatePresence>
</Flexbox>
- </>
- );
-});
+ );
+
+ return (
+ <>
+ <NavHeader
+ right={<WideScreenButton />}
+ styles={{
+ center: {
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'center',
+ minWidth: 0,
+ },
+ left: { flex: 1, minWidth: 0 },
+ right: { flex: 1, minWidth: 0 },
+ }}
+ />
+ {onUploadFiles ? (
+ <DragUploadZone
+ disabled={dragDisabled}
+ // Generation upload only accepts images; keep the overlay copy/icons
+ // image-only so a dropped PDF/text file isn't falsely invited.
+ enabledFiles={false}
+ style={dropZoneStyle}
+ onUploadFiles={onUploadFiles}
+ >
+ {content}
+ </DragUploadZone>
+ ) : (
+ content
+ )}
+ </>
+ );
+ },
+);
CreateGenerationPage.displayName = 'CreateGenerationPage';
diff --git a/src/routes/(main)/(create)/features/GenerationInput/InlineImageReference.tsx b/src/routes/(main)/(create)/features/GenerationInput/InlineImageReference.tsx
index bbde136a667..de8c6e44443 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/InlineImageReference.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/InlineImageReference.tsx
@@ -36,15 +36,31 @@ interface InlineImageReferenceProps {
maxFileSize?: number;
onAdd: (data: UploadData) => void;
onRemove: (url: string) => void;
+ /** Optional batch upload handler to enable multi-select on the add card. */
+ onUploadFiles?: (files: File[]) => void | Promise<void>;
+ /** In-flight upload previews (object URLs) rendered with a spinner. */
+ uploadingPreviews?: string[];
}
const InlineImageReference = memo<InlineImageReferenceProps>(
- ({ images, onAdd, onRemove, maxFileSize, maxCount = 5 }) => {
+ ({
+ images,
+ onAdd,
+ onRemove,
+ onUploadFiles,
+ maxFileSize,
+ maxCount = 5,
+ uploadingPreviews = [],
+ }) => {
const [isHovered, setIsHovered] = useState(false);
- const canAddMore = images.length < maxCount;
- const hasImages = images.length > 0;
- const shouldCollapse = hasImages && !isHovered;
+ const totalCount = images.length + uploadingPreviews.length;
+ const canAddMore = totalCount < maxCount;
+ const hasItems = totalCount > 0;
+ const shouldCollapse = hasItems && !isHovered;
+
+ const stackOffset = (index: number) =>
+ index > 0 ? (shouldCollapse ? STACK_OFFSET : EXPAND_OFFSET) : 0;
return (
<Flexbox
@@ -61,7 +77,7 @@ const InlineImageReference = memo<InlineImageReferenceProps>(
key={url}
maxFileSize={maxFileSize}
style={{
- marginInlineStart: index > 0 ? (shouldCollapse ? STACK_OFFSET : EXPAND_OFFSET) : 0,
+ marginInlineStart: stackOffset(index),
zIndex: index + 1,
}}
onRemove={() => onRemove(url)}
@@ -69,24 +85,43 @@ const InlineImageReference = memo<InlineImageReferenceProps>(
/>
))}
+ {uploadingPreviews.map((url, index) => (
+ <UploadCard
+ loading
+ imageUrl={url}
+ key={`uploading-${url}`}
+ maxFileSize={maxFileSize}
+ style={{
+ marginInlineStart: stackOffset(images.length + index),
+ zIndex: images.length + index + 1,
+ }}
+ onRemove={() => {}}
+ onUpload={() => {}}
+ />
+ ))}
+
{canAddMore &&
(shouldCollapse ? (
<UploadCard
className={styles.addCirclePos}
maxFileSize={maxFileSize}
+ multiple={!!onUploadFiles}
variant="circle"
onRemove={() => {}}
onUpload={onAdd}
+ onUploadFiles={onUploadFiles}
/>
) : (
<UploadCard
maxFileSize={maxFileSize}
+ multiple={!!onUploadFiles}
style={{
- marginInlineStart: hasImages ? EXPAND_OFFSET : 0,
- zIndex: images.length + 1,
+ marginInlineStart: hasItems ? EXPAND_OFFSET : 0,
+ zIndex: totalCount + 1,
}}
onRemove={() => {}}
onUpload={onAdd}
+ onUploadFiles={onUploadFiles}
/>
))}
</Flexbox>
diff --git a/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx b/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx
index 8ac89faae57..4fdef57d675 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx
@@ -49,6 +49,10 @@ interface InlineVideoFramesProps {
onImageChange: (data: UploadData | null) => void;
onImageUrlsChange?: (data: UploadData) => void;
onRemoveImageUrl?: (url: string) => void;
+ /** Optional batch upload handler to enable multi-select on the add card. */
+ onUploadFiles?: (files: File[]) => void | Promise<void>;
+ /** In-flight upload previews (object URLs) rendered with a spinner. */
+ uploadingPreviews?: string[];
}
const InlineVideoFrames = memo<InlineVideoFramesProps>(
@@ -60,9 +64,11 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(
onEndImageChange,
onImageUrlsChange,
onRemoveImageUrl,
+ onUploadFiles,
isSupportEndImage = true,
maxCount = 5,
maxFileSize,
+ uploadingPreviews = [],
}) => {
const { t } = useTranslation('video');
const [isHovered, setIsHovered] = useState(false);
@@ -78,8 +84,10 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(
}, [imageUrl, imageUrls]);
const hasRefFrames = refFrameUrls.length > 0;
- const canAddMore = refFrameUrls.length < maxCount;
- const shouldCollapse = hasRefFrames && !isHovered;
+ const totalCount = refFrameUrls.length + uploadingPreviews.length;
+ const hasItems = totalCount > 0;
+ const canAddMore = totalCount < maxCount;
+ const shouldCollapse = hasItems && !isHovered;
const showEndFrame = isSupportEndImage && hasRefFrames;
return (
@@ -127,14 +135,37 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(
);
})}
+ {/* In-flight upload placeholders (with spinner) */}
+ {uploadingPreviews.map((url, index) => (
+ <UploadCard
+ loading
+ imageUrl={url}
+ key={`uploading-${url}`}
+ maxFileSize={maxFileSize}
+ style={{
+ marginInlineStart:
+ refFrameUrls.length + index > 0
+ ? shouldCollapse
+ ? STACK_OFFSET
+ : EXPAND_OFFSET
+ : 0,
+ zIndex: refFrameUrls.length + index + 1,
+ }}
+ onRemove={() => {}}
+ onUpload={() => {}}
+ />
+ ))}
+
{/* Add new frame button */}
{canAddMore &&
(shouldCollapse ? (
<UploadCard
className={styles.addCirclePos}
maxFileSize={maxFileSize}
+ multiple={!!onUploadFiles}
variant="circle"
onRemove={() => {}}
+ onUploadFiles={onUploadFiles}
onUpload={(data) => {
if (onImageUrlsChange) {
onImageUrlsChange(data);
@@ -148,11 +179,13 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(
imageUrl={null}
label={t('config.referenceImage.label')}
maxFileSize={maxFileSize}
+ multiple={!!onUploadFiles}
style={{
- marginInlineStart: hasRefFrames ? EXPAND_OFFSET : 0,
- zIndex: refFrameUrls.length + 1,
+ marginInlineStart: hasItems ? EXPAND_OFFSET : 0,
+ zIndex: totalCount + 1,
}}
onRemove={() => {}}
+ onUploadFiles={onUploadFiles}
onUpload={(data) => {
if (hasRefFrames) {
if (onImageUrlsChange) {
diff --git a/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx b/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx
index 339711e516b..c61bf857fbb 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx
@@ -126,9 +126,19 @@ interface UploadCardProps {
closeClassName?: string;
imageUrl?: string | null;
label?: string;
+ /** Show an upload spinner overlay (for externally-managed batch uploads). */
+ loading?: boolean;
maxFileSize?: number;
+ /** Allow selecting multiple files at once (requires `onUploadFiles`). */
+ multiple?: boolean;
onRemove: () => void;
onUpload: (data: UploadData) => void;
+ /**
+ * Batch upload handler. When provided, file selection is delegated to the
+ * parent (which uploads + lands all files together) instead of the card's
+ * internal single-file upload, enabling multi-select.
+ */
+ onUploadFiles?: (files: File[]) => void | Promise<void>;
style?: CSSProperties;
variant?: 'card' | 'circle';
}
@@ -137,9 +147,12 @@ const UploadCard = memo<UploadCardProps>(
({
imageUrl,
label,
+ loading = false,
onUpload,
+ onUploadFiles,
onRemove,
maxFileSize,
+ multiple = false,
className,
closeClassName,
style,
@@ -150,12 +163,25 @@ const UploadCard = memo<UploadCardProps>(
const [isUploading, setIsUploading] = useState(false);
const [uploadPreview, setUploadPreview] = useState<string | null>(null);
+ // Combine internal single-upload spinner with externally-driven batch loading.
+ const uploading = isUploading || loading;
+
const handleFileSelect = useCallback(() => {
+ if (loading) return;
inputRef.current?.click();
- }, []);
+ }, [loading]);
const handleFileChange = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
+ // When a batch handler is provided, delegate all selected files to the
+ // parent so multiple references can be uploaded and landed at once.
+ if (onUploadFiles) {
+ const files = Array.from(e.target.files ?? []);
+ if (files.length === 0) return;
+ await onUploadFiles(files);
+ return;
+ }
+
const file = e.target.files?.[0];
if (!file) return;
@@ -184,7 +210,7 @@ const UploadCard = memo<UploadCardProps>(
setIsUploading(false);
}
},
- [maxFileSize, uploadWithProgress, onUpload],
+ [maxFileSize, uploadWithProgress, onUpload, onUploadFiles],
);
const showPreview = uploadPreview || imageUrl;
@@ -192,6 +218,7 @@ const UploadCard = memo<UploadCardProps>(
const fileInput = (
<input
accept="image/*"
+ multiple={multiple}
ref={inputRef}
style={{ display: 'none' }}
type="file"
@@ -236,13 +263,13 @@ const UploadCard = memo<UploadCardProps>(
src={uploadPreview || imageUrl!}
style={{ objectFit: 'cover' }}
/>
- {isUploading && (
+ {uploading && (
<div className={uploadCardStyles.uploadOverlay}>
<Spin percent={'auto'} size="small" />
</div>
)}
</div>
- {!isUploading && (
+ {!uploading && (
<ActionIcon
glass
className={cx(uploadCardStyles.closeButton, closeClassName, 'upload-card-close')}
diff --git a/src/routes/(main)/(create)/features/GenerationInput/useReferenceImageUpload.ts b/src/routes/(main)/(create)/features/GenerationInput/useReferenceImageUpload.ts
new file mode 100644
index 00000000000..86d00a5ffad
--- /dev/null
+++ b/src/routes/(main)/(create)/features/GenerationInput/useReferenceImageUpload.ts
@@ -0,0 +1,205 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+
+import { useFileStore } from '@/store/file';
+
+import type { UploadData } from './UploadCard';
+
+/**
+ * A single destination for dropped reference images (e.g. start frame, reference
+ * array, end frame). Slots are filled in array order: dropped files top up the
+ * first slot with remaining room, then overflow into the next.
+ */
+export interface ReferenceUploadSlot {
+ /** Maximum number of image URLs this slot can hold. */
+ capacity: number;
+ /**
+ * Read this slot's URLs fresh from the store. Used at landing time so a batch
+ * that finishes after a concurrent one merges against the latest content
+ * instead of overwriting it with a stale render-time snapshot.
+ */
+ getCurrentValues: () => string[];
+ /** Replace this slot's full content with the given URLs (already capped to capacity). */
+ set: (urls: string[]) => void;
+ /** URLs currently landed in this slot (render-time snapshot for previews/capacity). */
+ values: string[];
+}
+
+interface UseReferenceImageUploadOptions {
+ /** Append object-URL placeholders for in-flight uploads (store-backed, shared). */
+ addUploadingPreviews: (urls: string[]) => void;
+ /** Whether the user is permitted to add references. */
+ canCreate: boolean;
+ /** Largest accepted file size in bytes; larger files are skipped. */
+ maxFileSize?: number;
+ /** Set image dimensions from the first uploaded image (image page only). */
+ onFirstDimensions?: (dimensions: { height: number; width: number }) => void;
+ /** Called with the effective max count when a drop exceeds the remaining room. */
+ onLimitExceeded?: (maxCount: number) => void;
+ /** Remove this batch's object-URL placeholders once the upload settles. */
+ removeUploadingPreviews: (urls: string[]) => void;
+ /** Ordered destination slots; dropped files fill them by priority. */
+ slots: ReferenceUploadSlot[];
+ /** Object-URL placeholders for in-flight uploads (store-backed, shared). */
+ uploadingPreviews: string[];
+}
+
+const extractUrlAndDimensions = (data?: UploadData) => {
+ const url = typeof data === 'string' ? data : data?.url;
+ const dimensions = typeof data === 'object' ? data?.dimensions : undefined;
+ return { dimensions, url };
+};
+
+/**
+ * Store-agnostic core for drag/click reference-image upload, shared by the image
+ * and video creation pages.
+ *
+ * Callers describe their model's accepted reference slots (`slots`) and the
+ * store-backed in-flight preview state; this hook owns the tricky parts:
+ * filtering, capacity/limit handling, instant object-URL placeholders, the batch
+ * upload, single-shot landing across slots (avoiding the stale-closure race a
+ * per-file loop would cause), and placeholder cleanup.
+ *
+ * The page-specific differences (which store, end-frame slot, auto-dimensions)
+ * are injected via `slots` / `onFirstDimensions`, so the upload mechanics live
+ * in exactly one place.
+ */
+export const useReferenceImageUpload = ({
+ slots,
+ canCreate,
+ maxFileSize,
+ uploadingPreviews,
+ addUploadingPreviews,
+ removeUploadingPreviews,
+ onFirstDimensions,
+ onLimitExceeded,
+}: UseReferenceImageUploadOptions) => {
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+
+ const maxCount = useMemo(() => slots.reduce((sum, slot) => sum + slot.capacity, 0), [slots]);
+
+ const imagePreviewUrls = useMemo(
+ () => slots.flatMap((slot) => slot.values).filter(Boolean),
+ [slots],
+ );
+
+ // Gate on permission too: without `create_content` the upload handler bails
+ // immediately, so a true flag here would show an active drop zone that
+ // silently accepts and discards the drop.
+ const canDropImage = canCreate && maxCount > 0;
+
+ const handleUploadFiles = useCallback(
+ async (files: File[]) => {
+ if (!canCreate) return;
+
+ // Keep files whose type is an image OR empty: OS/browser drops of images
+ // with uncommon extensions can arrive with an empty `File.type`. Discarding
+ // them here would silently drop a valid reference before the upload pipeline
+ // (which sniffs the MIME from bytes) gets a chance. Known non-image types
+ // (PDF/video/text) still carry a populated `type` and are rejected.
+ const imageFiles = files.filter((file) => file.type === '' || file.type.startsWith('image/'));
+ if (imageFiles.length === 0) return;
+
+ // Drop files over the model's size limit before consuming capacity, so an
+ // oversized file doesn't steal a slot from a valid one later in the drop.
+ const uploadableFiles = maxFileSize
+ ? imageFiles.filter((file) => file.size <= maxFileSize)
+ : imageFiles;
+ if (uploadableFiles.length === 0) return;
+
+ // Account for both landed images and any in-flight uploads.
+ const remaining = maxCount - imagePreviewUrls.length - uploadingPreviews.length;
+ if (remaining <= 0) {
+ onLimitExceeded?.(maxCount);
+ return;
+ }
+
+ // Only take as many as there is still room for, and warn when truncating.
+ const accepted = uploadableFiles.slice(0, remaining);
+ if (uploadableFiles.length > remaining) {
+ onLimitExceeded?.(maxCount);
+ }
+
+ // Show instant local previews (with spinner) for the whole batch.
+ const previews = accepted.map((file) => URL.createObjectURL(file));
+ addUploadingPreviews(previews);
+
+ try {
+ // `allSettled` isolates per-file failures: a single rejected upload no
+ // longer discards the whole batch, so the images that did land stay.
+ const settled = await Promise.allSettled(
+ accepted.map(async (file): Promise<UploadData | null> => {
+ const result = await uploadWithProgress({
+ file,
+ onStatusUpdate: () => {},
+ skipCheckFileType: true,
+ });
+
+ if (!result?.url) return null;
+ return result.dimensions
+ ? { dimensions: result.dimensions, url: result.url }
+ : result.url;
+ }),
+ );
+ const results = settled.map((outcome) =>
+ outcome.status === 'fulfilled' ? outcome.value : null,
+ );
+
+ // Collect successful URLs and the first available dimensions.
+ const uploadedUrls: string[] = [];
+ let firstDimensions: { height: number; width: number } | undefined;
+ for (const data of results) {
+ if (!data) continue;
+ const { url, dimensions } = extractUrlAndDimensions(data);
+ if (!url) continue;
+ if (!firstDimensions && dimensions) firstDimensions = dimensions;
+ uploadedUrls.push(url);
+ }
+
+ if (firstDimensions) onFirstDimensions?.(firstDimensions);
+
+ // Distribute uploaded URLs across slots by priority, appending to the
+ // slot's *current* store content (read fresh, not the render-time
+ // snapshot) so a concurrent batch that already landed isn't overwritten.
+ // The loop is synchronous, so each batch's landing is atomic.
+ let pool = uploadedUrls;
+ for (const slot of slots) {
+ if (pool.length === 0) break;
+ const current = slot.getCurrentValues();
+ const room = slot.capacity - current.length;
+ if (room <= 0) continue;
+ const take = pool.slice(0, room);
+ pool = pool.slice(room);
+ slot.set([...current, ...take]);
+ }
+ } finally {
+ // Drop this batch's placeholders, then release the object URLs.
+ removeUploadingPreviews(previews);
+ previews.forEach((url) => URL.revokeObjectURL(url));
+ }
+ },
+ [
+ slots,
+ canCreate,
+ maxCount,
+ maxFileSize,
+ imagePreviewUrls,
+ uploadingPreviews,
+ uploadWithProgress,
+ addUploadingPreviews,
+ removeUploadingPreviews,
+ onFirstDimensions,
+ onLimitExceeded,
+ ],
+ );
+
+ return {
+ canDropImage,
+ handleUploadFiles,
+ imagePreviewUrls,
+ maxCount,
+ maxFileSize,
+ uploadingPreviews,
+ };
+};
diff --git a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
index 277532948f4..540113c8d97 100644
--- a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
@@ -4,7 +4,7 @@ import { ModelIcon } from '@lobehub/icons';
import { ActionIcon, Flexbox, Segmented, Text } from '@lobehub/ui';
import { Divider, Switch } from 'antd';
import { Images } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { loginRequired } from '@/components/Error/loginRequiredNotification';
@@ -30,7 +30,6 @@ import {
SeedNumberInput,
SizeSelect,
StepsSliderInput,
- useAutoDimensions,
} from '@/routes/(main)/(create)/image/features/ConfigPanel';
import ImageModelItem from '@/routes/(main)/(create)/image/features/ConfigPanel/components/ModelSelect/ImageModelItem';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -44,6 +43,7 @@ import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/slices/auth/selectors';
import PromptTitle from './Title';
+import { useImageReferenceUpload } from './useImageReferenceUpload';
interface PromptInputProps {
disableAnimation?: boolean;
@@ -126,22 +126,22 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const { t } = useTranslation('image');
const { allowed: canCreate } = usePermission('create_content');
const { value, setValue } = useGenerationConfigParam('prompt');
- const { value: imageUrl, setValue: setImageUrl } = useGenerationConfigParam('imageUrl');
const {
- value: imageUrls,
- setValue: setImageUrls,
- maxCount: imageUrlsMaxCount,
- maxFileSize: imageUrlsMaxFileSize,
- } = useGenerationConfigParam('imageUrls');
- const { maxFileSize: imageUrlMaxFileSize } = useGenerationConfigParam('imageUrl');
+ canDropImage,
+ handleAddImage,
+ handleRemoveImage,
+ handleUploadFiles,
+ imagePreviewUrls,
+ maxCount,
+ maxFileSize,
+ uploadingPreviews,
+ } = useImageReferenceUpload();
const isCreating = useImageStore(createImageSelectors.isCreating);
const createImage = useImageStore((s) => s.createImage);
const setModelAndProviderOnSelect = useImageStore((s) => s.setModelAndProviderOnSelect);
const currentModel = useImageStore(imageGenerationConfigSelectors.model);
const currentProvider = useImageStore(imageGenerationConfigSelectors.provider);
const isInit = useImageStore((s) => s.isInit);
- const isSupportImageUrl = useImageStore(isSupportedParamSelector('imageUrl'));
- const isSupportImageUrls = useImageStore(isSupportedParamSelector('imageUrls'));
const isSupportQuality = useImageStore(isSupportedParamSelector('quality'));
const isSupportResolution = useImageStore(isSupportedParamSelector('resolution'));
const isSupportSize = useImageStore(isSupportedParamSelector('size'));
@@ -154,7 +154,6 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isLogin = useUserStore(authSelectors.isLogin);
const enabledImageModelList = useAiInfraStore(aiProviderSelectors.enabledImageModelList);
const { showDimensionControl } = useDimensionControl();
- const { autoSetDimensions, extractUrlAndDimensions } = useAutoDimensions();
useFetchAiImageConfig();
@@ -208,66 +207,9 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
}
}, [promptParam, isLogin, canCreate, setValue, setPromptParam, createImage]);
- const imagePreviewUrls = useMemo(
- () => [imageUrl, ...(imageUrls ?? [])].filter(Boolean) as string[],
- [imageUrl, imageUrls],
- );
-
- const handleAddImage = useCallback(
- (data: string | { dimensions?: { height: number; width: number }; url: string }) => {
- if (!canCreate) return;
-
- const { url, dimensions } = extractUrlAndDimensions(data);
- if (!url) return;
-
- if (dimensions) {
- autoSetDimensions(dimensions);
- }
-
- if (isSupportImageUrl && !imageUrl) {
- setImageUrl(url);
- } else if (isSupportImageUrls) {
- setImageUrls([...(imageUrls ?? []), url] as any);
- } else if (isSupportImageUrl) {
- setImageUrl(url);
- }
- },
- [
- isSupportImageUrl,
- isSupportImageUrls,
- imageUrl,
- imageUrls,
- setImageUrl,
- setImageUrls,
- autoSetDimensions,
- extractUrlAndDimensions,
- canCreate,
- ],
- );
-
- const handleRemoveImage = useCallback(
- (url: string) => {
- if (!canCreate) return;
-
- if (url === imageUrl) {
- setImageUrl(null);
- } else {
- setImageUrls((imageUrls ?? []).filter((item) => item !== url) as any);
- }
- },
- [canCreate, imageUrl, imageUrls, setImageUrl, setImageUrls],
- );
-
- const showInlineRef = isSupportImageUrl || isSupportImageUrls;
+ const showInlineRef = canDropImage;
const hasRefImages = imagePreviewUrls.length > 0;
- const maxCount = useMemo(() => {
- let count = 0;
- if (isSupportImageUrl) count += 1;
- if (isSupportImageUrls) count += imageUrlsMaxCount ?? 4;
- return count;
- }, [isSupportImageUrl, isSupportImageUrls, imageUrlsMaxCount]);
-
return (
<Flexbox gap={32} width={'100%'}>
{showTitle && <PromptTitle />}
@@ -284,9 +226,11 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
<InlineImageReference
images={imagePreviewUrls}
maxCount={maxCount}
- maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}
+ maxFileSize={maxFileSize}
+ uploadingPreviews={uploadingPreviews}
onAdd={handleAddImage}
onRemove={handleRemoveImage}
+ onUploadFiles={handleUploadFiles}
/>
) : undefined
}
diff --git a/src/routes/(main)/(create)/image/features/PromptInput/useImageReferenceUpload.ts b/src/routes/(main)/(create)/image/features/PromptInput/useImageReferenceUpload.ts
new file mode 100644
index 00000000000..936f5fc6bb8
--- /dev/null
+++ b/src/routes/(main)/(create)/image/features/PromptInput/useImageReferenceUpload.ts
@@ -0,0 +1,163 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { usePermission } from '@/hooks/usePermission';
+import type { UploadData } from '@/routes/(main)/(create)/features/GenerationInput/UploadCard';
+import {
+ type ReferenceUploadSlot,
+ useReferenceImageUpload,
+} from '@/routes/(main)/(create)/features/GenerationInput/useReferenceImageUpload';
+import { useAutoDimensions } from '@/routes/(main)/(create)/image/features/ConfigPanel';
+import { useImageStore } from '@/store/image';
+import { imageGenerationConfigSelectors } from '@/store/image/selectors';
+import { useGenerationConfigParam } from '@/store/image/slices/generationConfig/hooks';
+
+const isSupportedParamSelector = imageGenerationConfigSelectors.isSupportedParam;
+
+/**
+ * Image-page binding for the shared {@link useReferenceImageUpload} core.
+ *
+ * Describes the image model's reference slots (`imageUrl` then `imageUrls`),
+ * wires the store-backed in-flight preview state, and auto-sets dimensions from
+ * the first dropped image. Also keeps the single add/remove handlers used by the
+ * inline reference cards.
+ */
+export const useImageReferenceUpload = () => {
+ const { t } = useTranslation('image');
+ const { allowed: canCreate } = usePermission('create_content');
+
+ const isSupportImageUrl = useImageStore(isSupportedParamSelector('imageUrl'));
+ const isSupportImageUrls = useImageStore(isSupportedParamSelector('imageUrls'));
+
+ const {
+ value: imageUrl,
+ setValue: setImageUrl,
+ maxFileSize: imageUrlMaxFileSize,
+ } = useGenerationConfigParam('imageUrl');
+ const {
+ value: imageUrls,
+ setValue: setImageUrls,
+ maxCount: imageUrlsMaxCount,
+ maxFileSize: imageUrlsMaxFileSize,
+ } = useGenerationConfigParam('imageUrls');
+
+ const { autoSetDimensions, extractUrlAndDimensions } = useAutoDimensions();
+
+ const uploadingPreviews = useImageStore(imageGenerationConfigSelectors.uploadingImagePreviews);
+ const addUploadingImagePreviews = useImageStore((s) => s.addUploadingImagePreviews);
+ const removeUploadingImagePreviews = useImageStore((s) => s.removeUploadingImagePreviews);
+
+ const slots = useMemo<ReferenceUploadSlot[]>(() => {
+ const readParams = () => imageGenerationConfigSelectors.parameters(useImageStore.getState());
+ const list: ReferenceUploadSlot[] = [];
+ if (isSupportImageUrl) {
+ list.push({
+ capacity: 1,
+ getCurrentValues: () => {
+ const v = readParams()?.imageUrl;
+ return v ? [v] : [];
+ },
+ set: (urls) => setImageUrl((urls[0] ?? null) as any),
+ values: imageUrl ? [imageUrl] : [],
+ });
+ }
+ if (isSupportImageUrls) {
+ list.push({
+ capacity: imageUrlsMaxCount ?? 4,
+ getCurrentValues: () => {
+ const v = readParams()?.imageUrls;
+ return Array.isArray(v) ? v : [];
+ },
+ set: (urls) => setImageUrls(urls as any),
+ values: imageUrls ?? [],
+ });
+ }
+ return list;
+ }, [
+ isSupportImageUrl,
+ isSupportImageUrls,
+ imageUrl,
+ imageUrls,
+ imageUrlsMaxCount,
+ setImageUrl,
+ setImageUrls,
+ ]);
+
+ const onLimitExceeded = useCallback(
+ (maxCount: number) => {
+ message.warning(t('config.imageUpload.maxCountReached', { count: maxCount }));
+ },
+ [t],
+ );
+
+ const { canDropImage, handleUploadFiles, imagePreviewUrls, maxCount, maxFileSize } =
+ useReferenceImageUpload({
+ addUploadingPreviews: addUploadingImagePreviews,
+ canCreate,
+ maxFileSize: imageUrlsMaxFileSize ?? imageUrlMaxFileSize,
+ onFirstDimensions: autoSetDimensions,
+ onLimitExceeded,
+ removeUploadingPreviews: removeUploadingImagePreviews,
+ slots,
+ uploadingPreviews,
+ });
+
+ const handleAddImage = useCallback(
+ (data: UploadData) => {
+ if (!canCreate) return;
+
+ const { url, dimensions } = extractUrlAndDimensions(data);
+ if (!url) return;
+
+ if (dimensions) {
+ autoSetDimensions(dimensions);
+ }
+
+ if (isSupportImageUrl && !imageUrl) {
+ setImageUrl(url);
+ } else if (isSupportImageUrls) {
+ setImageUrls([...(imageUrls ?? []), url] as any);
+ } else if (isSupportImageUrl) {
+ setImageUrl(url);
+ }
+ },
+ [
+ isSupportImageUrl,
+ isSupportImageUrls,
+ imageUrl,
+ imageUrls,
+ setImageUrl,
+ setImageUrls,
+ autoSetDimensions,
+ extractUrlAndDimensions,
+ canCreate,
+ ],
+ );
+
+ const handleRemoveImage = useCallback(
+ (url: string) => {
+ if (!canCreate) return;
+
+ if (url === imageUrl) {
+ setImageUrl(null);
+ } else {
+ setImageUrls((imageUrls ?? []).filter((item) => item !== url) as any);
+ }
+ },
+ [canCreate, imageUrl, imageUrls, setImageUrl, setImageUrls],
+ );
+
+ return {
+ canDropImage,
+ handleAddImage,
+ handleRemoveImage,
+ handleUploadFiles,
+ imagePreviewUrls,
+ maxCount,
+ maxFileSize,
+ uploadingPreviews,
+ };
+};
diff --git a/src/routes/(main)/(create)/image/index.tsx b/src/routes/(main)/(create)/image/index.tsx
index 7b7b55dc80e..88843a5f804 100644
--- a/src/routes/(main)/(create)/image/index.tsx
+++ b/src/routes/(main)/(create)/image/index.tsx
@@ -6,10 +6,21 @@ import CreateGenerationPage from '@/routes/(main)/(create)/features/CreateGenera
import ImageWorkspace from './features/ImageWorkspace';
import PromptInput from './features/PromptInput';
+import { useImageReferenceUpload } from './features/PromptInput/useImageReferenceUpload';
-const DesktopImagePage = memo(() => (
- <CreateGenerationPage PromptInput={PromptInput} Workspace={ImageWorkspace} path="/image" />
-));
+const DesktopImagePage = memo(() => {
+ const { canDropImage, handleUploadFiles } = useImageReferenceUpload();
+
+ return (
+ <CreateGenerationPage
+ PromptInput={PromptInput}
+ Workspace={ImageWorkspace}
+ dragDisabled={!canDropImage}
+ path="/image"
+ onUploadFiles={handleUploadFiles}
+ />
+ );
+});
DesktopImagePage.displayName = 'DesktopImagePage';
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
index 37b03b31041..1e530f41f88 100644
--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
@@ -34,6 +34,7 @@ import { useVideoGenerationConfigParam } from '@/store/video/slices/generationCo
import { generateUniqueSeeds } from '@/utils/number';
import PromptTitle from './Title';
+import { useVideoReferenceUpload } from './useVideoReferenceUpload';
interface PromptInputProps {
disableAnimation?: boolean;
@@ -311,6 +312,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isSupportWebSearch = useVideoStore(isSupportedParamSelector('webSearch'));
const isLogin = useUserStore(authSelectors.isLogin);
const { value: duration } = useVideoGenerationConfigParam('duration');
+ const { handleUploadFiles, uploadingPreviews } = useVideoReferenceUpload();
useFetchAiVideoConfig();
// Read query parameters
@@ -458,9 +460,11 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
isSupportEndImage={isSupportEndImageUrl}
maxCount={maxCount}
maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}
+ uploadingPreviews={uploadingPreviews}
onEndImageChange={handleEndImageChange}
onImageUrlsChange={handleAddImage}
onRemoveImageUrl={handleRemoveImage}
+ onUploadFiles={handleUploadFiles}
onImageChange={(data) => {
if (data === null) {
handleRemoveImage(imageUrl || '');
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts b/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts
new file mode 100644
index 00000000000..f2dfa68fa73
--- /dev/null
+++ b/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts
@@ -0,0 +1,124 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { usePermission } from '@/hooks/usePermission';
+import {
+ type ReferenceUploadSlot,
+ useReferenceImageUpload,
+} from '@/routes/(main)/(create)/features/GenerationInput/useReferenceImageUpload';
+import { useVideoStore } from '@/store/video';
+import { videoGenerationConfigSelectors } from '@/store/video/selectors';
+import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';
+
+const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam;
+
+/**
+ * Video-page binding for the shared {@link useReferenceImageUpload} core.
+ *
+ * Describes the video model's reference slots by priority — start frame
+ * (`imageUrl`) → reference array (`imageUrls`) → end frame (`endImageUrl`) — so a
+ * drop fills them in order. Single-image models accept one; first/end-frame
+ * models map a 2-image drop to start + end (the end frame's `requiresImageUrl`
+ * is satisfied because the start frame slot fills first).
+ */
+export const useVideoReferenceUpload = () => {
+ const { t } = useTranslation('video');
+ const { allowed: canCreate } = usePermission('create_content');
+
+ const isSupportImageUrl = useVideoStore(isSupportedParamSelector('imageUrl'));
+ const isSupportImageUrls = useVideoStore(isSupportedParamSelector('imageUrls'));
+ const isSupportEndImageUrl = useVideoStore(isSupportedParamSelector('endImageUrl'));
+
+ const {
+ value: imageUrl,
+ setValue: setImageUrl,
+ maxFileSize: imageUrlMaxFileSize,
+ } = useVideoGenerationConfigParam('imageUrl');
+ const {
+ value: imageUrls,
+ setValue: setImageUrls,
+ maxCount: imageUrlsMaxCount,
+ maxFileSize: imageUrlsMaxFileSize,
+ } = useVideoGenerationConfigParam('imageUrls');
+ const {
+ value: endImageUrl,
+ setValue: setEndImageUrl,
+ maxFileSize: endImageUrlMaxFileSize,
+ } = useVideoGenerationConfigParam('endImageUrl');
+
+ const uploadingPreviews = useVideoStore(videoGenerationConfigSelectors.uploadingImagePreviews);
+ const addUploadingImagePreviews = useVideoStore((s) => s.addUploadingImagePreviews);
+ const removeUploadingImagePreviews = useVideoStore((s) => s.removeUploadingImagePreviews);
+
+ const slots = useMemo<ReferenceUploadSlot[]>(() => {
+ const readParams = () => videoGenerationConfigSelectors.parameters(useVideoStore.getState());
+ const list: ReferenceUploadSlot[] = [];
+ if (isSupportImageUrl) {
+ list.push({
+ capacity: 1,
+ getCurrentValues: () => {
+ const v = readParams()?.imageUrl;
+ return v ? [v] : [];
+ },
+ set: (urls) => setImageUrl((urls[0] ?? null) as any),
+ values: imageUrl ? [imageUrl] : [],
+ });
+ }
+ if (isSupportImageUrls) {
+ list.push({
+ capacity: imageUrlsMaxCount ?? 4,
+ getCurrentValues: () => {
+ const v = readParams()?.imageUrls;
+ return Array.isArray(v) ? v : [];
+ },
+ set: (urls) => setImageUrls(urls as any),
+ values: imageUrls ?? [],
+ });
+ }
+ if (isSupportEndImageUrl) {
+ list.push({
+ capacity: 1,
+ getCurrentValues: () => {
+ const v = readParams()?.endImageUrl;
+ return v ? [v] : [];
+ },
+ set: (urls) => setEndImageUrl((urls[0] ?? null) as any),
+ values: endImageUrl ? [endImageUrl] : [],
+ });
+ }
+ return list;
+ }, [
+ isSupportImageUrl,
+ isSupportImageUrls,
+ isSupportEndImageUrl,
+ imageUrl,
+ imageUrls,
+ endImageUrl,
+ imageUrlsMaxCount,
+ setImageUrl,
+ setImageUrls,
+ setEndImageUrl,
+ ]);
+
+ const onLimitExceeded = useCallback(
+ (maxCount: number) => {
+ message.warning(t('config.imageUpload.maxCountReached', { count: maxCount }));
+ },
+ [t],
+ );
+
+ const { canDropImage, handleUploadFiles, maxCount, maxFileSize } = useReferenceImageUpload({
+ addUploadingPreviews: addUploadingImagePreviews,
+ canCreate,
+ maxFileSize: imageUrlsMaxFileSize ?? imageUrlMaxFileSize ?? endImageUrlMaxFileSize,
+ onLimitExceeded,
+ removeUploadingPreviews: removeUploadingImagePreviews,
+ slots,
+ uploadingPreviews,
+ });
+
+ return { canDropImage, handleUploadFiles, maxCount, maxFileSize, uploadingPreviews };
+};
diff --git a/src/routes/(main)/(create)/video/index.tsx b/src/routes/(main)/(create)/video/index.tsx
index f61524e8a53..85831e8e578 100644
--- a/src/routes/(main)/(create)/video/index.tsx
+++ b/src/routes/(main)/(create)/video/index.tsx
@@ -5,11 +5,22 @@ import { memo } from 'react';
import CreateGenerationPage from '@/routes/(main)/(create)/features/CreateGenerationPage';
import PromptInput from './features/PromptInput';
+import { useVideoReferenceUpload } from './features/PromptInput/useVideoReferenceUpload';
import VideoWorkspace from './features/VideoWorkspace';
-const DesktopVideoPage = memo(() => (
- <CreateGenerationPage PromptInput={PromptInput} Workspace={VideoWorkspace} path="/video" />
-));
+const DesktopVideoPage = memo(() => {
+ const { canDropImage, handleUploadFiles } = useVideoReferenceUpload();
+
+ return (
+ <CreateGenerationPage
+ PromptInput={PromptInput}
+ Workspace={VideoWorkspace}
+ dragDisabled={!canDropImage}
+ path="/video"
+ onUploadFiles={handleUploadFiles}
+ />
+ );
+});
DesktopVideoPage.displayName = 'DesktopVideoPage';
diff --git a/src/store/image/slices/generationConfig/action.ts b/src/store/image/slices/generationConfig/action.ts
index f69f69c9051..a0bea4ac558 100644
--- a/src/store/image/slices/generationConfig/action.ts
+++ b/src/store/image/slices/generationConfig/action.ts
@@ -324,6 +324,24 @@ export class GenerationConfigActionImpl {
this.#set(() => ({ imageNum }), false, `setImageNum/${imageNum}`);
};
+ addUploadingImagePreviews = (urls: string[]): void => {
+ this.#set(
+ (state) => ({ uploadingImagePreviews: [...state.uploadingImagePreviews, ...urls] }),
+ false,
+ 'addUploadingImagePreviews',
+ );
+ };
+
+ removeUploadingImagePreviews = (urls: string[]): void => {
+ this.#set(
+ (state) => ({
+ uploadingImagePreviews: state.uploadingImagePreviews.filter((url) => !urls.includes(url)),
+ }),
+ false,
+ 'removeUploadingImagePreviews',
+ );
+ };
+
reuseSettings = (
model: string,
provider: string,
diff --git a/src/store/image/slices/generationConfig/initialState.ts b/src/store/image/slices/generationConfig/initialState.ts
index 0ff7e3f1ac9..15978c0dd00 100644
--- a/src/store/image/slices/generationConfig/initialState.ts
+++ b/src/store/image/slices/generationConfig/initialState.ts
@@ -18,6 +18,13 @@ export interface GenerationConfigState {
isAspectRatioLocked: boolean;
activeAspectRatio: string | null; // string - virtual ratio; null - native ratio
+ /**
+ * Object-URL previews for reference images currently being uploaded. Shared
+ * across the inline reference cards and the page-level drag-upload zone so
+ * both surfaces show the same in-flight loading placeholders.
+ */
+ uploadingImagePreviews: string[];
+
/**
* Marks whether the configuration has been initialized (including restoration from memory)
*/
@@ -35,5 +42,6 @@ export const initialGenerationConfigState: GenerationConfigState = {
parametersSchema: nanoBanana2Parameters,
isAspectRatioLocked: false,
activeAspectRatio: null,
+ uploadingImagePreviews: [],
isInit: false,
};
diff --git a/src/store/image/slices/generationConfig/selectors.ts b/src/store/image/slices/generationConfig/selectors.ts
index e1cb6ae4f5c..227bc8fdd1a 100644
--- a/src/store/image/slices/generationConfig/selectors.ts
+++ b/src/store/image/slices/generationConfig/selectors.ts
@@ -5,6 +5,7 @@ import { type GenerationConfigState } from './initialState';
export const model = (s: GenerationConfigState) => s.model;
export const provider = (s: GenerationConfigState) => s.provider;
export const imageNum = (s: GenerationConfigState) => s.imageNum;
+const uploadingImagePreviews = (s: GenerationConfigState) => s.uploadingImagePreviews;
const parameters = (s: GenerationConfigState) => s.parameters;
const parametersSchema = (s: GenerationConfigState) => s.parametersSchema;
@@ -22,4 +23,5 @@ export const imageGenerationConfigSelectors = {
isSupportedParam,
parameters,
parametersSchema,
+ uploadingImagePreviews,
};
diff --git a/src/store/video/slices/generationConfig/action.test.ts b/src/store/video/slices/generationConfig/action.test.ts
index cb241bdae59..540c3fb767b 100644
--- a/src/store/video/slices/generationConfig/action.test.ts
+++ b/src/store/video/slices/generationConfig/action.test.ts
@@ -107,3 +107,28 @@ describe('video generationConfig actions', () => {
expect(result.current.parameters?.duration).toBe(modelBDefaultValues.duration);
});
});
+
+describe('uploading image previews', () => {
+ it('should append and remove in-flight upload previews', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ useVideoStore.setState({ uploadingImagePreviews: [] });
+ });
+
+ act(() => {
+ result.current.addUploadingImagePreviews(['blob:a', 'blob:b']);
+ });
+ expect(result.current.uploadingImagePreviews).toEqual(['blob:a', 'blob:b']);
+
+ act(() => {
+ result.current.addUploadingImagePreviews(['blob:c']);
+ });
+ expect(result.current.uploadingImagePreviews).toEqual(['blob:a', 'blob:b', 'blob:c']);
+
+ act(() => {
+ result.current.removeUploadingImagePreviews(['blob:a', 'blob:c']);
+ });
+ expect(result.current.uploadingImagePreviews).toEqual(['blob:b']);
+ });
+});
diff --git a/src/store/video/slices/generationConfig/action.ts b/src/store/video/slices/generationConfig/action.ts
index d5e273da43f..72192fb87a7 100644
--- a/src/store/video/slices/generationConfig/action.ts
+++ b/src/store/video/slices/generationConfig/action.ts
@@ -147,6 +147,24 @@ export class GenerationConfigActionImpl {
`setParamOnInput/${paramName}`,
);
};
+
+ addUploadingImagePreviews = (urls: string[]): void => {
+ this.#set(
+ (state) => ({ uploadingImagePreviews: [...state.uploadingImagePreviews, ...urls] }),
+ false,
+ 'addUploadingImagePreviews',
+ );
+ };
+
+ removeUploadingImagePreviews = (urls: string[]): void => {
+ this.#set(
+ (state) => ({
+ uploadingImagePreviews: state.uploadingImagePreviews.filter((url) => !urls.includes(url)),
+ }),
+ false,
+ 'removeUploadingImagePreviews',
+ );
+ };
}
export type GenerationConfigAction = Pick<
diff --git a/src/store/video/slices/generationConfig/initialState.ts b/src/store/video/slices/generationConfig/initialState.ts
index 34f3fcc6862..475007484bd 100644
--- a/src/store/video/slices/generationConfig/initialState.ts
+++ b/src/store/video/slices/generationConfig/initialState.ts
@@ -49,6 +49,13 @@ export interface VideoGenerationConfigState {
provider: string;
model: string;
+ /**
+ * Object-URL previews for reference images currently being uploaded. Shared
+ * across the inline reference frames and the page-level drag-upload zone so
+ * both surfaces show the same in-flight loading placeholders.
+ */
+ uploadingImagePreviews: string[];
+
/**
* Marks whether the configuration has been initialized (including restoration from memory)
*/
@@ -63,5 +70,6 @@ export const initialGenerationConfigState: VideoGenerationConfigState = {
provider: DEFAULT_AI_VIDEO_PROVIDER,
parameters: DEFAULT_VIDEO_GENERATION_PARAMETERS,
parametersSchema: seedance20Params,
+ uploadingImagePreviews: [],
isInit: false,
};
diff --git a/src/store/video/slices/generationConfig/selectors.ts b/src/store/video/slices/generationConfig/selectors.ts
index 30cc311024d..2735b81a8c7 100644
--- a/src/store/video/slices/generationConfig/selectors.ts
+++ b/src/store/video/slices/generationConfig/selectors.ts
@@ -4,6 +4,7 @@ import { type VideoGenerationConfigState } from './initialState';
const model = (s: VideoGenerationConfigState) => s.model;
const provider = (s: VideoGenerationConfigState) => s.provider;
+const uploadingImagePreviews = (s: VideoGenerationConfigState) => s.uploadingImagePreviews;
const parameters = (s: VideoGenerationConfigState) => s.parameters;
const parametersSchema = (s: VideoGenerationConfigState) => s.parametersSchema;
@@ -20,4 +21,5 @@ export const videoGenerationConfigSelectors = {
parameters,
parametersSchema,
provider,
+ uploadingImagePreviews,
};