Files

127 lines
10 KiB
TypeScript
Raw Permalink Normal View History

'use client';
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
import { Download, FileText, LoaderCircle, Paperclip, RotateCw, X } from 'lucide-react';
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, formatFileSize, type Attachment } from '@/lib/attachments';
import { appPath } from '@/lib/base-path';
export function AttachmentList({ files }: { files: Attachment[] }) {
if (!files.length) return <p className="review-meta">暂无附件</p>;
return <ul className="attachment-list">{files.map(file => <li key={file.id}>
<FileText size={18} aria-hidden="true"/>
<div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div>
<a className="icon-button" href={appPath(`/api/attachments/${file.id}`)} download={file.name} aria-label={`下载 ${file.name}`}><Download size={17}/></a>
</li>)}</ul>;
}
export function AttachmentPicker({ files, onChange, disabled, uploading, onUploadingChange, onNewUpload, inputRef, compact = false }: {
inputRef?: RefObject<HTMLInputElement | null>; compact?: boolean;
files: Attachment[]; onChange: (files: Attachment[]) => void; disabled: boolean; uploading: boolean;
onUploadingChange: (busy: boolean) => void; onNewUpload: (file: Attachment) => void;
}) {
const localInput = useRef<HTMLInputElement>(null);
const input = inputRef ?? localInput;
const inFlight = useRef(false);
const [errors, setErrors] = useState<string[]>([]);
const [progress, setProgress] = useState('');
const [recoverable, setRecoverable] = useState<Attachment[]>([]);
const [recoveryLoading, setRecoveryLoading] = useState(true);
const [recoveryError, setRecoveryError] = useState('');
const [recoveryOpen, setRecoveryOpen] = useState(false);
const recoveryRequest = useRef<AbortController | null>(null);
const loadRecovery = useCallback(() => {
recoveryRequest.current?.abort();
const controller = new AbortController();
recoveryRequest.current = controller;
const timeout = setTimeout(() => controller.abort(), 15000);
return fetch(appPath('/api/attachments'), { signal: controller.signal, cache: 'no-store' })
.then(async response => {
const result = await response.json().catch(() => null) as { attachments?: Attachment[]; error?: string } | null;
if (!response.ok || !Array.isArray(result?.attachments)) throw new Error(result?.error || '未能加载未保存附件,请重试。');
return result.attachments;
})
.then(attachments => { if (recoveryRequest.current === controller) setRecoverable(attachments); })
.catch(error => {
// Superseded requests and unmounted pickers must not replace the latest result.
if (recoveryRequest.current === controller) setRecoveryError(controller.signal.aborted ? '未保存附件加载超时,请重试。' : error instanceof Error ? error.message : '未能加载未保存附件,请重试。');
})
.finally(() => {
clearTimeout(timeout);
if (recoveryRequest.current === controller) { recoveryRequest.current = null; setRecoveryLoading(false); }
});
}, []);
function refreshRecovery() { setRecoveryLoading(true); setRecoveryError(''); void loadRecovery(); }
useEffect(() => {
void loadRecovery();
return () => { recoveryRequest.current?.abort(); recoveryRequest.current = null; };
}, [loadRecovery]);
const available = recoverable.filter(file => !files.some(selected => selected.id === file.id));
async function discard(file: Attachment) {
onUploadingChange(true);
try {
const response = await fetch(appPath('/api/attachments/' + file.id), { method: 'DELETE' });
if (!response.ok) throw new Error('该附件可能已保存,请刷新后核对。');
setRecoverable(previous => previous.filter(item => item.id !== file.id));
} catch (error) { setErrors([error instanceof Error ? error.message : '附件移除失败,请重试。']); }
finally { onUploadingChange(false); }
}
async function upload(selected: File[]) {
if (!selected.length || inFlight.current || disabled) return;
const issues: string[] = [];
const allowed: File[] = [];
for (const file of selected) {
if (!file.size) issues.push(`${file.name}:空文件无法上传。`);
else if (file.size > MAX_ATTACHMENT_BYTES) issues.push(`${file.name}:超过 20 MB,请压缩后重新选择。`);
else if (files.length + allowed.length >= MAX_ATTACHMENTS) issues.push(`${file.name}:每条需求最多 10 个附件。`);
else allowed.push(file);
}
setErrors(issues);
if (!allowed.length) return;
inFlight.current = true;
onUploadingChange(true);
const uploaded = [...files];
try {
for (let index = 0; index < allowed.length; index++) {
const file = allowed[index];
setProgress(`正在上传 ${index + 1}/${allowed.length}:${file.name}`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 120000);
let quotaReached = false;
try {
const body = new FormData(); body.append('file', file);
const response = await fetch(appPath('/api/attachments'), { method: 'POST', body, signal: controller.signal });
const result = await response.json().catch(() => ({})) as { error?: string; attachment?: Attachment };
if (response.status === 409) { quotaReached = true; setRecoveryOpen(true); refreshRecovery(); }
if (!response.ok || !result.attachment) throw new Error(result.error || '上传失败,请重新选择此文件重试。');
uploaded.push(result.attachment);
onNewUpload(result.attachment);
onChange([...uploaded]);
} catch (error) {
issues.push(`${file.name}:${controller.signal.aborted ? '上传超时,请重新选择此文件重试。' : error instanceof Error ? error.message : '上传失败,请重新选择重试。'}`);
if (quotaReached && index < allowed.length - 1) issues.push('本批剩余文件尚未上传,请先选用或清理未保存附件,再重新选择文件。');
setErrors([...issues]);
} finally { clearTimeout(timeout); }
if (quotaReached) break;
}
} finally { inFlight.current = false; onUploadingChange(false); setProgress(''); }
}
return <div className="attachment-picker span-two">
{!compact && <div className="attachment-heading"><span>文件附件</span><small>{files.length}/{MAX_ATTACHMENTS}</small></div>}
<p className="attachment-help" id="attachment-help">可上传文档、图片等参考材料,每个文件不超过 20 MB,最多 10 个。保存需求后生效。</p>
<input ref={input} className="attachment-input" type="file" multiple aria-label="选择文件附件" aria-describedby="attachment-help" disabled={disabled || uploading} onChange={event => { const selected = Array.from(event.currentTarget.files ?? []); event.currentTarget.value = ''; void upload(selected); }}/>
{!compact && <button className="btn" type="button" disabled={disabled || uploading || files.length >= MAX_ATTACHMENTS} onClick={() => input.current?.click()}><Paperclip size={16}/>{uploading ? '正在上传…' : '上传附件'}</button>}
{progress && <p className="attachment-progress" role="status"><LoaderCircle size={16} className="attachment-spinner"/>{progress}</p>}
{errors.length > 0 && <div className="error-banner attachment-errors" role="alert"><ul>{errors.map((message, index) => <li key={index}>{message}</li>)}</ul></div>}
{files.length > 0 && <ul className="attachment-list">{files.map(file => <li key={file.id}>
<FileText size={18} aria-hidden="true"/>
<div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div>
<button className="icon-button" type="button" disabled={disabled || uploading} aria-label={`移除 ${file.name}`} onClick={() => { onChange(files.filter(item => item.id !== file.id)); setRecoverable(previous => previous.filter(item => item.id !== file.id)); setErrors([]); }}><X size={17}/></button>
</li>)}</ul>}
<div className="attachment-recovery-controls">
{recoveryLoading ? <p className="attachment-help" role="status">正在读取未保存附件…</p> : recoveryError ? <div className="error-banner attachment-errors" role="alert"><span>未保存附件列表加载失败:{recoveryError}</span><button className="btn" type="button" disabled={disabled || uploading} onClick={refreshRecovery}><RotateCw size={15}/>重新加载未保存附件</button></div> : <button className="text-button" type="button" disabled={disabled || uploading} onClick={refreshRecovery}><RotateCw size={14}/>刷新未保存附件</button>}
</div>
{available.length > 0 && <details className="attachment-recovery" open={recoveryOpen} onToggle={event => setRecoveryOpen(event.currentTarget.open)}><summary>找回未保存的附件({available.length})</summary><p className="attachment-help">此前已上传但尚未保存到需求的文件,24 小时内可选用。选用后移除或取消编辑会保留原文件;“清理”会删除文件,请核对其他窗口是否仍在使用。</p><ul className="attachment-list">{available.map(file => <li key={file.id}><div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div><button className="btn" type="button" disabled={disabled || uploading || files.length >= MAX_ATTACHMENTS} aria-label={`选用 ${file.name}`} onClick={() => onChange([...files, file])}>选用</button><button className="icon-button" type="button" disabled={disabled || uploading} aria-label={`清理未保存附件 ${file.name}`} onClick={() => void discard(file)}><X size={17}/></button></li>)}</ul></details>}
<p className="attachment-help">{compact ? '文档链接可在下方填写。' : '链接可继续填写在上方。'}修改已有附件后需保存;历史评审引用的文件仍会保留。</p>
</div>;
}