BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

fix
timfa Tim Falken · pushed by timfa · 6 months ago
100f31a7 History
app.js 93.4 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, loadPreviewContent)
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 if (!STATE.previewObjectUrl)
1692 {
1693 toast('Preview still loading.', 'err');
1694 return;
1695 }
1696 triggerDownload(item.name, STATE.previewObjectUrl);
1697 });
1698
1699 iconEl.innerHTML = '';
1700
1701 if (originalIconSvg)
1702 {
1703 const outline = originalIconSvg.cloneNode(true);
1704 outline.classList.add('preview-expand-outline');
1705 iconEl.appendChild(outline);
1706 }
1707
1708 const previewMount = document.createElement('div');
1709 previewMount.className = 'preview-expand-content';
1710 iconEl.appendChild(previewMount);
1711
1712 // Show spinner during expansion animation; content loads after it finishes
1713 const spinner = document.createElement('div');
1714 spinner.className = 'preview-loading-spinner';
1715 previewMount.appendChild(spinner);
1716
1717 tileEl.insertBefore(titleEl, tileEl.firstChild);
1718 tileEl.appendChild(closeBtn);
1719 tileEl.appendChild(dlBtn);
1720
1721 STATE.previewExpandState = {
1722 item,
1723 tileEl,
1724 sourceSvgEl,
1725 parent,
1726 nextSibling,
1727 iconEl,
1728 iconHtml,
1729 nameEl,
1730 backdrop,
1731 closeBtn,
1732 dlBtn,
1733 titleEl,
1734 previewMount,
1735 startRect,
1736 };
1737
1738 const onBackdrop = (e) =>
1739 {
1740 if (e.target === backdrop) closePreview();
1741 };
1742 const onClose = () => closePreview();
1743 backdrop.addEventListener('click', onBackdrop);
1744 closeBtn.addEventListener('click', onClose);
1745 STATE.previewExpandState.onBackdrop = onBackdrop;
1746 STATE.previewExpandState.onClose = onClose;
1747
1748 requestAnimationFrame(() => backdrop.classList.add('visible'));
1749 await animateRect(tileEl, startRect, targetRect);
1750
1751 tileEl.style.left = `${targetRect.left}px`;
1752 tileEl.style.top = `${targetRect.top}px`;
1753 tileEl.style.width = `${targetRect.width}px`;
1754 tileEl.style.height = `${targetRect.height}px`;
1755
1756 try
1757 {
1758 await loadPreviewContent(previewMount);
1759 } catch
1760 {
1761 if (previewMount.isConnected)
1762 {
1763 previewMount.innerHTML = '';
1764 const msg = document.createElement('p');
1765 msg.className = 'preview-unsupported';
1766 msg.textContent = 'Preview failed to load. You can try again.';
1767 previewMount.appendChild(msg);
1768 }
1769 }
1770
1771 return true;
1772}
1773
1774async function closeExpandedTilePreview ()
1775{
1776 const st = STATE.previewExpandState;
1777 if (!st) return;
1778
1779 st.backdrop.classList.remove('visible');
1780 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
1781 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
1782
1783 const fromRect = st.tileEl.getBoundingClientRect();
1784 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
1785
1786 st.tileEl.classList.remove('file-item--preview');
1787 st.tileEl.style.position = '';
1788 st.tileEl.style.left = '';
1789 st.tileEl.style.top = '';
1790 st.tileEl.style.width = '';
1791 st.tileEl.style.height = '';
1792 st.tileEl.style.margin = '';
1793 st.tileEl.style.zIndex = '';
1794
1795 if (st.titleEl) st.titleEl.remove();
1796 if (st.closeBtn) st.closeBtn.remove();
1797 if (st.dlBtn) st.dlBtn.remove();
1798 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
1799 if (st.nameEl) st.nameEl.style.display = '';
1800
1801 if (st.parent)
1802 {
1803 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
1804 {
1805 st.parent.insertBefore(st.tileEl, st.nextSibling);
1806 } else
1807 {
1808 st.parent.appendChild(st.tileEl);
1809 }
1810 }
1811
1812 if (st.backdrop) st.backdrop.remove();
1813 STATE.previewExpandState = null;
1814}
1815
1816async function closePreview ()
1817{
1818 if (STATE.previewExpandState)
1819 {
1820 await closeExpandedTilePreview();
1821 clearPreviewObjectUrl();
1822 STATE.previewSourceEl = null;
1823 }
1824}
1825
1826async function fetchFileBlob (item)
1827{
1828 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
1829 try
1830 {
1831 const res = await fetch(url, {
1832 headers: {
1833 Authorization: 'Bearer ' + STATE.token,
1834 'X-Fp': getFingerprint(),
1835 },
1836 });
1837 if (!res.ok) throw new Error('Download failed.');
1838 return await res.blob();
1839 } catch
1840 {
1841 return null;
1842 }
1843}
1844
1845function triggerDownload (filename, objectUrl)
1846{
1847 const a = document.createElement('a');
1848 a.href = objectUrl;
1849 a.download = filename;
1850 a.click();
1851}
1852
1853async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
1854{
1855 const body = targetEl || document.getElementById('preview-body');
1856 body.innerHTML = '';
1857
1858 const mime = String(blob.type || '').toLowerCase();
1859 const previewable = isInlinePreviewableBlob(blob, item.name);
1860
1861 if (!previewable)
1862 {
1863 const msg = document.createElement('p');
1864 msg.className = 'preview-unsupported';
1865 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1866 body.appendChild(msg);
1867 return;
1868 }
1869
1870 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
1871 {
1872 const img = document.createElement('img');
1873 img.className = 'preview-media';
1874 img.src = objectUrl;
1875 img.alt = item.name;
1876 body.appendChild(img);
1877 return;
1878 }
1879
1880 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
1881 {
1882 const video = document.createElement('video');
1883 video.className = 'preview-media';
1884 video.src = objectUrl;
1885 video.controls = true;
1886 video.preload = 'metadata';
1887 body.appendChild(video);
1888 return;
1889 }
1890
1891 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
1892 {
1893 const audio = document.createElement('audio');
1894 audio.className = 'preview-audio';
1895 audio.src = objectUrl;
1896 audio.controls = true;
1897 body.appendChild(audio);
1898 return;
1899 }
1900
1901 if (mime === 'application/pdf')
1902 {
1903 const frame = document.createElement('iframe');
1904 frame.className = 'preview-frame';
1905 frame.src = objectUrl;
1906 frame.title = item.name;
1907 body.appendChild(frame);
1908 return;
1909 }
1910
1911 if (isTextLikeBlob(blob, item.name))
1912 {
1913 const text = await blob.text();
1914 const lang = detectCodeLanguage(item.name, mime);
1915 const formatted = prettyPrintCode(text, lang);
1916 const pre = document.createElement('pre');
1917 pre.className = 'preview-text preview-code';
1918 pre.innerHTML = highlightCode(formatted, lang);
1919 body.appendChild(pre);
1920 return;
1921 }
1922
1923 const msg = document.createElement('p');
1924 msg.className = 'preview-unsupported';
1925 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1926 body.appendChild(msg);
1927}
1928
1929async function downloadOrView (item, sourceSvgEl = null)
1930{
1931 if (STATE.previewExpandState)
1932 {
1933 await closePreview();
1934 }
1935
1936 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
1937 if (sourceTileEl)
1938 {
1939 STATE.previewSourceEl = sourceSvgEl;
1940 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
1941 {
1942 const blob = await fetchFileBlob(item);
1943 if (!blob) throw new Error('Download failed');
1944
1945 clearPreviewObjectUrl();
1946 const objectUrl = URL.createObjectURL(blob);
1947 STATE.previewObjectUrl = objectUrl;
1948
1949 if (!previewMount.isConnected) return;
1950
1951 previewMount.innerHTML = '';
1952 await renderPreviewBody(item, blob, objectUrl, previewMount);
1953 });
1954 if (expanded) return;
1955 }
1956
1957 toast('Preview unavailable — no source tile found.', 'err');
1958}
1959
1960// ───────────────────────────────────────────────────────────────────────────
1961// UPLOAD
1962// ───────────────────────────────────────────────────────────────────────────
1963
1964function canWrite (item = null)
1965{
1966 if (STATE.isAdmin) return true;
1967 const root = item && item._root
1968 ? item._root
1969 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
1970 if (!root) return false;
1971 const p = STATE.permissions[rootPermissionLabel(root)];
1972 return p && p.write;
1973}
1974
1975async function uploadFiles (fileList)
1976{
1977 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1978 if (!canWrite()) { toast('No write access.', 'err'); return; }
1979
1980 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
1981 const formData = new FormData();
1982 for (const f of fileList) formData.append('files', f);
1983
1984 // Show upload bar
1985 const wrap = document.createElement('div');
1986 wrap.className = 'upload-bar-wrap';
1987 wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
1988 document.body.appendChild(wrap);
1989 STATE.uploadInProgress = true;
1990
1991 try
1992 {
1993 const xhr = new XMLHttpRequest();
1994 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
1995 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1996 xhr.setRequestHeader('X-Fp', getFingerprint());
1997 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
1998 xhr.upload.addEventListener('progress', e =>
1999 {
2000 if (e.lengthComputable)
2001 {
2002 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
2003 }
2004 });
2005
2006 await new Promise((resolve, reject) =>
2007 {
2008 xhr.onload = () =>
2009 {
2010 if (xhr.status === 200) resolve();
2011 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
2012 };
2013 xhr.onerror = () => reject(new Error('Network error'));
2014 xhr.send(formData);
2015 });
2016
2017 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
2018 await navigateTo(STATE.currentDir, STATE.currentRoot);
2019 } catch (err)
2020 {
2021 toast(err.message, 'err');
2022 } finally
2023 {
2024 STATE.uploadInProgress = false;
2025 wrap.remove();
2026 }
2027}
2028
2029async function uploadSingleFile (file, targetDir)
2030{
2031 const formData = new FormData();
2032 formData.append('files', file);
2033
2034 await new Promise((resolve, reject) =>
2035 {
2036 const xhr = new XMLHttpRequest();
2037 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
2038 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2039 xhr.setRequestHeader('X-Fp', getFingerprint());
2040 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
2041 xhr.onload = () => xhr.status === 200
2042 ? resolve()
2043 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
2044 xhr.onerror = () => reject(new Error('Network error'));
2045 xhr.send(formData);
2046 });
2047}
2048
2049async function ensureServerDir (baseDir, relativeDir)
2050{
2051 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
2052 let current = baseDir;
2053 for (const part of parts)
2054 {
2055 try
2056 {
2057 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
2058 current = resp && resp.path ? resp.path : joinServerPath(current, part);
2059 } catch (err)
2060 {
2061 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2062 current = joinServerPath(current, part);
2063 }
2064 }
2065 return current;
2066}
2067
2068async function uploadFolderInputFiles (fileList)
2069{
2070 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2071 if (!canWrite()) { toast('No write access.', 'err'); return; }
2072 if (!fileList || !fileList.length) return;
2073
2074 const files = Array.from(fileList);
2075 const total = files.length;
2076 let done = 0;
2077
2078 const wrap = document.createElement('div');
2079 wrap.className = 'upload-bar-wrap';
2080 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2081 document.body.appendChild(wrap);
2082 STATE.uploadInProgress = true;
2083
2084 try
2085 {
2086 const dirCache = new Map();
2087 dirCache.set('', STATE.currentDir);
2088
2089 for (const file of files)
2090 {
2091 const rel = file.webkitRelativePath || file.name;
2092 const relParts = rel.split(/[\\/]/).filter(Boolean);
2093 const relDir = relParts.slice(0, -1).join('/');
2094
2095 if (!dirCache.has(relDir))
2096 {
2097 const parentRel = relParts.slice(0, -2).join('/');
2098 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
2099 const thisName = relParts[relParts.length - 2];
2100
2101 try
2102 {
2103 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
2104 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
2105 } catch (err)
2106 {
2107 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2108 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
2109 }
2110 }
2111
2112 const targetDir = dirCache.get(relDir) || STATE.currentDir;
2113 await uploadSingleFile(file, targetDir);
2114 done++;
2115 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2116 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2117 }
2118
2119 toast(`Uploaded ${total} file(s).`, 'ok');
2120 await navigateTo(STATE.currentDir, STATE.currentRoot);
2121 } catch (err)
2122 {
2123 toast(err.message, 'err');
2124 } finally
2125 {
2126 STATE.uploadInProgress = false;
2127 wrap.remove();
2128 }
2129}
2130
2131// ───────────────────────────────────────────────────────────────────────────
2132// FOLDER DRAG-AND-DROP (recursive)
2133// ───────────────────────────────────────────────────────────────────────────
2134
2135/**
2136 * Reads all readEntries batches from a DirectoryReader (browsers may return
2137 * results in chunks; we must keep calling until we get an empty array).
2138 */
2139function readAllEntries (reader)
2140{
2141 return new Promise((resolve, reject) =>
2142 {
2143 const all = [];
2144 function next ()
2145 {
2146 reader.readEntries(batch =>
2147 {
2148 if (!batch.length) { resolve(all); return; }
2149 all.push(...batch);
2150 next();
2151 }, reject);
2152 }
2153 next();
2154 });
2155}
2156
2157/**
2158 * Recursively walk a FileSystemEntry tree, creating server-side directories
2159 * on the fly and collecting { file, targetDir } pairs for upload.
2160 */
2161async function collectEntries (entry, serverDir, toUpload)
2162{
2163 if (entry.isFile)
2164 {
2165 const file = await new Promise((res, rej) => entry.file(res, rej));
2166 toUpload.push({ file, targetDir: serverDir });
2167 } else if (entry.isDirectory)
2168 {
2169 // Ask the server to create the directory; it returns the canonical path.
2170 let newServerDir;
2171 try
2172 {
2173 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
2174 newServerDir = resp.path;
2175 } catch
2176 {
2177 // Directory may already exist — reconstruct path from what we know.
2178 // The server always returns JSON with {error} on failure, so we can
2179 // still continue by falling back to a best-effort path join.
2180 // We rely on the fact that the server separator is consistent within
2181 // a session (the list/browse API already returned paths in that format).
2182 const sep = serverDir.includes('\\') ? '\\' : '/';
2183 newServerDir = serverDir + sep + entry.name;
2184 }
2185 const reader = entry.createReader();
2186 const subEntries = await readAllEntries(reader);
2187 for (const sub of subEntries)
2188 {
2189 await collectEntries(sub, newServerDir, toUpload);
2190 }
2191 }
2192}
2193
2194async function uploadEntries (entries)
2195{
2196 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2197 if (!canWrite()) { toast('No write access.', 'err'); return; }
2198
2199 const wrap = document.createElement('div');
2200 wrap.className = 'upload-bar-wrap';
2201 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2202 document.body.appendChild(wrap);
2203 STATE.uploadInProgress = true;
2204
2205 try
2206 {
2207 const toUpload = [];
2208 for (const entry of entries)
2209 {
2210 await collectEntries(entry, STATE.currentDir, toUpload);
2211 }
2212
2213 if (!toUpload.length) { toast('No files found.', 'err'); return; }
2214
2215 let done = 0;
2216 const total = toUpload.length;
2217 const updateBar = () =>
2218 {
2219 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2220 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2221 };
2222 updateBar();
2223
2224 for (const { file, targetDir } of toUpload)
2225 {
2226 await uploadSingleFile(file, targetDir);
2227 done++;
2228 updateBar();
2229 }
2230
2231 toast(`Uploaded ${total} file(s).`, 'ok');
2232 await navigateTo(STATE.currentDir, STATE.currentRoot);
2233 } catch (err)
2234 {
2235 toast(err.message, 'err');
2236 } finally
2237 {
2238 STATE.uploadInProgress = false;
2239 wrap.remove();
2240 }
2241}
2242
2243// DRAG-AND-DROP
2244// ───────────────────────────────────────────────────────────────────────────
2245
2246function initDragDrop ()
2247{
2248 const main = document.getElementById('main-content');
2249 const dropOvl = document.getElementById('drop-overlay');
2250 let dragDepth = 0;
2251
2252 main.addEventListener('dragenter', e =>
2253 {
2254 e.preventDefault();
2255 dragDepth++;
2256 dropOvl.classList.remove('hidden');
2257 });
2258 main.addEventListener('dragleave', () =>
2259 {
2260 dragDepth--;
2261 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
2262 });
2263 main.addEventListener('dragover', e => e.preventDefault());
2264 main.addEventListener('drop', async e =>
2265 {
2266 e.preventDefault();
2267 dragDepth = 0;
2268 dropOvl.classList.add('hidden');
2269 if (!canWrite()) { toast('No write access.', 'err'); return; }
2270
2271 const items = Array.from(e.dataTransfer.items || []);
2272 // Use the FileSystem Entry API when available so we can handle folders.
2273 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
2274 {
2275 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
2276 if (entries.some(en => en.isDirectory))
2277 {
2278 await uploadEntries(entries);
2279 return;
2280 }
2281 }
2282 // Plain files only — use the fast batch path.
2283 const files = e.dataTransfer.files;
2284 if (files.length) await uploadFiles(files);
2285 });
2286}
2287
2288// ───────────────────────────────────────────────────────────────────────────
2289// RENAME
2290// ───────────────────────────────────────────────────────────────────────────
2291
2292function openRenameModal (item)
2293{
2294 const modal = document.getElementById('rename-modal');
2295 modal.classList.remove('hidden');
2296 const input = document.getElementById('rename-input');
2297 input.value = item.name;
2298 input.focus();
2299 input.select();
2300 document.getElementById('rename-error').classList.add('hidden');
2301 document.getElementById('rename-form').onsubmit = async (e) =>
2302 {
2303 e.preventDefault();
2304 const newName = input.value.trim();
2305 if (!newName) return;
2306 try
2307 {
2308 if (item._root)
2309 {
2310 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
2311 } else
2312 {
2313 await api('POST', '/files/rename', { from: item.path, to: newName });
2314 }
2315 modal.classList.add('hidden');
2316 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
2317 if (item._root)
2318 {
2319 await loadRoots({
2320 preferredDir: STATE.currentDir,
2321 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
2322 });
2323 } else
2324 {
2325 await navigateTo(STATE.currentDir, STATE.currentRoot);
2326 }
2327 } catch (err)
2328 {
2329 document.getElementById('rename-error').textContent = err.message;
2330 document.getElementById('rename-error').classList.remove('hidden');
2331 }
2332 };
2333}
2334
2335// ───────────────────────────────────────────────────────────────────────────
2336// DELETE
2337// ───────────────────────────────────────────────────────────────────────────
2338
2339async function deleteItem (item)
2340{
2341 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
2342 try
2343 {
2344 await api('POST', '/files/delete', { path: item.path });
2345 toast('Deleted.', 'ok');
2346 closeSidebar();
2347 await navigateTo(STATE.currentDir, STATE.currentRoot);
2348 } catch (err)
2349 {
2350 toast(err.message, 'err');
2351 }
2352}
2353
2354// ───────────────────────────────────────────────────────────────────────────
2355// ADMIN PANEL
2356// ───────────────────────────────────────────────────────────────────────────
2357
2358async function openAdminModal ()
2359{
2360 document.getElementById('admin-modal').classList.remove('hidden');
2361 await refreshAdminConfig();
2362 await refreshAdminUsers();
2363}
2364
2365async function refreshAdminConfig ()
2366{
2367 const data = await api('GET', '/admin/config');
2368 if (!data) return;
2369 const container = document.getElementById('admin-paths');
2370 container.innerHTML = '';
2371 for (const p of data.paths)
2372 {
2373 const row = document.createElement('div');
2374 row.className = 'path-row';
2375 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
2376 row.querySelector('button').addEventListener('click', () =>
2377 {
2378 row.remove();
2379 });
2380 container.appendChild(row);
2381 }
2382}
2383
2384async function refreshAdminUsers ()
2385{
2386 const data = await api('GET', '/admin/users');
2387 if (!data) return;
2388 const container = document.getElementById('admin-users-list');
2389 container.innerHTML = '';
2390
2391 // Need paths for permission rows
2392 const cfg = await api('GET', '/admin/config');
2393 const paths = cfg ? (cfg.effectivePaths || []) : [];
2394
2395 for (const u of data.users)
2396 {
2397 const row = document.createElement('div');
2398 row.className = 'user-row';
2399 row.innerHTML = `
2400 <span class="user-name">${u.username}</span>
2401 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
2402 <button data-id="${u.id}" data-action="edit">Edit</button>
2403 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
2404 `;
2405 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
2406 openUserModal(u, paths));
2407 const deleteBtn = row.querySelector('[data-action="delete"]');
2408 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
2409 {
2410 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
2411 try
2412 {
2413 await api('DELETE', `/admin/users/${u.id}`);
2414 toast('User deleted.', 'ok');
2415 await refreshAdminUsers();
2416 } catch (err) { toast(err.message, 'err'); }
2417 });
2418 container.appendChild(row);
2419 }
2420}
2421
2422function openUserModal (user, paths)
2423{
2424 const modal = document.getElementById('user-modal');
2425 modal.classList.remove('hidden');
2426 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
2427 document.getElementById('user-error').classList.add('hidden');
2428
2429 const usernameInput = document.getElementById('user-username');
2430 usernameInput.value = user ? user.username : '';
2431 usernameInput.readOnly = !!user;
2432
2433 document.getElementById('user-password').value = '';
2434 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
2435
2436 // Password placeholder
2437 document.getElementById('user-password').placeholder =
2438 user ? 'Leave blank to keep current' : 'Min 8 characters';
2439
2440 // Build permissions grid
2441 const permDiv = document.getElementById('user-permissions');
2442 permDiv.innerHTML = '';
2443 if (paths.length)
2444 {
2445 const heading = document.createElement('h4');
2446 heading.textContent = 'Path Permissions';
2447 permDiv.appendChild(heading);
2448
2449 const isAdminUser = !!(user && user.isAdmin);
2450 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
2451 const adminChk = document.getElementById('user-is-admin');
2452 const rebuildPermRows = (admin) =>
2453 {
2454 permDiv.querySelectorAll('.perm-row').forEach(r =>
2455 {
2456 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
2457 {
2458 cb.disabled = admin;
2459 if (admin) cb.checked = true;
2460 });
2461 r.title = admin ? 'Admins always have full access' : '';
2462 });
2463 };
2464 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
2465
2466 for (const p of paths)
2467 {
2468 const label = p.split(/[\\/]/).pop();
2469 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
2470 const row = document.createElement('div');
2471 row.className = 'perm-row';
2472 const readChecked = isAdminUser || perms.read;
2473 const writeChecked = isAdminUser || perms.write;
2474 row.innerHTML = `
2475 <span class="perm-label">${label}</span>
2476 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
2477 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
2478 `;
2479 if (isAdminUser) row.title = 'Admins always have full access';
2480 permDiv.appendChild(row);
2481 }
2482 }
2483
2484 document.getElementById('user-form').onsubmit = async (e) =>
2485 {
2486 e.preventDefault();
2487 const password = document.getElementById('user-password').value;
2488 const isAdmin = document.getElementById('user-is-admin').checked;
2489 const permissions = {};
2490 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
2491 {
2492 const lbl = cb.dataset.label;
2493 if (!permissions[lbl]) permissions[lbl] = {};
2494 permissions[lbl][cb.dataset.type] = cb.checked;
2495 });
2496
2497 try
2498 {
2499 if (user)
2500 {
2501 const body = { isAdmin, permissions };
2502 if (password) body.password = password;
2503 await api('PATCH', `/admin/users/${user.id}`, body);
2504 } else
2505 {
2506 const uname = document.getElementById('user-username').value.trim();
2507 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
2508 }
2509 modal.classList.add('hidden');
2510 toast('User saved.', 'ok');
2511 await refreshAdminUsers();
2512 } catch (err)
2513 {
2514 document.getElementById('user-error').textContent = err.message;
2515 document.getElementById('user-error').classList.remove('hidden');
2516 }
2517 };
2518}
2519
2520// ───────────────────────────────────────────────────────────────────────────
2521// SVG ICONS
2522// ───────────────────────────────────────────────────────────────────────────
2523
2524const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
2525const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
2526const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
2527const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
2528const 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']);
2529const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
2530
2531function iconFolder (size = 52)
2532{
2533 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
2534 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
2535 <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"/>
2536 </svg>`;
2537}
2538
2539function iconFile (name, size = 52)
2540{
2541 const color = fileAccentColor(name);
2542 let symbol = '';
2543
2544 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
2545 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
2546 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
2547 <polyline points="14 2 14 8 20 8"/>
2548 </svg>`;
2549}
2550
2551// ───────────────────────────────────────────────────────────────────────────
2552// EVENT WIRING
2553// ───────────────────────────────────────────────────────────────────────────
2554
2555// ───────────────────────────────────────────────────────────────────────────
2556// THUMBNAIL PREVIEWS
2557// ───────────────────────────────────────────────────────────────────────────
2558
2559function revokeThumbnails ()
2560{
2561 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
2562 STATE.thumbnailUrls = [];
2563}
2564
2565function disconnectThumbnailObserver ()
2566{
2567 if (!STATE.thumbnailObserver) return;
2568 STATE.thumbnailObserver.disconnect();
2569 STATE.thumbnailObserver = null;
2570}
2571
2572function getThumbnailKind (name)
2573{
2574 const ext = extOf(name || '');
2575 if (IMAGE_EXTS.has(ext)) return 'image';
2576 if (CODE_EXTS.has(ext)) return 'text';
2577 return 'badge';
2578}
2579
2580function maxThumbBytesForKind (kind)
2581{
2582 if (kind === 'image') return 15 * 1024 * 1024;
2583 if (kind === 'text') return 1024 * 1024;
2584 return 0;
2585}
2586
2587function drawTokenizedLine (ctx, line, x, y)
2588{
2589 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;
2590 let last = 0;
2591 let cursor = x;
2592 for (const m of line.matchAll(tokenRe))
2593 {
2594 const i = m.index == null ? 0 : m.index;
2595 if (i > last)
2596 {
2597 const plain = line.slice(last, i);
2598 ctx.fillStyle = '#dce4ff';
2599 ctx.fillText(plain, cursor, y);
2600 cursor += ctx.measureText(plain).width;
2601 }
2602
2603 const tok = m[0];
2604 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
2605 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
2606 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
2607 else ctx.fillStyle = '#8bb4ff';
2608
2609 ctx.fillText(tok, cursor, y);
2610 cursor += ctx.measureText(tok).width;
2611 last = i + tok.length;
2612 }
2613
2614 if (last < line.length)
2615 {
2616 const tail = line.slice(last);
2617 ctx.fillStyle = '#dce4ff';
2618 ctx.fillText(tail, cursor, y);
2619 }
2620}
2621
2622function textThumbnailDataUrl (text)
2623{
2624 const canvas = document.createElement('canvas');
2625 canvas.width = 160;
2626 canvas.height = 200;
2627 const ctx = canvas.getContext('2d');
2628 if (!ctx) return null;
2629
2630 ctx.fillStyle = '#0d111a';
2631 ctx.fillRect(0, 0, canvas.width, canvas.height);
2632 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
2633 ctx.textBaseline = 'top';
2634
2635 const lines = String(text || '')
2636 .replace(/\r\n/g, '\n')
2637 .split('\n')
2638 .slice(0, 17);
2639
2640 let y = 8;
2641 for (const line of lines)
2642 {
2643 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
2644 y += 11;
2645 if (y > 190) break;
2646 }
2647 return canvas.toDataURL('image/png');
2648}
2649
2650function badgeThumbnailDataUrl (name, kind)
2651{
2652 const canvas = document.createElement('canvas');
2653 canvas.width = 160;
2654 canvas.height = 200;
2655 const ctx = canvas.getContext('2d');
2656 if (!ctx) return null;
2657
2658 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2659 const color = '#5b7fff';
2660
2661 ctx.fillStyle = '#111826';
2662 ctx.fillRect(0, 0, 160, 200);
2663 ctx.fillStyle = color;
2664 ctx.fillRect(0, 0, 160, 28);
2665 ctx.fillStyle = '#ffffff';
2666 ctx.font = 'bold 12px sans-serif';
2667 ctx.textAlign = 'center';
2668 ctx.fillText(ext, 80, 8);
2669 ctx.textAlign = 'left';
2670 ctx.fillStyle = '#9fb1d8';
2671 ctx.font = '10px sans-serif';
2672 ctx.fillText('Preview', 8, 48);
2673 ctx.fillStyle = '#dce4ff';
2674 ctx.font = 'bold 11px sans-serif';
2675 ctx.fillText(ext, 8, 66);
2676 return canvas.toDataURL('image/png');
2677}
2678
2679async function buildThumbnailSource (item, blob, kind)
2680{
2681 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2682 return badgeThumbnailDataUrl(item.name, kind);
2683}
2684
2685function observeThumbnailIcon (iconEl)
2686{
2687 if (!iconEl || !iconEl.isConnected) return;
2688 if (iconEl.dataset.thumbReady === '1') return;
2689
2690 if (!('IntersectionObserver' in window))
2691 {
2692 void loadOneThumbnail(iconEl);
2693 return;
2694 }
2695
2696 if (!STATE.thumbnailObserver)
2697 {
2698 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
2699 {
2700 for (const entry of entries)
2701 {
2702 if (!entry.isIntersecting) continue;
2703 const icon = entry.target;
2704 STATE.thumbnailObserver.unobserve(icon);
2705 void loadOneThumbnail(icon);
2706 }
2707 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
2708 }
2709
2710 STATE.thumbnailObserver.observe(iconEl);
2711}
2712
2713async function loadThumbnails ()
2714{
2715 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2716 if (!icons.length) return;
2717
2718 for (const icon of icons)
2719 {
2720 observeThumbnailIcon(icon);
2721 }
2722}
2723
2724async function loadOneThumbnail (iconEl)
2725{
2726 if (!iconEl.isConnected || !STATE.token) return;
2727 if (iconEl.dataset.thumbReady === '1') return;
2728 const filePath = iconEl.dataset.previewPath;
2729 const item = STATE.items.find(i => i.path === filePath);
2730 if (!item) return;
2731
2732 const kind = getThumbnailKind(item.name);
2733 let srcUrl = null;
2734
2735 if (kind === 'badge')
2736 {
2737 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2738 }
2739 else if (kind === 'image')
2740 {
2741 const url = `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
2742
2743 let res;
2744 try
2745 {
2746 res = await fetch(url, {
2747 headers: {
2748 Authorization: `Bearer ${STATE.token}`,
2749 'X-Fp': getFingerprint(),
2750 },
2751 });
2752 } catch
2753 {
2754 return;
2755 }
2756
2757 if (!res.ok || !iconEl.isConnected) return;
2758
2759 const blob = await res.blob();
2760 srcUrl = URL.createObjectURL(blob);
2761 STATE.thumbnailUrls.push(srcUrl);
2762 }
2763 else
2764 {
2765 const maxBytes = maxThumbBytesForKind(kind);
2766 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
2767 {
2768 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2769 } else
2770 {
2771 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
2772
2773 let res;
2774 try
2775 {
2776 res = await fetch(url, {
2777 headers: {
2778 Authorization: `Bearer ${STATE.token}`,
2779 'X-Fp': getFingerprint(),
2780 },
2781 });
2782 } catch { return; }
2783 if (!res.ok || !iconEl.isConnected) return;
2784
2785 const blob = await res.blob();
2786 srcUrl = await buildThumbnailSource(item, blob, kind);
2787 }
2788 }
2789 if (!srcUrl || !iconEl.isConnected) return;
2790
2791 const svg = iconEl.querySelector('svg');
2792 if (!svg)
2793 {
2794 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
2795 return;
2796 }
2797
2798 const NS = 'http://www.w3.org/2000/svg';
2799 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
2800
2801 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
2802 const defs = document.createElementNS(NS, 'defs');
2803 const clipPath = document.createElementNS(NS, 'clipPath');
2804 clipPath.setAttribute('id', id);
2805 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
2806 const clipShape = document.createElementNS(NS, 'path');
2807 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
2808 clipPath.appendChild(clipShape);
2809 defs.appendChild(clipPath);
2810
2811 // Image fills the file bounding box; clip keeps it inside the outline
2812 const img = document.createElementNS(NS, 'image');
2813 img.setAttribute('href', srcUrl);
2814 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
2815 img.setAttribute('x', '4');
2816 img.setAttribute('y', '2');
2817 img.setAttribute('width', '16');
2818 img.setAttribute('height', '20');
2819 img.setAttribute('clip-path', `url(#${id})`);
2820 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
2821
2822 // Prepend so existing path/polyline elements (the outline) render on top
2823 svg.prepend(img);
2824 svg.prepend(defs);
2825 iconEl.dataset.thumbReady = '1';
2826}
2827
2828function wireEvents ()
2829{
2830 // Auth form
2831 document.getElementById('auth-form').addEventListener('submit', async (e) =>
2832 {
2833 e.preventDefault();
2834 const username = document.getElementById('auth-username').value.trim();
2835 const password = document.getElementById('auth-password').value;
2836 const isSetup = e.target.dataset.mode === 'setup';
2837 const errEl = document.getElementById('auth-error');
2838 const btn = document.getElementById('auth-submit');
2839 btn.disabled = true;
2840 btn.textContent = 'Please wait…';
2841 const err = await doLogin(username, password, isSetup);
2842 if (err)
2843 {
2844 errEl.textContent = err;
2845 errEl.classList.remove('hidden');
2846 btn.disabled = false;
2847 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
2848 }
2849 });
2850
2851 // Logout
2852 document.getElementById('btn-logout').addEventListener('click', logout);
2853
2854 // Hard refresh while keeping auth/session state.
2855 document.getElementById('btn-refresh').addEventListener('click', () =>
2856 {
2857 saveSessionState();
2858 location.reload();
2859 });
2860
2861 // Upload button
2862 document.getElementById('btn-upload').addEventListener('click', () =>
2863 {
2864 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2865 if (!canWrite()) { toast('No write access.', 'err'); return; }
2866 document.getElementById('file-input').click();
2867 });
2868
2869 document.getElementById('file-input').addEventListener('change', async (e) =>
2870 {
2871 if (e.target.files.length) await uploadFiles(e.target.files);
2872 e.target.value = '';
2873 });
2874
2875 document.getElementById('btn-upload-folder').addEventListener('click', () =>
2876 {
2877 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2878 if (!canWrite()) { toast('No write access.', 'err'); return; }
2879 document.getElementById('folder-input').click();
2880 });
2881
2882 document.getElementById('folder-input').addEventListener('change', async (e) =>
2883 {
2884 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
2885 e.target.value = '';
2886 });
2887
2888 document.getElementById('btn-new-folder').addEventListener('click', async () =>
2889 {
2890 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2891 if (!canWrite()) { toast('No write access.', 'err'); return; }
2892
2893 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
2894 if (name == null) return;
2895 const folderName = name.trim();
2896 if (!folderName)
2897 {
2898 toast('Folder name is required.', 'err');
2899 return;
2900 }
2901
2902 try
2903 {
2904 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
2905 toast('Folder created.', 'ok');
2906 await navigateTo(STATE.currentDir, STATE.currentRoot);
2907 } catch (err)
2908 {
2909 toast(err.message, 'err');
2910 }
2911 });
2912
2913 document.getElementById('sidebar-close').addEventListener('click', (e) =>
2914 {
2915 e.stopPropagation();
2916 hideSidebarPanel();
2917 });
2918
2919 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
2920 const syncSidebarForViewport = () =>
2921 {
2922 if (isMobileViewport())
2923 {
2924 hideSidebarPanel();
2925 return;
2926 }
2927
2928 if (!STATE.selectedItem) openFolderSidebar();
2929 };
2930
2931 if (typeof mobileQuery.addEventListener === 'function')
2932 {
2933 mobileQuery.addEventListener('change', syncSidebarForViewport);
2934 } else if (typeof mobileQuery.addListener === 'function')
2935 {
2936 mobileQuery.addListener(syncSidebarForViewport);
2937 }
2938
2939 // Click outside grid clears selection and returns to folder sidebar info.
2940 document.getElementById('main-content').addEventListener('click', (e) =>
2941 {
2942 if (!e.target.closest('.file-item')) closeSidebar();
2943 });
2944
2945 // Admin panel
2946 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
2947 document.getElementById('admin-modal-close').addEventListener('click', () =>
2948 document.getElementById('admin-modal').classList.add('hidden'));
2949
2950 // Add path
2951 document.getElementById('admin-add-path').addEventListener('click', () =>
2952 {
2953 const val = document.getElementById('admin-new-path').value.trim();
2954 if (!val) return;
2955 const row = document.createElement('div');
2956 row.className = 'path-row';
2957 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
2958 row.querySelector('button').addEventListener('click', () => row.remove());
2959 document.getElementById('admin-paths').appendChild(row);
2960 document.getElementById('admin-new-path').value = '';
2961 });
2962
2963 // Save paths
2964 document.getElementById('admin-save-paths').addEventListener('click', async () =>
2965 {
2966 const rows = document.querySelectorAll('#admin-paths .path-row span');
2967 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
2968 try
2969 {
2970 await api('PUT', '/admin/config', { paths });
2971 toast('Paths saved.', 'ok');
2972 await loadRoots();
2973 } catch (err) { toast(err.message, 'err'); }
2974 });
2975
2976 // Shutdown server
2977 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
2978 {
2979 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
2980 try
2981 {
2982 await api('POST', '/admin/shutdown');
2983 toast('Server is shutting down…', 'ok');
2984 document.getElementById('admin-modal').classList.add('hidden');
2985 } catch
2986 {
2987 // Fetch may throw because the connection closes before a response arrives.
2988 toast('Server is shutting down…', 'ok');
2989 document.getElementById('admin-modal').classList.add('hidden');
2990 }
2991 });
2992
2993 // New user
2994 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
2995 {
2996 const cfg = await api('GET', '/admin/config');
2997 const paths = cfg ? (cfg.effectivePaths || []) : [];
2998 openUserModal(null, paths);
2999 });
3000
3001 // User modal close
3002 document.getElementById('user-modal-close').addEventListener('click', () =>
3003 document.getElementById('user-modal').classList.add('hidden'));
3004
3005 // Rename modal close
3006 document.getElementById('rename-modal-close').addEventListener('click', () =>
3007 document.getElementById('rename-modal').classList.add('hidden'));
3008
3009 // Close modals on backdrop click
3010 document.querySelectorAll('.modal-overlay').forEach(overlay =>
3011 {
3012 overlay.addEventListener('click', e =>
3013 {
3014 if (e.target === overlay) overlay.classList.add('hidden');
3015 });
3016 });
3017}
3018
3019// ───────────────────────────────────────────────────────────────────────────
3020// BOOT
3021// ───────────────────────────────────────────────────────────────────────────
3022
3023(async function boot ()
3024{
3025 wireEvents();
3026 initDragDrop();
3027 window.addEventListener('beforeunload', saveSessionState);
3028 await initAuth();
3029})();