BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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