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