Files
live-hub-py/web/frontend/src/components/HuyaCollabHomeImageUploader.tsx
T

228 lines
8.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 新建协作单时的「主页截图」上传(先传 OSS 拿 object_key,随表单一起提交)。
*
* - 第一张就是封面(列表和详情都按第一张当封面);
* - 新建时还没落库,所以预览用的地址来自上传接口返回的 thumbnail_url / url;
* - 放进 `Form.Item name="home_images"`,值就是 object_key 数组;
* - 支持点击选择、拖拽,以及剪贴板里的截图直接 Ctrl/Cmd+V 粘贴。
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { Button, Image, Popconfirm, Space, Tag, Tooltip, Typography, Upload } from 'antd';
import { CloudUploadOutlined, DeleteOutlined, SwapOutlined } from '@ant-design/icons';
import { fileApi } from '../api/files';
import type { FileUploadResult } from '../api/types';
import { message } from '../utils/antdMessage';
import { getErrorMessage } from '../utils/error';
const { Text } = Typography;
const { Dragger } = Upload;
const ACCEPTED_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
const ACCEPT_ATTR = ACCEPTED_IMAGE_TYPES.join(',');
type Preview = Pick<FileUploadResult, 'url' | 'thumbnail_url'>;
/** 从剪贴板里取图片文件;items 拿不到时退回 files。 */
function clipboardImageFiles(data: DataTransfer | null): File[] {
if (!data) return [];
const fromItems: File[] = [];
for (const item of Array.from(data.items ?? [])) {
if (item.kind !== 'file' || !ACCEPTED_IMAGE_TYPES.includes(item.type)) continue;
const file = item.getAsFile();
if (file) fromItems.push(file);
}
if (fromItems.length > 0) return fromItems;
return Array.from(data.files ?? []).filter((file) =>
ACCEPTED_IMAGE_TYPES.includes(file.type),
);
}
export default function HuyaCollabHomeImageUploader({
value = [],
max = 20,
disabled,
optional = false,
onChange,
}: {
value?: string[];
max?: number;
disabled?: boolean;
/** 草稿建单:主页截图可以先空着 */
optional?: boolean;
onChange?: (value: string[]) => void;
}) {
const [busy, setBusy] = useState(false);
const [previews, setPreviews] = useState<Record<string, Preview>>({});
// 连传多张时每次都用"上一次的结果 + 新 key",不吃闭包里的旧 value(否则会互相覆盖)
const keysRef = useRef<string[]>(value ?? []);
useEffect(() => {
keysRef.current = value ?? [];
}, [value]);
const keys = value ?? [];
const full = keys.length >= max;
// 上传串行执行:多选/拖拽/一次粘贴多张时,封面顺序和用户选择顺序一致
const uploadQueue = useRef<Promise<void>>(Promise.resolve());
const enqueueUploads = useCallback(
(files: File[]) => {
const images = files.filter((file) => ACCEPTED_IMAGE_TYPES.includes(file.type));
if (images.length === 0) {
if (files.length > 0) message.warning('只支持 PNG / JPG / WebP 图片');
return;
}
if (images.length < files.length) {
message.warning('已忽略非 PNG / JPG / WebP 文件');
}
uploadQueue.current = uploadQueue.current.catch(() => {}).then(async () => {
const remaining = Math.max(0, max - keysRef.current.length);
if (remaining === 0) {
message.warning(`最多上传 ${max} 张主页截图`);
return;
}
const accepted = images.slice(0, remaining);
if (accepted.length < images.length) {
message.warning(`最多上传 ${max} 张,已忽略多余图片`);
}
setBusy(true);
try {
for (const file of accepted) {
try {
const uploaded = await fileApi.upload(file, 'collab');
setPreviews((prev) => ({
...prev,
[uploaded.object_key]: {
url: uploaded.url,
thumbnail_url: uploaded.thumbnail_url,
},
}));
const next = [...keysRef.current, uploaded.object_key];
keysRef.current = next;
onChange?.(next);
} catch (e: unknown) {
message.error(getErrorMessage(e));
}
}
} finally {
setBusy(false);
}
});
},
[max, onChange],
);
useEffect(() => {
if (disabled) return undefined;
const handlePaste = (event: ClipboardEvent) => {
const files = clipboardImageFiles(event.clipboardData);
if (files.length === 0) return;
event.preventDefault();
enqueueUploads(files);
};
window.addEventListener('paste', handlePaste);
return () => window.removeEventListener('paste', handlePaste);
}, [disabled, enqueueUploads]);
const remove = (key: string) => {
const next = keysRef.current.filter((item) => item !== key);
keysRef.current = next;
onChange?.(next);
};
const setCover = (key: string) => {
const next = [key, ...keysRef.current.filter((item) => item !== key)];
keysRef.current = next;
onChange?.(next);
};
return (
<Space direction="vertical" size={8} style={{ width: '100%' }}>
{keys.length === 0 ? (
<Text type="secondary">
{optional ? '还没有图(可稍后补,第一张作封面)' : '还没有图(必填:至少 1 张,第一张作封面)'}
</Text>
) : (
<Image.PreviewGroup
items={keys.map((key) => previews[key]?.url || `/api/files/object?key=${encodeURIComponent(key)}`)}
>
<Space wrap size={12}>
{keys.map((key, index) => (
<Space key={key} direction="vertical" size={2} align="center">
<div style={{ position: 'relative' }}>
<Image
src={
previews[key]?.thumbnail_url
|| previews[key]?.url
|| `/api/files/object?key=${encodeURIComponent(key)}&variant=thumb`
}
width={88}
height={88}
style={{ objectFit: 'cover', borderRadius: 4 }}
alt={`主页截图${index + 1}`}
/>
{index === 0 && (
<Tag color="blue" style={{ position: 'absolute', left: 0, top: 0, margin: 0 }}>
封面
</Tag>
)}
</div>
{!disabled && (
<Space size={2}>
{index !== 0 && (
<Tooltip title="设为封面">
<Button size="small" type="text" icon={<SwapOutlined />} onClick={() => setCover(key)} />
</Tooltip>
)}
<Popconfirm
title="去掉这张图?"
description="对象不会立刻删除,交给孤儿清理脚本"
onConfirm={() => remove(key)}
>
<Tooltip title="移除">
<Button size="small" type="text" danger icon={<DeleteOutlined />} />
</Tooltip>
</Popconfirm>
</Space>
)}
</Space>
))}
</Space>
</Image.PreviewGroup>
)}
{!disabled && (
<Dragger
className="huya-collab-home-drop"
accept={ACCEPT_ATTR}
multiple
showUploadList={false}
disabled={busy || full}
beforeUpload={(file, fileList) => {
// beforeUpload 会按文件逐个调用;只在第一批触发一次,保持选择顺序
if (file === fileList[0]) enqueueUploads(fileList as File[]);
return false;
}}
>
<Space direction="vertical" size={2}>
<CloudUploadOutlined style={{ fontSize: 22 }} />
<Text strong>
{full
? `最多 ${max} 张`
: busy
? '上传中…'
: '点击、拖拽或 Ctrl/Cmd+V 粘贴主页截图'}
</Text>
{!full && (
<Text type="secondary" style={{ fontSize: 12 }}>
支持多张图片,第一张作封面
</Text>
)}
</Space>
</Dragger>
)}
</Space>
);
}