BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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