| 1 | /* ========================================================= |
| 2 | FILE MANAGER — CLIENT SPA |
| 3 | ========================================================= |
| 4 | Architecture: |
| 5 | - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API |
| 6 | - Token is stored in localStorage to survive full page refresh |
| 7 | - Token is sent as Bearer header on every API call |
| 8 | - Fingerprint (derived from navigator info) locks the token to this browser |
| 9 | ========================================================= */ |
| 10 | 'use strict'; |
| 11 | |
| 12 | // ─────────────────────────────────────────────────────────────────────────── |
| 13 | // STATE |
| 14 | // ─────────────────────────────────────────────────────────────────────────── |
| 15 | const STATE = { |
| 16 | token: null, // decrypted JWT string |
| 17 | username: null, |
| 18 | isAdmin: false, |
| 19 | permissions: {}, |
| 20 | roots: [], // [{ label, path }] |
| 21 | currentDir: null, // absolute path currently shown (null = roots view) |
| 22 | currentRoot: null, // { label, path } of the active root |
| 23 | items: [], // current directory listing |
| 24 | selectedItem: null, // item object selected in sidebar |
| 25 | |
| 26 | // Ephemeral key pair per session (client-side) |
| 27 | clientPrivateKey: null, |
| 28 | clientPublicKeyJwk: null, |
| 29 | |
| 30 | // Server public key for encrypting login |
| 31 | serverPublicKeyJwk: null, |
| 32 | |
| 33 | // Stable per-browser binding id used in fingerprint derivation |
| 34 | clientBindingId: null, |
| 35 | |
| 36 | // Persisted view state |
| 37 | restoreDir: null, |
| 38 | restoreRootPath: null, |
| 39 | lastOperationAt: null, |
| 40 | |
| 41 | // Background refresh state |
| 42 | autoRefreshTimer: null, |
| 43 | uploadInProgress: false, |
| 44 | // Blob URLs for thumbnail previews — revoked on each grid rebuild |
| 45 | thumbnailUrls: [], |
| 46 | |
| 47 | // Preview overlay state |
| 48 | previewObjectUrl: null, |
| 49 | previewSourceEl: null, // SVG element that triggered the preview |
| 50 | previewClosing: false, // guard to prevent double-close during animation |
| 51 | previewExpandState: null, // in-place expanded tile preview state |
| 52 | movePicker: null, |
| 53 | }; |
| 54 | |
| 55 | const SESSION_KEY = 'filemanager.session.v1'; |
| 56 | const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour |
| 57 | const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1'; |
| 58 | const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)'; |
| 59 | const MOBILE_LONG_PRESS_MS = 420; |
| 60 | const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10; |
| 61 | |
| 62 | // ─────────────────────────────────────────────────────────────────────────── |
| 63 | // CRYPTO HELPERS (Web Crypto API) |
| 64 | // ─────────────────────────────────────────────────────────────────────────── |
| 65 | |
| 66 | async function generateClientKeyPair () |
| 67 | { |
| 68 | if (!hasWebCrypto()) return; |
| 69 | const kp = await crypto.subtle.generateKey( |
| 70 | { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, |
| 71 | true, |
| 72 | ['encrypt', 'decrypt'], |
| 73 | ); |
| 74 | STATE.clientPrivateKey = kp.privateKey; |
| 75 | STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Hybrid-encrypt a JS object using the server's RSA public key. |
| 80 | * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. |
| 81 | */ |
| 82 | async function hybridEncryptForServer (obj) |
| 83 | { |
| 84 | if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) |
| 85 | { |
| 86 | return { plaintext: obj }; |
| 87 | } |
| 88 | |
| 89 | const serverPub = await crypto.subtle.importKey( |
| 90 | 'jwk', STATE.serverPublicKeyJwk, |
| 91 | { name: 'RSA-OAEP', hash: 'SHA-256' }, |
| 92 | false, ['encrypt'], |
| 93 | ); |
| 94 | |
| 95 | const plaintext = new TextEncoder().encode(JSON.stringify(obj)); |
| 96 | const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); |
| 97 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 98 | const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); |
| 99 | |
| 100 | // gcmResult = ciphertext || tag (last 16 bytes are auth tag) |
| 101 | const gcmBytes = new Uint8Array(gcmResult); |
| 102 | const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); |
| 103 | const tag = gcmBytes.slice(gcmBytes.length - 16); |
| 104 | |
| 105 | const rawAes = await crypto.subtle.exportKey('raw', aesKey); |
| 106 | const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); |
| 107 | |
| 108 | return { |
| 109 | encryptedKey: b64(encryptedKey), |
| 110 | iv: b64(iv), |
| 111 | ciphertext: b64(ciphertext), |
| 112 | tag: b64(tag), |
| 113 | }; |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Hybrid-decrypt a payload encrypted by the server for us (using our public key). |
| 118 | */ |
| 119 | async function hybridDecryptFromServer (payload) |
| 120 | { |
| 121 | if (!payload) return null; |
| 122 | if (payload.token) return payload.token; |
| 123 | if (!hasWebCrypto()) return null; |
| 124 | |
| 125 | const encryptedKey = unb64(payload.encryptedKey); |
| 126 | const iv = unb64(payload.iv); |
| 127 | const ciphertext = unb64(payload.ciphertext); |
| 128 | const tag = unb64(payload.tag); |
| 129 | |
| 130 | const rawAes = await crypto.subtle.decrypt( |
| 131 | { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, |
| 132 | ); |
| 133 | |
| 134 | const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); |
| 135 | |
| 136 | // Recombine ciphertext + tag for AES-GCM |
| 137 | const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); |
| 138 | combined.set(new Uint8Array(ciphertext)); |
| 139 | combined.set(new Uint8Array(tag), ciphertext.byteLength); |
| 140 | |
| 141 | const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); |
| 142 | return new TextDecoder().decode(plain); |
| 143 | } |
| 144 | |
| 145 | // ─────────────────────────────────────────────────────────────────────────── |
| 146 | // UTIL |
| 147 | // ─────────────────────────────────────────────────────────────────────────── |
| 148 | |
| 149 | function b64 (buf) |
| 150 | { |
| 151 | return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); |
| 152 | } |
| 153 | |
| 154 | function hasWebCrypto () |
| 155 | { |
| 156 | return !!(window.crypto && window.crypto.subtle); |
| 157 | } |
| 158 | |
| 159 | function unb64 (str) |
| 160 | { |
| 161 | const binary = atob(str); |
| 162 | const buf = new Uint8Array(binary.length); |
| 163 | for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); |
| 164 | return buf.buffer; |
| 165 | } |
| 166 | |
| 167 | /** Stable browser fingerprint (not stored, derived fresh each load) */ |
| 168 | function getFingerprint () |
| 169 | { |
| 170 | const binding = getOrCreateClientBindingId(); |
| 171 | const nav = navigator; |
| 172 | |
| 173 | // Keep this stable: avoid viewport/screen metrics that can change when |
| 174 | // devtools opens, orientation changes, or window state changes. |
| 175 | return [ |
| 176 | binding, |
| 177 | nav.userAgent || '', |
| 178 | nav.language, |
| 179 | nav.platform || nav.userAgentData?.platform || '', |
| 180 | Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 181 | ].join('|'); |
| 182 | } |
| 183 | |
| 184 | function randomIdHex (bytes = 16) |
| 185 | { |
| 186 | const arr = new Uint8Array(bytes); |
| 187 | if (window.crypto && typeof window.crypto.getRandomValues === 'function') |
| 188 | { |
| 189 | window.crypto.getRandomValues(arr); |
| 190 | } else |
| 191 | { |
| 192 | for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256); |
| 193 | } |
| 194 | return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join(''); |
| 195 | } |
| 196 | |
| 197 | function getOrCreateClientBindingId () |
| 198 | { |
| 199 | if (STATE.clientBindingId) return STATE.clientBindingId; |
| 200 | |
| 201 | try |
| 202 | { |
| 203 | const existing = localStorage.getItem(CLIENT_BINDING_KEY); |
| 204 | if (existing && typeof existing === 'string') |
| 205 | { |
| 206 | STATE.clientBindingId = existing; |
| 207 | return existing; |
| 208 | } |
| 209 | } catch |
| 210 | { |
| 211 | // Ignore storage read errors. |
| 212 | } |
| 213 | |
| 214 | const created = randomIdHex(16); |
| 215 | STATE.clientBindingId = created; |
| 216 | |
| 217 | try |
| 218 | { |
| 219 | localStorage.setItem(CLIENT_BINDING_KEY, created); |
| 220 | } catch |
| 221 | { |
| 222 | // Ignore storage write errors; in-memory fallback still keeps this stable |
| 223 | // for the current page session. |
| 224 | } |
| 225 | |
| 226 | return created; |
| 227 | } |
| 228 | |
| 229 | function formatBytes (bytes) |
| 230 | { |
| 231 | if (bytes == null) return '—'; |
| 232 | if (bytes < 1024) return bytes + ' B'; |
| 233 | if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; |
| 234 | if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; |
| 235 | return (bytes / 1073741824).toFixed(2) + ' GB'; |
| 236 | } |
| 237 | |
| 238 | function extOf (name) |
| 239 | { |
| 240 | const i = name.lastIndexOf('.'); |
| 241 | return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; |
| 242 | } |
| 243 | |
| 244 | function getPathSep (basePath) |
| 245 | { |
| 246 | return basePath && basePath.includes('\\') ? '\\' : '/'; |
| 247 | } |
| 248 | |
| 249 | function joinServerPath (basePath, segment) |
| 250 | { |
| 251 | const sep = getPathSep(basePath); |
| 252 | const base = String(basePath || '').replace(/[\\/]+$/, ''); |
| 253 | return base + sep + segment; |
| 254 | } |
| 255 | |
| 256 | function samePath (a, b) |
| 257 | { |
| 258 | if (!a || !b) return false; |
| 259 | return String(a).toLowerCase() === String(b).toLowerCase(); |
| 260 | } |
| 261 | |
| 262 | function pathInside (child, root) |
| 263 | { |
| 264 | if (!child || !root) return false; |
| 265 | if (samePath(child, root)) return true; |
| 266 | const sep = getPathSep(root); |
| 267 | return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase()); |
| 268 | } |
| 269 | |
| 270 | function saveSessionState () |
| 271 | { |
| 272 | if (!STATE.token) return; |
| 273 | const now = Date.now(); |
| 274 | STATE.lastOperationAt = now; |
| 275 | const payload = { |
| 276 | token: STATE.token, |
| 277 | dir: STATE.currentDir || null, |
| 278 | rootPath: STATE.currentRoot ? STATE.currentRoot.path : null, |
| 279 | lastOperationAt: STATE.lastOperationAt, |
| 280 | }; |
| 281 | try |
| 282 | { |
| 283 | localStorage.setItem(SESSION_KEY, JSON.stringify(payload)); |
| 284 | } catch |
| 285 | { |
| 286 | // Ignore storage errors (private mode/full quota). |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | function loadSessionState () |
| 291 | { |
| 292 | try |
| 293 | { |
| 294 | const raw = localStorage.getItem(SESSION_KEY); |
| 295 | if (!raw) return null; |
| 296 | const parsed = JSON.parse(raw); |
| 297 | if (!parsed || typeof parsed.token !== 'string') return null; |
| 298 | if (!Number.isFinite(parsed.lastOperationAt)) return null; |
| 299 | |
| 300 | if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) |
| 301 | { |
| 302 | clearSessionState(); |
| 303 | return null; |
| 304 | } |
| 305 | |
| 306 | return parsed; |
| 307 | } catch |
| 308 | { |
| 309 | return null; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | function clearSessionState () |
| 314 | { |
| 315 | try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ } |
| 316 | } |
| 317 | |
| 318 | // ─────────────────────────────────────────────────────────────────────────── |
| 319 | // API |
| 320 | // ─────────────────────────────────────────────────────────────────────────── |
| 321 | |
| 322 | async function api (method, path, body, opts = {}) |
| 323 | { |
| 324 | const headers = { 'Content-Type': 'application/json' }; |
| 325 | const noAutoLogout = !!opts.noAutoLogout; |
| 326 | if (STATE.token) |
| 327 | { |
| 328 | headers['Authorization'] = 'Bearer ' + STATE.token; |
| 329 | headers['X-Fp'] = getFingerprint(); |
| 330 | } |
| 331 | const fetchOpts = { ...opts }; |
| 332 | delete fetchOpts.noAutoLogout; |
| 333 | const res = await fetch('/api' + path, { |
| 334 | method, |
| 335 | headers, |
| 336 | body: body != null ? JSON.stringify(body) : undefined, |
| 337 | ...fetchOpts, |
| 338 | }); |
| 339 | if (!res.ok) |
| 340 | { |
| 341 | const j = await res.json().catch(() => ({})); |
| 342 | // Session-expired → force re-login |
| 343 | if (res.status === 401) |
| 344 | { |
| 345 | if (!noAutoLogout) logout(); |
| 346 | return null; |
| 347 | } |
| 348 | throw new Error(j.error || res.statusText); |
| 349 | } |
| 350 | if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) |
| 351 | { |
| 352 | saveSessionState(); |
| 353 | } |
| 354 | return res.json(); |
| 355 | } |
| 356 | |
| 357 | // ─────────────────────────────────────────────────────────────────────────── |
| 358 | // TOAST |
| 359 | // ─────────────────────────────────────────────────────────────────────────── |
| 360 | |
| 361 | function toast (msg, type = '') |
| 362 | { |
| 363 | const el = document.createElement('div'); |
| 364 | el.className = 'toast-msg' + (type ? ' ' + type : ''); |
| 365 | el.textContent = msg; |
| 366 | document.getElementById('toast').appendChild(el); |
| 367 | setTimeout(() => el.remove(), 3500); |
| 368 | } |
| 369 | |
| 370 | // ─────────────────────────────────────────────────────────────────────────── |
| 371 | // DIALOG MODALS — centralised replacements for alert / confirm / prompt |
| 372 | // ─────────────────────────────────────────────────────────────────────────── |
| 373 | |
| 374 | /** |
| 375 | * Show a confirmation dialog. |
| 376 | * @param {string} title |
| 377 | * @param {string} message |
| 378 | * @returns {Promise<boolean>} true = OK, false = Cancel |
| 379 | */ |
| 380 | function showConfirm (title, message) |
| 381 | { |
| 382 | return new Promise((resolve) => |
| 383 | { |
| 384 | const overlay = document.getElementById('confirm-modal'); |
| 385 | document.getElementById('confirm-modal-title').textContent = title; |
| 386 | document.getElementById('confirm-modal-message').textContent = message; |
| 387 | overlay.classList.remove('hidden'); |
| 388 | |
| 389 | const ok = document.getElementById('confirm-modal-ok'); |
| 390 | const cancel = document.getElementById('confirm-modal-cancel'); |
| 391 | |
| 392 | function finish (result) |
| 393 | { |
| 394 | overlay.classList.add('hidden'); |
| 395 | ok.removeEventListener('click', onOk); |
| 396 | cancel.removeEventListener('click', onCancel); |
| 397 | resolve(result); |
| 398 | } |
| 399 | function onOk () { finish(true); } |
| 400 | function onCancel () { finish(false); } |
| 401 | |
| 402 | ok.addEventListener('click', onOk); |
| 403 | cancel.addEventListener('click', onCancel); |
| 404 | ok.focus(); |
| 405 | }); |
| 406 | } |
| 407 | |
| 408 | /** |
| 409 | * Show a text-input dialog. |
| 410 | * @param {string} title |
| 411 | * @param {string} [message] — optional helper text shown above the input |
| 412 | * @param {string} [defaultValue] — pre-filled value |
| 413 | * @returns {Promise<string|null>} string = submitted value, null = cancelled |
| 414 | */ |
| 415 | function showPrompt (title, message = '', defaultValue = '') |
| 416 | { |
| 417 | return new Promise((resolve) => |
| 418 | { |
| 419 | const overlay = document.getElementById('prompt-modal'); |
| 420 | const msgEl = document.getElementById('prompt-modal-message'); |
| 421 | const input = document.getElementById('prompt-modal-input'); |
| 422 | const errorEl = document.getElementById('prompt-modal-error'); |
| 423 | const form = document.getElementById('prompt-modal-form'); |
| 424 | const cancel = document.getElementById('prompt-modal-cancel'); |
| 425 | |
| 426 | document.getElementById('prompt-modal-title').textContent = title; |
| 427 | msgEl.textContent = message; |
| 428 | msgEl.classList.toggle('hidden', !message); |
| 429 | input.value = defaultValue; |
| 430 | errorEl.classList.add('hidden'); |
| 431 | overlay.classList.remove('hidden'); |
| 432 | input.focus(); |
| 433 | input.select(); |
| 434 | |
| 435 | function finish (result) |
| 436 | { |
| 437 | overlay.classList.add('hidden'); |
| 438 | form.removeEventListener('submit', onSubmit); |
| 439 | cancel.removeEventListener('click', onCancel); |
| 440 | resolve(result); |
| 441 | } |
| 442 | function onSubmit (e) |
| 443 | { |
| 444 | e.preventDefault(); |
| 445 | finish(input.value); |
| 446 | } |
| 447 | function onCancel () { finish(null); } |
| 448 | |
| 449 | form.addEventListener('submit', onSubmit); |
| 450 | cancel.addEventListener('click', onCancel); |
| 451 | }); |
| 452 | } |
| 453 | |
| 454 | /** |
| 455 | * Show an overwrite-decision dialog for a single file conflict. |
| 456 | * @param {string} filename |
| 457 | * @returns {Promise<'yes'|'no'|'all'|'none'>} |
| 458 | */ |
| 459 | function showOverwrite (filename) |
| 460 | { |
| 461 | return new Promise((resolve) => |
| 462 | { |
| 463 | const overlay = document.getElementById('overwrite-modal'); |
| 464 | document.getElementById('overwrite-modal-filename').textContent = filename; |
| 465 | overlay.classList.remove('hidden'); |
| 466 | |
| 467 | const btnYes = document.getElementById('overwrite-modal-yes'); |
| 468 | const btnNo = document.getElementById('overwrite-modal-no'); |
| 469 | const btnAll = document.getElementById('overwrite-modal-all'); |
| 470 | const btnSkipAll = document.getElementById('overwrite-modal-skip-all'); |
| 471 | |
| 472 | function finish (result) |
| 473 | { |
| 474 | overlay.classList.add('hidden'); |
| 475 | btnYes.removeEventListener('click', onYes); |
| 476 | btnNo.removeEventListener('click', onNo); |
| 477 | btnAll.removeEventListener('click', onAll); |
| 478 | btnSkipAll.removeEventListener('click', onSkipAll); |
| 479 | resolve(result); |
| 480 | } |
| 481 | function onYes () { finish('yes'); } |
| 482 | function onNo () { finish('no'); } |
| 483 | function onAll () { finish('all'); } |
| 484 | function onSkipAll () { finish('none'); } |
| 485 | |
| 486 | btnYes.addEventListener('click', onYes); |
| 487 | btnNo.addEventListener('click', onNo); |
| 488 | btnAll.addEventListener('click', onAll); |
| 489 | btnSkipAll.addEventListener('click', onSkipAll); |
| 490 | btnNo.focus(); |
| 491 | }); |
| 492 | } |
| 493 | |
| 494 | // ─────────────────────────────────────────────────────────────────────────── |
| 495 | // AUTH FLOW |
| 496 | // ─────────────────────────────────────────────────────────────────────────── |
| 497 | |
| 498 | function showAuthOverlay (setupMode = false) |
| 499 | { |
| 500 | document.getElementById('app').classList.add('hidden'); |
| 501 | const overlay = document.getElementById('auth-overlay'); |
| 502 | overlay.classList.remove('hidden'); |
| 503 | document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; |
| 504 | document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); |
| 505 | const submitBtn = document.getElementById('auth-submit'); |
| 506 | submitBtn.disabled = false; |
| 507 | submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In'; |
| 508 | document.getElementById('auth-error').classList.add('hidden'); |
| 509 | document.getElementById('auth-username').value = ''; |
| 510 | document.getElementById('auth-password').value = ''; |
| 511 | document.getElementById('auth-username').focus(); |
| 512 | document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; |
| 513 | } |
| 514 | |
| 515 | function showApp () |
| 516 | { |
| 517 | document.getElementById('auth-overlay').classList.add('hidden'); |
| 518 | document.getElementById('app').classList.remove('hidden'); |
| 519 | if (isMobileViewport()) |
| 520 | { |
| 521 | hideSidebarPanel(); |
| 522 | } else |
| 523 | { |
| 524 | openFolderSidebar(); |
| 525 | } |
| 526 | document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); |
| 527 | startAutoRefresh(); |
| 528 | } |
| 529 | |
| 530 | async function initAuth () |
| 531 | { |
| 532 | // Always generate a fresh key pair so each page-load session is independent |
| 533 | await generateClientKeyPair().catch(() => |
| 534 | { |
| 535 | toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err'); |
| 536 | }); |
| 537 | |
| 538 | // Fetch server public key |
| 539 | const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); |
| 540 | if (publicKey) STATE.serverPublicKeyJwk = publicKey; |
| 541 | if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; } |
| 542 | STATE.serverPublicKeyJwk = publicKey; |
| 543 | |
| 544 | // Check whether first-run setup is needed |
| 545 | const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); |
| 546 | |
| 547 | if (!needed) |
| 548 | { |
| 549 | const saved = loadSessionState(); |
| 550 | if (saved && saved.token) |
| 551 | { |
| 552 | STATE.token = saved.token; |
| 553 | STATE.restoreDir = saved.dir || null; |
| 554 | STATE.restoreRootPath = saved.rootPath || null; |
| 555 | STATE.lastOperationAt = saved.lastOperationAt; |
| 556 | |
| 557 | const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null); |
| 558 | if (me) |
| 559 | { |
| 560 | STATE.username = me.username; |
| 561 | STATE.isAdmin = me.isAdmin; |
| 562 | STATE.permissions = me.permissions; |
| 563 | showApp(); |
| 564 | await loadRoots({ |
| 565 | preferredDir: STATE.restoreDir, |
| 566 | preferredRootPath: STATE.restoreRootPath, |
| 567 | }); |
| 568 | return; |
| 569 | } |
| 570 | |
| 571 | STATE.token = null; |
| 572 | clearSessionState(); |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | showAuthOverlay(needed); |
| 577 | } |
| 578 | |
| 579 | async function doLogin (username, password, isSetup) |
| 580 | { |
| 581 | const encrypted = await hybridEncryptForServer({ username, password }); |
| 582 | const endpoint = isSetup ? '/auth/setup' : '/auth/login'; |
| 583 | |
| 584 | let data; |
| 585 | try |
| 586 | { |
| 587 | data = await api('POST', endpoint, { |
| 588 | encrypted, |
| 589 | clientPublicKey: STATE.clientPublicKeyJwk, |
| 590 | fingerprint: getFingerprint(), |
| 591 | }); |
| 592 | } catch (err) |
| 593 | { |
| 594 | return err.message; |
| 595 | } |
| 596 | |
| 597 | if (!data) return 'Login failed.'; |
| 598 | |
| 599 | // Decrypt the token sent back by the server |
| 600 | const token = await hybridDecryptFromServer(data.encrypted || data); |
| 601 | if (!token) return 'Login failed.'; |
| 602 | STATE.token = token; |
| 603 | |
| 604 | // Load user info |
| 605 | const me = await api('GET', '/auth/me'); |
| 606 | if (!me) return 'Session error.'; |
| 607 | |
| 608 | STATE.username = me.username; |
| 609 | STATE.isAdmin = me.isAdmin; |
| 610 | STATE.permissions = me.permissions; |
| 611 | |
| 612 | saveSessionState(); |
| 613 | showApp(); |
| 614 | await loadRoots(); |
| 615 | return null; // no error |
| 616 | } |
| 617 | |
| 618 | function logout () |
| 619 | { |
| 620 | void performLogout(); |
| 621 | } |
| 622 | |
| 623 | async function performLogout () |
| 624 | { |
| 625 | const tokenAtStart = STATE.token; |
| 626 | stopAutoRefresh(); |
| 627 | |
| 628 | if (tokenAtStart) |
| 629 | { |
| 630 | try |
| 631 | { |
| 632 | await api('POST', '/auth/logout', {}, { noAutoLogout: true }); |
| 633 | } catch |
| 634 | { |
| 635 | // Ignore network errors while logging out locally. |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | STATE.token = null; |
| 640 | STATE.username = null; |
| 641 | STATE.isAdmin = false; |
| 642 | STATE.permissions = {}; |
| 643 | STATE.currentDir = null; |
| 644 | STATE.currentRoot = null; |
| 645 | STATE.items = []; |
| 646 | STATE.restoreDir = null; |
| 647 | STATE.restoreRootPath = null; |
| 648 | STATE.lastOperationAt = null; |
| 649 | clearSessionState(); |
| 650 | closePreview(); |
| 651 | closeSidebar(); |
| 652 | await initAuth(); |
| 653 | } |
| 654 | |
| 655 | // ─────────────────────────────────────────────────────────────────────────── |
| 656 | // NAVIGATION |
| 657 | // ─────────────────────────────────────────────────────────────────────────── |
| 658 | |
| 659 | async function loadRoots (opts = {}) |
| 660 | { |
| 661 | const data = await api('GET', '/files/roots'); |
| 662 | if (!data) return; |
| 663 | STATE.roots = data.roots; |
| 664 | |
| 665 | const preferredDir = opts.preferredDir || null; |
| 666 | const preferredRootPath = opts.preferredRootPath || null; |
| 667 | |
| 668 | if (preferredDir && preferredRootPath) |
| 669 | { |
| 670 | const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath)); |
| 671 | if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) |
| 672 | { |
| 673 | try |
| 674 | { |
| 675 | await navigateTo(preferredDir, preferredRoot, { keepSidebar: true }); |
| 676 | return; |
| 677 | } catch |
| 678 | { |
| 679 | // Fall back to default root behavior. |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | if (STATE.roots.length === 1) |
| 685 | { |
| 686 | // Single root → open it directly |
| 687 | await navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 688 | } else |
| 689 | { |
| 690 | renderRootsView(); |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | function renderRootsView () |
| 695 | { |
| 696 | STATE.currentDir = null; |
| 697 | STATE.currentRoot = null; |
| 698 | saveSessionState(); |
| 699 | renderBreadcrumb(); |
| 700 | const grid = document.getElementById('file-grid'); |
| 701 | grid.innerHTML = ''; |
| 702 | document.getElementById('empty-notice').classList.add('hidden'); |
| 703 | document.getElementById('folder-stats').classList.add('hidden'); |
| 704 | closeSidebar(); |
| 705 | |
| 706 | for (const root of STATE.roots) |
| 707 | { |
| 708 | const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); |
| 709 | grid.appendChild(el); |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | async function navigateTo (absPath, root, opts = {}) |
| 714 | { |
| 715 | if (root) STATE.currentRoot = root; |
| 716 | STATE.currentDir = absPath; |
| 717 | |
| 718 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); |
| 719 | if (!data) return; |
| 720 | |
| 721 | STATE.items = data.items; |
| 722 | saveSessionState(); |
| 723 | renderBreadcrumb(); |
| 724 | renderFileGrid(); |
| 725 | await refreshFolderStats(); |
| 726 | closeSidebar(); |
| 727 | } |
| 728 | |
| 729 | function renderBreadcrumb () |
| 730 | { |
| 731 | const nav = document.getElementById('breadcrumb'); |
| 732 | nav.innerHTML = ''; |
| 733 | |
| 734 | // "Home" crumb |
| 735 | const home = document.createElement('span'); |
| 736 | home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); |
| 737 | home.textContent = 'Home'; |
| 738 | home.addEventListener('click', () => |
| 739 | { |
| 740 | if (STATE.roots.length === 1) |
| 741 | { |
| 742 | navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 743 | } else |
| 744 | { |
| 745 | renderRootsView(); |
| 746 | } |
| 747 | }); |
| 748 | nav.appendChild(home); |
| 749 | |
| 750 | if (!STATE.currentDir || !STATE.currentRoot) return; |
| 751 | |
| 752 | // Build path segments relative to the root |
| 753 | const rootPath = STATE.currentRoot.path; |
| 754 | const relative = STATE.currentDir === rootPath |
| 755 | ? '' |
| 756 | : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, ''); |
| 757 | |
| 758 | const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)]; |
| 759 | let accumulated = rootPath; |
| 760 | |
| 761 | for (let i = 0; i < parts.length; i++) |
| 762 | { |
| 763 | const sep = document.createElement('span'); |
| 764 | sep.className = 'sep'; |
| 765 | sep.textContent = ' / '; |
| 766 | nav.appendChild(sep); |
| 767 | |
| 768 | const crumb = document.createElement('span'); |
| 769 | crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); |
| 770 | crumb.textContent = parts[i]; |
| 771 | |
| 772 | // Capture the path for this crumb |
| 773 | const capturedPath = i === 0 ? rootPath : accumulated; |
| 774 | crumb.classList.add('crumb-drop-target'); |
| 775 | crumb.dataset.path = capturedPath; |
| 776 | if (i < parts.length - 1) |
| 777 | { |
| 778 | crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); |
| 779 | } |
| 780 | |
| 781 | nav.appendChild(crumb); |
| 782 | |
| 783 | // Advance accumulated path (skip for root label) |
| 784 | if (i > 0) accumulated = accumulated + '/' + parts[i]; |
| 785 | else if (i === 0 && parts.length > 1) |
| 786 | { |
| 787 | // After root label, next crumb should append the next segment |
| 788 | accumulated = rootPath; |
| 789 | } |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | async function refreshFolderStats () |
| 794 | { |
| 795 | const el = document.getElementById('folder-stats'); |
| 796 | if (!STATE.currentDir) |
| 797 | { |
| 798 | el.classList.add('hidden'); |
| 799 | return; |
| 800 | } |
| 801 | |
| 802 | const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 803 | if (!data) |
| 804 | { |
| 805 | el.classList.add('hidden'); |
| 806 | return; |
| 807 | } |
| 808 | |
| 809 | const used = formatBytes(data.usedBytes); |
| 810 | const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes); |
| 811 | el.textContent = `Folder usage: ${used} | Free on disk: ${free}`; |
| 812 | el.classList.remove('hidden'); |
| 813 | } |
| 814 | |
| 815 | function itemsSignature (items) |
| 816 | { |
| 817 | return JSON.stringify( |
| 818 | (items || []).map(it => [it.path, it.mtime, it.size, it.isDir]) |
| 819 | .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), |
| 820 | ); |
| 821 | } |
| 822 | |
| 823 | async function incrementalRefreshCurrentDir () |
| 824 | { |
| 825 | if (STATE.previewExpandState) return; |
| 826 | if (!STATE.currentDir || STATE.uploadInProgress) return; |
| 827 | |
| 828 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 829 | if (!data) return; |
| 830 | |
| 831 | const oldSig = itemsSignature(STATE.items); |
| 832 | const newSig = itemsSignature(data.items); |
| 833 | if (oldSig !== newSig) |
| 834 | { |
| 835 | const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null; |
| 836 | STATE.items = data.items; |
| 837 | renderFileGrid(); |
| 838 | |
| 839 | if (selectedPath) |
| 840 | { |
| 841 | const match = STATE.items.find(i => i.path === selectedPath); |
| 842 | if (match) |
| 843 | { |
| 844 | const selectedEl = Array.from(document.querySelectorAll('.file-item')) |
| 845 | .find(el => el.dataset.path === selectedPath); |
| 846 | if (selectedEl) selectItem(selectedEl, match); |
| 847 | } else |
| 848 | { |
| 849 | closeSidebar(); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | await refreshFolderStats(); |
| 855 | } |
| 856 | |
| 857 | function startAutoRefresh () |
| 858 | { |
| 859 | stopAutoRefresh(); |
| 860 | STATE.autoRefreshTimer = setInterval(() => |
| 861 | { |
| 862 | if (document.hidden) return; |
| 863 | incrementalRefreshCurrentDir(); |
| 864 | }, 5000); |
| 865 | } |
| 866 | |
| 867 | function stopAutoRefresh () |
| 868 | { |
| 869 | if (STATE.autoRefreshTimer) |
| 870 | { |
| 871 | clearInterval(STATE.autoRefreshTimer); |
| 872 | STATE.autoRefreshTimer = null; |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | // ─────────────────────────────────────────────────────────────────────────── |
| 877 | // FILE GRID RENDERING |
| 878 | // ─────────────────────────────────────────────────────────────────────────── |
| 879 | |
| 880 | function renderFileGrid () |
| 881 | { |
| 882 | revokeThumbnails(); |
| 883 | const grid = document.getElementById('file-grid'); |
| 884 | grid.innerHTML = ''; |
| 885 | const empty = document.getElementById('empty-notice'); |
| 886 | |
| 887 | const sorted = [...STATE.items].sort((a, b) => |
| 888 | { |
| 889 | if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; |
| 890 | return a.name.localeCompare(b.name); |
| 891 | }); |
| 892 | |
| 893 | empty.classList.toggle('hidden', sorted.length > 0); |
| 894 | |
| 895 | for (const item of sorted) |
| 896 | { |
| 897 | grid.appendChild(makeFileItem(item)); |
| 898 | } |
| 899 | |
| 900 | loadThumbnails(); |
| 901 | } |
| 902 | |
| 903 | function makeFileItem (item) |
| 904 | { |
| 905 | const el = document.createElement('div'); |
| 906 | el.className = 'file-item'; |
| 907 | el.dataset.path = item.path; |
| 908 | if (item.isDir) el.dataset.isdir = '1'; |
| 909 | |
| 910 | const icon = document.createElement('div'); |
| 911 | icon.className = 'icon'; |
| 912 | icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); |
| 913 | if (!item.isDir) |
| 914 | { |
| 915 | icon.dataset.previewPath = item.path; |
| 916 | } |
| 917 | el.appendChild(icon); |
| 918 | |
| 919 | const name = document.createElement('div'); |
| 920 | name.className = 'name'; |
| 921 | name.textContent = item.name; |
| 922 | el.appendChild(name); |
| 923 | |
| 924 | makeDraggable(el, item); |
| 925 | attachMobileLongPress(el, item); |
| 926 | |
| 927 | el.addEventListener('contextmenu', (e) => |
| 928 | { |
| 929 | if (!isMobileViewport()) return; |
| 930 | e.preventDefault(); |
| 931 | e.stopPropagation(); |
| 932 | }); |
| 933 | |
| 934 | // Single-click: open sidebar |
| 935 | el.addEventListener('click', (e) => |
| 936 | { |
| 937 | e.stopPropagation(); |
| 938 | if (item._root) |
| 939 | { |
| 940 | // Clicking a root tile goes straight in |
| 941 | navigateTo(item.path, item._root); |
| 942 | return; |
| 943 | } |
| 944 | |
| 945 | if (isMobileViewport()) |
| 946 | { |
| 947 | if (el.dataset.longPressTriggered === '1') |
| 948 | { |
| 949 | el.dataset.longPressTriggered = '0'; |
| 950 | return; |
| 951 | } |
| 952 | |
| 953 | if (item.isDir) |
| 954 | { |
| 955 | navigateTo(item.path, STATE.currentRoot); |
| 956 | } else |
| 957 | { |
| 958 | downloadOrView(item, icon.querySelector('svg')); |
| 959 | } |
| 960 | return; |
| 961 | } |
| 962 | |
| 963 | selectItem(el, item); |
| 964 | }); |
| 965 | |
| 966 | // Double-click: enter folder or view/download file |
| 967 | el.addEventListener('dblclick', (e) => |
| 968 | { |
| 969 | e.stopPropagation(); |
| 970 | if (item.isDir) |
| 971 | { |
| 972 | navigateTo(item.path, STATE.currentRoot); |
| 973 | } else |
| 974 | { |
| 975 | downloadOrView(item, icon.querySelector('svg')); |
| 976 | } |
| 977 | }); |
| 978 | |
| 979 | return el; |
| 980 | } |
| 981 | |
| 982 | function attachMobileLongPress (el, item) |
| 983 | { |
| 984 | if (item._root) return; |
| 985 | |
| 986 | let pressTimer = null; |
| 987 | let startX = 0; |
| 988 | let startY = 0; |
| 989 | |
| 990 | function clearPress () |
| 991 | { |
| 992 | if (!pressTimer) return; |
| 993 | clearTimeout(pressTimer); |
| 994 | pressTimer = null; |
| 995 | } |
| 996 | |
| 997 | function cancelPress () |
| 998 | { |
| 999 | clearPress(); |
| 1000 | } |
| 1001 | |
| 1002 | el.addEventListener('pointerdown', (e) => |
| 1003 | { |
| 1004 | if (!isMobileViewport()) return; |
| 1005 | if (e.button !== undefined && e.button !== 0) return; |
| 1006 | if (e.pointerType && e.pointerType === 'mouse') return; |
| 1007 | |
| 1008 | startX = e.clientX; |
| 1009 | startY = e.clientY; |
| 1010 | clearPress(); |
| 1011 | |
| 1012 | pressTimer = setTimeout(() => |
| 1013 | { |
| 1014 | pressTimer = null; |
| 1015 | el.dataset.longPressTriggered = '1'; |
| 1016 | selectItem(el, item); |
| 1017 | }, MOBILE_LONG_PRESS_MS); |
| 1018 | }); |
| 1019 | |
| 1020 | el.addEventListener('pointermove', (e) => |
| 1021 | { |
| 1022 | if (!pressTimer) return; |
| 1023 | if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD) |
| 1024 | { |
| 1025 | clearPress(); |
| 1026 | } |
| 1027 | }); |
| 1028 | |
| 1029 | el.addEventListener('pointerup', cancelPress); |
| 1030 | el.addEventListener('pointercancel', cancelPress); |
| 1031 | el.addEventListener('pointerleave', cancelPress); |
| 1032 | } |
| 1033 | |
| 1034 | function selectItem (el, item) |
| 1035 | { |
| 1036 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 1037 | el.classList.add('selected'); |
| 1038 | STATE.selectedItem = item; |
| 1039 | openSidebar(item); |
| 1040 | } |
| 1041 | |
| 1042 | // ─────────────────────────────────────────────────────────────────────────── |
| 1043 | // SIDEBAR |
| 1044 | // ─────────────────────────────────────────────────────────────────────────── |
| 1045 | |
| 1046 | async function openSidebar (item) |
| 1047 | { |
| 1048 | const sidebar = document.getElementById('sidebar'); |
| 1049 | sidebar.classList.remove('hidden'); |
| 1050 | document.getElementById('app').classList.add('sidebar-open'); |
| 1051 | |
| 1052 | document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); |
| 1053 | document.getElementById('sidebar-name').textContent = item.name; |
| 1054 | |
| 1055 | // Load metadata |
| 1056 | const dl = document.getElementById('sidebar-meta'); |
| 1057 | dl.innerHTML = '<dt>Loading…</dt><dd></dd>'; |
| 1058 | |
| 1059 | const actions = document.getElementById('sidebar-actions'); |
| 1060 | actions.innerHTML = ''; |
| 1061 | |
| 1062 | if (!item.isDir) |
| 1063 | { |
| 1064 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`); |
| 1065 | if (meta) |
| 1066 | { |
| 1067 | dl.innerHTML = ` |
| 1068 | <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd> |
| 1069 | <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd> |
| 1070 | <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd> |
| 1071 | <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd> |
| 1072 | `; |
| 1073 | } |
| 1074 | |
| 1075 | // View / download button |
| 1076 | const btnDl = document.createElement('button'); |
| 1077 | btnDl.textContent = 'View / Download'; |
| 1078 | btnDl.addEventListener('click', () => |
| 1079 | { |
| 1080 | const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path); |
| 1081 | const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg'); |
| 1082 | downloadOrView(item, source); |
| 1083 | }); |
| 1084 | actions.appendChild(btnDl); |
| 1085 | } else |
| 1086 | { |
| 1087 | dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`; |
| 1088 | const btnOpen = document.createElement('button'); |
| 1089 | btnOpen.textContent = 'Open folder'; |
| 1090 | btnOpen.addEventListener('click', () => navigateTo(item.path, STATE.currentRoot)); |
| 1091 | actions.appendChild(btnOpen); |
| 1092 | } |
| 1093 | |
| 1094 | // Rename button (write access required) |
| 1095 | if (canWrite()) |
| 1096 | { |
| 1097 | const btnMove = document.createElement('button'); |
| 1098 | btnMove.textContent = 'Move to'; |
| 1099 | btnMove.addEventListener('click', () => openMovePicker(item)); |
| 1100 | actions.appendChild(btnMove); |
| 1101 | |
| 1102 | const btnRen = document.createElement('button'); |
| 1103 | btnRen.textContent = 'Rename'; |
| 1104 | btnRen.addEventListener('click', () => openRenameModal(item)); |
| 1105 | actions.appendChild(btnRen); |
| 1106 | |
| 1107 | const btnDel = document.createElement('button'); |
| 1108 | btnDel.textContent = 'Delete'; |
| 1109 | btnDel.className = 'danger'; |
| 1110 | btnDel.addEventListener('click', () => deleteItem(item)); |
| 1111 | actions.appendChild(btnDel); |
| 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | function openFolderSidebar () |
| 1116 | { |
| 1117 | const sidebar = document.getElementById('sidebar'); |
| 1118 | sidebar.classList.remove('hidden'); |
| 1119 | document.getElementById('app').classList.add('sidebar-open'); |
| 1120 | |
| 1121 | document.getElementById('sidebar-icon').innerHTML = iconFolder(64); |
| 1122 | |
| 1123 | const nameEl = document.getElementById('sidebar-name'); |
| 1124 | const dl = document.getElementById('sidebar-meta'); |
| 1125 | const actions = document.getElementById('sidebar-actions'); |
| 1126 | actions.innerHTML = ''; |
| 1127 | |
| 1128 | if (!STATE.currentDir || !STATE.currentRoot) |
| 1129 | { |
| 1130 | nameEl.textContent = 'Storage Roots'; |
| 1131 | dl.innerHTML = ` |
| 1132 | <dt>Type</dt><dd>Root overview</dd> |
| 1133 | <dt>Roots</dt><dd>${STATE.roots.length}</dd> |
| 1134 | `; |
| 1135 | return; |
| 1136 | } |
| 1137 | |
| 1138 | const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean); |
| 1139 | const fallback = STATE.currentRoot.label || 'Folder'; |
| 1140 | nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback; |
| 1141 | |
| 1142 | const dirs = STATE.items.filter(i => i.isDir).length; |
| 1143 | const files = STATE.items.length - dirs; |
| 1144 | dl.innerHTML = ` |
| 1145 | <dt>Path</dt><dd>${STATE.currentDir}</dd> |
| 1146 | <dt>Folders</dt><dd>${dirs}</dd> |
| 1147 | <dt>Files</dt><dd>${files}</dd> |
| 1148 | `; |
| 1149 | } |
| 1150 | |
| 1151 | function closeSidebar () |
| 1152 | { |
| 1153 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 1154 | STATE.selectedItem = null; |
| 1155 | |
| 1156 | if (isMobileViewport()) |
| 1157 | { |
| 1158 | hideSidebarPanel(); |
| 1159 | return; |
| 1160 | } |
| 1161 | |
| 1162 | openFolderSidebar(); |
| 1163 | } |
| 1164 | |
| 1165 | function isMobileViewport () |
| 1166 | { |
| 1167 | return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches; |
| 1168 | } |
| 1169 | |
| 1170 | function hideSidebarPanel () |
| 1171 | { |
| 1172 | const sidebar = document.getElementById('sidebar'); |
| 1173 | const app = document.getElementById('app'); |
| 1174 | sidebar.classList.add('hidden'); |
| 1175 | app.classList.remove('sidebar-open'); |
| 1176 | } |
| 1177 | |
| 1178 | function basenameOfPath (p) |
| 1179 | { |
| 1180 | const parts = String(p || '').split(/[\\/]/).filter(Boolean); |
| 1181 | return parts.length ? parts[parts.length - 1] : String(p || ''); |
| 1182 | } |
| 1183 | |
| 1184 | function writableRoots () |
| 1185 | { |
| 1186 | if (STATE.isAdmin) return STATE.roots.slice(); |
| 1187 | return STATE.roots.filter((r) => |
| 1188 | { |
| 1189 | const perm = STATE.permissions[r.label]; |
| 1190 | return !!(perm && perm.write); |
| 1191 | }); |
| 1192 | } |
| 1193 | |
| 1194 | function ensureMoveModal () |
| 1195 | { |
| 1196 | let overlay = document.getElementById('move-modal'); |
| 1197 | if (overlay) return overlay; |
| 1198 | |
| 1199 | overlay = document.createElement('div'); |
| 1200 | overlay.id = 'move-modal'; |
| 1201 | overlay.className = 'modal-overlay hidden'; |
| 1202 | overlay.innerHTML = ` |
| 1203 | <div class="modal move-modal"> |
| 1204 | <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button> |
| 1205 | <h2>Move To</h2> |
| 1206 | <p id="move-modal-caption" class="muted"></p> |
| 1207 | <div id="move-tree" class="move-tree"></div> |
| 1208 | <p id="move-selected" class="muted"></p> |
| 1209 | <div class="dialog-actions"> |
| 1210 | <button id="move-modal-cancel">Cancel</button> |
| 1211 | <button id="move-modal-confirm" class="primary">Move</button> |
| 1212 | </div> |
| 1213 | </div> |
| 1214 | `; |
| 1215 | document.body.appendChild(overlay); |
| 1216 | |
| 1217 | const closeBtn = overlay.querySelector('#move-modal-close'); |
| 1218 | const cancelBtn = overlay.querySelector('#move-modal-cancel'); |
| 1219 | const confirmBtn = overlay.querySelector('#move-modal-confirm'); |
| 1220 | |
| 1221 | function hide () |
| 1222 | { |
| 1223 | overlay.classList.add('hidden'); |
| 1224 | STATE.movePicker = null; |
| 1225 | } |
| 1226 | |
| 1227 | closeBtn.addEventListener('click', hide); |
| 1228 | cancelBtn.addEventListener('click', hide); |
| 1229 | overlay.addEventListener('click', (e) => |
| 1230 | { |
| 1231 | if (e.target === overlay) hide(); |
| 1232 | }); |
| 1233 | |
| 1234 | confirmBtn.addEventListener('click', async () => |
| 1235 | { |
| 1236 | const st = STATE.movePicker; |
| 1237 | if (!st || !st.item || !st.selectedPath) |
| 1238 | { |
| 1239 | toast('Select a destination folder first.', 'err'); |
| 1240 | return; |
| 1241 | } |
| 1242 | |
| 1243 | try |
| 1244 | { |
| 1245 | await api('POST', '/files/move', { from: st.item.path, toDir: st.selectedPath }); |
| 1246 | } |
| 1247 | catch (err) |
| 1248 | { |
| 1249 | toast('Move failed: ' + err.message, 'err'); |
| 1250 | return; |
| 1251 | } |
| 1252 | |
| 1253 | hide(); |
| 1254 | if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar(); |
| 1255 | navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1256 | }); |
| 1257 | |
| 1258 | return overlay; |
| 1259 | } |
| 1260 | |
| 1261 | function setMoveSelection (path, buttonEl) |
| 1262 | { |
| 1263 | if (!STATE.movePicker) return; |
| 1264 | STATE.movePicker.selectedPath = path; |
| 1265 | |
| 1266 | document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected')); |
| 1267 | if (buttonEl) buttonEl.classList.add('selected'); |
| 1268 | |
| 1269 | const selectedEl = document.getElementById('move-selected'); |
| 1270 | selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none'; |
| 1271 | } |
| 1272 | |
| 1273 | async function loadMoveChildren (containerEl, dirPath) |
| 1274 | { |
| 1275 | if (containerEl.dataset.loaded === '1') return; |
| 1276 | containerEl.dataset.loaded = '1'; |
| 1277 | |
| 1278 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null); |
| 1279 | const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : []; |
| 1280 | |
| 1281 | if (!folders.length) |
| 1282 | { |
| 1283 | const empty = document.createElement('div'); |
| 1284 | empty.className = 'move-empty'; |
| 1285 | empty.textContent = 'No subfolders'; |
| 1286 | containerEl.appendChild(empty); |
| 1287 | return; |
| 1288 | } |
| 1289 | |
| 1290 | for (const child of folders) |
| 1291 | { |
| 1292 | containerEl.appendChild(createMoveNode(child.path, child.name)); |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | function createMoveNode (folderPath, label) |
| 1297 | { |
| 1298 | const node = document.createElement('div'); |
| 1299 | node.className = 'move-node'; |
| 1300 | |
| 1301 | const row = document.createElement('div'); |
| 1302 | row.className = 'move-node-row'; |
| 1303 | |
| 1304 | const toggle = document.createElement('button'); |
| 1305 | toggle.type = 'button'; |
| 1306 | toggle.className = 'move-toggle'; |
| 1307 | toggle.textContent = '▸'; |
| 1308 | |
| 1309 | const selectBtn = document.createElement('button'); |
| 1310 | selectBtn.type = 'button'; |
| 1311 | selectBtn.className = 'move-node-label'; |
| 1312 | selectBtn.textContent = label; |
| 1313 | selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn)); |
| 1314 | |
| 1315 | const children = document.createElement('div'); |
| 1316 | children.className = 'move-children hidden'; |
| 1317 | |
| 1318 | toggle.addEventListener('click', async () => |
| 1319 | { |
| 1320 | if (children.classList.contains('hidden')) |
| 1321 | { |
| 1322 | await loadMoveChildren(children, folderPath); |
| 1323 | children.classList.remove('hidden'); |
| 1324 | toggle.textContent = '▾'; |
| 1325 | } else |
| 1326 | { |
| 1327 | children.classList.add('hidden'); |
| 1328 | toggle.textContent = '▸'; |
| 1329 | } |
| 1330 | }); |
| 1331 | |
| 1332 | row.appendChild(toggle); |
| 1333 | row.appendChild(selectBtn); |
| 1334 | node.appendChild(row); |
| 1335 | node.appendChild(children); |
| 1336 | return node; |
| 1337 | } |
| 1338 | |
| 1339 | function openMovePicker (item) |
| 1340 | { |
| 1341 | if (!canWrite()) |
| 1342 | { |
| 1343 | toast('No write access.', 'err'); |
| 1344 | return; |
| 1345 | } |
| 1346 | |
| 1347 | const roots = writableRoots(); |
| 1348 | if (!roots.length) |
| 1349 | { |
| 1350 | toast('No writable destination roots available.', 'err'); |
| 1351 | return; |
| 1352 | } |
| 1353 | |
| 1354 | const overlay = ensureMoveModal(); |
| 1355 | const tree = overlay.querySelector('#move-tree'); |
| 1356 | const caption = overlay.querySelector('#move-modal-caption'); |
| 1357 | |
| 1358 | STATE.movePicker = { item, selectedPath: null }; |
| 1359 | caption.textContent = `Select destination folder for: ${item.name}`; |
| 1360 | tree.innerHTML = ''; |
| 1361 | |
| 1362 | for (const root of roots) |
| 1363 | { |
| 1364 | tree.appendChild(createMoveNode(root.path, root.label)); |
| 1365 | } |
| 1366 | |
| 1367 | setMoveSelection(null, null); |
| 1368 | overlay.classList.remove('hidden'); |
| 1369 | } |
| 1370 | |
| 1371 | // ─────────────────────────────────────────────────────────────────────────── |
| 1372 | // DOWNLOAD / VIEW |
| 1373 | // ─────────────────────────────────────────────────────────────────────────── |
| 1374 | |
| 1375 | function isInlinePreviewableBlob (blob, name) |
| 1376 | { |
| 1377 | const mime = String(blob.type || '').toLowerCase(); |
| 1378 | if (/^(image|video|audio)\//.test(mime)) return true; |
| 1379 | if (/^text\//.test(mime)) return true; |
| 1380 | if (mime === 'application/pdf') return true; |
| 1381 | if (mime === 'application/json') return true; |
| 1382 | if (mime === 'application/xml') return true; |
| 1383 | if (mime === 'application/javascript') return true; |
| 1384 | |
| 1385 | // Fallback by extension when MIME is missing or generic. |
| 1386 | const ext = extOf(name || ''); |
| 1387 | if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true; |
| 1388 | if (CODE_EXTS.has(ext)) return true; |
| 1389 | return false; |
| 1390 | } |
| 1391 | |
| 1392 | function isTextLikeBlob (blob, name) |
| 1393 | { |
| 1394 | const mime = String(blob.type || '').toLowerCase(); |
| 1395 | if (/^text\//.test(mime)) return true; |
| 1396 | if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true; |
| 1397 | const ext = extOf(name || ''); |
| 1398 | return CODE_EXTS.has(ext); |
| 1399 | } |
| 1400 | |
| 1401 | function detectCodeLanguage (name, mime) |
| 1402 | { |
| 1403 | const ext = extOf(name || ''); |
| 1404 | const m = String(mime || '').toLowerCase(); |
| 1405 | if (m.includes('json') || ext === 'json') return 'json'; |
| 1406 | if (m.includes('xml') || ext === 'xml') return 'xml'; |
| 1407 | if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html'; |
| 1408 | if (m.includes('css') || ext === 'css') return 'css'; |
| 1409 | if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js'; |
| 1410 | if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts'; |
| 1411 | if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh'; |
| 1412 | if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain'; |
| 1413 | return CODE_EXTS.has(ext) ? 'js' : 'plain'; |
| 1414 | } |
| 1415 | |
| 1416 | function prettyPrintMarkup (raw) |
| 1417 | { |
| 1418 | const src = String(raw || '') |
| 1419 | .replace(/>\s+</g, '><') |
| 1420 | .replace(/\r\n/g, '\n'); |
| 1421 | |
| 1422 | const lines = src.replace(/></g, '>\n<').split('\n'); |
| 1423 | let indent = 0; |
| 1424 | const out = []; |
| 1425 | |
| 1426 | for (const ln of lines) |
| 1427 | { |
| 1428 | const line = ln.trim(); |
| 1429 | if (!line) continue; |
| 1430 | const isClose = /^<\//.test(line); |
| 1431 | const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line); |
| 1432 | const isOpen = /^<[^!?/][^>]*>$/.test(line); |
| 1433 | |
| 1434 | if (isClose) indent = Math.max(0, indent - 1); |
| 1435 | out.push(' '.repeat(indent) + line); |
| 1436 | if (isOpen && !isSelf) indent += 1; |
| 1437 | } |
| 1438 | |
| 1439 | return out.join('\n'); |
| 1440 | } |
| 1441 | |
| 1442 | function prettyPrintBraces (raw) |
| 1443 | { |
| 1444 | const lines = String(raw || '') |
| 1445 | .replace(/\r\n/g, '\n') |
| 1446 | .split('\n'); |
| 1447 | let indent = 0; |
| 1448 | const out = []; |
| 1449 | |
| 1450 | for (const ln of lines) |
| 1451 | { |
| 1452 | const line = ln.trim(); |
| 1453 | if (!line) |
| 1454 | { |
| 1455 | out.push(''); |
| 1456 | continue; |
| 1457 | } |
| 1458 | if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1); |
| 1459 | out.push(' '.repeat(indent) + line); |
| 1460 | if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1; |
| 1461 | } |
| 1462 | return out.join('\n'); |
| 1463 | } |
| 1464 | |
| 1465 | function prettyPrintCode (raw, lang) |
| 1466 | { |
| 1467 | const text = String(raw || '').replace(/\r\n/g, '\n'); |
| 1468 | if (lang === 'json') |
| 1469 | { |
| 1470 | try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; } |
| 1471 | } |
| 1472 | if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text); |
| 1473 | if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text); |
| 1474 | return text; |
| 1475 | } |
| 1476 | |
| 1477 | function escapeHtml (s) |
| 1478 | { |
| 1479 | return String(s) |
| 1480 | .replace(/&/g, '&') |
| 1481 | .replace(/</g, '<') |
| 1482 | .replace(/>/g, '>'); |
| 1483 | } |
| 1484 | |
| 1485 | function highlightCode (raw, lang) |
| 1486 | { |
| 1487 | if (lang === 'plain') return escapeHtml(raw); |
| 1488 | |
| 1489 | let html = escapeHtml(raw); |
| 1490 | const stash = []; |
| 1491 | const keep = (regex, cls) => |
| 1492 | { |
| 1493 | html = html.replace(regex, (m) => |
| 1494 | { |
| 1495 | const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1; |
| 1496 | return `@@TOK${idx}@@`; |
| 1497 | }); |
| 1498 | }; |
| 1499 | |
| 1500 | if (lang === 'json') |
| 1501 | { |
| 1502 | html = html |
| 1503 | .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:') |
| 1504 | .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>') |
| 1505 | .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>') |
| 1506 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 1507 | return html; |
| 1508 | } |
| 1509 | |
| 1510 | if (lang === 'xml' || lang === 'html') |
| 1511 | { |
| 1512 | html = html |
| 1513 | .replace(/(<\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>') |
| 1514 | .replace(/([a-zA-Z0-9:_-]+)=("[^&]*"|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>'); |
| 1515 | return html; |
| 1516 | } |
| 1517 | |
| 1518 | if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment'); |
| 1519 | else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment'); |
| 1520 | keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string'); |
| 1521 | |
| 1522 | html = html |
| 1523 | .replace(/\b(function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b/g, '<span class="tok-keyword">$1</span>') |
| 1524 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 1525 | |
| 1526 | html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || ''); |
| 1527 | return html; |
| 1528 | } |
| 1529 | |
| 1530 | function clearPreviewObjectUrl () |
| 1531 | { |
| 1532 | if (!STATE.previewObjectUrl) return; |
| 1533 | URL.revokeObjectURL(STATE.previewObjectUrl); |
| 1534 | STATE.previewObjectUrl = null; |
| 1535 | } |
| 1536 | |
| 1537 | function fileAccentColor (name) |
| 1538 | { |
| 1539 | const ext = extOf(name || ''); |
| 1540 | if (IMAGE_EXTS.has(ext)) return '#3fcf8e'; |
| 1541 | if (VIDEO_EXTS.has(ext)) return '#e05c6e'; |
| 1542 | if (AUDIO_EXTS.has(ext)) return '#c084fc'; |
| 1543 | if (DOC_EXTS.has(ext)) return '#f97316'; |
| 1544 | if (CODE_EXTS.has(ext)) return '#38bdf8'; |
| 1545 | if (ARCHIVE_EXTS.has(ext)) return '#facc15'; |
| 1546 | return '#7880a0'; |
| 1547 | } |
| 1548 | |
| 1549 | function animatePreviewOpen (sourceSvgEl, sheetEl) |
| 1550 | { |
| 1551 | if (!sourceSvgEl || !sheetEl || !sourceSvgEl.isConnected) return Promise.resolve({ startScale: 0.12 }); |
| 1552 | |
| 1553 | const start = sourceSvgEl.getBoundingClientRect(); |
| 1554 | const end = sheetEl.getBoundingClientRect(); |
| 1555 | if (!start.width || !start.height || !end.width || !end.height) return Promise.resolve({ startScale: 0.12 }); |
| 1556 | |
| 1557 | const ghost = document.createElement('div'); |
| 1558 | ghost.className = 'preview-ghost'; |
| 1559 | ghost.style.left = `${start.left}px`; |
| 1560 | ghost.style.top = `${start.top}px`; |
| 1561 | ghost.style.width = `${start.width}px`; |
| 1562 | ghost.style.height = `${start.height}px`; |
| 1563 | |
| 1564 | // Clone before hiding so the ghost is a visible copy |
| 1565 | const clone = sourceSvgEl.cloneNode(true); |
| 1566 | // Hide source icon for the duration of the preview |
| 1567 | sourceSvgEl.style.visibility = 'hidden'; |
| 1568 | clone.style.width = '100%'; |
| 1569 | clone.style.height = '100%'; |
| 1570 | clone.style.display = 'block'; |
| 1571 | ghost.appendChild(clone); |
| 1572 | document.body.appendChild(ghost); |
| 1573 | |
| 1574 | // Bézier path: random control points in viewport space |
| 1575 | const vw = window.innerWidth; |
| 1576 | const vh = window.innerHeight; |
| 1577 | const startCx = start.left + start.width / 2; |
| 1578 | const startCy = start.top + start.height / 2; |
| 1579 | const endCx = end.left + end.width / 2; |
| 1580 | const endCy = end.top + end.height / 2; |
| 1581 | const cp1x = startCx + (Math.random() - 0.5) * vw * 0.8; |
| 1582 | const cp1y = startCy + (Math.random() - 0.5) * vh * 0.8; |
| 1583 | const cp2x = endCx + (Math.random() - 0.5) * vw * 0.6; |
| 1584 | const cp2y = endCy + (Math.random() - 0.5) * vh * 0.6; |
| 1585 | |
| 1586 | // Random full rotations: -3 to +3 |
| 1587 | const totalDeg = (Math.random() * 6 - 3) * 360; |
| 1588 | const duration = 640; |
| 1589 | const startTime = performance.now(); |
| 1590 | const startScale = start.width / end.width; |
| 1591 | |
| 1592 | function easeInOut (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; } |
| 1593 | function bezier1D (p0, p1, p2, p3, t) |
| 1594 | { |
| 1595 | const u = 1 - t; |
| 1596 | return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3; |
| 1597 | } |
| 1598 | |
| 1599 | return new Promise((resolve) => |
| 1600 | { |
| 1601 | function frame (now) |
| 1602 | { |
| 1603 | const raw = Math.min((now - startTime) / duration, 1); |
| 1604 | const t = easeInOut(raw); |
| 1605 | |
| 1606 | const cx = bezier1D(startCx, cp1x, cp2x, endCx, t); |
| 1607 | const cy = bezier1D(startCy, cp1y, cp2y, endCy, t); |
| 1608 | const w = start.width + (end.width - start.width) * t; |
| 1609 | const h = start.height + (end.height - start.height) * t; |
| 1610 | const angle = t * totalDeg; |
| 1611 | const opacity = raw > 0.82 ? 1 - (raw - 0.82) / 0.18 : 1; |
| 1612 | |
| 1613 | ghost.style.left = `${cx - w / 2}px`; |
| 1614 | ghost.style.top = `${cy - h / 2}px`; |
| 1615 | ghost.style.width = `${w}px`; |
| 1616 | ghost.style.height = `${h}px`; |
| 1617 | ghost.style.transform = `rotate(${angle}deg)`; |
| 1618 | ghost.style.opacity = opacity; |
| 1619 | |
| 1620 | if (raw < 1) |
| 1621 | { |
| 1622 | requestAnimationFrame(frame); |
| 1623 | } else |
| 1624 | { |
| 1625 | ghost.remove(); |
| 1626 | resolve({ startScale }); |
| 1627 | } |
| 1628 | } |
| 1629 | requestAnimationFrame(frame); |
| 1630 | }); |
| 1631 | } |
| 1632 | |
| 1633 | function animatePreviewClose (sourceSvgEl, sheetEl) |
| 1634 | { |
| 1635 | if (!sourceSvgEl || !sheetEl || !sourceSvgEl.isConnected) return Promise.resolve(); |
| 1636 | |
| 1637 | const sheetRect = sheetEl.getBoundingClientRect(); |
| 1638 | const iconRect = sourceSvgEl.getBoundingClientRect(); |
| 1639 | if (!sheetRect.width || !iconRect.width) return Promise.resolve(); |
| 1640 | |
| 1641 | // Ghost starts at sheet center, icon-sized, then flies back to icon |
| 1642 | const ghost = document.createElement('div'); |
| 1643 | ghost.className = 'preview-ghost'; |
| 1644 | |
| 1645 | const clone = sourceSvgEl.cloneNode(true); |
| 1646 | clone.style.width = '100%'; |
| 1647 | clone.style.height = '100%'; |
| 1648 | clone.style.display = 'block'; |
| 1649 | ghost.appendChild(clone); |
| 1650 | document.body.appendChild(ghost); |
| 1651 | |
| 1652 | const vw = window.innerWidth; |
| 1653 | const vh = window.innerHeight; |
| 1654 | const startCx = sheetRect.left + sheetRect.width / 2; |
| 1655 | const startCy = sheetRect.top + sheetRect.height / 2; |
| 1656 | const endCx = iconRect.left + iconRect.width / 2; |
| 1657 | const endCy = iconRect.top + iconRect.height / 2; |
| 1658 | |
| 1659 | const cp1x = startCx + (Math.random() - 0.5) * vw * 0.6; |
| 1660 | const cp1y = startCy + (Math.random() - 0.5) * vh * 0.6; |
| 1661 | const cp2x = endCx + (Math.random() - 0.5) * vw * 0.5; |
| 1662 | const cp2y = endCy + (Math.random() - 0.5) * vh * 0.5; |
| 1663 | |
| 1664 | const totalDeg = (Math.random() * 6 - 3) * 360; |
| 1665 | const duration = 580; |
| 1666 | const startTime = performance.now(); |
| 1667 | |
| 1668 | function easeInOut (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; } |
| 1669 | function bezier1D (p0, p1, p2, p3, t) |
| 1670 | { |
| 1671 | const u = 1 - t; |
| 1672 | return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3; |
| 1673 | } |
| 1674 | |
| 1675 | return new Promise((resolve) => |
| 1676 | { |
| 1677 | function frame (now) |
| 1678 | { |
| 1679 | const raw = Math.min((now - startTime) / duration, 1); |
| 1680 | const t = easeInOut(raw); |
| 1681 | |
| 1682 | const cx = bezier1D(startCx, cp1x, cp2x, endCx, t); |
| 1683 | const cy = bezier1D(startCy, cp1y, cp2y, endCy, t); |
| 1684 | const angle = t * totalDeg; |
| 1685 | const opacity = raw < 0.85 ? 1 : 1 - (raw - 0.85) / 0.15; |
| 1686 | |
| 1687 | ghost.style.left = `${cx - iconRect.width / 2}px`; |
| 1688 | ghost.style.top = `${cy - iconRect.height / 2}px`; |
| 1689 | ghost.style.width = `${iconRect.width}px`; |
| 1690 | ghost.style.height = `${iconRect.height}px`; |
| 1691 | ghost.style.transform = `rotate(${angle}deg)`; |
| 1692 | ghost.style.opacity = opacity; |
| 1693 | |
| 1694 | if (raw < 1) |
| 1695 | { |
| 1696 | requestAnimationFrame(frame); |
| 1697 | } else |
| 1698 | { |
| 1699 | ghost.remove(); |
| 1700 | sourceSvgEl.style.visibility = ''; |
| 1701 | resolve(); |
| 1702 | } |
| 1703 | } |
| 1704 | requestAnimationFrame(frame); |
| 1705 | }); |
| 1706 | } |
| 1707 | |
| 1708 | function animateRect (el, fromRect, toRect, opts = {}) |
| 1709 | { |
| 1710 | const duration = opts.duration == null ? 260 : opts.duration; |
| 1711 | const easeOut = (t) => 1 - Math.pow(1 - t, 3); |
| 1712 | |
| 1713 | el.style.left = `${fromRect.left}px`; |
| 1714 | el.style.top = `${fromRect.top}px`; |
| 1715 | el.style.width = `${fromRect.width}px`; |
| 1716 | el.style.height = `${fromRect.height}px`; |
| 1717 | |
| 1718 | return new Promise((resolve) => |
| 1719 | { |
| 1720 | const t0 = performance.now(); |
| 1721 | |
| 1722 | function frame (now) |
| 1723 | { |
| 1724 | const raw = Math.min((now - t0) / duration, 1); |
| 1725 | const t = easeOut(raw); |
| 1726 | |
| 1727 | const left = fromRect.left + (toRect.left - fromRect.left) * t; |
| 1728 | const top = fromRect.top + (toRect.top - fromRect.top) * t; |
| 1729 | const width = fromRect.width + (toRect.width - fromRect.width) * t; |
| 1730 | const height = fromRect.height + (toRect.height - fromRect.height) * t; |
| 1731 | |
| 1732 | el.style.left = `${left}px`; |
| 1733 | el.style.top = `${top}px`; |
| 1734 | el.style.width = `${width}px`; |
| 1735 | el.style.height = `${height}px`; |
| 1736 | |
| 1737 | if (raw < 1) |
| 1738 | { |
| 1739 | requestAnimationFrame(frame); |
| 1740 | } else |
| 1741 | { |
| 1742 | resolve(); |
| 1743 | } |
| 1744 | } |
| 1745 | |
| 1746 | requestAnimationFrame(frame); |
| 1747 | }); |
| 1748 | } |
| 1749 | |
| 1750 | async function openExpandedTilePreview (item, tileEl, sourceSvgEl, blob, objectUrl) |
| 1751 | { |
| 1752 | if (!tileEl || !sourceSvgEl) return false; |
| 1753 | |
| 1754 | if (STATE.previewExpandState) |
| 1755 | { |
| 1756 | await closeExpandedTilePreview(); |
| 1757 | } |
| 1758 | |
| 1759 | const iconEl = tileEl.querySelector('.icon'); |
| 1760 | const nameEl = tileEl.querySelector('.name'); |
| 1761 | if (!iconEl) return false; |
| 1762 | |
| 1763 | const startRect = tileEl.getBoundingClientRect(); |
| 1764 | const targetW = Math.min(window.innerWidth * 0.94, 1100); |
| 1765 | const targetH = Math.min(window.innerHeight * 0.9, 860); |
| 1766 | const targetRect = { |
| 1767 | left: (window.innerWidth - targetW) / 2, |
| 1768 | top: (window.innerHeight - targetH) / 2, |
| 1769 | width: targetW, |
| 1770 | height: targetH, |
| 1771 | }; |
| 1772 | |
| 1773 | const backdrop = document.createElement('div'); |
| 1774 | backdrop.className = 'preview-backdrop'; |
| 1775 | document.body.appendChild(backdrop); |
| 1776 | |
| 1777 | const parent = tileEl.parentNode; |
| 1778 | const nextSibling = tileEl.nextSibling; |
| 1779 | const iconHtml = iconEl.innerHTML; |
| 1780 | const originalIconSvg = iconEl.querySelector('svg'); |
| 1781 | |
| 1782 | tileEl.remove(); |
| 1783 | document.body.appendChild(tileEl); |
| 1784 | tileEl.classList.add('file-item--preview'); |
| 1785 | tileEl.style.position = 'fixed'; |
| 1786 | tileEl.style.left = `${startRect.left}px`; |
| 1787 | tileEl.style.top = `${startRect.top}px`; |
| 1788 | tileEl.style.width = `${startRect.width}px`; |
| 1789 | tileEl.style.height = `${startRect.height}px`; |
| 1790 | tileEl.style.margin = '0'; |
| 1791 | tileEl.style.zIndex = '10000'; |
| 1792 | |
| 1793 | if (nameEl) nameEl.style.display = 'none'; |
| 1794 | |
| 1795 | const titleEl = document.createElement('div'); |
| 1796 | titleEl.className = 'preview-expand-title'; |
| 1797 | titleEl.textContent = item.name; |
| 1798 | |
| 1799 | const closeBtn = document.createElement('button'); |
| 1800 | closeBtn.className = 'preview-expand-close'; |
| 1801 | closeBtn.type = 'button'; |
| 1802 | closeBtn.textContent = '×'; |
| 1803 | closeBtn.setAttribute('aria-label', 'Close preview'); |
| 1804 | |
| 1805 | const dlBtn = document.createElement('button'); |
| 1806 | dlBtn.className = 'preview-expand-download'; |
| 1807 | dlBtn.type = 'button'; |
| 1808 | dlBtn.textContent = 'Download'; |
| 1809 | dlBtn.addEventListener('click', (e) => |
| 1810 | { |
| 1811 | e.stopPropagation(); |
| 1812 | triggerDownload(item.name, objectUrl); |
| 1813 | }); |
| 1814 | |
| 1815 | iconEl.innerHTML = ''; |
| 1816 | |
| 1817 | if (originalIconSvg) |
| 1818 | { |
| 1819 | const outline = originalIconSvg.cloneNode(true); |
| 1820 | outline.classList.add('preview-expand-outline'); |
| 1821 | iconEl.appendChild(outline); |
| 1822 | } |
| 1823 | |
| 1824 | const previewMount = document.createElement('div'); |
| 1825 | previewMount.className = 'preview-expand-content'; |
| 1826 | iconEl.appendChild(previewMount); |
| 1827 | |
| 1828 | await renderPreviewBody(item, blob, objectUrl, previewMount); |
| 1829 | |
| 1830 | tileEl.insertBefore(titleEl, tileEl.firstChild); |
| 1831 | tileEl.appendChild(closeBtn); |
| 1832 | tileEl.appendChild(dlBtn); |
| 1833 | |
| 1834 | STATE.previewExpandState = { |
| 1835 | item, |
| 1836 | tileEl, |
| 1837 | sourceSvgEl, |
| 1838 | parent, |
| 1839 | nextSibling, |
| 1840 | iconEl, |
| 1841 | iconHtml, |
| 1842 | nameEl, |
| 1843 | backdrop, |
| 1844 | closeBtn, |
| 1845 | dlBtn, |
| 1846 | titleEl, |
| 1847 | previewMount, |
| 1848 | startRect, |
| 1849 | }; |
| 1850 | |
| 1851 | const onBackdrop = (e) => |
| 1852 | { |
| 1853 | if (e.target === backdrop) closePreview(); |
| 1854 | }; |
| 1855 | const onClose = () => closePreview(); |
| 1856 | backdrop.addEventListener('click', onBackdrop); |
| 1857 | closeBtn.addEventListener('click', onClose); |
| 1858 | STATE.previewExpandState.onBackdrop = onBackdrop; |
| 1859 | STATE.previewExpandState.onClose = onClose; |
| 1860 | |
| 1861 | requestAnimationFrame(() => backdrop.classList.add('visible')); |
| 1862 | await animateRect(tileEl, startRect, targetRect); |
| 1863 | |
| 1864 | tileEl.style.left = `${targetRect.left}px`; |
| 1865 | tileEl.style.top = `${targetRect.top}px`; |
| 1866 | tileEl.style.width = `${targetRect.width}px`; |
| 1867 | tileEl.style.height = `${targetRect.height}px`; |
| 1868 | |
| 1869 | return true; |
| 1870 | } |
| 1871 | |
| 1872 | async function closeExpandedTilePreview () |
| 1873 | { |
| 1874 | const st = STATE.previewExpandState; |
| 1875 | if (!st) return; |
| 1876 | |
| 1877 | st.backdrop.classList.remove('visible'); |
| 1878 | if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop); |
| 1879 | if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose); |
| 1880 | |
| 1881 | const fromRect = st.tileEl.getBoundingClientRect(); |
| 1882 | await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 }); |
| 1883 | |
| 1884 | st.tileEl.classList.remove('file-item--preview'); |
| 1885 | st.tileEl.style.position = ''; |
| 1886 | st.tileEl.style.left = ''; |
| 1887 | st.tileEl.style.top = ''; |
| 1888 | st.tileEl.style.width = ''; |
| 1889 | st.tileEl.style.height = ''; |
| 1890 | st.tileEl.style.margin = ''; |
| 1891 | st.tileEl.style.zIndex = ''; |
| 1892 | |
| 1893 | if (st.titleEl) st.titleEl.remove(); |
| 1894 | if (st.closeBtn) st.closeBtn.remove(); |
| 1895 | if (st.dlBtn) st.dlBtn.remove(); |
| 1896 | if (st.iconEl) st.iconEl.innerHTML = st.iconHtml; |
| 1897 | if (st.nameEl) st.nameEl.style.display = ''; |
| 1898 | |
| 1899 | if (st.parent) |
| 1900 | { |
| 1901 | if (st.nextSibling && st.nextSibling.parentNode === st.parent) |
| 1902 | { |
| 1903 | st.parent.insertBefore(st.tileEl, st.nextSibling); |
| 1904 | } else |
| 1905 | { |
| 1906 | st.parent.appendChild(st.tileEl); |
| 1907 | } |
| 1908 | } |
| 1909 | |
| 1910 | if (st.backdrop) st.backdrop.remove(); |
| 1911 | STATE.previewExpandState = null; |
| 1912 | } |
| 1913 | |
| 1914 | async function closePreview () |
| 1915 | { |
| 1916 | if (STATE.previewExpandState) |
| 1917 | { |
| 1918 | await closeExpandedTilePreview(); |
| 1919 | clearPreviewObjectUrl(); |
| 1920 | STATE.previewSourceEl = null; |
| 1921 | return; |
| 1922 | } |
| 1923 | |
| 1924 | const overlay = document.getElementById('preview-overlay'); |
| 1925 | const body = document.getElementById('preview-body'); |
| 1926 | if (!overlay || !body) return; |
| 1927 | if (overlay.classList.contains('hidden')) return; |
| 1928 | if (STATE.previewClosing) return; |
| 1929 | STATE.previewClosing = true; |
| 1930 | |
| 1931 | const sourceSvgEl = STATE.previewSourceEl; |
| 1932 | if (sourceSvgEl && sourceSvgEl.isConnected) |
| 1933 | { |
| 1934 | const sheet = document.getElementById('preview-sheet'); |
| 1935 | // Shrink the sheet first, then fly ghost back |
| 1936 | await new Promise((res) => |
| 1937 | { |
| 1938 | const a = sheet.animate( |
| 1939 | [{ transform: 'scale(1)', opacity: 1 }, { transform: 'scale(0.06)', opacity: 0 }], |
| 1940 | { duration: 180, easing: 'cubic-bezier(0.4, 0, 1, 1)', fill: 'forwards' } |
| 1941 | ); |
| 1942 | a.onfinish = res; |
| 1943 | a.oncancel = res; |
| 1944 | }); |
| 1945 | overlay.classList.add('preview-prep'); |
| 1946 | sheet.style.transform = ''; |
| 1947 | sheet.style.opacity = ''; |
| 1948 | await animatePreviewClose(sourceSvgEl, sheet); |
| 1949 | } else if (sourceSvgEl) |
| 1950 | { |
| 1951 | sourceSvgEl.style.visibility = ''; |
| 1952 | } |
| 1953 | |
| 1954 | overlay.classList.add('hidden'); |
| 1955 | overlay.classList.remove('preview-prep'); |
| 1956 | body.innerHTML = ''; |
| 1957 | clearPreviewObjectUrl(); |
| 1958 | STATE.previewSourceEl = null; |
| 1959 | STATE.previewClosing = false; |
| 1960 | } |
| 1961 | |
| 1962 | async function fetchFileBlob (item) |
| 1963 | { |
| 1964 | const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; |
| 1965 | try |
| 1966 | { |
| 1967 | const res = await fetch(url, { |
| 1968 | headers: { |
| 1969 | Authorization: 'Bearer ' + STATE.token, |
| 1970 | 'X-Fp': getFingerprint(), |
| 1971 | }, |
| 1972 | }); |
| 1973 | if (!res.ok) throw new Error('Download failed.'); |
| 1974 | return await res.blob(); |
| 1975 | } catch |
| 1976 | { |
| 1977 | return null; |
| 1978 | } |
| 1979 | } |
| 1980 | |
| 1981 | function triggerDownload (filename, objectUrl) |
| 1982 | { |
| 1983 | const a = document.createElement('a'); |
| 1984 | a.href = objectUrl; |
| 1985 | a.download = filename; |
| 1986 | a.click(); |
| 1987 | } |
| 1988 | |
| 1989 | async function renderPreviewBody (item, blob, objectUrl, targetEl = null) |
| 1990 | { |
| 1991 | const body = targetEl || document.getElementById('preview-body'); |
| 1992 | body.innerHTML = ''; |
| 1993 | |
| 1994 | const mime = String(blob.type || '').toLowerCase(); |
| 1995 | const previewable = isInlinePreviewableBlob(blob, item.name); |
| 1996 | |
| 1997 | if (!previewable) |
| 1998 | { |
| 1999 | const msg = document.createElement('p'); |
| 2000 | msg.className = 'preview-unsupported'; |
| 2001 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 2002 | body.appendChild(msg); |
| 2003 | return; |
| 2004 | } |
| 2005 | |
| 2006 | if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name))) |
| 2007 | { |
| 2008 | const img = document.createElement('img'); |
| 2009 | img.className = 'preview-media'; |
| 2010 | img.src = objectUrl; |
| 2011 | img.alt = item.name; |
| 2012 | body.appendChild(img); |
| 2013 | return; |
| 2014 | } |
| 2015 | |
| 2016 | if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name))) |
| 2017 | { |
| 2018 | const video = document.createElement('video'); |
| 2019 | video.className = 'preview-media'; |
| 2020 | video.src = objectUrl; |
| 2021 | video.controls = true; |
| 2022 | video.preload = 'metadata'; |
| 2023 | body.appendChild(video); |
| 2024 | return; |
| 2025 | } |
| 2026 | |
| 2027 | if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name))) |
| 2028 | { |
| 2029 | const audio = document.createElement('audio'); |
| 2030 | audio.className = 'preview-audio'; |
| 2031 | audio.src = objectUrl; |
| 2032 | audio.controls = true; |
| 2033 | body.appendChild(audio); |
| 2034 | return; |
| 2035 | } |
| 2036 | |
| 2037 | if (mime === 'application/pdf') |
| 2038 | { |
| 2039 | const frame = document.createElement('iframe'); |
| 2040 | frame.className = 'preview-frame'; |
| 2041 | frame.src = objectUrl; |
| 2042 | frame.title = item.name; |
| 2043 | body.appendChild(frame); |
| 2044 | return; |
| 2045 | } |
| 2046 | |
| 2047 | if (isTextLikeBlob(blob, item.name)) |
| 2048 | { |
| 2049 | const text = await blob.text(); |
| 2050 | const lang = detectCodeLanguage(item.name, mime); |
| 2051 | const formatted = prettyPrintCode(text, lang); |
| 2052 | const pre = document.createElement('pre'); |
| 2053 | pre.className = 'preview-text preview-code'; |
| 2054 | pre.innerHTML = highlightCode(formatted, lang); |
| 2055 | body.appendChild(pre); |
| 2056 | return; |
| 2057 | } |
| 2058 | |
| 2059 | const msg = document.createElement('p'); |
| 2060 | msg.className = 'preview-unsupported'; |
| 2061 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 2062 | body.appendChild(msg); |
| 2063 | } |
| 2064 | |
| 2065 | async function downloadOrView (item, sourceSvgEl = null) |
| 2066 | { |
| 2067 | if (STATE.previewExpandState) |
| 2068 | { |
| 2069 | await closePreview(); |
| 2070 | } |
| 2071 | |
| 2072 | const blob = await fetchFileBlob(item); |
| 2073 | if (!blob) |
| 2074 | { |
| 2075 | toast('Download failed.', 'err'); |
| 2076 | return; |
| 2077 | } |
| 2078 | |
| 2079 | clearPreviewObjectUrl(); |
| 2080 | const objectUrl = URL.createObjectURL(blob); |
| 2081 | STATE.previewObjectUrl = objectUrl; |
| 2082 | |
| 2083 | const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null; |
| 2084 | if (sourceTileEl) |
| 2085 | { |
| 2086 | STATE.previewSourceEl = sourceSvgEl; |
| 2087 | const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, blob, objectUrl); |
| 2088 | if (expanded) return; |
| 2089 | } |
| 2090 | |
| 2091 | const overlay = document.getElementById('preview-overlay'); |
| 2092 | const sheet = document.getElementById('preview-sheet'); |
| 2093 | const title = document.getElementById('preview-title'); |
| 2094 | const dlBtn = document.getElementById('preview-download'); |
| 2095 | |
| 2096 | sheet.style.setProperty('--preview-accent', fileAccentColor(item.name)); |
| 2097 | title.textContent = item.name; |
| 2098 | dlBtn.onclick = () => triggerDownload(item.name, objectUrl); |
| 2099 | await renderPreviewBody(item, blob, objectUrl); |
| 2100 | |
| 2101 | STATE.previewSourceEl = sourceSvgEl || null; |
| 2102 | overlay.classList.add('preview-prep'); |
| 2103 | overlay.classList.remove('hidden'); |
| 2104 | const { startScale } = await animatePreviewOpen(sourceSvgEl, sheet); |
| 2105 | overlay.classList.remove('preview-prep'); |
| 2106 | |
| 2107 | // Scale sheet up from the icon's apparent size, driven by JS so the start |
| 2108 | // scale matches the actual icon-to-sheet ratio for this specific invocation |
| 2109 | const s = (startScale > 0 && startScale < 1) ? startScale : 0.12; |
| 2110 | const scaleAnim = sheet.animate( |
| 2111 | [{ transform: `scale(${s})`, opacity: 0 }, { transform: 'scale(1)', opacity: 1 }], |
| 2112 | { duration: 220, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1.05)', fill: 'forwards' } |
| 2113 | ); |
| 2114 | scaleAnim.onfinish = () => { sheet.style.transform = ''; sheet.style.opacity = ''; }; |
| 2115 | } |
| 2116 | |
| 2117 | // ─────────────────────────────────────────────────────────────────────────── |
| 2118 | // UPLOAD |
| 2119 | // ─────────────────────────────────────────────────────────────────────────── |
| 2120 | |
| 2121 | function canWrite () |
| 2122 | { |
| 2123 | if (STATE.isAdmin) return true; |
| 2124 | if (!STATE.currentRoot) return false; |
| 2125 | const p = STATE.permissions[STATE.currentRoot.label]; |
| 2126 | return p && p.write; |
| 2127 | } |
| 2128 | |
| 2129 | async function uploadFiles (fileList) |
| 2130 | { |
| 2131 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 2132 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 2133 | |
| 2134 | const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0); |
| 2135 | const formData = new FormData(); |
| 2136 | for (const f of fileList) formData.append('files', f); |
| 2137 | |
| 2138 | // Show upload bar |
| 2139 | const wrap = document.createElement('div'); |
| 2140 | wrap.className = 'upload-bar-wrap'; |
| 2141 | wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 2142 | document.body.appendChild(wrap); |
| 2143 | STATE.uploadInProgress = true; |
| 2144 | |
| 2145 | try |
| 2146 | { |
| 2147 | const xhr = new XMLHttpRequest(); |
| 2148 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`); |
| 2149 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 2150 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 2151 | xhr.setRequestHeader('X-Upload-Size', String(totalSize)); |
| 2152 | xhr.upload.addEventListener('progress', e => |
| 2153 | { |
| 2154 | if (e.lengthComputable) |
| 2155 | { |
| 2156 | wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%'; |
| 2157 | } |
| 2158 | }); |
| 2159 | |
| 2160 | await new Promise((resolve, reject) => |
| 2161 | { |
| 2162 | xhr.onload = () => |
| 2163 | { |
| 2164 | if (xhr.status === 200) resolve(); |
| 2165 | else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed')); |
| 2166 | }; |
| 2167 | xhr.onerror = () => reject(new Error('Network error')); |
| 2168 | xhr.send(formData); |
| 2169 | }); |
| 2170 | |
| 2171 | toast(`Uploaded ${fileList.length} file(s).`, 'ok'); |
| 2172 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 2173 | } catch (err) |
| 2174 | { |
| 2175 | toast(err.message, 'err'); |
| 2176 | } finally |
| 2177 | { |
| 2178 | STATE.uploadInProgress = false; |
| 2179 | wrap.remove(); |
| 2180 | } |
| 2181 | } |
| 2182 | |
| 2183 | async function uploadSingleFile (file, targetDir) |
| 2184 | { |
| 2185 | const formData = new FormData(); |
| 2186 | formData.append('files', file); |
| 2187 | |
| 2188 | await new Promise((resolve, reject) => |
| 2189 | { |
| 2190 | const xhr = new XMLHttpRequest(); |
| 2191 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); |
| 2192 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 2193 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 2194 | xhr.setRequestHeader('X-Upload-Size', String(file.size || 0)); |
| 2195 | xhr.onload = () => xhr.status === 200 |
| 2196 | ? resolve() |
| 2197 | : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); |
| 2198 | xhr.onerror = () => reject(new Error('Network error')); |
| 2199 | xhr.send(formData); |
| 2200 | }); |
| 2201 | } |
| 2202 | |
| 2203 | async function ensureServerDir (baseDir, relativeDir) |
| 2204 | { |
| 2205 | const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean); |
| 2206 | let current = baseDir; |
| 2207 | for (const part of parts) |
| 2208 | { |
| 2209 | try |
| 2210 | { |
| 2211 | const resp = await api('POST', '/files/mkdir', { dir: current, name: part }); |
| 2212 | current = resp && resp.path ? resp.path : joinServerPath(current, part); |
| 2213 | } catch (err) |
| 2214 | { |
| 2215 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 2216 | current = joinServerPath(current, part); |
| 2217 | } |
| 2218 | } |
| 2219 | return current; |
| 2220 | } |
| 2221 | |
| 2222 | async function uploadFolderInputFiles (fileList) |
| 2223 | { |
| 2224 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 2225 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 2226 | if (!fileList || !fileList.length) return; |
| 2227 | |
| 2228 | const files = Array.from(fileList); |
| 2229 | const total = files.length; |
| 2230 | let done = 0; |
| 2231 | |
| 2232 | const wrap = document.createElement('div'); |
| 2233 | wrap.className = 'upload-bar-wrap'; |
| 2234 | wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 2235 | document.body.appendChild(wrap); |
| 2236 | STATE.uploadInProgress = true; |
| 2237 | |
| 2238 | try |
| 2239 | { |
| 2240 | const dirCache = new Map(); |
| 2241 | dirCache.set('', STATE.currentDir); |
| 2242 | |
| 2243 | for (const file of files) |
| 2244 | { |
| 2245 | const rel = file.webkitRelativePath || file.name; |
| 2246 | const relParts = rel.split(/[\\/]/).filter(Boolean); |
| 2247 | const relDir = relParts.slice(0, -1).join('/'); |
| 2248 | |
| 2249 | if (!dirCache.has(relDir)) |
| 2250 | { |
| 2251 | const parentRel = relParts.slice(0, -2).join('/'); |
| 2252 | const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel); |
| 2253 | const thisName = relParts[relParts.length - 2]; |
| 2254 | |
| 2255 | try |
| 2256 | { |
| 2257 | const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName }); |
| 2258 | dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName)); |
| 2259 | } catch (err) |
| 2260 | { |
| 2261 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 2262 | dirCache.set(relDir, joinServerPath(parentAbs, thisName)); |
| 2263 | } |
| 2264 | } |
| 2265 | |
| 2266 | const targetDir = dirCache.get(relDir) || STATE.currentDir; |
| 2267 | await uploadSingleFile(file, targetDir); |
| 2268 | done++; |
| 2269 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 2270 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 2271 | } |
| 2272 | |
| 2273 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 2274 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 2275 | } catch (err) |
| 2276 | { |
| 2277 | toast(err.message, 'err'); |
| 2278 | } finally |
| 2279 | { |
| 2280 | STATE.uploadInProgress = false; |
| 2281 | wrap.remove(); |
| 2282 | } |
| 2283 | } |
| 2284 | |
| 2285 | // ─────────────────────────────────────────────────────────────────────────── |
| 2286 | // FOLDER DRAG-AND-DROP (recursive) |
| 2287 | // ─────────────────────────────────────────────────────────────────────────── |
| 2288 | |
| 2289 | /** |
| 2290 | * Reads all readEntries batches from a DirectoryReader (browsers may return |
| 2291 | * results in chunks; we must keep calling until we get an empty array). |
| 2292 | */ |
| 2293 | function readAllEntries (reader) |
| 2294 | { |
| 2295 | return new Promise((resolve, reject) => |
| 2296 | { |
| 2297 | const all = []; |
| 2298 | function next () |
| 2299 | { |
| 2300 | reader.readEntries(batch => |
| 2301 | { |
| 2302 | if (!batch.length) { resolve(all); return; } |
| 2303 | all.push(...batch); |
| 2304 | next(); |
| 2305 | }, reject); |
| 2306 | } |
| 2307 | next(); |
| 2308 | }); |
| 2309 | } |
| 2310 | |
| 2311 | /** |
| 2312 | * Recursively walk a FileSystemEntry tree, creating server-side directories |
| 2313 | * on the fly and collecting { file, targetDir } pairs for upload. |
| 2314 | */ |
| 2315 | async function collectEntries (entry, serverDir, toUpload) |
| 2316 | { |
| 2317 | if (entry.isFile) |
| 2318 | { |
| 2319 | const file = await new Promise((res, rej) => entry.file(res, rej)); |
| 2320 | toUpload.push({ file, targetDir: serverDir }); |
| 2321 | } else if (entry.isDirectory) |
| 2322 | { |
| 2323 | // Ask the server to create the directory; it returns the canonical path. |
| 2324 | let newServerDir; |
| 2325 | try |
| 2326 | { |
| 2327 | const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); |
| 2328 | newServerDir = resp.path; |
| 2329 | } catch |
| 2330 | { |
| 2331 | // Directory may already exist — reconstruct path from what we know. |
| 2332 | // The server always returns JSON with {error} on failure, so we can |
| 2333 | // still continue by falling back to a best-effort path join. |
| 2334 | // We rely on the fact that the server separator is consistent within |
| 2335 | // a session (the list/browse API already returned paths in that format). |
| 2336 | const sep = serverDir.includes('\\') ? '\\' : '/'; |
| 2337 | newServerDir = serverDir + sep + entry.name; |
| 2338 | } |
| 2339 | const reader = entry.createReader(); |
| 2340 | const subEntries = await readAllEntries(reader); |
| 2341 | for (const sub of subEntries) |
| 2342 | { |
| 2343 | await collectEntries(sub, newServerDir, toUpload); |
| 2344 | } |
| 2345 | } |
| 2346 | } |
| 2347 | |
| 2348 | async function uploadEntries (entries) |
| 2349 | { |
| 2350 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 2351 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 2352 | |
| 2353 | const wrap = document.createElement('div'); |
| 2354 | wrap.className = 'upload-bar-wrap'; |
| 2355 | wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 2356 | document.body.appendChild(wrap); |
| 2357 | STATE.uploadInProgress = true; |
| 2358 | |
| 2359 | try |
| 2360 | { |
| 2361 | const toUpload = []; |
| 2362 | for (const entry of entries) |
| 2363 | { |
| 2364 | await collectEntries(entry, STATE.currentDir, toUpload); |
| 2365 | } |
| 2366 | |
| 2367 | if (!toUpload.length) { toast('No files found.', 'err'); return; } |
| 2368 | |
| 2369 | let done = 0; |
| 2370 | const total = toUpload.length; |
| 2371 | const updateBar = () => |
| 2372 | { |
| 2373 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 2374 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 2375 | }; |
| 2376 | updateBar(); |
| 2377 | |
| 2378 | for (const { file, targetDir } of toUpload) |
| 2379 | { |
| 2380 | await uploadSingleFile(file, targetDir); |
| 2381 | done++; |
| 2382 | updateBar(); |
| 2383 | } |
| 2384 | |
| 2385 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 2386 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 2387 | } catch (err) |
| 2388 | { |
| 2389 | toast(err.message, 'err'); |
| 2390 | } finally |
| 2391 | { |
| 2392 | STATE.uploadInProgress = false; |
| 2393 | wrap.remove(); |
| 2394 | } |
| 2395 | } |
| 2396 | |
| 2397 | // DRAG-AND-DROP |
| 2398 | // ─────────────────────────────────────────────────────────────────────────── |
| 2399 | |
| 2400 | function initDragDrop () |
| 2401 | { |
| 2402 | const main = document.getElementById('main-content'); |
| 2403 | const dropOvl = document.getElementById('drop-overlay'); |
| 2404 | let dragDepth = 0; |
| 2405 | |
| 2406 | main.addEventListener('dragenter', e => |
| 2407 | { |
| 2408 | e.preventDefault(); |
| 2409 | dragDepth++; |
| 2410 | dropOvl.classList.remove('hidden'); |
| 2411 | }); |
| 2412 | main.addEventListener('dragleave', () => |
| 2413 | { |
| 2414 | dragDepth--; |
| 2415 | if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } |
| 2416 | }); |
| 2417 | main.addEventListener('dragover', e => e.preventDefault()); |
| 2418 | main.addEventListener('drop', async e => |
| 2419 | { |
| 2420 | e.preventDefault(); |
| 2421 | dragDepth = 0; |
| 2422 | dropOvl.classList.add('hidden'); |
| 2423 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 2424 | |
| 2425 | const items = Array.from(e.dataTransfer.items || []); |
| 2426 | // Use the FileSystem Entry API when available so we can handle folders. |
| 2427 | if (items.length && typeof items[0].webkitGetAsEntry === 'function') |
| 2428 | { |
| 2429 | const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); |
| 2430 | if (entries.some(en => en.isDirectory)) |
| 2431 | { |
| 2432 | await uploadEntries(entries); |
| 2433 | return; |
| 2434 | } |
| 2435 | } |
| 2436 | // Plain files only — use the fast batch path. |
| 2437 | const files = e.dataTransfer.files; |
| 2438 | if (files.length) await uploadFiles(files); |
| 2439 | }); |
| 2440 | } |
| 2441 | |
| 2442 | // ─────────────────────────────────────────────────────────────────────────── |
| 2443 | // RENAME |
| 2444 | // ─────────────────────────────────────────────────────────────────────────── |
| 2445 | |
| 2446 | function openRenameModal (item) |
| 2447 | { |
| 2448 | const modal = document.getElementById('rename-modal'); |
| 2449 | modal.classList.remove('hidden'); |
| 2450 | const input = document.getElementById('rename-input'); |
| 2451 | input.value = item.name; |
| 2452 | input.focus(); |
| 2453 | input.select(); |
| 2454 | document.getElementById('rename-error').classList.add('hidden'); |
| 2455 | document.getElementById('rename-form').onsubmit = async (e) => |
| 2456 | { |
| 2457 | e.preventDefault(); |
| 2458 | const newName = input.value.trim(); |
| 2459 | if (!newName) return; |
| 2460 | try |
| 2461 | { |
| 2462 | await api('POST', '/files/rename', { from: item.path, to: newName }); |
| 2463 | modal.classList.add('hidden'); |
| 2464 | toast('Renamed.', 'ok'); |
| 2465 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 2466 | } catch (err) |
| 2467 | { |
| 2468 | document.getElementById('rename-error').textContent = err.message; |
| 2469 | document.getElementById('rename-error').classList.remove('hidden'); |
| 2470 | } |
| 2471 | }; |
| 2472 | } |
| 2473 | |
| 2474 | // ─────────────────────────────────────────────────────────────────────────── |
| 2475 | // DELETE |
| 2476 | // ─────────────────────────────────────────────────────────────────────────── |
| 2477 | |
| 2478 | async function deleteItem (item) |
| 2479 | { |
| 2480 | if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return; |
| 2481 | try |
| 2482 | { |
| 2483 | await api('POST', '/files/delete', { path: item.path }); |
| 2484 | toast('Deleted.', 'ok'); |
| 2485 | closeSidebar(); |
| 2486 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 2487 | } catch (err) |
| 2488 | { |
| 2489 | toast(err.message, 'err'); |
| 2490 | } |
| 2491 | } |
| 2492 | |
| 2493 | // ─────────────────────────────────────────────────────────────────────────── |
| 2494 | // ADMIN PANEL |
| 2495 | // ─────────────────────────────────────────────────────────────────────────── |
| 2496 | |
| 2497 | async function openAdminModal () |
| 2498 | { |
| 2499 | document.getElementById('admin-modal').classList.remove('hidden'); |
| 2500 | await refreshAdminConfig(); |
| 2501 | await refreshAdminUsers(); |
| 2502 | } |
| 2503 | |
| 2504 | async function refreshAdminConfig () |
| 2505 | { |
| 2506 | const data = await api('GET', '/admin/config'); |
| 2507 | if (!data) return; |
| 2508 | const container = document.getElementById('admin-paths'); |
| 2509 | container.innerHTML = ''; |
| 2510 | for (const p of data.paths) |
| 2511 | { |
| 2512 | const row = document.createElement('div'); |
| 2513 | row.className = 'path-row'; |
| 2514 | row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`; |
| 2515 | row.querySelector('button').addEventListener('click', () => |
| 2516 | { |
| 2517 | row.remove(); |
| 2518 | }); |
| 2519 | container.appendChild(row); |
| 2520 | } |
| 2521 | } |
| 2522 | |
| 2523 | async function refreshAdminUsers () |
| 2524 | { |
| 2525 | const data = await api('GET', '/admin/users'); |
| 2526 | if (!data) return; |
| 2527 | const container = document.getElementById('admin-users-list'); |
| 2528 | container.innerHTML = ''; |
| 2529 | |
| 2530 | // Need paths for permission rows |
| 2531 | const cfg = await api('GET', '/admin/config'); |
| 2532 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 2533 | |
| 2534 | for (const u of data.users) |
| 2535 | { |
| 2536 | const row = document.createElement('div'); |
| 2537 | row.className = 'user-row'; |
| 2538 | row.innerHTML = ` |
| 2539 | <span class="user-name">${u.username}</span> |
| 2540 | ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''} |
| 2541 | <button data-id="${u.id}" data-action="edit">Edit</button> |
| 2542 | ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`} |
| 2543 | `; |
| 2544 | row.querySelector('[data-action="edit"]').addEventListener('click', () => |
| 2545 | openUserModal(u, paths)); |
| 2546 | const deleteBtn = row.querySelector('[data-action="delete"]'); |
| 2547 | if (deleteBtn) deleteBtn.addEventListener('click', async () => |
| 2548 | { |
| 2549 | if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return; |
| 2550 | try |
| 2551 | { |
| 2552 | await api('DELETE', `/admin/users/${u.id}`); |
| 2553 | toast('User deleted.', 'ok'); |
| 2554 | await refreshAdminUsers(); |
| 2555 | } catch (err) { toast(err.message, 'err'); } |
| 2556 | }); |
| 2557 | container.appendChild(row); |
| 2558 | } |
| 2559 | } |
| 2560 | |
| 2561 | function openUserModal (user, paths) |
| 2562 | { |
| 2563 | const modal = document.getElementById('user-modal'); |
| 2564 | modal.classList.remove('hidden'); |
| 2565 | document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; |
| 2566 | document.getElementById('user-error').classList.add('hidden'); |
| 2567 | |
| 2568 | const usernameInput = document.getElementById('user-username'); |
| 2569 | usernameInput.value = user ? user.username : ''; |
| 2570 | usernameInput.readOnly = !!user; |
| 2571 | |
| 2572 | document.getElementById('user-password').value = ''; |
| 2573 | document.getElementById('user-is-admin').checked = user ? user.isAdmin : false; |
| 2574 | |
| 2575 | // Password placeholder |
| 2576 | document.getElementById('user-password').placeholder = |
| 2577 | user ? 'Leave blank to keep current' : 'Min 8 characters'; |
| 2578 | |
| 2579 | // Build permissions grid |
| 2580 | const permDiv = document.getElementById('user-permissions'); |
| 2581 | permDiv.innerHTML = ''; |
| 2582 | if (paths.length) |
| 2583 | { |
| 2584 | const heading = document.createElement('h4'); |
| 2585 | heading.textContent = 'Path Permissions'; |
| 2586 | permDiv.appendChild(heading); |
| 2587 | |
| 2588 | const isAdminUser = !!(user && user.isAdmin); |
| 2589 | // Mirror the is-admin checkbox so toggling it live-updates the perm rows. |
| 2590 | const adminChk = document.getElementById('user-is-admin'); |
| 2591 | const rebuildPermRows = (admin) => |
| 2592 | { |
| 2593 | permDiv.querySelectorAll('.perm-row').forEach(r => |
| 2594 | { |
| 2595 | r.querySelectorAll('input[type=checkbox]').forEach(cb => |
| 2596 | { |
| 2597 | cb.disabled = admin; |
| 2598 | if (admin) cb.checked = true; |
| 2599 | }); |
| 2600 | r.title = admin ? 'Admins always have full access' : ''; |
| 2601 | }); |
| 2602 | }; |
| 2603 | adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); |
| 2604 | |
| 2605 | for (const p of paths) |
| 2606 | { |
| 2607 | const label = p.split(/[\\/]/).pop(); |
| 2608 | const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; |
| 2609 | const row = document.createElement('div'); |
| 2610 | row.className = 'perm-row'; |
| 2611 | const readChecked = isAdminUser || perms.read; |
| 2612 | const writeChecked = isAdminUser || perms.write; |
| 2613 | row.innerHTML = ` |
| 2614 | <span class="perm-label">${label}</span> |
| 2615 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label> |
| 2616 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label> |
| 2617 | `; |
| 2618 | if (isAdminUser) row.title = 'Admins always have full access'; |
| 2619 | permDiv.appendChild(row); |
| 2620 | } |
| 2621 | } |
| 2622 | |
| 2623 | document.getElementById('user-form').onsubmit = async (e) => |
| 2624 | { |
| 2625 | e.preventDefault(); |
| 2626 | const password = document.getElementById('user-password').value; |
| 2627 | const isAdmin = document.getElementById('user-is-admin').checked; |
| 2628 | const permissions = {}; |
| 2629 | permDiv.querySelectorAll('input[data-label]').forEach(cb => |
| 2630 | { |
| 2631 | const lbl = cb.dataset.label; |
| 2632 | if (!permissions[lbl]) permissions[lbl] = {}; |
| 2633 | permissions[lbl][cb.dataset.type] = cb.checked; |
| 2634 | }); |
| 2635 | |
| 2636 | try |
| 2637 | { |
| 2638 | if (user) |
| 2639 | { |
| 2640 | const body = { isAdmin, permissions }; |
| 2641 | if (password) body.password = password; |
| 2642 | await api('PATCH', `/admin/users/${user.id}`, body); |
| 2643 | } else |
| 2644 | { |
| 2645 | const uname = document.getElementById('user-username').value.trim(); |
| 2646 | await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); |
| 2647 | } |
| 2648 | modal.classList.add('hidden'); |
| 2649 | toast('User saved.', 'ok'); |
| 2650 | await refreshAdminUsers(); |
| 2651 | } catch (err) |
| 2652 | { |
| 2653 | document.getElementById('user-error').textContent = err.message; |
| 2654 | document.getElementById('user-error').classList.remove('hidden'); |
| 2655 | } |
| 2656 | }; |
| 2657 | } |
| 2658 | |
| 2659 | // ─────────────────────────────────────────────────────────────────────────── |
| 2660 | // SVG ICONS |
| 2661 | // ─────────────────────────────────────────────────────────────────────────── |
| 2662 | |
| 2663 | const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']); |
| 2664 | const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']); |
| 2665 | const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']); |
| 2666 | const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']); |
| 2667 | const CODE_EXTS = new Set(['js', 'ts', 'py', 'rb', 'go', 'rs', 'c', 'cpp', 'h', 'cs', 'java', 'php', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'txt']); |
| 2668 | const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']); |
| 2669 | |
| 2670 | function iconFolder (size = 52) |
| 2671 | { |
| 2672 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 2673 | stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 2674 | <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/> |
| 2675 | </svg>`; |
| 2676 | } |
| 2677 | |
| 2678 | function iconFile (name, size = 52) |
| 2679 | { |
| 2680 | const color = fileAccentColor(name); |
| 2681 | let symbol = ''; |
| 2682 | |
| 2683 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 2684 | stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 2685 | <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/> |
| 2686 | <polyline points="14 2 14 8 20 8"/> |
| 2687 | </svg>`; |
| 2688 | } |
| 2689 | |
| 2690 | // ─────────────────────────────────────────────────────────────────────────── |
| 2691 | // EVENT WIRING |
| 2692 | // ─────────────────────────────────────────────────────────────────────────── |
| 2693 | |
| 2694 | // ─────────────────────────────────────────────────────────────────────────── |
| 2695 | // THUMBNAIL PREVIEWS |
| 2696 | // ─────────────────────────────────────────────────────────────────────────── |
| 2697 | |
| 2698 | function revokeThumbnails () |
| 2699 | { |
| 2700 | STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u)); |
| 2701 | STATE.thumbnailUrls = []; |
| 2702 | } |
| 2703 | |
| 2704 | function getThumbnailKind (name) |
| 2705 | { |
| 2706 | const ext = extOf(name || ''); |
| 2707 | if (IMAGE_EXTS.has(ext)) return 'image'; |
| 2708 | if (VIDEO_EXTS.has(ext)) return 'video'; |
| 2709 | if (CODE_EXTS.has(ext)) return 'text'; |
| 2710 | if (AUDIO_EXTS.has(ext)) return 'audio'; |
| 2711 | if (ext === 'pdf') return 'pdf'; |
| 2712 | return 'badge'; |
| 2713 | } |
| 2714 | |
| 2715 | function maxThumbBytesForKind (kind) |
| 2716 | { |
| 2717 | if (kind === 'image') return 15 * 1024 * 1024; |
| 2718 | if (kind === 'video') return 25 * 1024 * 1024; |
| 2719 | if (kind === 'text') return 1024 * 1024; |
| 2720 | return 0; |
| 2721 | } |
| 2722 | |
| 2723 | function drawTokenizedLine (ctx, line, x, y) |
| 2724 | { |
| 2725 | const tokenRe = /(\/\/.*$|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\b(?:function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b|\b\d+(?:\.\d+)?\b)/g; |
| 2726 | let last = 0; |
| 2727 | let cursor = x; |
| 2728 | for (const m of line.matchAll(tokenRe)) |
| 2729 | { |
| 2730 | const i = m.index == null ? 0 : m.index; |
| 2731 | if (i > last) |
| 2732 | { |
| 2733 | const plain = line.slice(last, i); |
| 2734 | ctx.fillStyle = '#dce4ff'; |
| 2735 | ctx.fillText(plain, cursor, y); |
| 2736 | cursor += ctx.measureText(plain).width; |
| 2737 | } |
| 2738 | |
| 2739 | const tok = m[0]; |
| 2740 | if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a'; |
| 2741 | else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d'; |
| 2742 | else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a'; |
| 2743 | else ctx.fillStyle = '#8bb4ff'; |
| 2744 | |
| 2745 | ctx.fillText(tok, cursor, y); |
| 2746 | cursor += ctx.measureText(tok).width; |
| 2747 | last = i + tok.length; |
| 2748 | } |
| 2749 | |
| 2750 | if (last < line.length) |
| 2751 | { |
| 2752 | const tail = line.slice(last); |
| 2753 | ctx.fillStyle = '#dce4ff'; |
| 2754 | ctx.fillText(tail, cursor, y); |
| 2755 | } |
| 2756 | } |
| 2757 | |
| 2758 | function textThumbnailDataUrl (text) |
| 2759 | { |
| 2760 | const canvas = document.createElement('canvas'); |
| 2761 | canvas.width = 160; |
| 2762 | canvas.height = 200; |
| 2763 | const ctx = canvas.getContext('2d'); |
| 2764 | if (!ctx) return null; |
| 2765 | |
| 2766 | ctx.fillStyle = '#0d111a'; |
| 2767 | ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 2768 | ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace'; |
| 2769 | ctx.textBaseline = 'top'; |
| 2770 | |
| 2771 | const lines = String(text || '') |
| 2772 | .replace(/\r\n/g, '\n') |
| 2773 | .split('\n') |
| 2774 | .slice(0, 17); |
| 2775 | |
| 2776 | let y = 8; |
| 2777 | for (const line of lines) |
| 2778 | { |
| 2779 | drawTokenizedLine(ctx, line.slice(0, 42), 6, y); |
| 2780 | y += 11; |
| 2781 | if (y > 190) break; |
| 2782 | } |
| 2783 | return canvas.toDataURL('image/png'); |
| 2784 | } |
| 2785 | |
| 2786 | function badgeThumbnailDataUrl (name, kind) |
| 2787 | { |
| 2788 | const canvas = document.createElement('canvas'); |
| 2789 | canvas.width = 160; |
| 2790 | canvas.height = 200; |
| 2791 | const ctx = canvas.getContext('2d'); |
| 2792 | if (!ctx) return null; |
| 2793 | |
| 2794 | const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5); |
| 2795 | const color = kind === 'audio' ? '#c084fc' |
| 2796 | : kind === 'pdf' ? '#f97316' |
| 2797 | : '#5b7fff'; |
| 2798 | |
| 2799 | ctx.fillStyle = '#111826'; |
| 2800 | ctx.fillRect(0, 0, 160, 200); |
| 2801 | ctx.fillStyle = color; |
| 2802 | ctx.fillRect(0, 0, 160, 28); |
| 2803 | ctx.fillStyle = '#ffffff'; |
| 2804 | ctx.font = 'bold 12px sans-serif'; |
| 2805 | ctx.textAlign = 'center'; |
| 2806 | ctx.fillText(ext, 80, 8); |
| 2807 | ctx.textAlign = 'left'; |
| 2808 | ctx.fillStyle = '#9fb1d8'; |
| 2809 | ctx.font = '10px sans-serif'; |
| 2810 | ctx.fillText('Preview', 8, 48); |
| 2811 | ctx.fillStyle = '#dce4ff'; |
| 2812 | ctx.font = 'bold 11px sans-serif'; |
| 2813 | ctx.fillText(ext, 8, 66); |
| 2814 | return canvas.toDataURL('image/png'); |
| 2815 | } |
| 2816 | |
| 2817 | async function videoThumbnailDataUrl (blob) |
| 2818 | { |
| 2819 | const src = URL.createObjectURL(blob); |
| 2820 | try |
| 2821 | { |
| 2822 | const video = document.createElement('video'); |
| 2823 | video.src = src; |
| 2824 | video.muted = true; |
| 2825 | video.preload = 'metadata'; |
| 2826 | |
| 2827 | await new Promise((resolve, reject) => |
| 2828 | { |
| 2829 | const fail = () => reject(new Error('video load failed')); |
| 2830 | video.addEventListener('error', fail, { once: true }); |
| 2831 | video.addEventListener('loadeddata', resolve, { once: true }); |
| 2832 | }); |
| 2833 | |
| 2834 | const targetTime = Number.isFinite(video.duration) && video.duration > 1 ? 1 : 0; |
| 2835 | await new Promise((resolve) => |
| 2836 | { |
| 2837 | video.currentTime = targetTime; |
| 2838 | video.addEventListener('seeked', resolve, { once: true }); |
| 2839 | }); |
| 2840 | |
| 2841 | const canvas = document.createElement('canvas'); |
| 2842 | canvas.width = 160; |
| 2843 | canvas.height = 200; |
| 2844 | const ctx = canvas.getContext('2d'); |
| 2845 | if (!ctx) return null; |
| 2846 | |
| 2847 | ctx.fillStyle = '#0d111a'; |
| 2848 | ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 2849 | const rw = video.videoWidth || 1; |
| 2850 | const rh = video.videoHeight || 1; |
| 2851 | const scale = Math.max(canvas.width / rw, canvas.height / rh); |
| 2852 | const dw = rw * scale; |
| 2853 | const dh = rh * scale; |
| 2854 | ctx.drawImage(video, (canvas.width - dw) / 2, (canvas.height - dh) / 2, dw, dh); |
| 2855 | |
| 2856 | // subtle play badge |
| 2857 | ctx.fillStyle = 'rgba(0,0,0,0.45)'; |
| 2858 | ctx.beginPath(); |
| 2859 | ctx.arc(80, 100, 18, 0, Math.PI * 2); |
| 2860 | ctx.fill(); |
| 2861 | ctx.fillStyle = '#ffffff'; |
| 2862 | ctx.beginPath(); |
| 2863 | ctx.moveTo(75, 90); |
| 2864 | ctx.lineTo(75, 110); |
| 2865 | ctx.lineTo(90, 100); |
| 2866 | ctx.closePath(); |
| 2867 | ctx.fill(); |
| 2868 | |
| 2869 | return canvas.toDataURL('image/png'); |
| 2870 | } catch |
| 2871 | { |
| 2872 | return null; |
| 2873 | } finally |
| 2874 | { |
| 2875 | URL.revokeObjectURL(src); |
| 2876 | } |
| 2877 | } |
| 2878 | |
| 2879 | async function buildThumbnailSource (item, blob, kind) |
| 2880 | { |
| 2881 | if (kind === 'image') return URL.createObjectURL(blob); |
| 2882 | if (kind === 'video') return await videoThumbnailDataUrl(blob); |
| 2883 | if (kind === 'text') return textThumbnailDataUrl(await blob.text()); |
| 2884 | return badgeThumbnailDataUrl(item.name, kind); |
| 2885 | } |
| 2886 | |
| 2887 | async function loadThumbnails () |
| 2888 | { |
| 2889 | const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]')); |
| 2890 | if (!icons.length) return; |
| 2891 | |
| 2892 | const queue = [...icons]; |
| 2893 | async function worker () |
| 2894 | { |
| 2895 | while (queue.length) |
| 2896 | { |
| 2897 | await loadOneThumbnail(queue.shift()); |
| 2898 | } |
| 2899 | } |
| 2900 | // Four concurrent fetches — keeps the Pi's network from flooding |
| 2901 | await Promise.all(Array.from({ length: Math.min(4, icons.length) }, worker)); |
| 2902 | } |
| 2903 | |
| 2904 | async function loadOneThumbnail (iconEl) |
| 2905 | { |
| 2906 | if (!iconEl.isConnected || !STATE.token) return; |
| 2907 | if (iconEl.dataset.thumbReady === '1') return; |
| 2908 | const filePath = iconEl.dataset.previewPath; |
| 2909 | const item = STATE.items.find(i => i.path === filePath); |
| 2910 | if (!item) return; |
| 2911 | |
| 2912 | const kind = getThumbnailKind(item.name); |
| 2913 | let srcUrl = null; |
| 2914 | |
| 2915 | if (kind === 'badge' || kind === 'audio' || kind === 'pdf') |
| 2916 | { |
| 2917 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 2918 | } else |
| 2919 | { |
| 2920 | const maxBytes = maxThumbBytesForKind(kind); |
| 2921 | if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes) |
| 2922 | { |
| 2923 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 2924 | } else |
| 2925 | { |
| 2926 | const url = `/api/files/download?file=${encodeURIComponent(filePath)}`; |
| 2927 | |
| 2928 | let res; |
| 2929 | try |
| 2930 | { |
| 2931 | res = await fetch(url, { |
| 2932 | headers: { |
| 2933 | Authorization: `Bearer ${STATE.token}`, |
| 2934 | 'X-Fp': getFingerprint(), |
| 2935 | }, |
| 2936 | }); |
| 2937 | } catch { return; } |
| 2938 | if (!res.ok || !iconEl.isConnected) return; |
| 2939 | |
| 2940 | const blob = await res.blob(); |
| 2941 | srcUrl = await buildThumbnailSource(item, blob, kind); |
| 2942 | if (kind === 'image' && srcUrl) STATE.thumbnailUrls.push(srcUrl); |
| 2943 | } |
| 2944 | } |
| 2945 | if (!srcUrl || !iconEl.isConnected) return; |
| 2946 | |
| 2947 | const svg = iconEl.querySelector('svg'); |
| 2948 | if (!svg) |
| 2949 | { |
| 2950 | if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); |
| 2951 | return; |
| 2952 | } |
| 2953 | |
| 2954 | const NS = 'http://www.w3.org/2000/svg'; |
| 2955 | const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; |
| 2956 | |
| 2957 | // clipPath matches the main file body outline exactly (viewBox 0 0 24 24) |
| 2958 | const defs = document.createElementNS(NS, 'defs'); |
| 2959 | const clipPath = document.createElementNS(NS, 'clipPath'); |
| 2960 | clipPath.setAttribute('id', id); |
| 2961 | clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); |
| 2962 | const clipShape = document.createElementNS(NS, 'path'); |
| 2963 | clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'); |
| 2964 | clipPath.appendChild(clipShape); |
| 2965 | defs.appendChild(clipPath); |
| 2966 | |
| 2967 | // Image fills the file bounding box; clip keeps it inside the outline |
| 2968 | const img = document.createElementNS(NS, 'image'); |
| 2969 | img.setAttribute('href', srcUrl); |
| 2970 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); |
| 2971 | img.setAttribute('x', '4'); |
| 2972 | img.setAttribute('y', '2'); |
| 2973 | img.setAttribute('width', '16'); |
| 2974 | img.setAttribute('height', '20'); |
| 2975 | img.setAttribute('clip-path', `url(#${id})`); |
| 2976 | img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); |
| 2977 | |
| 2978 | // Prepend so existing path/polyline elements (the outline) render on top |
| 2979 | svg.prepend(img); |
| 2980 | svg.prepend(defs); |
| 2981 | iconEl.dataset.thumbReady = '1'; |
| 2982 | } |
| 2983 | |
| 2984 | function wireEvents () |
| 2985 | { |
| 2986 | // Auth form |
| 2987 | document.getElementById('auth-form').addEventListener('submit', async (e) => |
| 2988 | { |
| 2989 | e.preventDefault(); |
| 2990 | const username = document.getElementById('auth-username').value.trim(); |
| 2991 | const password = document.getElementById('auth-password').value; |
| 2992 | const isSetup = e.target.dataset.mode === 'setup'; |
| 2993 | const errEl = document.getElementById('auth-error'); |
| 2994 | const btn = document.getElementById('auth-submit'); |
| 2995 | btn.disabled = true; |
| 2996 | btn.textContent = 'Please wait…'; |
| 2997 | const err = await doLogin(username, password, isSetup); |
| 2998 | if (err) |
| 2999 | { |
| 3000 | errEl.textContent = err; |
| 3001 | errEl.classList.remove('hidden'); |
| 3002 | btn.disabled = false; |
| 3003 | btn.textContent = isSetup ? 'Create Account' : 'Sign In'; |
| 3004 | } |
| 3005 | }); |
| 3006 | |
| 3007 | // Logout |
| 3008 | document.getElementById('btn-logout').addEventListener('click', logout); |
| 3009 | |
| 3010 | // Hard refresh while keeping auth/session state. |
| 3011 | document.getElementById('btn-refresh').addEventListener('click', () => |
| 3012 | { |
| 3013 | saveSessionState(); |
| 3014 | location.reload(); |
| 3015 | }); |
| 3016 | |
| 3017 | // Upload button |
| 3018 | document.getElementById('btn-upload').addEventListener('click', () => |
| 3019 | { |
| 3020 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3021 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3022 | document.getElementById('file-input').click(); |
| 3023 | }); |
| 3024 | |
| 3025 | document.getElementById('file-input').addEventListener('change', async (e) => |
| 3026 | { |
| 3027 | if (e.target.files.length) await uploadFiles(e.target.files); |
| 3028 | e.target.value = ''; |
| 3029 | }); |
| 3030 | |
| 3031 | document.getElementById('btn-upload-folder').addEventListener('click', () => |
| 3032 | { |
| 3033 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3034 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3035 | document.getElementById('folder-input').click(); |
| 3036 | }); |
| 3037 | |
| 3038 | document.getElementById('folder-input').addEventListener('change', async (e) => |
| 3039 | { |
| 3040 | if (e.target.files.length) await uploadFolderInputFiles(e.target.files); |
| 3041 | e.target.value = ''; |
| 3042 | }); |
| 3043 | |
| 3044 | document.getElementById('btn-new-folder').addEventListener('click', async () => |
| 3045 | { |
| 3046 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3047 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3048 | |
| 3049 | const name = await showPrompt('New Folder', 'Enter a name for the new folder:'); |
| 3050 | if (name == null) return; |
| 3051 | const folderName = name.trim(); |
| 3052 | if (!folderName) |
| 3053 | { |
| 3054 | toast('Folder name is required.', 'err'); |
| 3055 | return; |
| 3056 | } |
| 3057 | |
| 3058 | try |
| 3059 | { |
| 3060 | await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName }); |
| 3061 | toast('Folder created.', 'ok'); |
| 3062 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3063 | } catch (err) |
| 3064 | { |
| 3065 | toast(err.message, 'err'); |
| 3066 | } |
| 3067 | }); |
| 3068 | |
| 3069 | document.getElementById('sidebar-close').addEventListener('click', (e) => |
| 3070 | { |
| 3071 | e.stopPropagation(); |
| 3072 | hideSidebarPanel(); |
| 3073 | }); |
| 3074 | |
| 3075 | const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY); |
| 3076 | const syncSidebarForViewport = () => |
| 3077 | { |
| 3078 | if (isMobileViewport()) |
| 3079 | { |
| 3080 | hideSidebarPanel(); |
| 3081 | return; |
| 3082 | } |
| 3083 | |
| 3084 | if (!STATE.selectedItem) openFolderSidebar(); |
| 3085 | }; |
| 3086 | |
| 3087 | if (typeof mobileQuery.addEventListener === 'function') |
| 3088 | { |
| 3089 | mobileQuery.addEventListener('change', syncSidebarForViewport); |
| 3090 | } else if (typeof mobileQuery.addListener === 'function') |
| 3091 | { |
| 3092 | mobileQuery.addListener(syncSidebarForViewport); |
| 3093 | } |
| 3094 | |
| 3095 | // Click outside grid clears selection and returns to folder sidebar info. |
| 3096 | document.getElementById('main-content').addEventListener('click', (e) => |
| 3097 | { |
| 3098 | if (!e.target.closest('.file-item')) closeSidebar(); |
| 3099 | }); |
| 3100 | |
| 3101 | // Admin panel |
| 3102 | document.getElementById('btn-admin').addEventListener('click', openAdminModal); |
| 3103 | document.getElementById('admin-modal-close').addEventListener('click', () => |
| 3104 | document.getElementById('admin-modal').classList.add('hidden')); |
| 3105 | |
| 3106 | // Add path |
| 3107 | document.getElementById('admin-add-path').addEventListener('click', () => |
| 3108 | { |
| 3109 | const val = document.getElementById('admin-new-path').value.trim(); |
| 3110 | if (!val) return; |
| 3111 | const row = document.createElement('div'); |
| 3112 | row.className = 'path-row'; |
| 3113 | row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`; |
| 3114 | row.querySelector('button').addEventListener('click', () => row.remove()); |
| 3115 | document.getElementById('admin-paths').appendChild(row); |
| 3116 | document.getElementById('admin-new-path').value = ''; |
| 3117 | }); |
| 3118 | |
| 3119 | // Save paths |
| 3120 | document.getElementById('admin-save-paths').addEventListener('click', async () => |
| 3121 | { |
| 3122 | const rows = document.querySelectorAll('#admin-paths .path-row span'); |
| 3123 | const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); |
| 3124 | try |
| 3125 | { |
| 3126 | await api('PUT', '/admin/config', { paths }); |
| 3127 | toast('Paths saved.', 'ok'); |
| 3128 | await loadRoots(); |
| 3129 | } catch (err) { toast(err.message, 'err'); } |
| 3130 | }); |
| 3131 | |
| 3132 | // Shutdown server |
| 3133 | document.getElementById('admin-shutdown-btn').addEventListener('click', async () => |
| 3134 | { |
| 3135 | if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return; |
| 3136 | try |
| 3137 | { |
| 3138 | await api('POST', '/admin/shutdown'); |
| 3139 | toast('Server is shutting down…', 'ok'); |
| 3140 | document.getElementById('admin-modal').classList.add('hidden'); |
| 3141 | } catch |
| 3142 | { |
| 3143 | // Fetch may throw because the connection closes before a response arrives. |
| 3144 | toast('Server is shutting down…', 'ok'); |
| 3145 | document.getElementById('admin-modal').classList.add('hidden'); |
| 3146 | } |
| 3147 | }); |
| 3148 | |
| 3149 | // New user |
| 3150 | document.getElementById('admin-new-user-btn').addEventListener('click', async () => |
| 3151 | { |
| 3152 | const cfg = await api('GET', '/admin/config'); |
| 3153 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 3154 | openUserModal(null, paths); |
| 3155 | }); |
| 3156 | |
| 3157 | // User modal close |
| 3158 | document.getElementById('user-modal-close').addEventListener('click', () => |
| 3159 | document.getElementById('user-modal').classList.add('hidden')); |
| 3160 | |
| 3161 | // Rename modal close |
| 3162 | document.getElementById('rename-modal-close').addEventListener('click', () => |
| 3163 | document.getElementById('rename-modal').classList.add('hidden')); |
| 3164 | |
| 3165 | // Preview close |
| 3166 | document.getElementById('preview-close').addEventListener('click', closePreview); |
| 3167 | document.getElementById('preview-overlay').addEventListener('click', (e) => |
| 3168 | { |
| 3169 | if (e.target.id === 'preview-overlay') closePreview(); |
| 3170 | }); |
| 3171 | |
| 3172 | document.addEventListener('keydown', (e) => |
| 3173 | { |
| 3174 | if (e.key === 'Escape' && !document.getElementById('preview-overlay').classList.contains('hidden')) |
| 3175 | { |
| 3176 | closePreview(); |
| 3177 | } |
| 3178 | }); |
| 3179 | |
| 3180 | // Close modals on backdrop click |
| 3181 | document.querySelectorAll('.modal-overlay').forEach(overlay => |
| 3182 | { |
| 3183 | overlay.addEventListener('click', e => |
| 3184 | { |
| 3185 | if (e.target === overlay) overlay.classList.add('hidden'); |
| 3186 | }); |
| 3187 | }); |
| 3188 | } |
| 3189 | |
| 3190 | // ─────────────────────────────────────────────────────────────────────────── |
| 3191 | // BOOT |
| 3192 | // ─────────────────────────────────────────────────────────────────────────── |
| 3193 | |
| 3194 | (async function boot () |
| 3195 | { |
| 3196 | wireEvents(); |
| 3197 | initDragDrop(); |
| 3198 | window.addEventListener('beforeunload', saveSessionState); |
| 3199 | await initAuth(); |
| 3200 | })(); |