BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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