BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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