BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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