Files
upload-gltf/components/UploadZone.tsx
T
2026-04-05 12:32:38 +02:00

468 lines
18 KiB
TypeScript

'use client'
import { useCallback, useRef, useState } from 'react'
import dynamic from 'next/dynamic'
const ModelViewer = dynamic(() => import('./ModelViewer'), { ssr: false })
type FileStatus = 'pending' | 'uploading' | 'success' | 'error'
interface TextureFile {
name: string
file: File
}
interface FolderEntry {
folderName: string
modelFile: File
textures: TextureFile[]
status: FileStatus
progress: number
error?: string
filename?: string
modelUrl?: string
viewerOpen?: boolean
warnings: string[]
}
const REQUIRED_TEXTURES = ['roughness', 'normal', 'metalness', 'color', 'displace']
const TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp']
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
function getTextureType(filename: string): string | null {
const name = filename.toLowerCase().replace(/\.[^.]+$/, '')
if (REQUIRED_TEXTURES.includes(name)) return name
return null
}
function validateFolder(files: File[]): { model?: File; textures: TextureFile[]; errors: string[]; warnings: string[] } {
const result: { model?: File; textures: TextureFile[]; errors: string[]; warnings: string[] } = {
textures: [],
errors: [],
warnings: []
}
const modelFiles = files.filter(f => {
const name = f.name.toLowerCase()
return name === 'model.glb' || name === 'model.gltf'
})
if (modelFiles.length === 0) {
result.errors.push('model.glb ou model.gltf manquant (obligatoire)')
} else {
result.model = modelFiles[0]
}
const textureFiles = files.filter(f => {
const ext = f.name.slice(f.name.lastIndexOf('.')).toLowerCase()
return TEXTURE_EXTENSIONS.includes(ext) && getTextureType(f.name) !== null
})
for (const tf of textureFiles) {
result.textures.push({ name: tf.name, file: tf })
}
const foundTextures = new Set(result.textures.map(t => t.name.toLowerCase().replace(/\.[^.]+$/, '')))
for (const req of REQUIRED_TEXTURES) {
if (!foundTextures.has(req)) {
result.warnings.push(`${req}.webp/png/jpg manquant`)
}
}
return result
}
function uploadFolder(
folder: FolderEntry,
secret: string,
onProgress: (pct: number) => void,
xhrRef: { current: XMLHttpRequest | null }
): Promise<{ success: boolean; filename?: string; error?: string }> {
return new Promise((resolve) => {
const totalFiles = 1 + folder.textures.length
let completed = 0
const checkDone = () => {
completed++
onProgress(Math.round((completed / totalFiles) * 100))
if (completed >= totalFiles) {
resolve({ success: true, filename: folder.folderName })
}
}
const formData = new FormData()
formData.append('folderName', folder.folderName)
formData.append('file', folder.modelFile)
formData.append('fileType', 'model')
for (const tex of folder.textures) {
const texForm = new FormData()
texForm.append('folderName', folder.folderName)
texForm.append('file', tex.file)
texForm.append('fileType', 'texture')
texForm.append('textureName', tex.name)
const xhr = new XMLHttpRequest()
xhrRef.current = xhr
xhr.onload = () => {
try {
const res = JSON.parse(xhr.responseText)
if (!res.success) {
resolve({ success: false, error: `Texture ${tex.name} : ${res.error}` })
} else {
checkDone()
}
} catch {
checkDone()
}
}
xhr.onerror = () => resolve({ success: false, error: `Erreur réseau: ${tex.name}` })
xhr.open('POST', '/api/upload')
xhr.setRequestHeader('x-upload-secret', secret.trim())
xhr.send(texForm)
}
const modelXhr = new XMLHttpRequest()
xhrRef.current = modelXhr
modelXhr.onload = () => {
try {
const res = JSON.parse(modelXhr.responseText)
if (!res.success) {
resolve({ success: false, error: res.error })
} else {
checkDone()
}
} catch {
checkDone()
}
}
modelXhr.onerror = () => resolve({ success: false, error: 'Erreur réseau: model' })
modelXhr.open('POST', '/api/upload')
modelXhr.setRequestHeader('x-upload-secret', secret.trim())
modelXhr.send(formData)
})
}
export default function UploadZone() {
const [files, setFiles] = useState<FolderEntry[]>([])
const [isUploading, setIsUploading] = useState(false)
const [secret, setSecret] = useState('')
const [secretVisible, setSecretVisible] = useState(false)
const [globalError, setGlobalError] = useState<string | null>(null)
const xhrRef = useRef<XMLHttpRequest | null>(null)
const updateFile = (index: number, patch: Partial<FolderEntry>) => {
setFiles((prev) => prev.map((f, i) => i === index ? { ...f, ...patch } : f))
}
const handleUpload = useCallback(async () => {
if (!secret.trim()) {
setGlobalError('Veuillez entrer la clé d\'accès avant d\'uploader.')
return
}
if (files.length === 0) return
setIsUploading(true)
setGlobalError(null)
for (let i = 0; i < files.length; i++) {
if (files[i].status === 'success') continue
updateFile(i, { status: 'uploading', progress: 0, error: undefined })
const result = await uploadFolder(
files[i],
secret,
(pct) => updateFile(i, { progress: pct }),
xhrRef
)
updateFile(i, {
status: result.success ? 'success' : 'error',
progress: result.success ? 100 : 0,
error: result.success ? undefined : result.error,
filename: result.filename,
})
}
setIsUploading(false)
}, [files, secret])
const handleCancel = () => { xhrRef.current?.abort() }
const removeFile = (index: number) => {
const file = files[index]
if (file.modelUrl) URL.revokeObjectURL(file.modelUrl)
setFiles((prev) => prev.filter((_, i) => i !== index))
}
const handleReset = () => {
files.forEach((f) => {
if (f.modelUrl) URL.revokeObjectURL(f.modelUrl)
})
setFiles([])
setGlobalError(null)
setIsUploading(false)
}
const allDone = files.length > 0 && files.every((f) => f.status === 'success')
const hasErrors = files.some((f) => f.status === 'error')
return (
<div className="w-full max-w-2xl space-y-4">
<div className="space-y-1.5">
<label className="block text-sm font-medium text-gray-300">Access Key</label>
<div className="relative">
<input
type={secretVisible ? 'text' : 'password'}
value={secret}
onChange={(e) => setSecret(e.target.value)}
placeholder="Enter secret key..."
disabled={isUploading}
className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5 pr-12
text-gray-100 placeholder-gray-500 text-sm
focus:outline-none focus:ring-2 focus:ring-white/50 focus:border-white/50
disabled:opacity-50 disabled:cursor-not-allowed transition"
/>
<button
type="button"
onClick={() => setSecretVisible((v) => !v)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300 transition"
tabIndex={-1}
>
{secretVisible ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
</div>
</div>
<input
type="file"
id="folder-input"
{...({ webkitdirectory: '', directory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
multiple
className="hidden"
onChange={(e) => {
const files = e.target.files
if (files && files.length > 0) {
const fileArray = Array.from(files)
const folderName = fileArray[0].webkitRelativePath?.split('/')[0] || 'folder'
const validation = validateFolder(fileArray)
if (validation.errors.length > 0) {
setGlobalError(validation.errors.join(' | '))
return
}
setGlobalError(null)
const entry: FolderEntry = {
folderName,
modelFile: validation.model!,
textures: validation.textures,
status: 'pending',
progress: 0,
warnings: validation.warnings,
modelUrl: URL.createObjectURL(validation.model!),
viewerOpen: true,
}
setFiles([entry])
}
}}
/>
{files.length === 0 && (
<div
onClick={() => document.getElementById('folder-input')?.click()}
className={`
relative border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-all duration-200 bg-black-800
${isUploading ? 'cursor-not-allowed opacity-60 border-white/20' : ''}
${!isUploading ? 'border-white/30 hover:border-white/50 hover:bg-black-700' : ''}
`}
>
<div className="flex justify-center mb-3">
<div className="w-12 h-12 rounded-full flex items-center justify-center bg-black-700">
<svg className="w-6 h-6 text-gray-400"
fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round"
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
</svg>
</div>
</div>
<p className="text-sm font-medium text-gray-300">
Drop ton dossier ici
<span className="text-gray-500 font-normal"> ou click pour parcourir</span>
</p>
<p className="text-xs text-gray-500 mt-1">
Contient: model.glb/gltf + textures (roughness, normal, metalness, color, displace)
</p>
</div>
)}
{globalError && (
<p className="text-xs text-red-400 text-center">{globalError}</p>
)}
{files.length > 0 && (
<div className="space-y-2">
{files.map((entry, i) => (
<div key={i}>
<div className="flex items-center gap-3 bg-black-800 border border-white/20 rounded-xl px-4 py-3">
<div className="shrink-0">
{entry.status === 'success' ? (
<div className="w-8 h-8 rounded-full bg-green-900/30 flex items-center justify-center">
<svg className="w-4 h-4 text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
</div>
) : entry.status === 'error' ? (
<div className="w-8 h-8 rounded-full bg-red-900/30 flex items-center justify-center">
<svg className="w-4 h-4 text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
) : entry.status === 'uploading' ? (
<div className="w-8 h-8 rounded-full bg-gray-700 flex items-center justify-center">
<svg className="w-4 h-4 text-gray-300 animate-spin" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
</div>
) : (
<button
onClick={() => entry.modelUrl ? updateFile(i, { viewerOpen: !entry.viewerOpen }) : null}
className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition ${
entry.modelUrl ? 'bg-black-700 hover:bg-gray-700 cursor-pointer' : 'bg-black-700 cursor-default'
}`}
>
<svg
className={`w-4 h-4 text-gray-500 transition-transform ${entry.viewerOpen ? 'rotate-180' : ''}`}
fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}
>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</button>
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-200 font-mono truncate">{entry.folderName}/</span>
<span className="shrink-0 text-xs px-1.5 py-0.5 rounded-full bg-gray-700 text-gray-300">Folder</span>
</div>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-gray-500">model: {entry.modelFile.name}</span>
{entry.status === 'error' && entry.error && (
<span className="text-xs text-red-400 truncate">{entry.error}</span>
)}
{entry.status === 'success' && entry.filename && (
<span className="text-xs text-green-400 font-mono">{entry.filename}</span>
)}
</div>
{entry.status === 'uploading' && (
<div className="mt-1.5 w-full h-1 bg-black-700 rounded-full overflow-hidden">
<div
className="h-full bg-gray-400 rounded-full transition-all duration-200"
style={{ width: `${entry.progress}%` }}
/>
</div>
)}
</div>
{entry.status !== 'uploading' && (
<button
onClick={() => removeFile(i)}
className="shrink-0 text-gray-600 hover:text-red-400 transition"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
{entry.warnings.length > 0 && entry.status !== 'success' && (
<div className="mt-2 px-3 py-2 bg-yellow-900/20 border border-yellow-700/30 rounded-lg">
<div className="flex items-center gap-2 text-xs text-yellow-400">
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<span>Textures manquantes: {entry.warnings.join(', ')}</span>
</div>
</div>
)}
{entry.modelUrl && entry.status !== 'success' && (
<div
className={`transition-all duration-300 ease-in-out ${
entry.viewerOpen ? 'max-h-[500px] opacity-100 mt-2' : 'max-h-0 opacity-0'
}`}
>
<ModelViewer
url={entry.modelUrl}
filename={entry.modelFile.name}
size={formatBytes(entry.modelFile.size)}
/>
</div>
)}
</div>
))}
</div>
)}
<div className="flex gap-3">
{!isUploading && files.some((f) => f.status === 'pending' || f.status === 'error') && (
<button
onClick={handleUpload}
className="flex-1 bg-white text-black font-medium text-sm
py-2.5 px-6 rounded-xl transition-all duration-150
hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-white/50 border border-white/20"
style={{ color: '#000000' }}
>
Upload & Push to Git
</button>
)}
{isUploading && (
<button
onClick={handleCancel}
className="flex-1 bg-black-700 text-gray-300 font-medium text-sm
py-2.5 px-6 rounded-xl border border-black-600 transition-colors duration-150
hover:bg-black-600"
>
Cancel
</button>
)}
{(allDone || hasErrors) && !isUploading && (
<button
onClick={handleReset}
className="flex-1 bg-black-700 text-gray-300 font-medium text-sm
py-2.5 px-6 rounded-xl border border-black-600 transition-colors duration-150
hover:bg-black-600"
>
{allDone ? 'Clear All' : 'Retry'}
</button>
)}
</div>
</div>
)
}