BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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