fix: issue on viewer
This commit is contained in:
+36
-71
@@ -1,23 +1,17 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { writeFileSync, mkdirSync } from 'fs'
|
||||
import { writeFileSync, mkdirSync, existsSync, rmSync } from 'fs'
|
||||
import { join, extname, basename } from 'path'
|
||||
import { execSync } from 'child_process'
|
||||
|
||||
// Forcer le runtime Node.js (nécessaire pour fs, child_process)
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
// Formats autorisés par type
|
||||
const MODEL_EXTENSIONS = new Set(['.glb', '.gltf', '.fbx'])
|
||||
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.ktx2'])
|
||||
const MODEL_EXTENSIONS = new Set(['.glb', '.gltf'])
|
||||
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp'])
|
||||
const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS])
|
||||
|
||||
const MODELS_DIR = join(process.cwd(), 'public', 'models')
|
||||
const TEXTURES_DIR = join(process.cwd(), 'public', 'textures')
|
||||
const ASSETS_DIR = join(process.cwd(), 'public', 'assets')
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// Utilitaire : sanitiser le nom de fichier
|
||||
// ─────────────────────────────────────────────
|
||||
function sanitizeFilename(name: string): string {
|
||||
return basename(name)
|
||||
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
||||
@@ -25,35 +19,33 @@ function sanitizeFilename(name: string): string {
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// Utilitaire : parser le multipart via req.formData()
|
||||
// Retourne { filename, savedPath } ou throw
|
||||
// ─────────────────────────────────────────────
|
||||
async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string }> {
|
||||
async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string; folderName: string }> {
|
||||
const formData = await req.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
const assetName = (formData.get('assetName') as string | null)?.trim()
|
||||
const folderName = (formData.get('folderName') as string | null)?.trim() || 'assets'
|
||||
const fileType = formData.get('fileType') as string | null
|
||||
const textureName = formData.get('textureName') as string | null
|
||||
|
||||
if (!file || file.size === 0) {
|
||||
throw new Error('Aucun fichier reçu dans la requête')
|
||||
throw new Error('Aucun fichier reçu')
|
||||
}
|
||||
|
||||
const originalSafe = sanitizeFilename(file.name)
|
||||
const ext = extname(originalSafe).toLowerCase()
|
||||
|
||||
if (!ALL_ALLOWED_EXTENSIONS.has(ext)) {
|
||||
throw new Error(`Extension non autorisée : "${ext}". Formats acceptés : .glb, .gltf, .fbx, .png, .jpg, .jpeg, .webp, .ktx2`)
|
||||
throw new Error(`Extension non autorisée: "${ext}"`)
|
||||
}
|
||||
|
||||
// Renommer avec le nom fourni par le designer si disponible
|
||||
const baseName = assetName
|
||||
? sanitizeFilename(assetName).replace(/\.[^.]+$/, '') // retirer extension si présente
|
||||
: originalSafe.replace(/\.[^.]+$/, '')
|
||||
const filename = `${baseName}${ext}`
|
||||
const safeFolderName = sanitizeFilename(folderName).replace(/[^a-zA-Z0-9-_]/g, '-')
|
||||
const destDir = join(ASSETS_DIR, safeFolderName)
|
||||
|
||||
const isTexture = TEXTURE_EXTENSIONS.has(ext)
|
||||
const destDir = isTexture ? TEXTURES_DIR : MODELS_DIR
|
||||
const relPath = join('public', isTexture ? 'textures' : 'models', filename)
|
||||
let filename: string
|
||||
if (fileType === 'texture' && textureName) {
|
||||
filename = sanitizeFilename(textureName)
|
||||
} else {
|
||||
filename = originalSafe
|
||||
}
|
||||
|
||||
mkdirSync(destDir, { recursive: true })
|
||||
|
||||
@@ -61,20 +53,19 @@ async function parseUpload(req: NextRequest): Promise<{ filename: string; savedP
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
writeFileSync(savedPath, buffer)
|
||||
|
||||
return { filename, savedPath, relPath }
|
||||
const relPath = join('public', 'assets', safeFolderName, filename)
|
||||
|
||||
return { filename, savedPath, relPath, folderName: safeFolderName }
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// Utilitaire : exécuter la séquence git
|
||||
// ─────────────────────────────────────────────
|
||||
function runGitPush(filename: string, relPath: string): { output: string } {
|
||||
function runGitPush(folderName: string): { output: string } {
|
||||
const branch = process.env.GIT_BRANCH ?? 'main'
|
||||
const repoUrl = process.env.GIT_REPO_URL
|
||||
|
||||
const execOpts = {
|
||||
cwd: process.cwd(),
|
||||
encoding: 'utf-8' as const,
|
||||
timeout: 60_000,
|
||||
timeout: 120_000,
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_SSH_COMMAND: 'ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/root/.ssh/known_hosts',
|
||||
@@ -85,18 +76,13 @@ function runGitPush(filename: string, relPath: string): { output: string } {
|
||||
},
|
||||
}
|
||||
|
||||
// S'assurer que le repo est initialisé et que le remote est configuré
|
||||
try {
|
||||
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
|
||||
} catch {
|
||||
// Pas encore de repo git — initialiser
|
||||
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
|
||||
|
||||
if (repoUrl) {
|
||||
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||
}
|
||||
|
||||
// Récupérer l'historique distant si possible
|
||||
try {
|
||||
execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 })
|
||||
execSync(`git checkout -b ${branch} --track origin/${branch}`, { ...execOpts, stdio: 'pipe' })
|
||||
@@ -105,25 +91,23 @@ function runGitPush(filename: string, relPath: string): { output: string } {
|
||||
}
|
||||
}
|
||||
|
||||
// Mettre à jour l'URL du remote avec le token (au cas où elle aurait changé)
|
||||
if (repoUrl) {
|
||||
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString()
|
||||
|
||||
let output = ''
|
||||
|
||||
// Sync avec le remote avant de committer
|
||||
output += execSync(`git fetch origin ${branch}`, execOpts)
|
||||
output += execSync(`git reset --hard origin/${branch}`, execOpts)
|
||||
|
||||
// git add
|
||||
output += execSync(`git add "${relPath}"`, execOpts)
|
||||
const folderPath = join('public', 'assets', folderName)
|
||||
if (existsSync(folderPath)) {
|
||||
output += execSync(`git add "${folderPath}"`, execOpts)
|
||||
}
|
||||
|
||||
// git commit — ignoré si rien à committer (fichier identique)
|
||||
try {
|
||||
output += execSync(`git commit -m "Design Update: ${filename} [${timestamp}]"`, execOpts)
|
||||
output += execSync(`git commit -m "Design Update: ${folderName} [${timestamp}]"`, execOpts)
|
||||
} catch (err) {
|
||||
const msg = [
|
||||
err instanceof Error ? err.message : '',
|
||||
@@ -133,25 +117,19 @@ function runGitPush(filename: string, relPath: string): { output: string } {
|
||||
if (!msg.includes('nothing to commit') && !msg.includes('nothing added to commit')) {
|
||||
throw err
|
||||
}
|
||||
output += '[rien à committer — fichier identique]\n'
|
||||
output += '[rien à committer]\n'
|
||||
}
|
||||
|
||||
// git push
|
||||
output += execSync(`git push origin ${branch}`, execOpts)
|
||||
|
||||
return { output }
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// POST /api/upload
|
||||
// ─────────────────────────────────────────────
|
||||
export async function POST(req: NextRequest) {
|
||||
// 1. Authentification
|
||||
const secret = req.headers.get('x-upload-secret')
|
||||
const expectedSecret = process.env.UPLOAD_SECRET_KEY
|
||||
|
||||
if (!expectedSecret) {
|
||||
console.error('[upload] UPLOAD_SECRET_KEY non configurée côté serveur')
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Configuration serveur incomplète' },
|
||||
{ status: 500 }
|
||||
@@ -165,46 +143,33 @@ export async function POST(req: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
// 2. Parse & écriture disque
|
||||
let filename: string
|
||||
let savedPath: string
|
||||
let relPath: string
|
||||
let folderName: string
|
||||
|
||||
try {
|
||||
;({ filename, savedPath, relPath } = await parseUpload(req))
|
||||
console.log(`[upload] Fichier reçu et sauvegardé : ${savedPath}`)
|
||||
;({ filename, savedPath, relPath, folderName } = await parseUpload(req))
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur inconnue lors de l\'upload'
|
||||
console.error('[upload] Erreur parsing :', message)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: message },
|
||||
{ status: 400 }
|
||||
)
|
||||
const message = err instanceof Error ? err.message : 'Erreur inconnue'
|
||||
return NextResponse.json({ success: false, error: message }, { status: 400 })
|
||||
}
|
||||
|
||||
// 3. Séquence git push
|
||||
try {
|
||||
const { output } = runGitPush(filename, relPath)
|
||||
console.log(`[upload] Git push réussi pour ${filename}`)
|
||||
const { output } = runGitPush(folderName)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
filename,
|
||||
message: `"${filename}" sauvegardé et poussé sur Git avec succès.`,
|
||||
message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur Git.`,
|
||||
gitOutput: output,
|
||||
})
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur git inconnue'
|
||||
const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? ''
|
||||
console.error('[upload] Erreur git push :', message, stderr)
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
filename,
|
||||
error: `Fichier sauvegardé mais git push a échoué : ${message}`,
|
||||
gitError: stderr,
|
||||
},
|
||||
{ success: false, error: `Fichier sauvegardé mais git push a échoué: ${message}`, gitError: stderr },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
+193
-174
@@ -1,111 +1,174 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useDropzone, FileRejection } from 'react-dropzone'
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const ModelViewer = dynamic(() => import('./ModelViewer'), { ssr: false })
|
||||
|
||||
type FileStatus = 'pending' | 'uploading' | 'success' | 'error'
|
||||
|
||||
interface FileEntry {
|
||||
interface TextureFile {
|
||||
name: string
|
||||
file: File
|
||||
}
|
||||
|
||||
interface FolderEntry {
|
||||
folderName: string
|
||||
modelFile: File
|
||||
textures: TextureFile[]
|
||||
status: FileStatus
|
||||
progress: number
|
||||
error?: string
|
||||
filename?: string
|
||||
previewUrl?: string
|
||||
modelUrl?: string
|
||||
viewerOpen?: boolean
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
interface UploadResult {
|
||||
success: boolean
|
||||
filename?: string
|
||||
message?: string
|
||||
error?: string
|
||||
gitOutput?: string
|
||||
gitError?: string
|
||||
}
|
||||
|
||||
const ACCEPTED_FORMATS = {
|
||||
'model/gltf-binary': ['.glb'],
|
||||
'model/gltf+json': ['.gltf'],
|
||||
'image/png': ['.png'],
|
||||
'image/jpeg': ['.jpg', '.jpeg'],
|
||||
'image/webp': ['.webp'],
|
||||
}
|
||||
|
||||
const MODEL_EXTENSIONS = ['.glb', '.gltf']
|
||||
const REQUIRED_TEXTURES = ['roughness', 'normal', 'metalness', 'color', 'displace']
|
||||
const TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp']
|
||||
const ALL_EXTENSIONS = [...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS]
|
||||
|
||||
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]}`
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
function getFileType(filename: string): 'model' | 'texture' | null {
|
||||
const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase()
|
||||
if (MODEL_EXTENSIONS.includes(ext)) return 'model'
|
||||
if (TEXTURE_EXTENSIONS.includes(ext)) return 'texture'
|
||||
function getTextureType(filename: string): string | null {
|
||||
const name = filename.toLowerCase().replace(/\.[^.]+$/, '')
|
||||
if (REQUIRED_TEXTURES.includes(name)) return name
|
||||
return null
|
||||
}
|
||||
|
||||
function uploadSingleFile(
|
||||
file: File,
|
||||
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,
|
||||
assetName: string,
|
||||
onProgress: (pct: number) => void,
|
||||
xhrRef: { current: XMLHttpRequest | null }
|
||||
): Promise<UploadResult> {
|
||||
): Promise<{ success: boolean; filename?: string; error?: string }> {
|
||||
return new Promise((resolve) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
if (assetName.trim()) formData.append('assetName', assetName.trim())
|
||||
const totalFiles = 1 + folder.textures.length
|
||||
let completed = 0
|
||||
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhrRef.current = xhr
|
||||
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
try {
|
||||
resolve(JSON.parse(xhr.responseText))
|
||||
} catch {
|
||||
resolve({ success: false, error: `Unexpected response (HTTP ${xhr.status})` })
|
||||
const checkDone = () => {
|
||||
completed++
|
||||
onProgress(Math.round((completed / totalFiles) * 100))
|
||||
if (completed >= totalFiles) {
|
||||
resolve({ success: true, filename: folder.folderName })
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onerror = () => resolve({ success: false, error: 'Network error.' })
|
||||
xhr.onabort = () => resolve({ success: false, error: 'Cancelled.' })
|
||||
const formData = new FormData()
|
||||
formData.append('folderName', folder.folderName)
|
||||
formData.append('file', folder.modelFile)
|
||||
formData.append('fileType', 'model')
|
||||
|
||||
xhr.open('POST', '/api/upload')
|
||||
xhr.setRequestHeader('x-upload-secret', secret.trim())
|
||||
xhr.send(formData)
|
||||
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<FileEntry[]>([])
|
||||
const [files, setFiles] = useState<FolderEntry[]>([])
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [secret, setSecret] = useState('')
|
||||
const [secretVisible, setSecretVisible] = useState(false)
|
||||
const [assetName, setAssetName] = useState('')
|
||||
const [globalError, setGlobalError] = useState<string | null>(null)
|
||||
const xhrRef = useRef<XMLHttpRequest | null>(null)
|
||||
|
||||
const updateFile = (index: number, patch: Partial<FileEntry>) => {
|
||||
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('Please enter the access key before uploading.')
|
||||
setGlobalError('Veuillez entrer la clé d\'accès avant d\'uploader.')
|
||||
return
|
||||
}
|
||||
if (files.length === 0) return
|
||||
@@ -118,10 +181,9 @@ export default function UploadZone() {
|
||||
|
||||
updateFile(i, { status: 'uploading', progress: 0, error: undefined })
|
||||
|
||||
const result = await uploadSingleFile(
|
||||
files[i].file,
|
||||
const result = await uploadFolder(
|
||||
files[i],
|
||||
secret,
|
||||
assetName,
|
||||
(pct) => updateFile(i, { progress: pct }),
|
||||
xhrRef
|
||||
)
|
||||
@@ -135,65 +197,25 @@ export default function UploadZone() {
|
||||
}
|
||||
|
||||
setIsUploading(false)
|
||||
}, [files, secret, assetName])
|
||||
}, [files, secret])
|
||||
|
||||
const handleCancel = () => { xhrRef.current?.abort() }
|
||||
|
||||
const removeFile = (index: number) => {
|
||||
const file = files[index]
|
||||
if (file.previewUrl) {
|
||||
URL.revokeObjectURL(file.previewUrl)
|
||||
}
|
||||
if (file.modelUrl) URL.revokeObjectURL(file.modelUrl)
|
||||
setFiles((prev) => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
files.forEach((f) => {
|
||||
if (f.previewUrl) URL.revokeObjectURL(f.previewUrl)
|
||||
if (f.modelUrl) URL.revokeObjectURL(f.modelUrl)
|
||||
})
|
||||
setFiles([])
|
||||
setGlobalError(null)
|
||||
setIsUploading(false)
|
||||
}
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
|
||||
if (rejectedFiles.length > 0) {
|
||||
const codes = rejectedFiles[0].errors.map((e) => e.code).join(', ')
|
||||
setGlobalError(
|
||||
codes.includes('file-invalid-type')
|
||||
? `Unsupported format. Use: ${ALL_EXTENSIONS.join(', ')}`
|
||||
: codes.includes('file-too-large')
|
||||
? 'File too large (max 2 GB)'
|
||||
: `File rejected: ${codes}`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
setGlobalError(null)
|
||||
setFiles((prev) => {
|
||||
const existingNames = new Set(prev.map((f) => f.file.name))
|
||||
const newEntries: FileEntry[] = acceptedFiles
|
||||
.filter((f) => !existingNames.has(f.name))
|
||||
.map((file) => {
|
||||
const entry: FileEntry = { file, status: 'pending', progress: 0, viewerOpen: true }
|
||||
const type = getFileType(file.name)
|
||||
if (type === 'model') {
|
||||
entry.previewUrl = URL.createObjectURL(file)
|
||||
}
|
||||
return entry
|
||||
})
|
||||
return [...prev, ...newEntries]
|
||||
})
|
||||
}, [])
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({
|
||||
onDrop,
|
||||
accept: ACCEPTED_FORMATS,
|
||||
maxSize: 2 * 1024 * 1024 * 1024,
|
||||
disabled: isUploading,
|
||||
multiple: false,
|
||||
})
|
||||
|
||||
const allDone = files.length > 0 && files.every((f) => f.status === 'success')
|
||||
const hasErrors = files.some((f) => f.status === 'error')
|
||||
|
||||
@@ -233,62 +255,65 @@ export default function UploadZone() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-sm font-medium text-gray-300">
|
||||
Asset Name
|
||||
<span className="text-gray-500 font-normal ml-2">— common name for model and texture</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={assetName}
|
||||
onChange={(e) => setAssetName(e.target.value)}
|
||||
placeholder="e.g., tower, stone_floor, brick_wall..."
|
||||
disabled={isUploading}
|
||||
className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
text-gray-100 placeholder-gray-500 text-sm font-mono
|
||||
focus:outline-none focus:ring-2 focus:ring-white/50 focus:border-white/50
|
||||
disabled:opacity-50 disabled:cursor-not-allowed transition"
|
||||
/>
|
||||
</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
|
||||
{...getRootProps()}
|
||||
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' : ''}
|
||||
${isDragReject ? 'border-red-500 bg-red-900/20' : ''}
|
||||
${isDragActive && !isDragReject ? 'border-white/50 bg-black-700 scale-[1.01]' : ''}
|
||||
${!isDragActive && !isDragReject && !isUploading
|
||||
? 'border-white/30 hover:border-white/50 hover:bg-black-700'
|
||||
: ''}
|
||||
${!isUploading ? 'border-white/30 hover:border-white/50 hover:bg-black-700' : ''}
|
||||
`}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
<div className="flex justify-center mb-3">
|
||||
<div className={`w-12 h-12 rounded-full flex items-center justify-center transition ${isDragActive ? 'bg-gray-700' : 'bg-black-700'}`}>
|
||||
<svg className={`w-6 h-6 transition ${isDragActive ? 'text-white' : 'text-gray-400'}`}
|
||||
<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 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
|
||||
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>
|
||||
{isDragReject ? (
|
||||
<p className="text-sm font-medium text-red-400">Unsupported format</p>
|
||||
) : isDragActive ? (
|
||||
<p className="text-sm font-medium text-gray-200">Release to add</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm font-medium text-gray-300">
|
||||
Drag files here
|
||||
<span className="text-gray-500 font-normal"> or click to browse</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Models: .glb, .gltf · Textures: .png, .jpg, .webp
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
)}
|
||||
|
||||
@@ -298,12 +323,9 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
|
||||
{files.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{files.map((entry, i) => {
|
||||
const type = getFileType(entry.file.name)
|
||||
return (
|
||||
<div key={`${entry.file.name}-${i}`}>
|
||||
<div className="flex items-center gap-3 bg-black-800 border border-white/20 rounded-xl px-4 py-3">
|
||||
|
||||
{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">
|
||||
@@ -326,15 +348,9 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (entry.previewUrl && type === 'model') {
|
||||
updateFile(i, { viewerOpen: !entry.viewerOpen })
|
||||
}
|
||||
}}
|
||||
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.previewUrl && type === 'model'
|
||||
? 'bg-black-700 hover:bg-gray-700 cursor-pointer'
|
||||
: 'bg-black-700 cursor-default'
|
||||
entry.modelUrl ? 'bg-black-700 hover:bg-gray-700 cursor-pointer' : 'bg-black-700 cursor-default'
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
@@ -349,16 +365,11 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
|
||||
<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.file.name}</span>
|
||||
{type && (
|
||||
<span className={`shrink-0 text-xs px-1.5 py-0.5 rounded-full
|
||||
${type === 'model' ? 'bg-gray-700 text-gray-300' : 'bg-gray-700 text-gray-300'}`}>
|
||||
{type === 'model' ? '3D' : 'Texture'}
|
||||
</span>
|
||||
)}
|
||||
<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">{formatBytes(entry.file.size)}</span>
|
||||
<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>
|
||||
)}
|
||||
@@ -388,22 +399,32 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
)}
|
||||
</div>
|
||||
|
||||
{entry.previewUrl && type === 'model' && entry.status !== 'success' && (
|
||||
{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.previewUrl}
|
||||
filename={entry.file.name}
|
||||
size={formatBytes(entry.file.size)}
|
||||
url={entry.modelUrl}
|
||||
filename={entry.modelFile.name}
|
||||
size={formatBytes(entry.modelFile.size)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -416,9 +437,7 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
||||
hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-white/50 border border-white/20"
|
||||
style={{ color: '#000000' }}
|
||||
>
|
||||
Upload {files.filter(f => f.status !== 'success').length > 1
|
||||
? `${files.filter(f => f.status !== 'success').length} files`
|
||||
: 'file'} & Push to Git
|
||||
Upload & Push to Git
|
||||
</button>
|
||||
)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user