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