BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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