|
@@ -0,0 +1,630 @@
|
|
|
|
|
+'use client';
|
|
|
|
|
+
|
|
|
|
|
+import React, { useRef, useState, useId } from 'react';
|
|
|
|
|
+import {
|
|
|
|
|
+ Upload,
|
|
|
|
|
+ X,
|
|
|
|
|
+ Loader2,
|
|
|
|
|
+ FileText,
|
|
|
|
|
+ ExternalLink,
|
|
|
|
|
+ FileCheck,
|
|
|
|
|
+ Link as LinkIcon,
|
|
|
|
|
+ File,
|
|
|
|
|
+ AlertCircle,
|
|
|
|
|
+ Eye
|
|
|
|
|
+} from 'lucide-react';
|
|
|
|
|
+import { toast } from 'react-hot-toast';
|
|
|
|
|
+import { storageService } from '@/lib/services/storageService';
|
|
|
|
|
+import { useLanguage } from '@/lib/i18n/LanguageContext';
|
|
|
|
|
+
|
|
|
|
|
+export interface FileUploadFieldProps {
|
|
|
|
|
+ label?: string;
|
|
|
|
|
+ value: string;
|
|
|
|
|
+ onChange: (url: string) => void;
|
|
|
|
|
+ prefix?: string;
|
|
|
|
|
+ maxSizeMB?: number;
|
|
|
|
|
+ helperText?: string;
|
|
|
|
|
+ accept?: string;
|
|
|
|
|
+ required?: boolean;
|
|
|
|
|
+ compact?: boolean;
|
|
|
|
|
+ disabled?: boolean;
|
|
|
|
|
+ className?: string;
|
|
|
|
|
+ onBeforeUpload?: () => Promise<boolean | void>;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 判断 URL 是否属于 PDF 文件
|
|
|
|
|
+ */
|
|
|
|
|
+export function isPdfUrl(url: string, keyName: string = ''): boolean {
|
|
|
|
|
+ if (!url) return false;
|
|
|
|
|
+ const clean = url.split('?')[0].toLowerCase();
|
|
|
|
|
+ return clean.endsWith('.pdf') || keyName.toLowerCase().includes('pdf');
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 判断 URL 是否属于图片
|
|
|
|
|
+ */
|
|
|
|
|
+export function isImageUrl(url: string): boolean {
|
|
|
|
|
+ if (!url) return false;
|
|
|
|
|
+ const clean = url.split('?')[0].toLowerCase();
|
|
|
|
|
+ return (
|
|
|
|
|
+ clean.endsWith('.png') ||
|
|
|
|
|
+ clean.endsWith('.jpg') ||
|
|
|
|
|
+ clean.endsWith('.jpeg') ||
|
|
|
|
|
+ clean.endsWith('.webp') ||
|
|
|
|
|
+ clean.endsWith('.gif') ||
|
|
|
|
|
+ clean.endsWith('.svg')
|
|
|
|
|
+ );
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 提取展示用文件名
|
|
|
|
|
+ */
|
|
|
|
|
+export function extractFileName(url: string, defaultName: string = 'Uploaded File'): string {
|
|
|
|
|
+ if (!url) return defaultName;
|
|
|
|
|
+ try {
|
|
|
|
|
+ const urlObj = new URL(url, 'https://dummy.base');
|
|
|
|
|
+ const key = urlObj.searchParams.get('key');
|
|
|
|
|
+ if (key) {
|
|
|
|
|
+ return key.split('/').pop() || defaultName;
|
|
|
|
|
+ }
|
|
|
|
|
+ const pathname = urlObj.pathname;
|
|
|
|
|
+ const parts = pathname.split('/').filter(Boolean);
|
|
|
|
|
+ if (parts.length > 0) {
|
|
|
|
|
+ return decodeURIComponent(parts[parts.length - 1]);
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ const parts = url.split('/');
|
|
|
|
|
+ if (parts.length > 0) {
|
|
|
|
|
+ return parts[parts.length - 1].split('?')[0];
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return defaultName;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 判断 Schema 属性是否代表文件上传项 (PDF, 文件, 图片等)
|
|
|
|
|
+ */
|
|
|
|
|
+export function isFileProperty(key: string, prop: any): boolean {
|
|
|
|
|
+ if (!prop || typeof prop !== 'object') return false;
|
|
|
|
|
+ // 1. 标准及常见 format / widget
|
|
|
|
|
+ if (prop.format === 'uri' || prop.format === 'data-url' || prop.format === 'file') return true;
|
|
|
|
|
+ if (prop['ui:widget'] === 'file' || prop['ui:widget'] === 'upload') return true;
|
|
|
|
|
+ if (prop.contentMediaType) return true;
|
|
|
|
|
+ // 2. 字段名规则 (以 _pdf, _file, _image 等结尾)
|
|
|
|
|
+ const lowerKey = key.toLowerCase();
|
|
|
|
|
+ if (
|
|
|
|
|
+ lowerKey.endsWith('_pdf') ||
|
|
|
|
|
+ lowerKey.endsWith('_file') ||
|
|
|
|
|
+ lowerKey.endsWith('_doc') ||
|
|
|
|
|
+ lowerKey.endsWith('_image') ||
|
|
|
|
|
+ lowerKey.endsWith('_img') ||
|
|
|
|
|
+ lowerKey.endsWith('_attachment') ||
|
|
|
|
|
+ lowerKey.endsWith('_voucher')
|
|
|
|
|
+ ) {
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ // 3. description 包含明确文件上传描述
|
|
|
|
|
+ if (typeof prop.description === 'string') {
|
|
|
|
|
+ const desc = prop.description.toLowerCase();
|
|
|
|
|
+ if (desc.includes('pdf') || desc.includes('download link') || desc.includes('file size')) {
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return false;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 根据字段特征推断文件选择类型
|
|
|
|
|
+ */
|
|
|
|
|
+export function inferAcceptType(key: string, prop: any): string {
|
|
|
|
|
+ const lowerKey = key.toLowerCase();
|
|
|
|
|
+ const desc = (prop?.description || '').toLowerCase();
|
|
|
|
|
+ const title = (prop?.title || '').toLowerCase();
|
|
|
|
|
+
|
|
|
|
|
+ if (prop?.contentMediaType) {
|
|
|
|
|
+ return prop.contentMediaType;
|
|
|
|
|
+ }
|
|
|
|
|
+ if (lowerKey.includes('pdf') || desc.includes('pdf') || title.includes('pdf')) {
|
|
|
|
|
+ return 'application/pdf,.pdf';
|
|
|
|
|
+ }
|
|
|
|
|
+ if (
|
|
|
|
|
+ lowerKey.includes('image') ||
|
|
|
|
|
+ lowerKey.includes('img') ||
|
|
|
|
|
+ lowerKey.includes('pic') ||
|
|
|
|
|
+ lowerKey.includes('photo') ||
|
|
|
|
|
+ desc.includes('image')
|
|
|
|
|
+ ) {
|
|
|
|
|
+ return 'image/png,image/jpeg,image/webp,image/gif';
|
|
|
|
|
+ }
|
|
|
|
|
+ return '.pdf,image/png,image/jpeg,image/webp,application/pdf';
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 多语言字典映射(支持全部 7 种系统官方语言)
|
|
|
|
|
+ */
|
|
|
|
|
+const I18N_MAP: Record<string, {
|
|
|
|
|
+ maxSize: (mb: number) => string;
|
|
|
|
|
+ pdfUploaded: string;
|
|
|
|
|
+ fileUploaded: string;
|
|
|
|
|
+ uploadFailed: string;
|
|
|
|
|
+ uploadFailedPrefix: string;
|
|
|
|
|
+ noUrlReturned: string;
|
|
|
|
|
+ switchToUpload: string;
|
|
|
|
|
+ manualHint: string;
|
|
|
|
|
+ viewDownload: string;
|
|
|
|
|
+ view: string;
|
|
|
|
|
+ replace: string;
|
|
|
|
|
+ remove: string;
|
|
|
|
|
+ dragOrClick: string;
|
|
|
|
|
+ defaultHelper: (mb: number) => string;
|
|
|
|
|
+ pasteLink: string;
|
|
|
|
|
+ uploading: string;
|
|
|
|
|
+ validating: string;
|
|
|
|
|
+ pdfBadge: string;
|
|
|
|
|
+ imageBadge: string;
|
|
|
|
|
+ fileBadge: string;
|
|
|
|
|
+ maxLabel: (mb: number) => string;
|
|
|
|
|
+ pastePlaceholder: string;
|
|
|
|
|
+}> = {
|
|
|
|
|
+ zh: {
|
|
|
|
|
+ maxSize: (mb) => `文件体积超出限制(最大允许 ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'PDF 文件上传成功',
|
|
|
|
|
+ fileUploaded: '文件已上传至云端存储',
|
|
|
|
|
+ uploadFailed: '文件上传失败,请检查网络后重试',
|
|
|
|
|
+ uploadFailedPrefix: '上传失败: ',
|
|
|
|
|
+ noUrlReturned: '未获取到返回的文件链接',
|
|
|
|
|
+ switchToUpload: '[ 切换上传 ]',
|
|
|
|
|
+ manualHint: '输入已托管的文件直链,或点击右侧切换为本地文件上传',
|
|
|
|
|
+ viewDownload: '[ 查看/下载 ]',
|
|
|
|
|
+ view: '[ 查看 ]',
|
|
|
|
|
+ replace: '[ 更换 ]',
|
|
|
|
|
+ remove: '[ 移除 ]',
|
|
|
|
|
+ dragOrClick: '[ 点击选择文件 或 拖拽至此处上传 ]',
|
|
|
|
|
+ defaultHelper: (mb) => `支持 PDF 及安全图片格式(单文件最大限制 ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ 或手动粘贴外部直接下载链接 ]',
|
|
|
|
|
+ uploading: '[ 正在上传至云端存储... ]',
|
|
|
|
|
+ validating: '正在校验文件格式并加密传输至存储桶...',
|
|
|
|
|
+ pdfBadge: 'PDF 档案',
|
|
|
|
|
+ imageBadge: '图片',
|
|
|
|
|
+ fileBadge: '文件',
|
|
|
|
|
+ maxLabel: (mb) => `[ 最大 ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... 或 /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ en: {
|
|
|
|
|
+ maxSize: (mb) => `File size exceeds the allowed limit (max ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'PDF document uploaded successfully',
|
|
|
|
|
+ fileUploaded: 'File uploaded successfully to cloud storage',
|
|
|
|
|
+ uploadFailed: 'File upload failed, please check network and retry',
|
|
|
|
|
+ uploadFailedPrefix: 'Upload failed: ',
|
|
|
|
|
+ noUrlReturned: 'No file URL returned from upload service',
|
|
|
|
|
+ switchToUpload: '[ Switch to Upload ]',
|
|
|
|
|
+ manualHint: 'Enter hosted file direct link, or click to switch to local file upload',
|
|
|
|
|
+ viewDownload: '[ View / Download ]',
|
|
|
|
|
+ view: '[ View ]',
|
|
|
|
|
+ replace: '[ Replace ]',
|
|
|
|
|
+ remove: '[ Remove ]',
|
|
|
|
|
+ dragOrClick: '[ Click to choose file or drag & drop here ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Supports PDF and safe image formats (max ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ Or paste external download link manually ]',
|
|
|
|
|
+ uploading: '[ UPLOADING TO SECURE STORAGE... ]',
|
|
|
|
|
+ validating: 'Validating format and streaming to storage bucket...',
|
|
|
|
|
+ pdfBadge: 'PDF DOSSIER',
|
|
|
|
|
+ imageBadge: 'IMAGE',
|
|
|
|
|
+ fileBadge: 'FILE',
|
|
|
|
|
+ maxLabel: (mb) => `[ MAX ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... or /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ de: {
|
|
|
|
|
+ maxSize: (mb) => `Dateigröße überschreitet das Limit (max. ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'PDF-Dokument erfolgreich hochgeladen',
|
|
|
|
|
+ fileUploaded: 'Datei erfolgreich in den Cloud-Speicher hochgeladen',
|
|
|
|
|
+ uploadFailed: 'Upload fehlgeschlagen, bitte erneut versuchen',
|
|
|
|
|
+ uploadFailedPrefix: 'Upload fehlgeschlagen: ',
|
|
|
|
|
+ noUrlReturned: 'Keine Datei-URL vom Speicherdienst zurückgegeben',
|
|
|
|
|
+ switchToUpload: '[ Zu Upload wechseln ]',
|
|
|
|
|
+ manualHint: 'Geben Sie die gehostete Datei-URL ein oder wechseln Sie zum lokalen Upload',
|
|
|
|
|
+ viewDownload: '[ Anzeigen / Herunterladen ]',
|
|
|
|
|
+ view: '[ Anzeigen ]',
|
|
|
|
|
+ replace: '[ Ersetzen ]',
|
|
|
|
|
+ remove: '[ Entfernen ]',
|
|
|
|
|
+ dragOrClick: '[ Datei auswählen oder hierher ziehen ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Unterstützt PDF und sichere Bildformate (max. ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ Oder externen Download-Link manuell einfügen ]',
|
|
|
|
|
+ uploading: '[ WIRD IN DEN SPEICHER HOCHGELADEN... ]',
|
|
|
|
|
+ validating: 'Format wird überprüft und sicher übertragen...',
|
|
|
|
|
+ pdfBadge: 'PDF-DOSSIER',
|
|
|
|
|
+ imageBadge: 'BILD',
|
|
|
|
|
+ fileBadge: 'DATEI',
|
|
|
|
|
+ maxLabel: (mb) => `[ MAX. ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... oder /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ fr: {
|
|
|
|
|
+ maxSize: (mb) => `La taille du fichier dépasse la limite (max. ${mb}Mo)`,
|
|
|
|
|
+ pdfUploaded: 'Document PDF téléversé avec succès',
|
|
|
|
|
+ fileUploaded: 'Fichier téléversé avec succès sur le stockage cloud',
|
|
|
|
|
+ uploadFailed: 'Échec du téléversement, veuillez réessayer',
|
|
|
|
|
+ uploadFailedPrefix: 'Échec du téléversement: ',
|
|
|
|
|
+ noUrlReturned: 'Aucune URL de fichier renvoyée',
|
|
|
|
|
+ switchToUpload: '[ Passer au téléversement ]',
|
|
|
|
|
+ manualHint: 'Entrez l\'URL directe hébergée ou cliquez pour téléverser un fichier local',
|
|
|
|
|
+ viewDownload: '[ Voir / Télécharger ]',
|
|
|
|
|
+ view: '[ Voir ]',
|
|
|
|
|
+ replace: '[ Remplacer ]',
|
|
|
|
|
+ remove: '[ Supprimer ]',
|
|
|
|
|
+ dragOrClick: '[ Cliquer pour choisir un fichier ou glisser-déposer ici ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Prend en charge les formats PDF et images sûrs (max. ${mb}Mo)`,
|
|
|
|
|
+ pasteLink: '[ Ou coller le lien de téléchargement direct ]',
|
|
|
|
|
+ uploading: '[ TÉLÉVERSEMENT VERS LE STOCKAGE EN COURS... ]',
|
|
|
|
|
+ validating: 'Validation du format et chiffrement en cours...',
|
|
|
|
|
+ pdfBadge: 'DOSSIER PDF',
|
|
|
|
|
+ imageBadge: 'IMAGE',
|
|
|
|
|
+ fileBadge: 'FICHIER',
|
|
|
|
|
+ maxLabel: (mb) => `[ MAX ${mb}Mo ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... ou /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ es: {
|
|
|
|
|
+ maxSize: (mb) => `El tamaño del archivo excede el límite (máx. ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'Documento PDF subido con éxito',
|
|
|
|
|
+ fileUploaded: 'Archivo subido con éxito al almacenamiento en la nube',
|
|
|
|
|
+ uploadFailed: 'Error al subir el archivo, inténtelo de nuevo',
|
|
|
|
|
+ uploadFailedPrefix: 'Error al subir: ',
|
|
|
|
|
+ noUrlReturned: 'No se devolvió la URL del archivo',
|
|
|
|
|
+ switchToUpload: '[ Cambiar a subir archivo ]',
|
|
|
|
|
+ manualHint: 'Ingrese el enlace directo o cambie a subida local',
|
|
|
|
|
+ viewDownload: '[ Ver / Descargar ]',
|
|
|
|
|
+ view: '[ Ver ]',
|
|
|
|
|
+ replace: '[ Reemplazar ]',
|
|
|
|
|
+ remove: '[ Eliminar ]',
|
|
|
|
|
+ dragOrClick: '[ Haga clic para seleccionar o arrastre el archivo aquí ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Admite formatos PDF e imágenes seguros (máx. ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ O pegue el enlace de descarga directamente ]',
|
|
|
|
|
+ uploading: '[ SUBIENDO AL ALMACENAMIENTO SEGURO... ]',
|
|
|
|
|
+ validating: 'Validando formato y transfiriendo de forma segura...',
|
|
|
|
|
+ pdfBadge: 'EXPEDIENTE PDF',
|
|
|
|
|
+ imageBadge: 'IMAGEN',
|
|
|
|
|
+ fileBadge: 'ARCHIVO',
|
|
|
|
|
+ maxLabel: (mb) => `[ MÁX ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... o /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ it: {
|
|
|
|
|
+ maxSize: (mb) => `La dimensione del file supera il limite (max. ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'Documento PDF caricato con successo',
|
|
|
|
|
+ fileUploaded: 'File caricato con successo nello spazio di archiviazione',
|
|
|
|
|
+ uploadFailed: 'Caricamento non riuscito, riprova',
|
|
|
|
|
+ uploadFailedPrefix: 'Caricamento non riuscito: ',
|
|
|
|
|
+ noUrlReturned: 'Nessun URL restituito dal servizio di archiviazione',
|
|
|
|
|
+ switchToUpload: '[ Passa al caricamento ]',
|
|
|
|
|
+ manualHint: 'Inserisci il link diretto o passa al caricamento locale',
|
|
|
|
|
+ viewDownload: '[ Visualizza / Scarica ]',
|
|
|
|
|
+ view: '[ Visualizza ]',
|
|
|
|
|
+ replace: '[ Sostituisci ]',
|
|
|
|
|
+ remove: '[ Rimuovi ]',
|
|
|
|
|
+ dragOrClick: '[ Fai clic per selezionare o trascina il file qui ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Supporta PDF e formati immagine sicuri (max. ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ O incolla manualmente il link di download ]',
|
|
|
|
|
+ uploading: '[ CARICAMENTO NELL\'ARCHIVIO IN CORSO... ]',
|
|
|
|
|
+ validating: 'Convalida del formato e trasferimento protetto in corso...',
|
|
|
|
|
+ pdfBadge: 'DOSSIER PDF',
|
|
|
|
|
+ imageBadge: 'IMMAGINE',
|
|
|
|
|
+ fileBadge: 'FILE',
|
|
|
|
|
+ maxLabel: (mb) => `[ MAX ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... o /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+ pt: {
|
|
|
|
|
+ maxSize: (mb) => `O tamanho do arquivo excede o limite (máx. ${mb}MB)`,
|
|
|
|
|
+ pdfUploaded: 'Documento PDF enviado com sucesso',
|
|
|
|
|
+ fileUploaded: 'Arquivo enviado com sucesso para o armazenamento em nuvem',
|
|
|
|
|
+ uploadFailed: 'Falha no envio do arquivo, tente novamente',
|
|
|
|
|
+ uploadFailedPrefix: 'Falha no envio: ',
|
|
|
|
|
+ noUrlReturned: 'Nenhum URL retornado pelo serviço de armazenamento',
|
|
|
|
|
+ switchToUpload: '[ Alternar para envio ]',
|
|
|
|
|
+ manualHint: 'Insira o link direto ou alterne para envio local',
|
|
|
|
|
+ viewDownload: '[ Ver / Baixar ]',
|
|
|
|
|
+ view: '[ Ver ]',
|
|
|
|
|
+ replace: '[ Substituir ]',
|
|
|
|
|
+ remove: '[ Remover ]',
|
|
|
|
|
+ dragOrClick: '[ Clique para selecionar ou arraste o arquivo para cá ]',
|
|
|
|
|
+ defaultHelper: (mb) => `Suporta PDF e formatos de imagem seguros (máx. ${mb}MB)`,
|
|
|
|
|
+ pasteLink: '[ Ou cole o link de download direto ]',
|
|
|
|
|
+ uploading: '[ ENVIANDO PARA O ARMAZENAMENTO SEGURO... ]',
|
|
|
|
|
+ validating: 'Validando formato e transferindo com segurança...',
|
|
|
|
|
+ pdfBadge: 'DOSSIÊ PDF',
|
|
|
|
|
+ imageBadge: 'IMAGEM',
|
|
|
|
|
+ fileBadge: 'ARQUIVO',
|
|
|
|
|
+ maxLabel: (mb) => `[ MÁX ${mb}MB ]`,
|
|
|
|
|
+ pastePlaceholder: 'https://... ou /api/r2/file?key=...',
|
|
|
|
|
+ },
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+export default function FileUploadField({
|
|
|
|
|
+ label,
|
|
|
|
|
+ value,
|
|
|
|
|
+ onChange,
|
|
|
|
|
+ prefix = 'uploads',
|
|
|
|
|
+ maxSizeMB = 1,
|
|
|
|
|
+ helperText,
|
|
|
|
|
+ accept = 'application/pdf,.pdf,image/png,image/jpeg,image/webp',
|
|
|
|
|
+ required = false,
|
|
|
|
|
+ compact = false,
|
|
|
|
|
+ disabled = false,
|
|
|
|
|
+ className = '',
|
|
|
|
|
+ onBeforeUpload,
|
|
|
|
|
+}: FileUploadFieldProps) {
|
|
|
|
|
+ const inputId = useId();
|
|
|
|
|
+ const fileInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
|
+ const [uploading, setUploading] = useState(false);
|
|
|
|
|
+ const [isDragOver, setIsDragOver] = useState(false);
|
|
|
|
|
+ const [manualInputMode, setManualInputMode] = useState(false);
|
|
|
|
|
+
|
|
|
|
|
+ // 获取当前环境语言,缺失则智能回退
|
|
|
|
|
+ let currentLang = 'zh';
|
|
|
|
|
+ try {
|
|
|
|
|
+ const langContext = useLanguage();
|
|
|
|
|
+ if (langContext?.lang) {
|
|
|
|
|
+ currentLang = langContext.lang;
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ // 兼容在非 LanguageProvider 上下文下使用
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const i18n = I18N_MAP[currentLang] || I18N_MAP.en;
|
|
|
|
|
+
|
|
|
|
|
+ const isPdf = isPdfUrl(value);
|
|
|
|
|
+ const isImg = isImageUrl(value);
|
|
|
|
|
+ const fileName = extractFileName(value, isPdf ? 'document.pdf' : 'uploaded_file');
|
|
|
|
|
+
|
|
|
|
|
+ const processUpload = async (file: File) => {
|
|
|
|
|
+ if (fileInputRef.current) {
|
|
|
|
|
+ fileInputRef.current.value = '';
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (file.size > maxSizeMB * 1024 * 1024) {
|
|
|
|
|
+ toast.error(i18n.maxSize(maxSizeMB));
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (onBeforeUpload) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ const canProceed = await onBeforeUpload();
|
|
|
|
|
+ if (canProceed === false) return;
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ console.warn('onBeforeUpload check failed:', e);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ setUploading(true);
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await storageService.upload(file, prefix);
|
|
|
|
|
+ if (!res?.url) {
|
|
|
|
|
+ throw new Error(i18n.noUrlReturned);
|
|
|
|
|
+ }
|
|
|
|
|
+ onChange(res.url);
|
|
|
|
|
+ toast.success(isPdfUrl(res.url) ? i18n.pdfUploaded : i18n.fileUploaded);
|
|
|
|
|
+ } catch (err: any) {
|
|
|
|
|
+ console.error('[File Upload Error]', err);
|
|
|
|
|
+ const msg = err.response?.data?.message || err.message || i18n.uploadFailed;
|
|
|
|
|
+ toast.error(`${i18n.uploadFailedPrefix}${msg}`);
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ setUploading(false);
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
|
|
|
+ const file = e.target.files?.[0];
|
|
|
|
|
+ if (file) {
|
|
|
|
|
+ processUpload(file);
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ const handleDragOver = (e: React.DragEvent) => {
|
|
|
|
|
+ e.preventDefault();
|
|
|
|
|
+ if (!disabled && !uploading) {
|
|
|
|
|
+ setIsDragOver(true);
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ const handleDragLeave = (e: React.DragEvent) => {
|
|
|
|
|
+ e.preventDefault();
|
|
|
|
|
+ setIsDragOver(false);
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ const handleDrop = (e: React.DragEvent) => {
|
|
|
|
|
+ e.preventDefault();
|
|
|
|
|
+ setIsDragOver(false);
|
|
|
|
|
+ if (disabled || uploading) return;
|
|
|
|
|
+ const file = e.dataTransfer.files?.[0];
|
|
|
|
|
+ if (file) {
|
|
|
|
|
+ processUpload(file);
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ const handleRemove = (e: React.MouseEvent) => {
|
|
|
|
|
+ e.stopPropagation();
|
|
|
|
|
+ onChange('');
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ return (
|
|
|
|
|
+ <div className={`space-y-1.5 font-mono ${className}`}>
|
|
|
|
|
+ {label && (
|
|
|
|
|
+ <label htmlFor={inputId} className="text-xs font-bold text-black uppercase block flex items-center justify-between">
|
|
|
|
|
+ <span>
|
|
|
|
|
+ {label}
|
|
|
|
|
+ {required && <span className="text-rose-600 font-bold ml-1">*</span>}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="text-[10px] text-neutral-500 font-normal">
|
|
|
|
|
+ {i18n.maxLabel(maxSizeMB)}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </label>
|
|
|
|
|
+ )}
|
|
|
|
|
+
|
|
|
|
|
+ {/* 原生隐藏 file input */}
|
|
|
|
|
+ <input
|
|
|
|
|
+ id={inputId}
|
|
|
|
|
+ type="file"
|
|
|
|
|
+ ref={fileInputRef}
|
|
|
|
|
+ onChange={handleFileSelect}
|
|
|
|
|
+ accept={accept}
|
|
|
|
|
+ disabled={disabled || uploading}
|
|
|
|
|
+ className="hidden"
|
|
|
|
|
+ />
|
|
|
|
|
+
|
|
|
|
|
+ {/* 状态 1: 手动输入 URL 模式 */}
|
|
|
|
|
+ {manualInputMode ? (
|
|
|
|
|
+ <div className="space-y-1.5">
|
|
|
|
|
+ <div className="flex gap-1.5">
|
|
|
|
|
+ <input
|
|
|
|
|
+ type="url"
|
|
|
|
|
+ value={value}
|
|
|
|
|
+ onChange={(e) => onChange(e.target.value)}
|
|
|
|
|
+ placeholder={i18n.pastePlaceholder}
|
|
|
|
|
+ className="flex-1 border-2 border-black bg-white p-2.5 text-xs text-black outline-none shadow-[2px_2px_0px_#000] focus:bg-amber-50"
|
|
|
|
|
+ />
|
|
|
|
|
+ <button
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ onClick={() => setManualInputMode(false)}
|
|
|
|
|
+ className="px-2.5 py-1 bg-neutral-200 hover:bg-neutral-300 border-2 border-black text-black text-xs font-bold uppercase shadow-[2px_2px_0px_#000]"
|
|
|
|
|
+ >
|
|
|
|
|
+ {i18n.switchToUpload}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <p className="text-[10px] text-neutral-500 font-sans">
|
|
|
|
|
+ {i18n.manualHint}
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ ) : value ? (
|
|
|
|
|
+ /* 状态 2: 已上传/已有文件展示 */
|
|
|
|
|
+ <div className="border-2 border-black bg-white p-3 shadow-[3px_3px_0px_#000] space-y-2.5">
|
|
|
|
|
+ <div className="flex items-start justify-between gap-3">
|
|
|
|
|
+ <div className="flex items-center gap-2.5 min-w-0">
|
|
|
|
|
+ {/* 文件图标徽标 */}
|
|
|
|
|
+ <div className={`w-10 h-10 border-2 border-black flex items-center justify-center shrink-0 shadow-[2px_2px_0px_#000] ${
|
|
|
|
|
+ isPdf ? 'bg-rose-100 text-rose-700' : isImg ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-800'
|
|
|
|
|
+ }`}>
|
|
|
|
|
+ {isPdf ? (
|
|
|
|
|
+ <FileText size={20} className="stroke-[2.2]" />
|
|
|
|
|
+ ) : isImg ? (
|
|
|
|
|
+ <FileCheck size={20} className="stroke-[2.2]" />
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <File size={20} className="stroke-[2.2]" />
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ <div className="min-w-0">
|
|
|
|
|
+ <div className="flex items-center gap-1.5 flex-wrap">
|
|
|
|
|
+ <span className={`px-1.5 py-0.2 border border-black text-[9px] font-black uppercase ${
|
|
|
|
|
+ isPdf ? 'bg-rose-300 text-black' : isImg ? 'bg-emerald-300 text-black' : 'bg-neutral-200 text-black'
|
|
|
|
|
+ }`}>
|
|
|
|
|
+ {isPdf ? i18n.pdfBadge : isImg ? i18n.imageBadge : i18n.fileBadge}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="text-xs font-bold text-black truncate max-w-[220px] sm:max-w-xs block" title={fileName}>
|
|
|
|
|
+ {fileName}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <p className="text-[10px] text-neutral-500 truncate max-w-[240px] sm:max-w-sm mt-0.5" title={value}>
|
|
|
|
|
+ {value}
|
|
|
|
|
+ </p>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {/* 操作按键区 */}
|
|
|
|
|
+ <div className="flex items-center gap-1.5 shrink-0">
|
|
|
|
|
+ <a
|
|
|
|
|
+ href={value}
|
|
|
|
|
+ target="_blank"
|
|
|
|
|
+ rel="noreferrer"
|
|
|
|
|
+ className="px-2 py-1 bg-white hover:bg-neutral-100 border-2 border-black text-black text-xs font-bold flex items-center gap-1 shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 transition"
|
|
|
|
|
+ title={i18n.viewDownload}
|
|
|
|
|
+ >
|
|
|
|
|
+ <ExternalLink size={12} />
|
|
|
|
|
+ <span className="hidden sm:inline">{i18n.viewDownload}</span>
|
|
|
|
|
+ <span className="sm:hidden">{i18n.view}</span>
|
|
|
|
|
+ </a>
|
|
|
|
|
+
|
|
|
|
|
+ <button
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ disabled={disabled || uploading}
|
|
|
|
|
+ onClick={() => fileInputRef.current?.click()}
|
|
|
|
|
+ className="px-2 py-1 bg-amber-300 hover:bg-amber-400 border-2 border-black text-black text-xs font-bold uppercase shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 transition disabled:opacity-50"
|
|
|
|
|
+ >
|
|
|
|
|
+ {i18n.replace}
|
|
|
|
|
+ </button>
|
|
|
|
|
+
|
|
|
|
|
+ <button
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ disabled={disabled || uploading}
|
|
|
|
|
+ onClick={handleRemove}
|
|
|
|
|
+ className="px-2 py-1 bg-rose-100 hover:bg-rose-200 border-2 border-black text-rose-800 text-xs font-bold uppercase shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 transition disabled:opacity-50"
|
|
|
|
|
+ >
|
|
|
|
|
+ {i18n.remove}
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {/* 如果是图片,可展开小缩略图 */}
|
|
|
|
|
+ {isImg && (
|
|
|
|
|
+ <div className="pt-2 border-t border-dashed border-neutral-300">
|
|
|
|
|
+ <img
|
|
|
|
|
+ src={value}
|
|
|
|
|
+ alt="Uploaded preview"
|
|
|
|
|
+ className="max-h-24 max-w-full object-contain border border-black bg-neutral-100 p-1"
|
|
|
|
|
+ />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ /* 状态 3: 未上传,拖拽与点击上传区域 */
|
|
|
|
|
+ <div
|
|
|
|
|
+ onDragOver={handleDragOver}
|
|
|
|
|
+ onDragLeave={handleDragLeave}
|
|
|
|
|
+ onDrop={handleDrop}
|
|
|
|
|
+ onClick={() => !disabled && !uploading && fileInputRef.current?.click()}
|
|
|
|
|
+ className={`border-2 border-dashed transition cursor-pointer flex flex-col items-center justify-center shadow-[2px_2px_0px_#000] select-none ${
|
|
|
|
|
+ isDragOver
|
|
|
|
|
+ ? 'border-black bg-amber-200 scale-[1.01]'
|
|
|
|
|
+ : 'border-black bg-neutral-50 hover:bg-amber-50/70'
|
|
|
|
|
+ } ${compact ? 'p-3' : 'p-5 sm:p-6'}`}
|
|
|
|
|
+ >
|
|
|
|
|
+ {uploading ? (
|
|
|
|
|
+ <div className="flex flex-col items-center gap-1.5 text-black">
|
|
|
|
|
+ <Loader2 size={22} className="animate-spin text-amber-500" />
|
|
|
|
|
+ <span className="text-xs font-black uppercase">
|
|
|
|
|
+ {i18n.uploading}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="text-[10px] text-neutral-500 font-sans">
|
|
|
|
|
+ {i18n.validating}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ ) : (
|
|
|
|
|
+ <div className="flex flex-col items-center gap-1.5 text-center">
|
|
|
|
|
+ <div className="w-9 h-9 border-2 border-black bg-white flex items-center justify-center shadow-[2px_2px_0px_#000] mb-0.5">
|
|
|
|
|
+ <Upload size={16} className="text-black" />
|
|
|
|
|
+ </div>
|
|
|
|
|
+ <div>
|
|
|
|
|
+ <span className="text-xs font-black text-black uppercase block">
|
|
|
|
|
+ {i18n.dragOrClick}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ <span className="text-[10px] text-neutral-500 block mt-0.5 font-sans">
|
|
|
|
|
+ {helperText || i18n.defaultHelper(maxSizeMB)}
|
|
|
|
|
+ </span>
|
|
|
|
|
+ </div>
|
|
|
|
|
+
|
|
|
|
|
+ {/* 手动输入直链切换按钮 */}
|
|
|
|
|
+ <button
|
|
|
|
|
+ type="button"
|
|
|
|
|
+ onClick={(e) => {
|
|
|
|
|
+ e.stopPropagation();
|
|
|
|
|
+ setManualInputMode(true);
|
|
|
|
|
+ }}
|
|
|
|
|
+ className="mt-1 text-[10px] text-neutral-600 hover:text-black underline font-mono flex items-center gap-1"
|
|
|
|
|
+ >
|
|
|
|
|
+ <LinkIcon size={10} />
|
|
|
|
|
+ <span>{i18n.pasteLink}</span>
|
|
|
|
|
+ </button>
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ )}
|
|
|
|
|
+ </div>
|
|
|
|
|
+ );
|
|
|
|
|
+}
|