BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

app.js 96.8 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 return users.map(u => `${u.username} ${u.mode}`).join(', ');
1248}
1249
1250function rootPermissionLabel (root)
1251{
1252 return (root && (root.originalName || root.label)) || '';
1253}
1254
1255function resolveRootForPath (targetPath)
1256{
1257 if (!targetPath) return null;
1258 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
1259}
1260
1261function writableRoots ()
1262{
1263 if (STATE.isAdmin) return STATE.roots.slice();
1264 return STATE.roots.filter((r) =>
1265 {
1266 const perm = STATE.permissions[rootPermissionLabel(r)];
1267 return !!(perm && perm.write);
1268 });
1269}
1270
1271function ensureMoveModal ()
1272{
1273 let overlay = document.getElementById('move-modal');
1274 if (overlay) return overlay;
1275
1276 overlay = document.createElement('div');
1277 overlay.id = 'move-modal';
1278 overlay.className = 'modal-overlay hidden';
1279 overlay.innerHTML = `
1280 <div class="modal move-modal">
1281 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
1282 <h2>Move To</h2>
1283 <p id="move-modal-caption" class="muted"></p>
1284 <div id="move-tree" class="move-tree"></div>
1285 <p id="move-selected" class="muted"></p>
1286 <div class="dialog-actions">
1287 <button id="move-modal-cancel">Cancel</button>
1288 <button id="move-modal-confirm" class="primary">Move</button>
1289 </div>
1290 </div>
1291 `;
1292 document.body.appendChild(overlay);
1293
1294 const closeBtn = overlay.querySelector('#move-modal-close');
1295 const cancelBtn = overlay.querySelector('#move-modal-cancel');
1296 const confirmBtn = overlay.querySelector('#move-modal-confirm');
1297
1298 function hide ()
1299 {
1300 overlay.classList.add('hidden');
1301 STATE.movePicker = null;
1302 }
1303
1304 closeBtn.addEventListener('click', hide);
1305 cancelBtn.addEventListener('click', hide);
1306 overlay.addEventListener('click', (e) =>
1307 {
1308 if (e.target === overlay) hide();
1309 });
1310
1311 confirmBtn.addEventListener('click', async () =>
1312 {
1313 const st = STATE.movePicker;
1314 if (!st || !st.item || !st.selectedPath)
1315 {
1316 toast('Select a destination folder first.', 'err');
1317 return;
1318 }
1319
1320 try
1321 {
1322 await api('POST', '/files/move', { from: st.item.path, toDir: st.selectedPath });
1323 }
1324 catch (err)
1325 {
1326 toast('Move failed: ' + err.message, 'err');
1327 return;
1328 }
1329
1330 hide();
1331 if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
1332 navigateTo(STATE.currentDir, STATE.currentRoot);
1333 });
1334
1335 return overlay;
1336}
1337
1338function setMoveSelection (path, buttonEl)
1339{
1340 if (!STATE.movePicker) return;
1341 STATE.movePicker.selectedPath = path;
1342
1343 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
1344 if (buttonEl) buttonEl.classList.add('selected');
1345
1346 const selectedEl = document.getElementById('move-selected');
1347 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
1348}
1349
1350async function loadMoveChildren (containerEl, dirPath)
1351{
1352 if (containerEl.dataset.loaded === '1') return;
1353 containerEl.dataset.loaded = '1';
1354
1355 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
1356 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
1357
1358 if (!folders.length)
1359 {
1360 const empty = document.createElement('div');
1361 empty.className = 'move-empty';
1362 empty.textContent = 'No subfolders';
1363 containerEl.appendChild(empty);
1364 return;
1365 }
1366
1367 for (const child of folders)
1368 {
1369 containerEl.appendChild(createMoveNode(child.path, child.name));
1370 }
1371}
1372
1373function createMoveNode (folderPath, label)
1374{
1375 const node = document.createElement('div');
1376 node.className = 'move-node';
1377
1378 const row = document.createElement('div');
1379 row.className = 'move-node-row';
1380
1381 const toggle = document.createElement('button');
1382 toggle.type = 'button';
1383 toggle.className = 'move-toggle';
1384 toggle.textContent = '▸';
1385
1386 const selectBtn = document.createElement('button');
1387 selectBtn.type = 'button';
1388 selectBtn.className = 'move-node-label';
1389 selectBtn.textContent = label;
1390 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
1391
1392 const children = document.createElement('div');
1393 children.className = 'move-children hidden';
1394
1395 toggle.addEventListener('click', async () =>
1396 {
1397 if (children.classList.contains('hidden'))
1398 {
1399 await loadMoveChildren(children, folderPath);
1400 children.classList.remove('hidden');
1401 toggle.textContent = '▾';
1402 } else
1403 {
1404 children.classList.add('hidden');
1405 toggle.textContent = '▸';
1406 }
1407 });
1408
1409 row.appendChild(toggle);
1410 row.appendChild(selectBtn);
1411 node.appendChild(row);
1412 node.appendChild(children);
1413 return node;
1414}
1415
1416function openMovePicker (item)
1417{
1418 if (!canWrite())
1419 {
1420 toast('No write access.', 'err');
1421 return;
1422 }
1423
1424 const roots = writableRoots();
1425 if (!roots.length)
1426 {
1427 toast('No writable destination roots available.', 'err');
1428 return;
1429 }
1430
1431 const overlay = ensureMoveModal();
1432 const tree = overlay.querySelector('#move-tree');
1433 const caption = overlay.querySelector('#move-modal-caption');
1434
1435 STATE.movePicker = { item, selectedPath: null };
1436 caption.textContent = `Select destination folder for: ${item.name}`;
1437 tree.innerHTML = '';
1438
1439 for (const root of roots)
1440 {
1441 tree.appendChild(createMoveNode(root.path, root.label));
1442 }
1443
1444 setMoveSelection(null, null);
1445 overlay.classList.remove('hidden');
1446}
1447
1448// ───────────────────────────────────────────────────────────────────────────
1449// DOWNLOAD / VIEW
1450// ───────────────────────────────────────────────────────────────────────────
1451
1452function isInlinePreviewableBlob (blob, name)
1453{
1454 const mime = String(blob.type || '').toLowerCase();
1455 if (/^(image|video|audio)\//.test(mime)) return true;
1456 if (/^text\//.test(mime)) return true;
1457 if (mime === 'application/pdf') return true;
1458 if (mime === 'application/json') return true;
1459 if (mime === 'application/xml') return true;
1460 if (mime === 'application/javascript') return true;
1461
1462 // Fallback by extension when MIME is missing or generic.
1463 const ext = extOf(name || '');
1464 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
1465 if (CODE_EXTS.has(ext)) return true;
1466 return false;
1467}
1468
1469function isTextLikeBlob (blob, name)
1470{
1471 const mime = String(blob.type || '').toLowerCase();
1472 if (/^text\//.test(mime)) return true;
1473 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
1474 const ext = extOf(name || '');
1475 return CODE_EXTS.has(ext);
1476}
1477
1478function detectCodeLanguage (name, mime)
1479{
1480 const ext = extOf(name || '');
1481 const m = String(mime || '').toLowerCase();
1482 if (m.includes('json') || ext === 'json') return 'json';
1483 if (m.includes('xml') || ext === 'xml') return 'xml';
1484 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
1485 if (m.includes('css') || ext === 'css') return 'css';
1486 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
1487 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
1488 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
1489 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
1490 return CODE_EXTS.has(ext) ? 'js' : 'plain';
1491}
1492
1493function prettyPrintMarkup (raw)
1494{
1495 const src = String(raw || '')
1496 .replace(/>\s+</g, '><')
1497 .replace(/\r\n/g, '\n');
1498
1499 const lines = src.replace(/></g, '>\n<').split('\n');
1500 let indent = 0;
1501 const out = [];
1502
1503 for (const ln of lines)
1504 {
1505 const line = ln.trim();
1506 if (!line) continue;
1507 const isClose = /^<\//.test(line);
1508 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
1509 const isOpen = /^<[^!?/][^>]*>$/.test(line);
1510
1511 if (isClose) indent = Math.max(0, indent - 1);
1512 out.push(' '.repeat(indent) + line);
1513 if (isOpen && !isSelf) indent += 1;
1514 }
1515
1516 return out.join('\n');
1517}
1518
1519function prettyPrintBraces (raw)
1520{
1521 const lines = String(raw || '')
1522 .replace(/\r\n/g, '\n')
1523 .split('\n');
1524 let indent = 0;
1525 const out = [];
1526
1527 for (const ln of lines)
1528 {
1529 const line = ln.trim();
1530 if (!line)
1531 {
1532 out.push('');
1533 continue;
1534 }
1535 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
1536 out.push(' '.repeat(indent) + line);
1537 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
1538 }
1539 return out.join('\n');
1540}
1541
1542function prettyPrintCode (raw, lang)
1543{
1544 const text = String(raw || '').replace(/\r\n/g, '\n');
1545 if (lang === 'json')
1546 {
1547 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
1548 }
1549 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
1550 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
1551 return text;
1552}
1553
1554function escapeHtml (s)
1555{
1556 return String(s)
1557 .replace(/&/g, '&amp;')
1558 .replace(/</g, '&lt;')
1559 .replace(/>/g, '&gt;');
1560}
1561
1562function highlightCode (raw, lang)
1563{
1564 if (lang === 'plain') return escapeHtml(raw);
1565
1566 let html = escapeHtml(raw);
1567 const stash = [];
1568 const keep = (regex, cls) =>
1569 {
1570 html = html.replace(regex, (m) =>
1571 {
1572 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
1573 return `@@TOK${idx}@@`;
1574 });
1575 };
1576
1577 if (lang === 'json')
1578 {
1579 html = html
1580 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
1581 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
1582 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
1583 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1584 return html;
1585 }
1586
1587 if (lang === 'xml' || lang === 'html')
1588 {
1589 html = html
1590 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
1591 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
1592 return html;
1593 }
1594
1595 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
1596 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
1597 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
1598
1599 html = html
1600 .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>')
1601 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1602
1603 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
1604 return html;
1605}
1606
1607function clearPreviewObjectUrl ()
1608{
1609 if (!STATE.previewObjectUrl) return;
1610 URL.revokeObjectURL(STATE.previewObjectUrl);
1611 STATE.previewObjectUrl = null;
1612}
1613
1614function fileAccentColor (name)
1615{
1616 const ext = extOf(name || '');
1617 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
1618 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
1619 if (AUDIO_EXTS.has(ext)) return '#c084fc';
1620 if (DOC_EXTS.has(ext)) return '#f97316';
1621 if (CODE_EXTS.has(ext)) return '#38bdf8';
1622 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
1623 return '#7880a0';
1624}
1625
1626function animateRect (el, fromRect, toRect, opts = {})
1627{
1628 const duration = opts.duration == null ? 260 : opts.duration;
1629 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
1630
1631 el.style.left = `${fromRect.left}px`;
1632 el.style.top = `${fromRect.top}px`;
1633 el.style.width = `${fromRect.width}px`;
1634 el.style.height = `${fromRect.height}px`;
1635
1636 return new Promise((resolve) =>
1637 {
1638 const t0 = performance.now();
1639
1640 function frame (now)
1641 {
1642 const raw = Math.min((now - t0) / duration, 1);
1643 const t = easeOut(raw);
1644
1645 const left = fromRect.left + (toRect.left - fromRect.left) * t;
1646 const top = fromRect.top + (toRect.top - fromRect.top) * t;
1647 const width = fromRect.width + (toRect.width - fromRect.width) * t;
1648 const height = fromRect.height + (toRect.height - fromRect.height) * t;
1649
1650 el.style.left = `${left}px`;
1651 el.style.top = `${top}px`;
1652 el.style.width = `${width}px`;
1653 el.style.height = `${height}px`;
1654
1655 if (raw < 1)
1656 {
1657 requestAnimationFrame(frame);
1658 } else
1659 {
1660 resolve();
1661 }
1662 }
1663
1664 requestAnimationFrame(frame);
1665 });
1666}
1667
1668async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
1669{
1670 if (!tileEl || !sourceSvgEl) return false;
1671
1672 if (STATE.previewExpandState)
1673 {
1674 await closeExpandedTilePreview();
1675 }
1676
1677 const iconEl = tileEl.querySelector('.icon');
1678 const nameEl = tileEl.querySelector('.name');
1679 if (!iconEl) return false;
1680
1681 const startRect = tileEl.getBoundingClientRect();
1682 const targetW = Math.min(window.innerWidth * 0.94, 1100);
1683 const targetH = Math.min(window.innerHeight * 0.9, 860);
1684 const targetRect = {
1685 left: (window.innerWidth - targetW) / 2,
1686 top: (window.innerHeight - targetH) / 2,
1687 width: targetW,
1688 height: targetH,
1689 };
1690
1691 const backdrop = document.createElement('div');
1692 backdrop.className = 'preview-backdrop';
1693 document.body.appendChild(backdrop);
1694
1695 const parent = tileEl.parentNode;
1696 const nextSibling = tileEl.nextSibling;
1697 const iconHtml = iconEl.innerHTML;
1698 const originalIconSvg = iconEl.querySelector('svg');
1699
1700 tileEl.remove();
1701 document.body.appendChild(tileEl);
1702 tileEl.classList.add('file-item--preview');
1703 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
1704 tileEl.style.position = 'fixed';
1705 tileEl.style.left = `${startRect.left}px`;
1706 tileEl.style.top = `${startRect.top}px`;
1707 tileEl.style.width = `${startRect.width}px`;
1708 tileEl.style.height = `${startRect.height}px`;
1709 tileEl.style.margin = '0';
1710 tileEl.style.zIndex = '10000';
1711
1712 if (nameEl) nameEl.style.display = 'none';
1713
1714 const titleEl = document.createElement('div');
1715 titleEl.className = 'preview-expand-title';
1716 titleEl.textContent = item.name;
1717
1718 const closeBtn = document.createElement('button');
1719 closeBtn.className = 'preview-expand-close';
1720 closeBtn.type = 'button';
1721 closeBtn.textContent = '×';
1722 closeBtn.setAttribute('aria-label', 'Close preview');
1723
1724 const dlBtn = document.createElement('button');
1725 dlBtn.className = 'preview-expand-download';
1726 dlBtn.type = 'button';
1727 dlBtn.textContent = 'Download';
1728 dlBtn.addEventListener('click', (e) =>
1729 {
1730 e.stopPropagation();
1731 if (!STATE.previewObjectUrl)
1732 {
1733 toast('Preview still loading.', 'err');
1734 return;
1735 }
1736 triggerDownload(item.name, STATE.previewObjectUrl);
1737 });
1738
1739 iconEl.innerHTML = '';
1740
1741 if (originalIconSvg)
1742 {
1743 const outline = originalIconSvg.cloneNode(true);
1744 outline.classList.add('preview-expand-outline');
1745 iconEl.appendChild(outline);
1746 }
1747
1748 const previewMount = document.createElement('div');
1749 previewMount.className = 'preview-expand-content';
1750 iconEl.appendChild(previewMount);
1751
1752 // Show spinner during expansion animation; content loads after it finishes
1753 const spinner = document.createElement('div');
1754 spinner.className = 'preview-loading-spinner';
1755 previewMount.appendChild(spinner);
1756
1757 tileEl.insertBefore(titleEl, tileEl.firstChild);
1758 tileEl.appendChild(closeBtn);
1759 tileEl.appendChild(dlBtn);
1760
1761 STATE.previewExpandState = {
1762 item,
1763 tileEl,
1764 sourceSvgEl,
1765 parent,
1766 nextSibling,
1767 iconEl,
1768 iconHtml,
1769 nameEl,
1770 backdrop,
1771 closeBtn,
1772 dlBtn,
1773 titleEl,
1774 previewMount,
1775 startRect,
1776 };
1777
1778 const onBackdrop = (e) =>
1779 {
1780 if (e.target === backdrop) closePreview();
1781 };
1782 const onClose = () => closePreview();
1783 backdrop.addEventListener('click', onBackdrop);
1784 closeBtn.addEventListener('click', onClose);
1785 STATE.previewExpandState.onBackdrop = onBackdrop;
1786 STATE.previewExpandState.onClose = onClose;
1787
1788 requestAnimationFrame(() => backdrop.classList.add('visible'));
1789 await animateRect(tileEl, startRect, targetRect);
1790
1791 tileEl.style.left = `${targetRect.left}px`;
1792 tileEl.style.top = `${targetRect.top}px`;
1793 tileEl.style.width = `${targetRect.width}px`;
1794 tileEl.style.height = `${targetRect.height}px`;
1795
1796 try
1797 {
1798 await loadPreviewContent(previewMount);
1799 } catch
1800 {
1801 if (previewMount.isConnected)
1802 {
1803 previewMount.innerHTML = '';
1804 const msg = document.createElement('p');
1805 msg.className = 'preview-unsupported';
1806 msg.textContent = 'Preview failed to load. You can try again.';
1807 previewMount.appendChild(msg);
1808 }
1809 }
1810
1811 return true;
1812}
1813
1814async function closeExpandedTilePreview ()
1815{
1816 const st = STATE.previewExpandState;
1817 if (!st) return;
1818
1819 st.backdrop.classList.remove('visible');
1820 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
1821 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
1822
1823 const fromRect = st.tileEl.getBoundingClientRect();
1824 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
1825
1826 st.tileEl.classList.remove('file-item--preview');
1827 st.tileEl.style.position = '';
1828 st.tileEl.style.left = '';
1829 st.tileEl.style.top = '';
1830 st.tileEl.style.width = '';
1831 st.tileEl.style.height = '';
1832 st.tileEl.style.margin = '';
1833 st.tileEl.style.zIndex = '';
1834
1835 if (st.titleEl) st.titleEl.remove();
1836 if (st.closeBtn) st.closeBtn.remove();
1837 if (st.dlBtn) st.dlBtn.remove();
1838 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
1839 if (st.nameEl) st.nameEl.style.display = '';
1840
1841 if (st.parent)
1842 {
1843 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
1844 {
1845 st.parent.insertBefore(st.tileEl, st.nextSibling);
1846 } else
1847 {
1848 st.parent.appendChild(st.tileEl);
1849 }
1850 }
1851
1852 if (st.backdrop) st.backdrop.remove();
1853 STATE.previewExpandState = null;
1854}
1855
1856async function closePreview ()
1857{
1858 if (STATE.previewExpandState)
1859 {
1860 await closeExpandedTilePreview();
1861 clearPreviewObjectUrl();
1862 STATE.previewSourceEl = null;
1863 }
1864}
1865
1866async function fetchFileBlob (item)
1867{
1868 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
1869 try
1870 {
1871 const res = await fetch(url, {
1872 headers: {
1873 Authorization: 'Bearer ' + STATE.token,
1874 'X-Fp': getFingerprint(),
1875 },
1876 });
1877 if (!res.ok) throw new Error('Download failed.');
1878 return await res.blob();
1879 } catch
1880 {
1881 return null;
1882 }
1883}
1884
1885function triggerDownload (filename, objectUrl)
1886{
1887 const a = document.createElement('a');
1888 a.href = objectUrl;
1889 a.download = filename;
1890 a.click();
1891}
1892
1893async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
1894{
1895 const body = targetEl || document.getElementById('preview-body');
1896 body.innerHTML = '';
1897
1898 const mime = String(blob.type || '').toLowerCase();
1899 const previewable = isInlinePreviewableBlob(blob, item.name);
1900
1901 if (!previewable)
1902 {
1903 const msg = document.createElement('p');
1904 msg.className = 'preview-unsupported';
1905 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1906 body.appendChild(msg);
1907 return;
1908 }
1909
1910 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
1911 {
1912 const img = document.createElement('img');
1913 img.className = 'preview-media';
1914 img.src = objectUrl;
1915 img.alt = item.name;
1916 body.appendChild(img);
1917 return;
1918 }
1919
1920 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
1921 {
1922 const video = document.createElement('video');
1923 video.className = 'preview-media';
1924 video.src = objectUrl;
1925 video.controls = true;
1926 video.preload = 'metadata';
1927 body.appendChild(video);
1928 return;
1929 }
1930
1931 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
1932 {
1933 const audio = document.createElement('audio');
1934 audio.className = 'preview-audio';
1935 audio.src = objectUrl;
1936 audio.controls = true;
1937 body.appendChild(audio);
1938 return;
1939 }
1940
1941 if (mime === 'application/pdf')
1942 {
1943 const frame = document.createElement('iframe');
1944 frame.className = 'preview-frame';
1945 frame.src = objectUrl;
1946 frame.title = item.name;
1947 body.appendChild(frame);
1948 return;
1949 }
1950
1951 if (isTextLikeBlob(blob, item.name))
1952 {
1953 const text = await blob.text();
1954 const lang = detectCodeLanguage(item.name, mime);
1955 const formatted = prettyPrintCode(text, lang);
1956 const pre = document.createElement('pre');
1957 pre.className = 'preview-text preview-code';
1958 pre.innerHTML = highlightCode(formatted, lang);
1959 body.appendChild(pre);
1960 return;
1961 }
1962
1963 const msg = document.createElement('p');
1964 msg.className = 'preview-unsupported';
1965 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1966 body.appendChild(msg);
1967}
1968
1969async function downloadOrView (item, sourceSvgEl = null)
1970{
1971 if (STATE.previewExpandState)
1972 {
1973 await closePreview();
1974 }
1975
1976 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
1977 if (sourceTileEl)
1978 {
1979 STATE.previewSourceEl = sourceSvgEl;
1980 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
1981 {
1982 const blob = await fetchFileBlob(item);
1983 if (!blob) throw new Error('Download failed');
1984
1985 clearPreviewObjectUrl();
1986 const objectUrl = URL.createObjectURL(blob);
1987 STATE.previewObjectUrl = objectUrl;
1988
1989 if (!previewMount.isConnected) return;
1990
1991 previewMount.innerHTML = '';
1992 await renderPreviewBody(item, blob, objectUrl, previewMount);
1993 });
1994 if (expanded) return;
1995 }
1996
1997 toast('Preview unavailable — no source tile found.', 'err');
1998}
1999
2000// ───────────────────────────────────────────────────────────────────────────
2001// UPLOAD
2002// ───────────────────────────────────────────────────────────────────────────
2003
2004function canWrite (item = null)
2005{
2006 if (STATE.isAdmin) return true;
2007 const root = item && item._root
2008 ? item._root
2009 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
2010 if (!root) return false;
2011 const p = STATE.permissions[rootPermissionLabel(root)];
2012 return p && p.write;
2013}
2014
2015async function uploadFiles (fileList)
2016{
2017 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2018 if (!canWrite()) { toast('No write access.', 'err'); return; }
2019
2020 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
2021 const formData = new FormData();
2022 for (const f of fileList) formData.append('files', f);
2023
2024 // Show upload bar
2025 const wrap = document.createElement('div');
2026 wrap.className = 'upload-bar-wrap';
2027 wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2028 document.body.appendChild(wrap);
2029 STATE.uploadInProgress = true;
2030
2031 try
2032 {
2033 const xhr = new XMLHttpRequest();
2034 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
2035 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2036 xhr.setRequestHeader('X-Fp', getFingerprint());
2037 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
2038 xhr.upload.addEventListener('progress', e =>
2039 {
2040 if (e.lengthComputable)
2041 {
2042 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
2043 }
2044 });
2045
2046 await new Promise((resolve, reject) =>
2047 {
2048 xhr.onload = () =>
2049 {
2050 if (xhr.status === 200) resolve();
2051 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
2052 };
2053 xhr.onerror = () => reject(new Error('Network error'));
2054 xhr.send(formData);
2055 });
2056
2057 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
2058 await navigateTo(STATE.currentDir, STATE.currentRoot);
2059 } catch (err)
2060 {
2061 toast(err.message, 'err');
2062 } finally
2063 {
2064 STATE.uploadInProgress = false;
2065 wrap.remove();
2066 }
2067}
2068
2069async function uploadSingleFile (file, targetDir)
2070{
2071 const formData = new FormData();
2072 formData.append('files', file);
2073
2074 await new Promise((resolve, reject) =>
2075 {
2076 const xhr = new XMLHttpRequest();
2077 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
2078 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2079 xhr.setRequestHeader('X-Fp', getFingerprint());
2080 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
2081 xhr.onload = () => xhr.status === 200
2082 ? resolve()
2083 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
2084 xhr.onerror = () => reject(new Error('Network error'));
2085 xhr.send(formData);
2086 });
2087}
2088
2089async function ensureServerDir (baseDir, relativeDir)
2090{
2091 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
2092 let current = baseDir;
2093 for (const part of parts)
2094 {
2095 try
2096 {
2097 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
2098 current = resp && resp.path ? resp.path : joinServerPath(current, part);
2099 } catch (err)
2100 {
2101 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2102 current = joinServerPath(current, part);
2103 }
2104 }
2105 return current;
2106}
2107
2108async function uploadFolderInputFiles (fileList)
2109{
2110 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2111 if (!canWrite()) { toast('No write access.', 'err'); return; }
2112 if (!fileList || !fileList.length) return;
2113
2114 const files = Array.from(fileList);
2115 const total = files.length;
2116 let done = 0;
2117
2118 const wrap = document.createElement('div');
2119 wrap.className = 'upload-bar-wrap';
2120 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2121 document.body.appendChild(wrap);
2122 STATE.uploadInProgress = true;
2123
2124 try
2125 {
2126 const dirCache = new Map();
2127 dirCache.set('', STATE.currentDir);
2128
2129 for (const file of files)
2130 {
2131 const rel = file.webkitRelativePath || file.name;
2132 const relParts = rel.split(/[\\/]/).filter(Boolean);
2133 const relDir = relParts.slice(0, -1).join('/');
2134
2135 if (!dirCache.has(relDir))
2136 {
2137 const parentRel = relParts.slice(0, -2).join('/');
2138 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
2139 const thisName = relParts[relParts.length - 2];
2140
2141 try
2142 {
2143 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
2144 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
2145 } catch (err)
2146 {
2147 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2148 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
2149 }
2150 }
2151
2152 const targetDir = dirCache.get(relDir) || STATE.currentDir;
2153 await uploadSingleFile(file, targetDir);
2154 done++;
2155 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2156 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2157 }
2158
2159 toast(`Uploaded ${total} file(s).`, 'ok');
2160 await navigateTo(STATE.currentDir, STATE.currentRoot);
2161 } catch (err)
2162 {
2163 toast(err.message, 'err');
2164 } finally
2165 {
2166 STATE.uploadInProgress = false;
2167 wrap.remove();
2168 }
2169}
2170
2171// ───────────────────────────────────────────────────────────────────────────
2172// FOLDER DRAG-AND-DROP (recursive)
2173// ───────────────────────────────────────────────────────────────────────────
2174
2175/**
2176 * Reads all readEntries batches from a DirectoryReader (browsers may return
2177 * results in chunks; we must keep calling until we get an empty array).
2178 */
2179function readAllEntries (reader)
2180{
2181 return new Promise((resolve, reject) =>
2182 {
2183 const all = [];
2184 function next ()
2185 {
2186 reader.readEntries(batch =>
2187 {
2188 if (!batch.length) { resolve(all); return; }
2189 all.push(...batch);
2190 next();
2191 }, reject);
2192 }
2193 next();
2194 });
2195}
2196
2197/**
2198 * Recursively walk a FileSystemEntry tree, creating server-side directories
2199 * on the fly and collecting { file, targetDir } pairs for upload.
2200 */
2201async function collectEntries (entry, serverDir, toUpload)
2202{
2203 if (entry.isFile)
2204 {
2205 const file = await new Promise((res, rej) => entry.file(res, rej));
2206 toUpload.push({ file, targetDir: serverDir });
2207 } else if (entry.isDirectory)
2208 {
2209 // Ask the server to create the directory; it returns the canonical path.
2210 let newServerDir;
2211 try
2212 {
2213 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
2214 newServerDir = resp.path;
2215 } catch
2216 {
2217 // Directory may already exist — reconstruct path from what we know.
2218 // The server always returns JSON with {error} on failure, so we can
2219 // still continue by falling back to a best-effort path join.
2220 // We rely on the fact that the server separator is consistent within
2221 // a session (the list/browse API already returned paths in that format).
2222 const sep = serverDir.includes('\\') ? '\\' : '/';
2223 newServerDir = serverDir + sep + entry.name;
2224 }
2225 const reader = entry.createReader();
2226 const subEntries = await readAllEntries(reader);
2227 for (const sub of subEntries)
2228 {
2229 await collectEntries(sub, newServerDir, toUpload);
2230 }
2231 }
2232}
2233
2234async function uploadEntries (entries)
2235{
2236 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2237 if (!canWrite()) { toast('No write access.', 'err'); return; }
2238
2239 const wrap = document.createElement('div');
2240 wrap.className = 'upload-bar-wrap';
2241 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2242 document.body.appendChild(wrap);
2243 STATE.uploadInProgress = true;
2244
2245 try
2246 {
2247 const toUpload = [];
2248 for (const entry of entries)
2249 {
2250 await collectEntries(entry, STATE.currentDir, toUpload);
2251 }
2252
2253 if (!toUpload.length) { toast('No files found.', 'err'); return; }
2254
2255 let done = 0;
2256 const total = toUpload.length;
2257 const updateBar = () =>
2258 {
2259 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2260 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2261 };
2262 updateBar();
2263
2264 for (const { file, targetDir } of toUpload)
2265 {
2266 await uploadSingleFile(file, targetDir);
2267 done++;
2268 updateBar();
2269 }
2270
2271 toast(`Uploaded ${total} file(s).`, 'ok');
2272 await navigateTo(STATE.currentDir, STATE.currentRoot);
2273 } catch (err)
2274 {
2275 toast(err.message, 'err');
2276 } finally
2277 {
2278 STATE.uploadInProgress = false;
2279 wrap.remove();
2280 }
2281}
2282
2283// DRAG-AND-DROP
2284// ───────────────────────────────────────────────────────────────────────────
2285
2286function initDragDrop ()
2287{
2288 const main = document.getElementById('main-content');
2289 const dropOvl = document.getElementById('drop-overlay');
2290 let dragDepth = 0;
2291
2292 main.addEventListener('dragenter', e =>
2293 {
2294 e.preventDefault();
2295 dragDepth++;
2296 dropOvl.classList.remove('hidden');
2297 });
2298 main.addEventListener('dragleave', () =>
2299 {
2300 dragDepth--;
2301 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
2302 });
2303 main.addEventListener('dragover', e => e.preventDefault());
2304 main.addEventListener('drop', async e =>
2305 {
2306 e.preventDefault();
2307 dragDepth = 0;
2308 dropOvl.classList.add('hidden');
2309 if (!canWrite()) { toast('No write access.', 'err'); return; }
2310
2311 const items = Array.from(e.dataTransfer.items || []);
2312 // Use the FileSystem Entry API when available so we can handle folders.
2313 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
2314 {
2315 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
2316 if (entries.some(en => en.isDirectory))
2317 {
2318 await uploadEntries(entries);
2319 return;
2320 }
2321 }
2322 // Plain files only — use the fast batch path.
2323 const files = e.dataTransfer.files;
2324 if (files.length) await uploadFiles(files);
2325 });
2326}
2327
2328// ───────────────────────────────────────────────────────────────────────────
2329// RENAME
2330// ───────────────────────────────────────────────────────────────────────────
2331
2332function openRenameModal (item)
2333{
2334 const modal = document.getElementById('rename-modal');
2335 modal.classList.remove('hidden');
2336 const input = document.getElementById('rename-input');
2337 input.value = item.name;
2338 input.focus();
2339 input.select();
2340 document.getElementById('rename-error').classList.add('hidden');
2341 document.getElementById('rename-form').onsubmit = async (e) =>
2342 {
2343 e.preventDefault();
2344 const newName = input.value.trim();
2345 if (!newName) return;
2346 try
2347 {
2348 if (item._root)
2349 {
2350 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
2351 } else
2352 {
2353 await api('POST', '/files/rename', { from: item.path, to: newName });
2354 }
2355 modal.classList.add('hidden');
2356 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
2357 if (item._root)
2358 {
2359 await loadRoots({
2360 preferredDir: STATE.currentDir,
2361 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
2362 });
2363 } else
2364 {
2365 await navigateTo(STATE.currentDir, STATE.currentRoot);
2366 }
2367 } catch (err)
2368 {
2369 document.getElementById('rename-error').textContent = err.message;
2370 document.getElementById('rename-error').classList.remove('hidden');
2371 }
2372 };
2373}
2374
2375// ───────────────────────────────────────────────────────────────────────────
2376// DELETE
2377// ───────────────────────────────────────────────────────────────────────────
2378
2379async function deleteItem (item)
2380{
2381 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
2382 try
2383 {
2384 await api('POST', '/files/delete', { path: item.path });
2385 toast('Deleted.', 'ok');
2386 closeSidebar();
2387 await navigateTo(STATE.currentDir, STATE.currentRoot);
2388 } catch (err)
2389 {
2390 toast(err.message, 'err');
2391 }
2392}
2393
2394// ───────────────────────────────────────────────────────────────────────────
2395// ADMIN PANEL
2396// ───────────────────────────────────────────────────────────────────────────
2397
2398async function openAdminModal ()
2399{
2400 document.getElementById('admin-modal').classList.remove('hidden');
2401 await refreshAdminConfig();
2402 await refreshAdminUsers();
2403}
2404
2405async function refreshAdminConfig ()
2406{
2407 const data = await api('GET', '/admin/config');
2408 if (!data) return;
2409 const container = document.getElementById('admin-paths');
2410 container.innerHTML = '';
2411 for (const p of data.paths)
2412 {
2413 const row = document.createElement('div');
2414 row.className = 'path-row';
2415 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
2416 row.querySelector('button').addEventListener('click', () =>
2417 {
2418 row.remove();
2419 });
2420 container.appendChild(row);
2421 }
2422}
2423
2424async function refreshAdminUsers ()
2425{
2426 const data = await api('GET', '/admin/users');
2427 if (!data) return;
2428 const container = document.getElementById('admin-users-list');
2429 container.innerHTML = '';
2430
2431 // Need paths for permission rows
2432 const cfg = await api('GET', '/admin/config');
2433 const paths = cfg ? (cfg.effectivePaths || []) : [];
2434
2435 for (const u of data.users)
2436 {
2437 const row = document.createElement('div');
2438 row.className = 'user-row';
2439 row.innerHTML = `
2440 <span class="user-name">${u.username}</span>
2441 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
2442 <button data-id="${u.id}" data-action="edit">Edit</button>
2443 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
2444 `;
2445 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
2446 openUserModal(u, paths));
2447 const deleteBtn = row.querySelector('[data-action="delete"]');
2448 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
2449 {
2450 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
2451 try
2452 {
2453 await api('DELETE', `/admin/users/${u.id}`);
2454 toast('User deleted.', 'ok');
2455 await refreshAdminUsers();
2456 } catch (err) { toast(err.message, 'err'); }
2457 });
2458 container.appendChild(row);
2459 }
2460}
2461
2462function openUserModal (user, paths)
2463{
2464 const modal = document.getElementById('user-modal');
2465 modal.classList.remove('hidden');
2466 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
2467 document.getElementById('user-error').classList.add('hidden');
2468
2469 const usernameInput = document.getElementById('user-username');
2470 usernameInput.value = user ? user.username : '';
2471 usernameInput.readOnly = !!user;
2472
2473 document.getElementById('user-password').value = '';
2474 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
2475
2476 // Password placeholder
2477 document.getElementById('user-password').placeholder =
2478 user ? 'Leave blank to keep current' : 'Min 8 characters';
2479
2480 // Build permissions grid
2481 const permDiv = document.getElementById('user-permissions');
2482 permDiv.innerHTML = '';
2483 if (paths.length)
2484 {
2485 const heading = document.createElement('h4');
2486 heading.textContent = 'Path Permissions';
2487 permDiv.appendChild(heading);
2488
2489 const isAdminUser = !!(user && user.isAdmin);
2490 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
2491 const adminChk = document.getElementById('user-is-admin');
2492 const rebuildPermRows = (admin) =>
2493 {
2494 permDiv.querySelectorAll('.perm-row').forEach(r =>
2495 {
2496 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
2497 {
2498 cb.disabled = admin;
2499 if (admin) cb.checked = true;
2500 });
2501 r.title = admin ? 'Admins always have full access' : '';
2502 });
2503 };
2504 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
2505
2506 const syncReadWriteConstraints = (row, admin = false) =>
2507 {
2508 const readCb = row.querySelector('input[data-type="read"]');
2509 const writeCb = row.querySelector('input[data-type="write"]');
2510 if (!readCb || !writeCb) return;
2511
2512 if (admin)
2513 {
2514 readCb.checked = true;
2515 writeCb.checked = true;
2516 readCb.disabled = true;
2517 writeCb.disabled = true;
2518 return;
2519 }
2520
2521 readCb.disabled = false;
2522 if (!readCb.checked)
2523 {
2524 writeCb.checked = false;
2525 writeCb.disabled = true;
2526 }
2527 else
2528 {
2529 writeCb.disabled = false;
2530 }
2531 };
2532
2533 const syncAllReadWriteConstraints = () =>
2534 {
2535 const admin = adminChk.checked;
2536 permDiv.querySelectorAll('.perm-row').forEach((row) =>
2537 {
2538 syncReadWriteConstraints(row, admin);
2539 });
2540 };
2541
2542 for (const p of paths)
2543 {
2544 const label = p.split(/[\\/]/).pop();
2545 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
2546 const row = document.createElement('div');
2547 row.className = 'perm-row';
2548 const readChecked = isAdminUser || perms.read;
2549 const writeChecked = isAdminUser || perms.write;
2550 row.innerHTML = `
2551 <span class="perm-label">${label}</span>
2552 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
2553 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
2554 `;
2555 if (isAdminUser) row.title = 'Admins always have full access';
2556 const readCb = row.querySelector('input[data-type="read"]');
2557 if (readCb)
2558 {
2559 readCb.addEventListener('change', () =>
2560 {
2561 syncReadWriteConstraints(row, adminChk.checked);
2562 });
2563 }
2564 permDiv.appendChild(row);
2565 }
2566
2567 syncAllReadWriteConstraints();
2568 adminChk.addEventListener('change', syncAllReadWriteConstraints);
2569 }
2570
2571 document.getElementById('user-form').onsubmit = async (e) =>
2572 {
2573 e.preventDefault();
2574 const password = document.getElementById('user-password').value;
2575 const isAdmin = document.getElementById('user-is-admin').checked;
2576 const permissions = {};
2577 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
2578 {
2579 const lbl = cb.dataset.label;
2580 if (!permissions[lbl]) permissions[lbl] = {};
2581 permissions[lbl][cb.dataset.type] = cb.checked;
2582 });
2583
2584 try
2585 {
2586 if (user)
2587 {
2588 const body = { isAdmin, permissions };
2589 if (password) body.password = password;
2590 await api('PATCH', `/admin/users/${user.id}`, body);
2591 } else
2592 {
2593 const uname = document.getElementById('user-username').value.trim();
2594 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
2595 }
2596 modal.classList.add('hidden');
2597 toast('User saved.', 'ok');
2598 await refreshAdminUsers();
2599 } catch (err)
2600 {
2601 document.getElementById('user-error').textContent = err.message;
2602 document.getElementById('user-error').classList.remove('hidden');
2603 }
2604 };
2605}
2606
2607// ───────────────────────────────────────────────────────────────────────────
2608// SVG ICONS
2609// ───────────────────────────────────────────────────────────────────────────
2610
2611const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
2612const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
2613const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
2614const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
2615const 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']);
2616const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
2617const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
2618
2619function iconFolder (size = 52)
2620{
2621 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
2622 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
2623 <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"/>
2624 </svg>`;
2625}
2626
2627function iconFile (name, size = 52)
2628{
2629 const color = fileAccentColor(name);
2630 let symbol = '';
2631
2632 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
2633 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
2634 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
2635 <polyline points="14 2 14 8 20 8"/>
2636 </svg>`;
2637}
2638
2639// ───────────────────────────────────────────────────────────────────────────
2640// EVENT WIRING
2641// ───────────────────────────────────────────────────────────────────────────
2642
2643// ───────────────────────────────────────────────────────────────────────────
2644// THUMBNAIL PREVIEWS
2645// ───────────────────────────────────────────────────────────────────────────
2646
2647function revokeThumbnails ()
2648{
2649 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
2650 STATE.thumbnailUrls = [];
2651}
2652
2653function disconnectThumbnailObserver ()
2654{
2655 if (!STATE.thumbnailObserver) return;
2656 STATE.thumbnailObserver.disconnect();
2657 STATE.thumbnailObserver = null;
2658}
2659
2660function setThumbnailPending (iconEl, pending)
2661{
2662 if (!iconEl) return;
2663 if (pending)
2664 {
2665 iconEl.classList.add('thumb-pending');
2666 iconEl.dataset.thumbPending = '1';
2667 return;
2668 }
2669
2670 iconEl.classList.remove('thumb-pending');
2671 delete iconEl.dataset.thumbPending;
2672}
2673
2674function getThumbnailKind (name)
2675{
2676 const ext = extOf(name || '');
2677 if (IMAGE_EXTS.has(ext)) return 'image';
2678 if (CODE_EXTS.has(ext)) return 'text';
2679 return 'badge';
2680}
2681
2682function maxThumbBytesForKind (kind)
2683{
2684 if (kind === 'image') return 15 * 1024 * 1024;
2685 if (kind === 'text') return 1024 * 1024;
2686 return 0;
2687}
2688
2689function drawTokenizedLine (ctx, line, x, y)
2690{
2691 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;
2692 let last = 0;
2693 let cursor = x;
2694 for (const m of line.matchAll(tokenRe))
2695 {
2696 const i = m.index == null ? 0 : m.index;
2697 if (i > last)
2698 {
2699 const plain = line.slice(last, i);
2700 ctx.fillStyle = '#dce4ff';
2701 ctx.fillText(plain, cursor, y);
2702 cursor += ctx.measureText(plain).width;
2703 }
2704
2705 const tok = m[0];
2706 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
2707 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
2708 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
2709 else ctx.fillStyle = '#8bb4ff';
2710
2711 ctx.fillText(tok, cursor, y);
2712 cursor += ctx.measureText(tok).width;
2713 last = i + tok.length;
2714 }
2715
2716 if (last < line.length)
2717 {
2718 const tail = line.slice(last);
2719 ctx.fillStyle = '#dce4ff';
2720 ctx.fillText(tail, cursor, y);
2721 }
2722}
2723
2724function textThumbnailDataUrl (text)
2725{
2726 const canvas = document.createElement('canvas');
2727 canvas.width = 160;
2728 canvas.height = 200;
2729 const ctx = canvas.getContext('2d');
2730 if (!ctx) return null;
2731
2732 ctx.fillStyle = '#0d111a';
2733 ctx.fillRect(0, 0, canvas.width, canvas.height);
2734 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
2735 ctx.textBaseline = 'top';
2736
2737 const lines = String(text || '')
2738 .replace(/\r\n/g, '\n')
2739 .split('\n')
2740 .slice(0, 17);
2741
2742 let y = 8;
2743 for (const line of lines)
2744 {
2745 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
2746 y += 11;
2747 if (y > 190) break;
2748 }
2749 return canvas.toDataURL('image/png');
2750}
2751
2752function badgeThumbnailDataUrl (name, kind)
2753{
2754 const canvas = document.createElement('canvas');
2755 canvas.width = 160;
2756 canvas.height = 200;
2757 const ctx = canvas.getContext('2d');
2758 if (!ctx) return null;
2759
2760 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2761 const color = '#5b7fff';
2762
2763 ctx.fillStyle = '#111826';
2764 ctx.fillRect(0, 0, 160, 200);
2765 ctx.fillStyle = color;
2766 ctx.fillRect(0, 0, 160, 28);
2767 ctx.fillStyle = '#ffffff';
2768 ctx.font = 'bold 12px sans-serif';
2769 ctx.textAlign = 'center';
2770 ctx.fillText(ext, 80, 8);
2771 ctx.textAlign = 'left';
2772 ctx.fillStyle = '#9fb1d8';
2773 ctx.font = '10px sans-serif';
2774 ctx.fillText('Preview', 8, 48);
2775 ctx.fillStyle = '#dce4ff';
2776 ctx.font = 'bold 11px sans-serif';
2777 ctx.fillText(ext, 8, 66);
2778 return canvas.toDataURL('image/png');
2779}
2780
2781async function buildThumbnailSource (item, blob, kind)
2782{
2783 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2784 return badgeThumbnailDataUrl(item.name, kind);
2785}
2786
2787function observeThumbnailIcon (iconEl)
2788{
2789 if (!iconEl || !iconEl.isConnected) return;
2790 if (iconEl.dataset.thumbReady === '1') return;
2791
2792 if (!('IntersectionObserver' in window))
2793 {
2794 void loadOneThumbnail(iconEl);
2795 return;
2796 }
2797
2798 if (!STATE.thumbnailObserver)
2799 {
2800 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
2801 {
2802 for (const entry of entries)
2803 {
2804 if (!entry.isIntersecting) continue;
2805 const icon = entry.target;
2806 STATE.thumbnailObserver.unobserve(icon);
2807 void loadOneThumbnail(icon);
2808 }
2809 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
2810 }
2811
2812 STATE.thumbnailObserver.observe(iconEl);
2813}
2814
2815async function loadThumbnails ()
2816{
2817 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2818 if (!icons.length) return;
2819
2820 for (const icon of icons)
2821 {
2822 observeThumbnailIcon(icon);
2823 }
2824}
2825
2826async function loadOneThumbnail (iconEl)
2827{
2828 if (!iconEl.isConnected || !STATE.token) return;
2829 if (iconEl.dataset.thumbReady === '1') return;
2830 const filePath = iconEl.dataset.previewPath;
2831 const item = STATE.items.find(i => i.path === filePath);
2832 if (!item) return;
2833
2834 const kind = getThumbnailKind(item.name);
2835 let srcUrl = null;
2836
2837 if (kind === 'badge')
2838 {
2839 setThumbnailPending(iconEl, false);
2840 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2841 }
2842 else if (kind === 'image')
2843 {
2844 const ext = extOf(item.name || '');
2845 const useDirectSvg =
2846 ext === 'svg' &&
2847 typeof item.size === 'number' &&
2848 item.size > 0 &&
2849 item.size <= MAX_DIRECT_SVG_THUMB_BYTES;
2850
2851 const url = useDirectSvg
2852 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
2853 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
2854
2855 let res;
2856 try
2857 {
2858 res = await fetch(url, {
2859 headers: {
2860 Authorization: `Bearer ${STATE.token}`,
2861 'X-Fp': getFingerprint(),
2862 },
2863 });
2864 } catch
2865 {
2866 return;
2867 }
2868
2869 if (!useDirectSvg && res.status === 404)
2870 {
2871 setThumbnailPending(iconEl, true);
2872 return;
2873 }
2874
2875 if (!res.ok || !iconEl.isConnected) return;
2876 setThumbnailPending(iconEl, false);
2877
2878 const blob = await res.blob();
2879 srcUrl = URL.createObjectURL(blob);
2880 STATE.thumbnailUrls.push(srcUrl);
2881 }
2882 else
2883 {
2884 setThumbnailPending(iconEl, false);
2885 const maxBytes = maxThumbBytesForKind(kind);
2886 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
2887 {
2888 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2889 } else
2890 {
2891 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
2892
2893 let res;
2894 try
2895 {
2896 res = await fetch(url, {
2897 headers: {
2898 Authorization: `Bearer ${STATE.token}`,
2899 'X-Fp': getFingerprint(),
2900 },
2901 });
2902 } catch { return; }
2903 if (!res.ok || !iconEl.isConnected) return;
2904
2905 const blob = await res.blob();
2906 srcUrl = await buildThumbnailSource(item, blob, kind);
2907 }
2908 }
2909 if (!srcUrl || !iconEl.isConnected) return;
2910
2911 const svg = iconEl.querySelector('svg');
2912 if (!svg)
2913 {
2914 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
2915 return;
2916 }
2917
2918 const NS = 'http://www.w3.org/2000/svg';
2919 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
2920
2921 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
2922 const defs = document.createElementNS(NS, 'defs');
2923 const clipPath = document.createElementNS(NS, 'clipPath');
2924 clipPath.setAttribute('id', id);
2925 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
2926 const clipShape = document.createElementNS(NS, 'path');
2927 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
2928 clipPath.appendChild(clipShape);
2929 defs.appendChild(clipPath);
2930
2931 // Image fills the file bounding box; clip keeps it inside the outline
2932 const img = document.createElementNS(NS, 'image');
2933 img.setAttribute('href', srcUrl);
2934 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
2935 img.setAttribute('x', '4');
2936 img.setAttribute('y', '2');
2937 img.setAttribute('width', '16');
2938 img.setAttribute('height', '20');
2939 img.setAttribute('clip-path', `url(#${id})`);
2940 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
2941
2942 // Prepend so existing path/polyline elements (the outline) render on top
2943 svg.prepend(img);
2944 svg.prepend(defs);
2945 iconEl.dataset.thumbReady = '1';
2946}
2947
2948function wireEvents ()
2949{
2950 // Auth form
2951 document.getElementById('auth-form').addEventListener('submit', async (e) =>
2952 {
2953 e.preventDefault();
2954 const username = document.getElementById('auth-username').value.trim();
2955 const password = document.getElementById('auth-password').value;
2956 const isSetup = e.target.dataset.mode === 'setup';
2957 const errEl = document.getElementById('auth-error');
2958 const btn = document.getElementById('auth-submit');
2959 btn.disabled = true;
2960 btn.textContent = 'Please wait…';
2961 const err = await doLogin(username, password, isSetup);
2962 if (err)
2963 {
2964 errEl.textContent = err;
2965 errEl.classList.remove('hidden');
2966 btn.disabled = false;
2967 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
2968 }
2969 });
2970
2971 // Logout
2972 document.getElementById('btn-logout').addEventListener('click', logout);
2973
2974 // Hard refresh while keeping auth/session state.
2975 document.getElementById('btn-refresh').addEventListener('click', () =>
2976 {
2977 saveSessionState();
2978 location.reload();
2979 });
2980
2981 // Upload button
2982 document.getElementById('btn-upload').addEventListener('click', () =>
2983 {
2984 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2985 if (!canWrite()) { toast('No write access.', 'err'); return; }
2986 document.getElementById('file-input').click();
2987 });
2988
2989 document.getElementById('file-input').addEventListener('change', async (e) =>
2990 {
2991 if (e.target.files.length) await uploadFiles(e.target.files);
2992 e.target.value = '';
2993 });
2994
2995 document.getElementById('btn-upload-folder').addEventListener('click', () =>
2996 {
2997 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2998 if (!canWrite()) { toast('No write access.', 'err'); return; }
2999 document.getElementById('folder-input').click();
3000 });
3001
3002 document.getElementById('folder-input').addEventListener('change', async (e) =>
3003 {
3004 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
3005 e.target.value = '';
3006 });
3007
3008 document.getElementById('btn-new-folder').addEventListener('click', async () =>
3009 {
3010 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3011 if (!canWrite()) { toast('No write access.', 'err'); return; }
3012
3013 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
3014 if (name == null) return;
3015 const folderName = name.trim();
3016 if (!folderName)
3017 {
3018 toast('Folder name is required.', 'err');
3019 return;
3020 }
3021
3022 try
3023 {
3024 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
3025 toast('Folder created.', 'ok');
3026 await navigateTo(STATE.currentDir, STATE.currentRoot);
3027 } catch (err)
3028 {
3029 toast(err.message, 'err');
3030 }
3031 });
3032
3033 document.getElementById('sidebar-close').addEventListener('click', (e) =>
3034 {
3035 e.stopPropagation();
3036 hideSidebarPanel();
3037 });
3038
3039 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
3040 const syncSidebarForViewport = () =>
3041 {
3042 if (isMobileViewport())
3043 {
3044 hideSidebarPanel();
3045 return;
3046 }
3047
3048 if (!STATE.selectedItem) openFolderSidebar();
3049 };
3050
3051 if (typeof mobileQuery.addEventListener === 'function')
3052 {
3053 mobileQuery.addEventListener('change', syncSidebarForViewport);
3054 } else if (typeof mobileQuery.addListener === 'function')
3055 {
3056 mobileQuery.addListener(syncSidebarForViewport);
3057 }
3058
3059 // Click outside grid clears selection and returns to folder sidebar info.
3060 document.getElementById('main-content').addEventListener('click', (e) =>
3061 {
3062 if (!e.target.closest('.file-item')) closeSidebar();
3063 });
3064
3065 // Admin panel
3066 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
3067 document.getElementById('admin-modal-close').addEventListener('click', () =>
3068 document.getElementById('admin-modal').classList.add('hidden'));
3069
3070 // Add path
3071 document.getElementById('admin-add-path').addEventListener('click', () =>
3072 {
3073 const val = document.getElementById('admin-new-path').value.trim();
3074 if (!val) return;
3075 const row = document.createElement('div');
3076 row.className = 'path-row';
3077 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
3078 row.querySelector('button').addEventListener('click', () => row.remove());
3079 document.getElementById('admin-paths').appendChild(row);
3080 document.getElementById('admin-new-path').value = '';
3081 });
3082
3083 // Save paths
3084 document.getElementById('admin-save-paths').addEventListener('click', async () =>
3085 {
3086 const rows = document.querySelectorAll('#admin-paths .path-row span');
3087 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
3088 try
3089 {
3090 await api('PUT', '/admin/config', { paths });
3091 toast('Paths saved.', 'ok');
3092 await loadRoots();
3093 } catch (err) { toast(err.message, 'err'); }
3094 });
3095
3096 // Shutdown server
3097 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
3098 {
3099 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
3100 try
3101 {
3102 await api('POST', '/admin/shutdown');
3103 toast('Server is shutting down…', 'ok');
3104 document.getElementById('admin-modal').classList.add('hidden');
3105 } catch
3106 {
3107 // Fetch may throw because the connection closes before a response arrives.
3108 toast('Server is shutting down…', 'ok');
3109 document.getElementById('admin-modal').classList.add('hidden');
3110 }
3111 });
3112
3113 // New user
3114 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
3115 {
3116 const cfg = await api('GET', '/admin/config');
3117 const paths = cfg ? (cfg.effectivePaths || []) : [];
3118 openUserModal(null, paths);
3119 });
3120
3121 // User modal close
3122 document.getElementById('user-modal-close').addEventListener('click', () =>
3123 document.getElementById('user-modal').classList.add('hidden'));
3124
3125 // Rename modal close
3126 document.getElementById('rename-modal-close').addEventListener('click', () =>
3127 document.getElementById('rename-modal').classList.add('hidden'));
3128
3129 // Close modals on backdrop click
3130 document.querySelectorAll('.modal-overlay').forEach(overlay =>
3131 {
3132 overlay.addEventListener('click', e =>
3133 {
3134 if (e.target === overlay) overlay.classList.add('hidden');
3135 });
3136 });
3137}
3138
3139// ───────────────────────────────────────────────────────────────────────────
3140// BOOT
3141// ───────────────────────────────────────────────────────────────────────────
3142
3143(async function boot ()
3144{
3145 wireEvents();
3146 initDragDrop();
3147 window.addEventListener('beforeunload', saveSessionState);
3148 await initAuth();
3149})();