BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

app.js 116.4 KiB Download Raw
1/* =========================================================
2 FILE MANAGER — CLIENT SPA
3 =========================================================
4 Architecture:
5 - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API
6 - Token is stored in localStorage to survive full page refresh
7 - Token is sent as Bearer header on every API call
8 - Fingerprint (derived from navigator info) locks the token to this browser
9 ========================================================= */
10'use strict';
11
12// ───────────────────────────────────────────────────────────────────────────
13// STATE
14// ───────────────────────────────────────────────────────────────────────────
15const STATE = {
16 token: null, // decrypted JWT string
17 username: null,
18 isAdmin: false,
19 permissions: {},
20 roots: [], // [{ label, path }]
21 currentDir: null, // absolute path currently shown (null = roots view)
22 currentRoot: null, // { label, path } of the active root
23 items: [], // current directory listing
24 selectedItem: null, // item object selected in sidebar
25
26 // Ephemeral key pair per session (client-side)
27 clientPrivateKey: null,
28 clientPublicKeyJwk: null,
29
30 // Server public key for encrypting login
31 serverPublicKeyJwk: null,
32
33 // Stable per-browser binding id used in fingerprint derivation
34 clientBindingId: null,
35
36 // Persisted view state
37 restoreDir: null,
38 restoreRootPath: null,
39 lastOperationAt: null,
40
41 // Background refresh state
42 autoRefreshTimer: null,
43 uploadInProgress: false,
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 thumbnailUrls: [],
46 thumbnailObserver: null,
47 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 = {
1326 Authorization: 'Bearer ' + STATE.token,
1327 'X-Fp': getFingerprint(),
1328 };
1329 fetch(url, { headers })
1330 .then(res =>
1331 {
1332 if (!res.ok) throw new Error('Download mislukt');
1333 return res.blob();
1334 })
1335 .then(blob =>
1336 {
1337 const blobUrl = URL.createObjectURL(blob);
1338 const a = document.createElement('a');
1339 a.href = blobUrl;
1340 a.download = item.name + '.zip';
1341 a.click();
1342 setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
1343 })
1344 .catch((err) => toast(err.message || 'Download mislukt', 'err'))
1345 .finally(() =>
1346 {
1347 btnZip.disabled = false;
1348 btnZip.textContent = 'Download als zip';
1349 });
1350 });
1351 actions.appendChild(btnZip);
1352
1353 // Share button (folder)
1354 const btnShareFolder = document.createElement('button');
1355 btnShareFolder.textContent = 'Delen';
1356 btnShareFolder.addEventListener('click', () => openShareModal(item));
1357 actions.appendChild(btnShareFolder);
1358
1359 // Load folder icon thumbnail into the sidebar icon element.
1360 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
1361 }
1362
1363 // Rename button (write access required)
1364 if (canWrite(item))
1365 {
1366 if (item.isDir)
1367 {
1368 const btnSetIcon = document.createElement('button');
1369 btnSetIcon.textContent = 'Set icon';
1370 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
1371 actions.appendChild(btnSetIcon);
1372 }
1373
1374 if (!item._root)
1375 {
1376 const btnMove = document.createElement('button');
1377 btnMove.textContent = 'Move to';
1378 btnMove.addEventListener('click', () => openMovePicker(item));
1379 actions.appendChild(btnMove);
1380 }
1381
1382 const btnRen = document.createElement('button');
1383 btnRen.textContent = 'Rename';
1384 btnRen.addEventListener('click', () => openRenameModal(item));
1385 actions.appendChild(btnRen);
1386
1387 if (!item._root)
1388 {
1389 const btnDel = document.createElement('button');
1390 btnDel.textContent = 'Delete';
1391 btnDel.className = 'danger';
1392 btnDel.addEventListener('click', () => deleteItem(item));
1393 actions.appendChild(btnDel);
1394 }
1395 }
1396}
1397
1398function openFolderSidebar ()
1399{
1400 const sidebar = document.getElementById('sidebar');
1401 sidebar.classList.remove('hidden');
1402 document.getElementById('app').classList.add('sidebar-open');
1403
1404 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
1405
1406 const nameEl = document.getElementById('sidebar-name');
1407 const dl = document.getElementById('sidebar-meta');
1408 const actions = document.getElementById('sidebar-actions');
1409 actions.innerHTML = '';
1410
1411 if (!STATE.currentDir || !STATE.currentRoot)
1412 {
1413 nameEl.textContent = 'Storage Roots';
1414 dl.innerHTML = `
1415 <dt>Type</dt><dd>Root overview</dd>
1416 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
1417 `;
1418 return;
1419 }
1420
1421 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
1422 const fallback = STATE.currentRoot.label || 'Folder';
1423 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
1424
1425 const dirs = STATE.items.filter(i => i.isDir).length;
1426 const files = STATE.items.length - dirs;
1427 const baseDetails = `
1428 <dt>Path</dt><dd>${STATE.currentDir}</dd>
1429 <dt>Folders</dt><dd>${dirs}</dd>
1430 <dt>Files</dt><dd>${files}</dd>
1431 `;
1432 dl.innerHTML = baseDetails;
1433
1434 if (samePath(STATE.currentDir, STATE.currentRoot.path))
1435 {
1436 dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>';
1437 const currentDirAtStart = STATE.currentDir;
1438 const currentRootPathAtStart = STATE.currentRoot.path;
1439 void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) =>
1440 {
1441 if (!accessUsers) return;
1442 if (!STATE.currentRoot) return;
1443 if (!samePath(STATE.currentDir, currentDirAtStart)) return;
1444 if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return;
1445 dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`;
1446 });
1447 }
1448}
1449
1450function closeSidebar ()
1451{
1452 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
1453 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1454 STATE.selectedItem = null;
1455
1456 if (isMobileViewport())
1457 {
1458 hideSidebarPanel();
1459 return;
1460 }
1461
1462 openFolderSidebar();
1463}
1464
1465function isMobileViewport ()
1466{
1467 return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
1468}
1469
1470function hideSidebarPanel ()
1471{
1472 const sidebar = document.getElementById('sidebar');
1473 const app = document.getElementById('app');
1474 sidebar.classList.add('hidden');
1475 app.classList.remove('sidebar-open');
1476}
1477
1478function basenameOfPath (p)
1479{
1480 const parts = String(p || '').split(/[\\/]/).filter(Boolean);
1481 return parts.length ? parts[parts.length - 1] : String(p || '');
1482}
1483
1484async function fetchRootAccessList (rootPath)
1485{
1486 if (!rootPath) return null;
1487 const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch(() => null);
1488 if (!data || !Array.isArray(data.users)) return null;
1489 return data.users;
1490}
1491
1492function formatRootAccessList (users)
1493{
1494 if (!Array.isArray(users) || users.length === 0) return 'No users';
1495
1496 const sorted = [...users].sort((a, b) =>
1497 {
1498 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
1499 const byMode = modeRank(a.mode) - modeRank(b.mode);
1500 if (byMode !== 0) return byMode;
1501 return String(a.username).localeCompare(String(b.username));
1502 });
1503
1504 const items = sorted
1505 .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`)
1506 .join('');
1507 return `<ul class="root-access-list">${items}</ul>`;
1508}
1509
1510function rootPermissionLabel (root)
1511{
1512 return (root && (root.originalName || root.label)) || '';
1513}
1514
1515function resolveRootForPath (targetPath)
1516{
1517 if (!targetPath) return null;
1518 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
1519}
1520
1521function writableRoots ()
1522{
1523 if (STATE.isAdmin) return STATE.roots.slice();
1524 return STATE.roots.filter((r) =>
1525 {
1526 const perm = STATE.permissions[rootPermissionLabel(r)];
1527 return !!(perm && perm.write);
1528 });
1529}
1530
1531async function moveWithConflictResolution (item, targetDir)
1532{
1533 try
1534 {
1535 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
1536 }
1537 catch (err)
1538 {
1539 if (!/already exists/i.test(err.message || '')) throw err;
1540
1541 const existingNames = await listDirNameSet(targetDir);
1542 const desiredName = item.name || basenameOfPath(item.path) || 'file';
1543 const suggestedName = nextAvailableName(desiredName, existingNames);
1544 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
1545 if (decision === 'cancel') return null;
1546
1547 if (decision === 'overwrite')
1548 {
1549 return api('POST', '/files/move', {
1550 from: item.path,
1551 toDir: targetDir,
1552 conflict: 'overwrite',
1553 });
1554 }
1555
1556 return api('POST', '/files/move', {
1557 from: item.path,
1558 toDir: targetDir,
1559 conflict: 'rename',
1560 targetName: suggestedName,
1561 });
1562 }
1563}
1564
1565function ensureMoveModal ()
1566{
1567 let overlay = document.getElementById('move-modal');
1568 if (overlay) return overlay;
1569
1570 overlay = document.createElement('div');
1571 overlay.id = 'move-modal';
1572 overlay.className = 'modal-overlay hidden';
1573 overlay.innerHTML = `
1574 <div class="modal move-modal">
1575 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
1576 <h2>Move To</h2>
1577 <p id="move-modal-caption" class="muted"></p>
1578 <div id="move-tree" class="move-tree"></div>
1579 <p id="move-selected" class="muted"></p>
1580 <div class="dialog-actions">
1581 <button id="move-modal-cancel">Cancel</button>
1582 <button id="move-modal-confirm" class="primary">Move</button>
1583 </div>
1584 </div>
1585 `;
1586 document.body.appendChild(overlay);
1587
1588 const closeBtn = overlay.querySelector('#move-modal-close');
1589 const cancelBtn = overlay.querySelector('#move-modal-cancel');
1590 const confirmBtn = overlay.querySelector('#move-modal-confirm');
1591
1592 function hide ()
1593 {
1594 overlay.classList.add('hidden');
1595 STATE.movePicker = null;
1596 }
1597
1598 closeBtn.addEventListener('click', hide);
1599 cancelBtn.addEventListener('click', hide);
1600 overlay.addEventListener('click', (e) =>
1601 {
1602 if (e.target === overlay) hide();
1603 });
1604
1605 confirmBtn.addEventListener('click', async () =>
1606 {
1607 const st = STATE.movePicker;
1608 if (!st || !st.item || !st.selectedPath)
1609 {
1610 toast('Select a destination folder first.', 'err');
1611 return;
1612 }
1613
1614 try
1615 {
1616 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
1617 if (!moved) return;
1618 }
1619 catch (err)
1620 {
1621 toast('Move failed: ' + err.message, 'err');
1622 return;
1623 }
1624
1625 hide();
1626 if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
1627 navigateTo(STATE.currentDir, STATE.currentRoot);
1628 });
1629
1630 return overlay;
1631}
1632
1633function setMoveSelection (path, buttonEl)
1634{
1635 if (!STATE.movePicker) return;
1636 STATE.movePicker.selectedPath = path;
1637
1638 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
1639 if (buttonEl) buttonEl.classList.add('selected');
1640
1641 const selectedEl = document.getElementById('move-selected');
1642 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
1643}
1644
1645async function loadMoveChildren (containerEl, dirPath)
1646{
1647 if (containerEl.dataset.loaded === '1') return;
1648 containerEl.dataset.loaded = '1';
1649
1650 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
1651 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
1652
1653 if (!folders.length)
1654 {
1655 const empty = document.createElement('div');
1656 empty.className = 'move-empty';
1657 empty.textContent = 'No subfolders';
1658 containerEl.appendChild(empty);
1659 return;
1660 }
1661
1662 for (const child of folders)
1663 {
1664 containerEl.appendChild(createMoveNode(child.path, child.name));
1665 }
1666}
1667
1668function createMoveNode (folderPath, label)
1669{
1670 const node = document.createElement('div');
1671 node.className = 'move-node';
1672
1673 const row = document.createElement('div');
1674 row.className = 'move-node-row';
1675
1676 const toggle = document.createElement('button');
1677 toggle.type = 'button';
1678 toggle.className = 'move-toggle';
1679 toggle.textContent = '▸';
1680
1681 const selectBtn = document.createElement('button');
1682 selectBtn.type = 'button';
1683 selectBtn.className = 'move-node-label';
1684 selectBtn.textContent = label;
1685 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
1686
1687 const children = document.createElement('div');
1688 children.className = 'move-children hidden';
1689
1690 toggle.addEventListener('click', async () =>
1691 {
1692 if (children.classList.contains('hidden'))
1693 {
1694 await loadMoveChildren(children, folderPath);
1695 children.classList.remove('hidden');
1696 toggle.textContent = '▾';
1697 } else
1698 {
1699 children.classList.add('hidden');
1700 toggle.textContent = '▸';
1701 }
1702 });
1703
1704 row.appendChild(toggle);
1705 row.appendChild(selectBtn);
1706 node.appendChild(row);
1707 node.appendChild(children);
1708 return node;
1709}
1710
1711function openMovePicker (item)
1712{
1713 if (!canWrite())
1714 {
1715 toast('No write access.', 'err');
1716 return;
1717 }
1718
1719 const roots = writableRoots();
1720 if (!roots.length)
1721 {
1722 toast('No writable destination roots available.', 'err');
1723 return;
1724 }
1725
1726 const overlay = ensureMoveModal();
1727 const tree = overlay.querySelector('#move-tree');
1728 const caption = overlay.querySelector('#move-modal-caption');
1729
1730 STATE.movePicker = { item, selectedPath: null };
1731 caption.textContent = `Select destination folder for: ${item.name}`;
1732 tree.innerHTML = '';
1733
1734 for (const root of roots)
1735 {
1736 tree.appendChild(createMoveNode(root.path, root.label));
1737 }
1738
1739 setMoveSelection(null, null);
1740 overlay.classList.remove('hidden');
1741}
1742
1743// ───────────────────────────────────────────────────────────────────────────
1744// FOLDER ICON PICKER
1745// ───────────────────────────────────────────────────────────────────────────
1746
1747async function openFolderIconPicker (item)
1748{
1749 if (!canWrite(item))
1750 {
1751 toast('No write access.', 'err');
1752 return;
1753 }
1754
1755 // Fetch the list of available images (only those with cached thumbnails).
1756 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1757 const images = data ? data.images : [];
1758
1759 let existingIconOverlay = document.getElementById('folder-icon-picker');
1760 if (existingIconOverlay) existingIconOverlay.remove();
1761
1762 const overlay = document.createElement('div');
1763 overlay.id = 'folder-icon-picker';
1764 overlay.className = 'modal-overlay';
1765
1766 const modal = document.createElement('div');
1767 modal.className = 'modal folder-icon-modal';
1768
1769 const closeBtn = document.createElement('button');
1770 closeBtn.className = 'modal-close';
1771 closeBtn.setAttribute('aria-label', 'Close');
1772 closeBtn.textContent = '✕';
1773
1774 const title = document.createElement('h2');
1775 title.textContent = 'Set folder icon';
1776
1777 const subtitle = document.createElement('p');
1778 subtitle.className = 'muted';
1779
1780 const grid = document.createElement('div');
1781 grid.className = 'folder-icon-grid';
1782
1783 if (!images.length)
1784 {
1785 subtitle.textContent = 'No images with cached thumbnails were found inside this folder.';
1786 } else
1787 {
1788 subtitle.textContent = 'Select an image to use as the folder icon.';
1789
1790 for (const { filePath } of images)
1791 {
1792 const cell = document.createElement('div');
1793 cell.className = 'folder-icon-cell';
1794 cell.dataset.path = filePath;
1795
1796 const imgEl = document.createElement('img');
1797 imgEl.alt = filePath.split('/').pop();
1798 imgEl.className = 'folder-icon-thumb';
1799 // Lazy-load via IntersectionObserver on the cell.
1800 imgEl.dataset.src = filePath;
1801
1802 const label = document.createElement('div');
1803 label.className = 'folder-icon-label';
1804 label.textContent = filePath.split('/').pop();
1805
1806 cell.appendChild(imgEl);
1807 cell.appendChild(label);
1808
1809 cell.addEventListener('click', () =>
1810 {
1811 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
1812 cell.classList.add('selected');
1813 confirmBtn.disabled = false;
1814 });
1815
1816 grid.appendChild(cell);
1817 }
1818 }
1819
1820 const dialogActions = document.createElement('div');
1821 dialogActions.className = 'dialog-actions';
1822
1823 const clearBtn = document.createElement('button');
1824 clearBtn.textContent = 'Clear icon';
1825 clearBtn.addEventListener('click', async () =>
1826 {
1827 try
1828 {
1829 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
1830 } catch (err)
1831 {
1832 toast('Failed to clear icon: ' + err.message, 'err');
1833 return;
1834 }
1835 hide();
1836 refreshAfterIconChange(item);
1837 });
1838
1839 const cancelBtn = document.createElement('button');
1840 cancelBtn.textContent = 'Cancel';
1841 cancelBtn.addEventListener('click', () => hide());
1842
1843 const confirmBtn = document.createElement('button');
1844 confirmBtn.className = 'primary';
1845 confirmBtn.textContent = 'Set icon';
1846 confirmBtn.disabled = true;
1847 confirmBtn.addEventListener('click', async () =>
1848 {
1849 const selected = grid.querySelector('.folder-icon-cell.selected');
1850 if (!selected) return;
1851 const imagePath = selected.dataset.path;
1852 try
1853 {
1854 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
1855 } catch (err)
1856 {
1857 toast('Failed to set icon: ' + err.message, 'err');
1858 return;
1859 }
1860 hide();
1861 refreshAfterIconChange(item);
1862 });
1863
1864 dialogActions.appendChild(clearBtn);
1865 dialogActions.appendChild(cancelBtn);
1866 dialogActions.appendChild(confirmBtn);
1867
1868 modal.appendChild(closeBtn);
1869 modal.appendChild(title);
1870 modal.appendChild(subtitle);
1871 modal.appendChild(grid);
1872 modal.appendChild(dialogActions);
1873 overlay.appendChild(modal);
1874 document.body.appendChild(overlay);
1875
1876 function hide ()
1877 {
1878 overlay.remove();
1879 // Revoke any blob URLs we created for the picker thumbnails.
1880 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
1881 {
1882 URL.revokeObjectURL(img.src);
1883 });
1884 }
1885
1886 closeBtn.addEventListener('click', hide);
1887 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
1888
1889 // Eagerly load thumbnails for all cells (picker is small, fetch all).
1890 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
1891 {
1892 const imgEl = cell.querySelector('.folder-icon-thumb');
1893 const filePath = imgEl.dataset.src;
1894 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
1895 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
1896 }).then(async (r) =>
1897 {
1898 if (!r.ok || !overlay.isConnected) return;
1899 const blob = await r.blob();
1900 const url = URL.createObjectURL(blob);
1901 imgEl.src = url;
1902 }).catch(() => {});
1903 }
1904}
1905
1906function refreshAfterIconChange (item)
1907{
1908 // Reset and reload icon in grid tiles.
1909 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
1910 .find(el => el.dataset.folderPath === item.path);
1911 if (gridTile)
1912 {
1913 const svg = gridTile.querySelector('svg');
1914 if (svg)
1915 {
1916 // Rebuild to plain folder SVG, then reload.
1917 gridTile.innerHTML = iconFolder();
1918 delete gridTile.dataset.thumbReady;
1919 gridTile.dataset.folderPath = item.path;
1920 void loadOneFolderIcon(gridTile);
1921 }
1922 }
1923
1924 // Also reset the sidebar icon if it's showing the same folder.
1925 const sidebarIcon = document.getElementById('sidebar-icon');
1926 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
1927 {
1928 sidebarIcon.innerHTML = iconFolder(64);
1929 delete sidebarIcon.dataset.thumbReady;
1930 void loadOneFolderIcon(sidebarIcon);
1931 }
1932}
1933
1934// ───────────────────────────────────────────────────────────────────────────
1935// DOWNLOAD / VIEW
1936// ───────────────────────────────────────────────────────────────────────────
1937
1938function isInlinePreviewableBlob (blob, name)
1939{
1940 const mime = String(blob.type || '').toLowerCase();
1941 if (/^(image|video|audio)\//.test(mime)) return true;
1942 if (/^text\//.test(mime)) return true;
1943 if (mime === 'application/pdf') return true;
1944 if (mime === 'application/json') return true;
1945 if (mime === 'application/xml') return true;
1946 if (mime === 'application/javascript') return true;
1947
1948 // Fallback by extension when MIME is missing or generic.
1949 const ext = extOf(name || '');
1950 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
1951 if (CODE_EXTS.has(ext)) return true;
1952 return false;
1953}
1954
1955function isTextLikeBlob (blob, name)
1956{
1957 const mime = String(blob.type || '').toLowerCase();
1958 if (/^text\//.test(mime)) return true;
1959 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
1960 const ext = extOf(name || '');
1961 return CODE_EXTS.has(ext);
1962}
1963
1964function detectCodeLanguage (name, mime)
1965{
1966 const ext = extOf(name || '');
1967 const m = String(mime || '').toLowerCase();
1968 if (m.includes('json') || ext === 'json') return 'json';
1969 if (m.includes('xml') || ext === 'xml') return 'xml';
1970 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
1971 if (m.includes('css') || ext === 'css') return 'css';
1972 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
1973 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
1974 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
1975 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
1976 return CODE_EXTS.has(ext) ? 'js' : 'plain';
1977}
1978
1979function prettyPrintMarkup (raw)
1980{
1981 const src = String(raw || '')
1982 .replace(/>\s+</g, '><')
1983 .replace(/\r\n/g, '\n');
1984
1985 const lines = src.replace(/></g, '>\n<').split('\n');
1986 let indent = 0;
1987 const out = [];
1988
1989 for (const ln of lines)
1990 {
1991 const line = ln.trim();
1992 if (!line) continue;
1993 const isClose = /^<\//.test(line);
1994 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
1995 const isOpen = /^<[^!?/][^>]*>$/.test(line);
1996
1997 if (isClose) indent = Math.max(0, indent - 1);
1998 out.push(' '.repeat(indent) + line);
1999 if (isOpen && !isSelf) indent += 1;
2000 }
2001
2002 return out.join('\n');
2003}
2004
2005function prettyPrintBraces (raw)
2006{
2007 const lines = String(raw || '')
2008 .replace(/\r\n/g, '\n')
2009 .split('\n');
2010 let indent = 0;
2011 const out = [];
2012
2013 for (const ln of lines)
2014 {
2015 const line = ln.trim();
2016 if (!line)
2017 {
2018 out.push('');
2019 continue;
2020 }
2021 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
2022 out.push(' '.repeat(indent) + line);
2023 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
2024 }
2025 return out.join('\n');
2026}
2027
2028function prettyPrintCode (raw, lang)
2029{
2030 const text = String(raw || '').replace(/\r\n/g, '\n');
2031 if (lang === 'json')
2032 {
2033 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
2034 }
2035 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
2036 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
2037 return text;
2038}
2039
2040function escapeHtml (s)
2041{
2042 return String(s)
2043 .replace(/&/g, '&amp;')
2044 .replace(/</g, '&lt;')
2045 .replace(/>/g, '&gt;');
2046}
2047
2048function highlightCode (raw, lang)
2049{
2050 if (lang === 'plain') return escapeHtml(raw);
2051
2052 let html = escapeHtml(raw);
2053 const stash = [];
2054 const keep = (regex, cls) =>
2055 {
2056 html = html.replace(regex, (m) =>
2057 {
2058 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
2059 return `@@TOK${idx}@@`;
2060 });
2061 };
2062
2063 if (lang === 'json')
2064 {
2065 html = html
2066 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
2067 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
2068 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
2069 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2070 return html;
2071 }
2072
2073 if (lang === 'xml' || lang === 'html')
2074 {
2075 html = html
2076 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
2077 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
2078 return html;
2079 }
2080
2081 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
2082 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
2083 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
2084
2085 html = html
2086 .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>')
2087 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2088
2089 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
2090 return html;
2091}
2092
2093function clearPreviewObjectUrl ()
2094{
2095 if (!STATE.previewObjectUrl) return;
2096 URL.revokeObjectURL(STATE.previewObjectUrl);
2097 STATE.previewObjectUrl = null;
2098}
2099
2100function fileAccentColor (name)
2101{
2102 const ext = extOf(name || '');
2103 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
2104 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
2105 if (AUDIO_EXTS.has(ext)) return '#c084fc';
2106 if (DOC_EXTS.has(ext)) return '#f97316';
2107 if (CODE_EXTS.has(ext)) return '#38bdf8';
2108 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
2109 return '#7880a0';
2110}
2111
2112function animateRect (el, fromRect, toRect, opts = {})
2113{
2114 const duration = opts.duration == null ? 260 : opts.duration;
2115 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
2116
2117 el.style.left = `${fromRect.left}px`;
2118 el.style.top = `${fromRect.top}px`;
2119 el.style.width = `${fromRect.width}px`;
2120 el.style.height = `${fromRect.height}px`;
2121
2122 return new Promise((resolve) =>
2123 {
2124 const t0 = performance.now();
2125
2126 function frame (now)
2127 {
2128 const raw = Math.min((now - t0) / duration, 1);
2129 const t = easeOut(raw);
2130
2131 const left = fromRect.left + (toRect.left - fromRect.left) * t;
2132 const top = fromRect.top + (toRect.top - fromRect.top) * t;
2133 const width = fromRect.width + (toRect.width - fromRect.width) * t;
2134 const height = fromRect.height + (toRect.height - fromRect.height) * t;
2135
2136 el.style.left = `${left}px`;
2137 el.style.top = `${top}px`;
2138 el.style.width = `${width}px`;
2139 el.style.height = `${height}px`;
2140
2141 if (raw < 1)
2142 {
2143 requestAnimationFrame(frame);
2144 } else
2145 {
2146 resolve();
2147 }
2148 }
2149
2150 requestAnimationFrame(frame);
2151 });
2152}
2153
2154async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
2155{
2156 if (!tileEl || !sourceSvgEl) return false;
2157
2158 if (STATE.previewExpandState)
2159 {
2160 await closeExpandedTilePreview();
2161 }
2162
2163 const iconEl = tileEl.querySelector('.icon');
2164 const nameEl = tileEl.querySelector('.name');
2165 if (!iconEl) return false;
2166
2167 const startRect = tileEl.getBoundingClientRect();
2168 const targetW = Math.min(window.innerWidth * 0.94, 1100);
2169 const targetH = Math.min(window.innerHeight * 0.9, 860);
2170 const targetRect = {
2171 left: (window.innerWidth - targetW) / 2,
2172 top: (window.innerHeight - targetH) / 2,
2173 width: targetW,
2174 height: targetH,
2175 };
2176
2177 const backdrop = document.createElement('div');
2178 backdrop.className = 'preview-backdrop';
2179 document.body.appendChild(backdrop);
2180
2181 const parent = tileEl.parentNode;
2182 const nextSibling = tileEl.nextSibling;
2183 const iconHtml = iconEl.innerHTML;
2184 const originalIconSvg = iconEl.querySelector('svg');
2185
2186 tileEl.remove();
2187 document.body.appendChild(tileEl);
2188 tileEl.classList.add('file-item--preview');
2189 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
2190 tileEl.style.position = 'fixed';
2191 tileEl.style.left = `${startRect.left}px`;
2192 tileEl.style.top = `${startRect.top}px`;
2193 tileEl.style.width = `${startRect.width}px`;
2194 tileEl.style.height = `${startRect.height}px`;
2195 tileEl.style.margin = '0';
2196 tileEl.style.zIndex = '10000';
2197
2198 if (nameEl) nameEl.style.display = 'none';
2199
2200 const titleEl = document.createElement('div');
2201 titleEl.className = 'preview-expand-title';
2202 titleEl.textContent = item.name;
2203
2204 const closeBtn = document.createElement('button');
2205 closeBtn.className = 'preview-expand-close';
2206 closeBtn.type = 'button';
2207 closeBtn.textContent = '×';
2208 closeBtn.setAttribute('aria-label', 'Close preview');
2209
2210 const dlBtn = document.createElement('button');
2211 dlBtn.className = 'preview-expand-download';
2212 dlBtn.type = 'button';
2213 dlBtn.textContent = 'Download';
2214 dlBtn.addEventListener('click', (e) =>
2215 {
2216 e.stopPropagation();
2217 if (!STATE.previewObjectUrl)
2218 {
2219 toast('Preview still loading.', 'err');
2220 return;
2221 }
2222 triggerDownload(item.name, STATE.previewObjectUrl);
2223 });
2224
2225 iconEl.innerHTML = '';
2226
2227 if (originalIconSvg)
2228 {
2229 const outline = originalIconSvg.cloneNode(true);
2230 outline.classList.add('preview-expand-outline');
2231 iconEl.appendChild(outline);
2232 }
2233
2234 const previewMount = document.createElement('div');
2235 previewMount.className = 'preview-expand-content';
2236 iconEl.appendChild(previewMount);
2237
2238 // Show spinner during expansion animation; content loads after it finishes
2239 const spinner = document.createElement('div');
2240 spinner.className = 'preview-loading-spinner';
2241 previewMount.appendChild(spinner);
2242
2243 tileEl.insertBefore(titleEl, tileEl.firstChild);
2244 tileEl.appendChild(closeBtn);
2245 tileEl.appendChild(dlBtn);
2246
2247 STATE.previewExpandState = {
2248 item,
2249 tileEl,
2250 sourceSvgEl,
2251 parent,
2252 nextSibling,
2253 iconEl,
2254 iconHtml,
2255 nameEl,
2256 backdrop,
2257 closeBtn,
2258 dlBtn,
2259 titleEl,
2260 previewMount,
2261 startRect,
2262 };
2263
2264 const onBackdrop = (e) =>
2265 {
2266 if (e.target === backdrop) closePreview();
2267 };
2268 const onClose = () => closePreview();
2269 backdrop.addEventListener('click', onBackdrop);
2270 closeBtn.addEventListener('click', onClose);
2271 STATE.previewExpandState.onBackdrop = onBackdrop;
2272 STATE.previewExpandState.onClose = onClose;
2273
2274 requestAnimationFrame(() => backdrop.classList.add('visible'));
2275 await animateRect(tileEl, startRect, targetRect);
2276
2277 tileEl.style.left = `${targetRect.left}px`;
2278 tileEl.style.top = `${targetRect.top}px`;
2279 tileEl.style.width = `${targetRect.width}px`;
2280 tileEl.style.height = `${targetRect.height}px`;
2281
2282 try
2283 {
2284 await loadPreviewContent(previewMount);
2285 } catch
2286 {
2287 if (previewMount.isConnected)
2288 {
2289 previewMount.innerHTML = '';
2290 const msg = document.createElement('p');
2291 msg.className = 'preview-unsupported';
2292 msg.textContent = 'Preview failed to load. You can try again.';
2293 previewMount.appendChild(msg);
2294 }
2295 }
2296
2297 return true;
2298}
2299
2300async function closeExpandedTilePreview ()
2301{
2302 const st = STATE.previewExpandState;
2303 if (!st) return;
2304
2305 st.backdrop.classList.remove('visible');
2306 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
2307 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
2308
2309 const fromRect = st.tileEl.getBoundingClientRect();
2310 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
2311
2312 st.tileEl.classList.remove('file-item--preview');
2313 st.tileEl.style.position = '';
2314 st.tileEl.style.left = '';
2315 st.tileEl.style.top = '';
2316 st.tileEl.style.width = '';
2317 st.tileEl.style.height = '';
2318 st.tileEl.style.margin = '';
2319 st.tileEl.style.zIndex = '';
2320
2321 if (st.titleEl) st.titleEl.remove();
2322 if (st.closeBtn) st.closeBtn.remove();
2323 if (st.dlBtn) st.dlBtn.remove();
2324 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
2325 if (st.nameEl) st.nameEl.style.display = '';
2326
2327 if (st.parent)
2328 {
2329 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
2330 {
2331 st.parent.insertBefore(st.tileEl, st.nextSibling);
2332 } else
2333 {
2334 st.parent.appendChild(st.tileEl);
2335 }
2336 }
2337
2338 if (st.backdrop) st.backdrop.remove();
2339 STATE.previewExpandState = null;
2340}
2341
2342async function closePreview ()
2343{
2344 if (STATE.previewExpandState)
2345 {
2346 await closeExpandedTilePreview();
2347 clearPreviewObjectUrl();
2348 STATE.previewSourceEl = null;
2349 }
2350}
2351
2352async function fetchFileBlob (item)
2353{
2354 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
2355 try
2356 {
2357 const res = await fetch(url, {
2358 headers: {
2359 Authorization: 'Bearer ' + STATE.token,
2360 'X-Fp': getFingerprint(),
2361 },
2362 });
2363 if (!res.ok) throw new Error('Download failed.');
2364 return await res.blob();
2365 } catch
2366 {
2367 return null;
2368 }
2369}
2370
2371function triggerDownload (filename, objectUrl)
2372{
2373 const a = document.createElement('a');
2374 a.href = objectUrl;
2375 a.download = filename;
2376 a.click();
2377}
2378
2379async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
2380{
2381 const body = targetEl || document.getElementById('preview-body');
2382 body.innerHTML = '';
2383
2384 const mime = String(blob.type || '').toLowerCase();
2385 const previewable = isInlinePreviewableBlob(blob, item.name);
2386
2387 if (!previewable)
2388 {
2389 const msg = document.createElement('p');
2390 msg.className = 'preview-unsupported';
2391 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
2392 body.appendChild(msg);
2393 return;
2394 }
2395
2396 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
2397 {
2398 const img = document.createElement('img');
2399 img.className = 'preview-media';
2400 img.src = objectUrl;
2401 img.alt = item.name;
2402 body.appendChild(img);
2403 return;
2404 }
2405
2406 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
2407 {
2408 const video = document.createElement('video');
2409 video.className = 'preview-media';
2410 video.src = objectUrl;
2411 video.controls = true;
2412 video.preload = 'metadata';
2413 body.appendChild(video);
2414 return;
2415 }
2416
2417 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
2418 {
2419 const audio = document.createElement('audio');
2420 audio.className = 'preview-audio';
2421 audio.src = objectUrl;
2422 audio.controls = true;
2423 body.appendChild(audio);
2424 return;
2425 }
2426
2427 if (mime === 'application/pdf')
2428 {
2429 const frame = document.createElement('iframe');
2430 frame.className = 'preview-frame';
2431 frame.src = objectUrl;
2432 frame.title = item.name;
2433 body.appendChild(frame);
2434 return;
2435 }
2436
2437 if (isTextLikeBlob(blob, item.name))
2438 {
2439 const text = await blob.text();
2440 const lang = detectCodeLanguage(item.name, mime);
2441 const formatted = prettyPrintCode(text, lang);
2442 const pre = document.createElement('pre');
2443 pre.className = 'preview-text preview-code';
2444 pre.innerHTML = highlightCode(formatted, lang);
2445 body.appendChild(pre);
2446 return;
2447 }
2448
2449 const msg = document.createElement('p');
2450 msg.className = 'preview-unsupported';
2451 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
2452 body.appendChild(msg);
2453}
2454
2455async function downloadOrView (item, sourceSvgEl = null)
2456{
2457 if (STATE.previewExpandState)
2458 {
2459 await closePreview();
2460 }
2461
2462 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
2463 if (sourceTileEl)
2464 {
2465 STATE.previewSourceEl = sourceSvgEl;
2466 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
2467 {
2468 const blob = await fetchFileBlob(item);
2469 if (!blob) throw new Error('Download failed');
2470
2471 clearPreviewObjectUrl();
2472 const objectUrl = URL.createObjectURL(blob);
2473 STATE.previewObjectUrl = objectUrl;
2474
2475 if (!previewMount.isConnected) return;
2476
2477 previewMount.innerHTML = '';
2478 await renderPreviewBody(item, blob, objectUrl, previewMount);
2479 });
2480 if (expanded) return;
2481 }
2482
2483 toast('Preview unavailable — no source tile found.', 'err');
2484}
2485
2486// ───────────────────────────────────────────────────────────────────────────
2487// UPLOAD
2488// ───────────────────────────────────────────────────────────────────────────
2489
2490function canWrite (item = null)
2491{
2492 if (STATE.isAdmin) return true;
2493 const root = item && item._root
2494 ? item._root
2495 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
2496 if (!root) return false;
2497 const p = STATE.permissions[rootPermissionLabel(root)];
2498 return p && p.write;
2499}
2500
2501async function uploadFiles (fileList)
2502{
2503 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2504 if (!canWrite()) { toast('No write access.', 'err'); return; }
2505
2506 const files = Array.from(fileList || []);
2507 if (!files.length) return;
2508
2509 // Show upload bar
2510 const wrap = document.createElement('div');
2511 wrap.className = 'upload-bar-wrap';
2512 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2513 document.body.appendChild(wrap);
2514 STATE.uploadInProgress = true;
2515
2516 try
2517 {
2518 const existingNames = await listDirNameSet(STATE.currentDir);
2519 let done = 0;
2520 let uploaded = 0;
2521
2522 for (const original of files)
2523 {
2524 let fileToUpload = original;
2525
2526 if (existingNames.has(original.name))
2527 {
2528 const suggested = nextAvailableName(original.name, existingNames);
2529 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
2530 if (decision === 'cancel')
2531 {
2532 done++;
2533 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2534 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2535 continue;
2536 }
2537
2538 if (decision === 'rename')
2539 {
2540 fileToUpload = cloneFileWithName(original, suggested);
2541 }
2542 }
2543
2544 await uploadSingleFile(fileToUpload, STATE.currentDir);
2545 existingNames.add(fileToUpload.name);
2546 done++;
2547 uploaded++;
2548 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
2549 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
2550 }
2551
2552 toast(`Uploaded ${uploaded} file(s).`, 'ok');
2553 await navigateTo(STATE.currentDir, STATE.currentRoot);
2554 } catch (err)
2555 {
2556 toast(err.message, 'err');
2557 } finally
2558 {
2559 STATE.uploadInProgress = false;
2560 wrap.remove();
2561 }
2562}
2563
2564async function uploadSingleFile (file, targetDir)
2565{
2566 const formData = new FormData();
2567 formData.append('files', file);
2568
2569 await new Promise((resolve, reject) =>
2570 {
2571 const xhr = new XMLHttpRequest();
2572 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
2573 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
2574 xhr.setRequestHeader('X-Fp', getFingerprint());
2575 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
2576 xhr.onload = () => xhr.status === 200
2577 ? resolve()
2578 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
2579 xhr.onerror = () => reject(new Error('Network error'));
2580 xhr.send(formData);
2581 });
2582}
2583
2584async function ensureServerDir (baseDir, relativeDir)
2585{
2586 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
2587 let current = baseDir;
2588 for (const part of parts)
2589 {
2590 try
2591 {
2592 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
2593 current = resp && resp.path ? resp.path : joinServerPath(current, part);
2594 } catch (err)
2595 {
2596 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2597 current = joinServerPath(current, part);
2598 }
2599 }
2600 return current;
2601}
2602
2603async function uploadFolderInputFiles (fileList)
2604{
2605 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2606 if (!canWrite()) { toast('No write access.', 'err'); return; }
2607 if (!fileList || !fileList.length) return;
2608
2609 const files = Array.from(fileList);
2610 const total = files.length;
2611 let done = 0;
2612
2613 const wrap = document.createElement('div');
2614 wrap.className = 'upload-bar-wrap';
2615 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2616 document.body.appendChild(wrap);
2617 STATE.uploadInProgress = true;
2618
2619 try
2620 {
2621 const dirCache = new Map();
2622 dirCache.set('', STATE.currentDir);
2623
2624 for (const file of files)
2625 {
2626 const rel = file.webkitRelativePath || file.name;
2627 const relParts = rel.split(/[\\/]/).filter(Boolean);
2628 const relDir = relParts.slice(0, -1).join('/');
2629
2630 if (!dirCache.has(relDir))
2631 {
2632 const parentRel = relParts.slice(0, -2).join('/');
2633 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
2634 const thisName = relParts[relParts.length - 2];
2635
2636 try
2637 {
2638 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
2639 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
2640 } catch (err)
2641 {
2642 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
2643 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
2644 }
2645 }
2646
2647 const targetDir = dirCache.get(relDir) || STATE.currentDir;
2648 await uploadSingleFile(file, targetDir);
2649 done++;
2650 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2651 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2652 }
2653
2654 toast(`Uploaded ${total} file(s).`, 'ok');
2655 await navigateTo(STATE.currentDir, STATE.currentRoot);
2656 } catch (err)
2657 {
2658 toast(err.message, 'err');
2659 } finally
2660 {
2661 STATE.uploadInProgress = false;
2662 wrap.remove();
2663 }
2664}
2665
2666// ───────────────────────────────────────────────────────────────────────────
2667// FOLDER DRAG-AND-DROP (recursive)
2668// ───────────────────────────────────────────────────────────────────────────
2669
2670/**
2671 * Reads all readEntries batches from a DirectoryReader (browsers may return
2672 * results in chunks; we must keep calling until we get an empty array).
2673 */
2674function readAllEntries (reader)
2675{
2676 return new Promise((resolve, reject) =>
2677 {
2678 const all = [];
2679 function next ()
2680 {
2681 reader.readEntries(batch =>
2682 {
2683 if (!batch.length) { resolve(all); return; }
2684 all.push(...batch);
2685 next();
2686 }, reject);
2687 }
2688 next();
2689 });
2690}
2691
2692/**
2693 * Recursively walk a FileSystemEntry tree, creating server-side directories
2694 * on the fly and collecting { file, targetDir } pairs for upload.
2695 */
2696async function collectEntries (entry, serverDir, toUpload)
2697{
2698 if (entry.isFile)
2699 {
2700 const file = await new Promise((res, rej) => entry.file(res, rej));
2701 toUpload.push({ file, targetDir: serverDir });
2702 } else if (entry.isDirectory)
2703 {
2704 // Ask the server to create the directory; it returns the canonical path.
2705 let newServerDir;
2706 try
2707 {
2708 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
2709 newServerDir = resp.path;
2710 } catch
2711 {
2712 // Directory may already exist — reconstruct path from what we know.
2713 // The server always returns JSON with {error} on failure, so we can
2714 // still continue by falling back to a best-effort path join.
2715 // We rely on the fact that the server separator is consistent within
2716 // a session (the list/browse API already returned paths in that format).
2717 const sep = serverDir.includes('\\') ? '\\' : '/';
2718 newServerDir = serverDir + sep + entry.name;
2719 }
2720 const reader = entry.createReader();
2721 const subEntries = await readAllEntries(reader);
2722 for (const sub of subEntries)
2723 {
2724 await collectEntries(sub, newServerDir, toUpload);
2725 }
2726 }
2727}
2728
2729async function uploadEntries (entries)
2730{
2731 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2732 if (!canWrite()) { toast('No write access.', 'err'); return; }
2733
2734 const wrap = document.createElement('div');
2735 wrap.className = 'upload-bar-wrap';
2736 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
2737 document.body.appendChild(wrap);
2738 STATE.uploadInProgress = true;
2739
2740 try
2741 {
2742 const toUpload = [];
2743 for (const entry of entries)
2744 {
2745 await collectEntries(entry, STATE.currentDir, toUpload);
2746 }
2747
2748 if (!toUpload.length) { toast('No files found.', 'err'); return; }
2749
2750 let done = 0;
2751 const total = toUpload.length;
2752 const updateBar = () =>
2753 {
2754 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
2755 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
2756 };
2757 updateBar();
2758
2759 for (const { file, targetDir } of toUpload)
2760 {
2761 await uploadSingleFile(file, targetDir);
2762 done++;
2763 updateBar();
2764 }
2765
2766 toast(`Uploaded ${total} file(s).`, 'ok');
2767 await navigateTo(STATE.currentDir, STATE.currentRoot);
2768 } catch (err)
2769 {
2770 toast(err.message, 'err');
2771 } finally
2772 {
2773 STATE.uploadInProgress = false;
2774 wrap.remove();
2775 }
2776}
2777
2778// DRAG-AND-DROP
2779// ───────────────────────────────────────────────────────────────────────────
2780
2781function initDragDrop ()
2782{
2783 const main = document.getElementById('main-content');
2784 const dropOvl = document.getElementById('drop-overlay');
2785 let dragDepth = 0;
2786
2787 main.addEventListener('dragenter', e =>
2788 {
2789 e.preventDefault();
2790 dragDepth++;
2791 dropOvl.classList.remove('hidden');
2792 });
2793 main.addEventListener('dragleave', () =>
2794 {
2795 dragDepth--;
2796 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
2797 });
2798 main.addEventListener('dragover', e => e.preventDefault());
2799 main.addEventListener('drop', async e =>
2800 {
2801 e.preventDefault();
2802 dragDepth = 0;
2803 dropOvl.classList.add('hidden');
2804 if (!canWrite()) { toast('No write access.', 'err'); return; }
2805
2806 const items = Array.from(e.dataTransfer.items || []);
2807 // Use the FileSystem Entry API when available so we can handle folders.
2808 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
2809 {
2810 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
2811 if (entries.some(en => en.isDirectory))
2812 {
2813 await uploadEntries(entries);
2814 return;
2815 }
2816 }
2817 // Plain files only — use the fast batch path.
2818 const files = e.dataTransfer.files;
2819 if (files.length) await uploadFiles(files);
2820 });
2821}
2822
2823// ───────────────────────────────────────────────────────────────────────────
2824// RENAME
2825// ───────────────────────────────────────────────────────────────────────────
2826
2827function openRenameModal (item)
2828{
2829 const modal = document.getElementById('rename-modal');
2830 modal.classList.remove('hidden');
2831 const input = document.getElementById('rename-input');
2832 input.value = item.name;
2833 input.focus();
2834 input.select();
2835 document.getElementById('rename-error').classList.add('hidden');
2836 document.getElementById('rename-form').onsubmit = async (e) =>
2837 {
2838 e.preventDefault();
2839 const newName = input.value.trim();
2840 if (!newName) return;
2841 try
2842 {
2843 if (item._root)
2844 {
2845 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
2846 } else
2847 {
2848 await api('POST', '/files/rename', { from: item.path, to: newName });
2849 }
2850 modal.classList.add('hidden');
2851 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
2852 if (item._root)
2853 {
2854 await loadRoots({
2855 preferredDir: STATE.currentDir,
2856 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
2857 });
2858 } else
2859 {
2860 await navigateTo(STATE.currentDir, STATE.currentRoot);
2861 }
2862 } catch (err)
2863 {
2864 document.getElementById('rename-error').textContent = err.message;
2865 document.getElementById('rename-error').classList.remove('hidden');
2866 }
2867 };
2868}
2869
2870// ───────────────────────────────────────────────────────────────────────────
2871// DELETE
2872// ───────────────────────────────────────────────────────────────────────────
2873
2874async function deleteItem (item)
2875{
2876 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
2877 try
2878 {
2879 await api('POST', '/files/delete', { path: item.path });
2880 toast('Deleted.', 'ok');
2881 closeSidebar();
2882 await navigateTo(STATE.currentDir, STATE.currentRoot);
2883 } catch (err)
2884 {
2885 toast(err.message, 'err');
2886 }
2887}
2888
2889// ───────────────────────────────────────────────────────────────────────────
2890// ADMIN PANEL
2891// ───────────────────────────────────────────────────────────────────────────
2892
2893async function openAdminModal ()
2894{
2895 document.getElementById('admin-modal').classList.remove('hidden');
2896 await refreshAdminConfig();
2897 await refreshAdminUsers();
2898}
2899
2900async function refreshAdminConfig ()
2901{
2902 const data = await api('GET', '/admin/config');
2903 if (!data) return;
2904 const container = document.getElementById('admin-paths');
2905 container.innerHTML = '';
2906 for (const p of data.paths)
2907 {
2908 const row = document.createElement('div');
2909 row.className = 'path-row';
2910 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
2911 row.querySelector('button').addEventListener('click', () =>
2912 {
2913 row.remove();
2914 });
2915 container.appendChild(row);
2916 }
2917}
2918
2919async function refreshAdminUsers ()
2920{
2921 const data = await api('GET', '/admin/users');
2922 if (!data) return;
2923 const container = document.getElementById('admin-users-list');
2924 container.innerHTML = '';
2925
2926 // Need paths for permission rows
2927 const cfg = await api('GET', '/admin/config');
2928 const paths = cfg ? (cfg.effectivePaths || []) : [];
2929
2930 for (const u of data.users)
2931 {
2932 const row = document.createElement('div');
2933 row.className = 'user-row';
2934 row.innerHTML = `
2935 <span class="user-name">${u.username}</span>
2936 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
2937 <button data-id="${u.id}" data-action="edit">Edit</button>
2938 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
2939 `;
2940 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
2941 openUserModal(u, paths));
2942 const deleteBtn = row.querySelector('[data-action="delete"]');
2943 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
2944 {
2945 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
2946 try
2947 {
2948 await api('DELETE', `/admin/users/${u.id}`);
2949 toast('User deleted.', 'ok');
2950 await refreshAdminUsers();
2951 } catch (err) { toast(err.message, 'err'); }
2952 });
2953 container.appendChild(row);
2954 }
2955}
2956
2957function openUserModal (user, paths)
2958{
2959 const modal = document.getElementById('user-modal');
2960 modal.classList.remove('hidden');
2961 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
2962 document.getElementById('user-error').classList.add('hidden');
2963
2964 const usernameInput = document.getElementById('user-username');
2965 usernameInput.value = user ? user.username : '';
2966 usernameInput.readOnly = !!user;
2967
2968 document.getElementById('user-password').value = '';
2969 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
2970
2971 // Password placeholder
2972 document.getElementById('user-password').placeholder =
2973 user ? 'Leave blank to keep current' : 'Min 8 characters';
2974
2975 // Build permissions grid
2976 const permDiv = document.getElementById('user-permissions');
2977 permDiv.innerHTML = '';
2978 if (paths.length)
2979 {
2980 const heading = document.createElement('h4');
2981 heading.textContent = 'Path Permissions';
2982 permDiv.appendChild(heading);
2983
2984 const isAdminUser = !!(user && user.isAdmin);
2985 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
2986 const adminChk = document.getElementById('user-is-admin');
2987 const rebuildPermRows = (admin) =>
2988 {
2989 permDiv.querySelectorAll('.perm-row').forEach(r =>
2990 {
2991 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
2992 {
2993 cb.disabled = admin;
2994 if (admin) cb.checked = true;
2995 });
2996 r.title = admin ? 'Admins always have full access' : '';
2997 });
2998 };
2999 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
3000
3001 const syncReadWriteConstraints = (row, admin = false) =>
3002 {
3003 const readCb = row.querySelector('input[data-type="read"]');
3004 const writeCb = row.querySelector('input[data-type="write"]');
3005 if (!readCb || !writeCb) return;
3006
3007 if (admin)
3008 {
3009 readCb.checked = true;
3010 writeCb.checked = true;
3011 readCb.disabled = true;
3012 writeCb.disabled = true;
3013 return;
3014 }
3015
3016 readCb.disabled = false;
3017 if (!readCb.checked)
3018 {
3019 writeCb.checked = false;
3020 writeCb.disabled = true;
3021 }
3022 else
3023 {
3024 writeCb.disabled = false;
3025 }
3026 };
3027
3028 const syncAllReadWriteConstraints = () =>
3029 {
3030 const admin = adminChk.checked;
3031 permDiv.querySelectorAll('.perm-row').forEach((row) =>
3032 {
3033 syncReadWriteConstraints(row, admin);
3034 });
3035 };
3036
3037 for (const p of paths)
3038 {
3039 const label = p.split(/[\\/]/).pop();
3040 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
3041 const row = document.createElement('div');
3042 row.className = 'perm-row';
3043 const readChecked = isAdminUser || perms.read;
3044 const writeChecked = isAdminUser || perms.write;
3045 row.innerHTML = `
3046 <span class="perm-label">${label}</span>
3047 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
3048 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
3049 `;
3050 if (isAdminUser) row.title = 'Admins always have full access';
3051 const readCb = row.querySelector('input[data-type="read"]');
3052 if (readCb)
3053 {
3054 readCb.addEventListener('change', () =>
3055 {
3056 syncReadWriteConstraints(row, adminChk.checked);
3057 });
3058 }
3059 permDiv.appendChild(row);
3060 }
3061
3062 syncAllReadWriteConstraints();
3063 adminChk.addEventListener('change', syncAllReadWriteConstraints);
3064 }
3065
3066 document.getElementById('user-form').onsubmit = async (e) =>
3067 {
3068 e.preventDefault();
3069 const password = document.getElementById('user-password').value;
3070 const isAdmin = document.getElementById('user-is-admin').checked;
3071 const permissions = {};
3072 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
3073 {
3074 const lbl = cb.dataset.label;
3075 if (!permissions[lbl]) permissions[lbl] = {};
3076 permissions[lbl][cb.dataset.type] = cb.checked;
3077 });
3078
3079 try
3080 {
3081 if (user)
3082 {
3083 const body = { isAdmin, permissions };
3084 if (password) body.password = password;
3085 await api('PATCH', `/admin/users/${user.id}`, body);
3086 } else
3087 {
3088 const uname = document.getElementById('user-username').value.trim();
3089 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
3090 }
3091 modal.classList.add('hidden');
3092 toast('User saved.', 'ok');
3093 await refreshAdminUsers();
3094 } catch (err)
3095 {
3096 document.getElementById('user-error').textContent = err.message;
3097 document.getElementById('user-error').classList.remove('hidden');
3098 }
3099 };
3100}
3101
3102// ───────────────────────────────────────────────────────────────────────────
3103// SVG ICONS
3104// ───────────────────────────────────────────────────────────────────────────
3105
3106const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
3107const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
3108const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
3109const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
3110const 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']);
3111const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
3112const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
3113
3114function iconFolder (size = 52)
3115{
3116 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
3117 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
3118 <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"/>
3119 </svg>`;
3120}
3121
3122function iconFile (name, size = 52)
3123{
3124 const color = fileAccentColor(name);
3125 let symbol = '';
3126
3127 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
3128 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
3129 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
3130 <polyline points="14 2 14 8 20 8"/>
3131 </svg>`;
3132}
3133
3134// ───────────────────────────────────────────────────────────────────────────
3135// EVENT WIRING
3136// ───────────────────────────────────────────────────────────────────────────
3137
3138// ───────────────────────────────────────────────────────────────────────────
3139// THUMBNAIL PREVIEWS
3140// ───────────────────────────────────────────────────────────────────────────
3141
3142function revokeThumbnails ()
3143{
3144 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
3145 STATE.thumbnailUrls = [];
3146}
3147
3148function disconnectThumbnailObserver ()
3149{
3150 if (!STATE.thumbnailObserver) return;
3151 STATE.thumbnailObserver.disconnect();
3152 STATE.thumbnailObserver = null;
3153}
3154
3155function disconnectFolderIconObserver ()
3156{
3157 if (!STATE.folderIconObserver) return;
3158 STATE.folderIconObserver.disconnect();
3159 STATE.folderIconObserver = null;
3160}
3161
3162function setThumbnailPending (iconEl, pending)
3163{
3164 if (!iconEl) return;
3165 if (pending)
3166 {
3167 iconEl.classList.add('thumb-pending');
3168 iconEl.dataset.thumbPending = '1';
3169 return;
3170 }
3171
3172 iconEl.classList.remove('thumb-pending');
3173 delete iconEl.dataset.thumbPending;
3174}
3175
3176function getThumbnailKind (name)
3177{
3178 const ext = extOf(name || '');
3179 if (IMAGE_EXTS.has(ext)) return 'image';
3180 if (CODE_EXTS.has(ext)) return 'text';
3181 return 'badge';
3182}
3183
3184function maxThumbBytesForKind (kind)
3185{
3186 if (kind === 'image') return 15 * 1024 * 1024;
3187 if (kind === 'text') return 1024 * 1024;
3188 return 0;
3189}
3190
3191function drawTokenizedLine (ctx, line, x, y)
3192{
3193 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;
3194 let last = 0;
3195 let cursor = x;
3196 for (const m of line.matchAll(tokenRe))
3197 {
3198 const i = m.index == null ? 0 : m.index;
3199 if (i > last)
3200 {
3201 const plain = line.slice(last, i);
3202 ctx.fillStyle = '#dce4ff';
3203 ctx.fillText(plain, cursor, y);
3204 cursor += ctx.measureText(plain).width;
3205 }
3206
3207 const tok = m[0];
3208 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
3209 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
3210 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
3211 else ctx.fillStyle = '#8bb4ff';
3212
3213 ctx.fillText(tok, cursor, y);
3214 cursor += ctx.measureText(tok).width;
3215 last = i + tok.length;
3216 }
3217
3218 if (last < line.length)
3219 {
3220 const tail = line.slice(last);
3221 ctx.fillStyle = '#dce4ff';
3222 ctx.fillText(tail, cursor, y);
3223 }
3224}
3225
3226function textThumbnailDataUrl (text)
3227{
3228 const canvas = document.createElement('canvas');
3229 canvas.width = 160;
3230 canvas.height = 200;
3231 const ctx = canvas.getContext('2d');
3232 if (!ctx) return null;
3233
3234 ctx.fillStyle = '#0d111a';
3235 ctx.fillRect(0, 0, canvas.width, canvas.height);
3236 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
3237 ctx.textBaseline = 'top';
3238
3239 const lines = String(text || '')
3240 .replace(/\r\n/g, '\n')
3241 .split('\n')
3242 .slice(0, 17);
3243
3244 let y = 8;
3245 for (const line of lines)
3246 {
3247 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
3248 y += 11;
3249 if (y > 190) break;
3250 }
3251 return canvas.toDataURL('image/png');
3252}
3253
3254function badgeThumbnailDataUrl (name, kind)
3255{
3256 const canvas = document.createElement('canvas');
3257 canvas.width = 160;
3258 canvas.height = 200;
3259 const ctx = canvas.getContext('2d');
3260 if (!ctx) return null;
3261
3262 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
3263 const color = '#5b7fff';
3264
3265 ctx.fillStyle = '#111826';
3266 ctx.fillRect(0, 0, 160, 200);
3267 ctx.fillStyle = color;
3268 ctx.fillRect(0, 0, 160, 28);
3269 ctx.fillStyle = '#ffffff';
3270 ctx.font = 'bold 12px sans-serif';
3271 ctx.textAlign = 'center';
3272 ctx.fillText(ext, 80, 8);
3273 ctx.textAlign = 'left';
3274 ctx.fillStyle = '#9fb1d8';
3275 ctx.font = '10px sans-serif';
3276 ctx.fillText('Preview', 8, 48);
3277 ctx.fillStyle = '#dce4ff';
3278 ctx.font = 'bold 11px sans-serif';
3279 ctx.fillText(ext, 8, 66);
3280 return canvas.toDataURL('image/png');
3281}
3282
3283async function buildThumbnailSource (item, blob, kind)
3284{
3285 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
3286 return badgeThumbnailDataUrl(item.name, kind);
3287}
3288
3289function observeThumbnailIcon (iconEl)
3290{
3291 if (!iconEl || !iconEl.isConnected) return;
3292 if (iconEl.dataset.thumbReady === '1') return;
3293
3294 if (!('IntersectionObserver' in window))
3295 {
3296 void loadOneThumbnail(iconEl);
3297 return;
3298 }
3299
3300 if (!STATE.thumbnailObserver)
3301 {
3302 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
3303 {
3304 for (const entry of entries)
3305 {
3306 if (!entry.isIntersecting) continue;
3307 const icon = entry.target;
3308 STATE.thumbnailObserver.unobserve(icon);
3309 void loadOneThumbnail(icon);
3310 }
3311 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
3312 }
3313
3314 STATE.thumbnailObserver.observe(iconEl);
3315}
3316
3317async function loadThumbnails ()
3318{
3319 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
3320 for (const icon of icons)
3321 {
3322 observeThumbnailIcon(icon);
3323 }
3324
3325 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
3326 for (const icon of folderIcons)
3327 {
3328 observeFolderIcon(icon);
3329 }
3330}
3331
3332async function loadOneThumbnail (iconEl)
3333{
3334 if (!iconEl.isConnected || !STATE.token) return;
3335 if (iconEl.dataset.thumbReady === '1') return;
3336 const filePath = iconEl.dataset.previewPath;
3337 const item = STATE.items.find(i => i.path === filePath);
3338 if (!item) return;
3339
3340 const kind = getThumbnailKind(item.name);
3341 let srcUrl = null;
3342
3343 if (kind === 'badge')
3344 {
3345 setThumbnailPending(iconEl, false);
3346 srcUrl = badgeThumbnailDataUrl(item.name, kind);
3347 }
3348 else if (kind === 'image')
3349 {
3350 const ext = extOf(item.name || '');
3351 const useDirectSvg =
3352 ext === 'svg' &&
3353 typeof item.size === 'number' &&
3354 item.size > 0 &&
3355 item.size <= MAX_DIRECT_SVG_THUMB_BYTES;
3356
3357 const url = useDirectSvg
3358 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
3359 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
3360
3361 let res;
3362 try
3363 {
3364 res = await fetch(url, {
3365 headers: {
3366 Authorization: `Bearer ${STATE.token}`,
3367 'X-Fp': getFingerprint(),
3368 },
3369 });
3370 } catch
3371 {
3372 return;
3373 }
3374
3375 if (!useDirectSvg && res.status === 404)
3376 {
3377 setThumbnailPending(iconEl, true);
3378 return;
3379 }
3380
3381 if (!res.ok || !iconEl.isConnected) return;
3382 setThumbnailPending(iconEl, false);
3383
3384 const blob = await res.blob();
3385 srcUrl = URL.createObjectURL(blob);
3386 STATE.thumbnailUrls.push(srcUrl);
3387 }
3388 else
3389 {
3390 setThumbnailPending(iconEl, false);
3391 const maxBytes = maxThumbBytesForKind(kind);
3392 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
3393 {
3394 srcUrl = badgeThumbnailDataUrl(item.name, kind);
3395 } else
3396 {
3397 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
3398
3399 let res;
3400 try
3401 {
3402 res = await fetch(url, {
3403 headers: {
3404 Authorization: `Bearer ${STATE.token}`,
3405 'X-Fp': getFingerprint(),
3406 },
3407 });
3408 } catch { return; }
3409 if (!res.ok || !iconEl.isConnected) return;
3410
3411 const blob = await res.blob();
3412 srcUrl = await buildThumbnailSource(item, blob, kind);
3413 }
3414 }
3415 if (!srcUrl || !iconEl.isConnected) return;
3416
3417 const svg = iconEl.querySelector('svg');
3418 if (!svg)
3419 {
3420 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
3421 return;
3422 }
3423
3424 const NS = 'http://www.w3.org/2000/svg';
3425 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
3426
3427 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
3428 const defs = document.createElementNS(NS, 'defs');
3429 const clipPath = document.createElementNS(NS, 'clipPath');
3430 clipPath.setAttribute('id', id);
3431 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
3432 const clipShape = document.createElementNS(NS, 'path');
3433 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
3434 clipPath.appendChild(clipShape);
3435 defs.appendChild(clipPath);
3436
3437 // Image fills the file bounding box; clip keeps it inside the outline
3438 const img = document.createElementNS(NS, 'image');
3439 img.setAttribute('href', srcUrl);
3440 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
3441 img.setAttribute('x', '4');
3442 img.setAttribute('y', '2');
3443 img.setAttribute('width', '16');
3444 img.setAttribute('height', '20');
3445 img.setAttribute('clip-path', `url(#${id})`);
3446 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
3447
3448 // Prepend so existing path/polyline elements (the outline) render on top
3449 svg.prepend(img);
3450 svg.prepend(defs);
3451 iconEl.dataset.thumbReady = '1';
3452}
3453
3454// ───────────────────────────────────────────────────────────────────────────
3455// FOLDER ICON THUMBNAILS
3456// ───────────────────────────────────────────────────────────────────────────
3457
3458function observeFolderIcon (iconEl)
3459{
3460 if (!iconEl || !iconEl.isConnected) return;
3461 if (iconEl.dataset.thumbReady === '1') return;
3462
3463 if (!('IntersectionObserver' in window))
3464 {
3465 void loadOneFolderIcon(iconEl);
3466 return;
3467 }
3468
3469 if (!STATE.folderIconObserver)
3470 {
3471 STATE.folderIconObserver = new IntersectionObserver((entries) =>
3472 {
3473 for (const entry of entries)
3474 {
3475 if (!entry.isIntersecting) continue;
3476 const icon = entry.target;
3477 STATE.folderIconObserver.unobserve(icon);
3478 void loadOneFolderIcon(icon);
3479 }
3480 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
3481 }
3482
3483 STATE.folderIconObserver.observe(iconEl);
3484}
3485
3486async function loadOneFolderIcon (iconEl)
3487{
3488 if (!iconEl.isConnected || !STATE.token) return;
3489 if (iconEl.dataset.thumbReady === '1') return;
3490
3491 const folderPath = iconEl.dataset.folderPath;
3492 if (!folderPath) return;
3493
3494 let res;
3495 try
3496 {
3497 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
3498 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3499 });
3500 } catch { return; }
3501
3502 if (!res.ok || !iconEl.isConnected) return;
3503
3504 const data = await res.json();
3505 if (!data.icon) return; // No icon available — keep plain folder SVG.
3506
3507 // Fetch the thumbnail through the auth-gated endpoint.
3508 let thumbRes;
3509 try
3510 {
3511 thumbRes = await fetch(
3512 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
3513 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
3514 );
3515 } catch { return; }
3516
3517 if (!thumbRes.ok || !iconEl.isConnected) return;
3518
3519 const blob = await thumbRes.blob();
3520 const srcUrl = URL.createObjectURL(blob);
3521 STATE.thumbnailUrls.push(srcUrl);
3522
3523 applyFolderThumbnail(iconEl, srcUrl);
3524}
3525
3526/**
3527 * Overlays a thumbnail image inside the folder SVG outline.
3528 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
3529 */
3530function applyFolderThumbnail (iconEl, srcUrl)
3531{
3532 if (!iconEl.isConnected) return;
3533 const svg = iconEl.querySelector('svg');
3534 if (!svg)
3535 {
3536 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
3537 return;
3538 }
3539
3540 const NS = 'http://www.w3.org/2000/svg';
3541 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
3542
3543 const defs = document.createElementNS(NS, 'defs');
3544 const clipPath = document.createElementNS(NS, 'clipPath');
3545 clipPath.setAttribute('id', id);
3546 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
3547 const clipShape = document.createElementNS(NS, 'path');
3548 // Folder outline path (same as iconFolder SVG path)
3549 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');
3550 clipPath.appendChild(clipShape);
3551 defs.appendChild(clipPath);
3552
3553 // Image covers the folder body area; clip keeps it inside the outline.
3554 const img = document.createElementNS(NS, 'image');
3555 img.setAttribute('href', srcUrl);
3556 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
3557 img.setAttribute('x', '2');
3558 img.setAttribute('y', '3');
3559 img.setAttribute('width', '20');
3560 img.setAttribute('height', '18');
3561 img.setAttribute('clip-path', `url(#${id})`);
3562 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
3563
3564 // Prepend so the folder outline strokes render on top.
3565 svg.prepend(img);
3566 svg.prepend(defs);
3567 iconEl.dataset.thumbReady = '1';
3568}
3569
3570function wireEvents ()
3571{
3572 // Auth form
3573 document.getElementById('auth-form').addEventListener('submit', async (e) =>
3574 {
3575 e.preventDefault();
3576 const username = document.getElementById('auth-username').value.trim();
3577 const password = document.getElementById('auth-password').value;
3578 const isSetup = e.target.dataset.mode === 'setup';
3579 const errEl = document.getElementById('auth-error');
3580 const btn = document.getElementById('auth-submit');
3581 btn.disabled = true;
3582 btn.textContent = 'Please wait…';
3583 const err = await doLogin(username, password, isSetup);
3584 if (err)
3585 {
3586 errEl.textContent = err;
3587 errEl.classList.remove('hidden');
3588 btn.disabled = false;
3589 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
3590 }
3591 });
3592
3593 // Logout
3594 document.getElementById('btn-logout').addEventListener('click', logout);
3595
3596 // Hard refresh while keeping auth/session state.
3597 document.getElementById('btn-refresh').addEventListener('click', () =>
3598 {
3599 saveSessionState();
3600 location.reload();
3601 });
3602
3603 // Upload button
3604 document.getElementById('btn-upload').addEventListener('click', () =>
3605 {
3606 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3607 if (!canWrite()) { toast('No write access.', 'err'); return; }
3608 document.getElementById('file-input').click();
3609 });
3610
3611 document.getElementById('file-input').addEventListener('change', async (e) =>
3612 {
3613 if (e.target.files.length) await uploadFiles(e.target.files);
3614 e.target.value = '';
3615 });
3616
3617 document.getElementById('btn-upload-folder').addEventListener('click', () =>
3618 {
3619 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3620 if (!canWrite()) { toast('No write access.', 'err'); return; }
3621 document.getElementById('folder-input').click();
3622 });
3623
3624 document.getElementById('folder-input').addEventListener('change', async (e) =>
3625 {
3626 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
3627 e.target.value = '';
3628 });
3629
3630 document.getElementById('btn-new-folder').addEventListener('click', async () =>
3631 {
3632 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3633 if (!canWrite()) { toast('No write access.', 'err'); return; }
3634
3635 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
3636 if (name == null) return;
3637 const folderName = name.trim();
3638 if (!folderName)
3639 {
3640 toast('Folder name is required.', 'err');
3641 return;
3642 }
3643
3644 try
3645 {
3646 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
3647 toast('Folder created.', 'ok');
3648 await navigateTo(STATE.currentDir, STATE.currentRoot);
3649 } catch (err)
3650 {
3651 toast(err.message, 'err');
3652 }
3653 });
3654
3655 document.getElementById('sidebar-close').addEventListener('click', (e) =>
3656 {
3657 e.stopPropagation();
3658 hideSidebarPanel();
3659 });
3660
3661 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
3662 const syncSidebarForViewport = () =>
3663 {
3664 if (isMobileViewport())
3665 {
3666 hideSidebarPanel();
3667 return;
3668 }
3669
3670 if (!STATE.selectedItem) openFolderSidebar();
3671 };
3672
3673 if (typeof mobileQuery.addEventListener === 'function')
3674 {
3675 mobileQuery.addEventListener('change', syncSidebarForViewport);
3676 } else if (typeof mobileQuery.addListener === 'function')
3677 {
3678 mobileQuery.addListener(syncSidebarForViewport);
3679 }
3680
3681 // Click outside grid clears selection and returns to folder sidebar info.
3682 document.getElementById('main-content').addEventListener('click', (e) =>
3683 {
3684 if (!e.target.closest('.file-item')) closeSidebar();
3685 });
3686
3687 // Admin panel
3688 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
3689 document.getElementById('admin-modal-close').addEventListener('click', () =>
3690 document.getElementById('admin-modal').classList.add('hidden'));
3691
3692 // Add path
3693 document.getElementById('admin-add-path').addEventListener('click', () =>
3694 {
3695 const val = document.getElementById('admin-new-path').value.trim();
3696 if (!val) return;
3697 const row = document.createElement('div');
3698 row.className = 'path-row';
3699 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
3700 row.querySelector('button').addEventListener('click', () => row.remove());
3701 document.getElementById('admin-paths').appendChild(row);
3702 document.getElementById('admin-new-path').value = '';
3703 });
3704
3705 // Save paths
3706 document.getElementById('admin-save-paths').addEventListener('click', async () =>
3707 {
3708 const rows = document.querySelectorAll('#admin-paths .path-row span');
3709 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
3710 try
3711 {
3712 await api('PUT', '/admin/config', { paths });
3713 toast('Paths saved.', 'ok');
3714 await loadRoots();
3715 } catch (err) { toast(err.message, 'err'); }
3716 });
3717
3718 // Shutdown server
3719 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
3720 {
3721 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
3722 try
3723 {
3724 await api('POST', '/admin/shutdown');
3725 toast('Server is shutting down…', 'ok');
3726 document.getElementById('admin-modal').classList.add('hidden');
3727 } catch
3728 {
3729 // Fetch may throw because the connection closes before a response arrives.
3730 toast('Server is shutting down…', 'ok');
3731 document.getElementById('admin-modal').classList.add('hidden');
3732 }
3733 });
3734
3735 // New user
3736 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
3737 {
3738 const cfg = await api('GET', '/admin/config');
3739 const paths = cfg ? (cfg.effectivePaths || []) : [];
3740 openUserModal(null, paths);
3741 });
3742
3743 // User modal close
3744 document.getElementById('user-modal-close').addEventListener('click', () =>
3745 document.getElementById('user-modal').classList.add('hidden'));
3746
3747 // Rename modal close
3748 document.getElementById('rename-modal-close').addEventListener('click', () =>
3749 document.getElementById('rename-modal').classList.add('hidden'));
3750
3751 // Close modals on backdrop click
3752 document.querySelectorAll('.modal-overlay').forEach(overlay =>
3753 {
3754 overlay.addEventListener('click', e =>
3755 {
3756 if (e.target === overlay) overlay.classList.add('hidden');
3757 });
3758 });
3759}
3760
3761// ───────────────────────────────────────────────────────────────────────────
3762// BOOT
3763// ───────────────────────────────────────────────────────────────────────────
3764
3765(async function boot ()
3766{
3767 wireEvents();
3768 initDragDrop();
3769 window.addEventListener('beforeunload', saveSessionState);
3770 await initAuth();
3771})();