BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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