BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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