BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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