BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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