BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

test
timfa Tim Falken · pushed by timfa · 5 months ago
3a9cbe01 History
app.js 210.3 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 previewVideoStreamSessionId: null,
54 previewSourceEl: null, // SVG element that triggered the preview
55 previewClosing: false, // guard to prevent double-close during animation
56 previewExpandState: null, // in-place expanded tile preview state
57 movePicker: null,
58
59 // Sidebar async loading guard to prevent stale updates on rapid selection changes.
60 sidebarLoadId: 0,
61 sidebarAbortController: null,
62
63 // Watched overlays are resolved asynchronously from /files/meta responses.
64 watchedStatusByPath: {},
65 watchedLoadId: 0,
66
67 // Cross-root file search mode (null = regular folder browsing).
68 searchQuery: null,
69
70 // Bust cache when favicon changes.
71 faviconVersion: Date.now(),
72};
73
74const SESSION_KEY = 'filemanager.session.v1';
75const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
76const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
77const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
78const MOBILE_LONG_PRESS_MS = 420;
79const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
80const THUMB_OBSERVER_ROOT_MARGIN = '120px';
81const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
82const FOLDER_VIEW_PREFS_KEY_PREFIX = 'filemanager.folder-view-prefs.v1.';
83const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
84const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
85 backgroundOpacity: '0',
86 edgeStyle: 'uniform',
87});
88const DEFAULT_FOLDER_VIEW_PREFS = {
89 sortBy: 'alphabetical',
90 groupBy: 'none',
91 foldersFirst: true,
92 ascending: true,
93};
94const FOLDER_SORT_OPTIONS = [
95 { value: 'alphabetical', label: 'Alphabetically' },
96 { value: 'fileType', label: 'File type' },
97 { value: 'lastChanged', label: 'Last changed' },
98 { value: 'timeUploaded', label: 'Time uploaded' },
99 { value: 'size', label: 'Size' },
100];
101const FOLDER_GROUP_OPTIONS = [
102 { value: 'none', label: 'None' },
103 { value: 'alphabetical', label: 'Alphabetically' },
104 { value: 'fileType', label: 'File type' },
105 { value: 'lastChangedDate', label: 'Last changed date' },
106 { value: 'timeUploadedDate', label: 'Upload date' },
107 { value: 'size', label: 'Size' },
108];
109const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
110const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
111const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
112let videoJsLoaderPromise = null;
113let threePreviewModulesPromise = null;
114
115// ───────────────────────────────────────────────────────────────────────────
116// CRYPTO HELPERS (Web Crypto API)
117// ───────────────────────────────────────────────────────────────────────────
118
119async function generateClientKeyPair ()
120{
121 if (!hasWebCrypto()) return;
122 const kp = await crypto.subtle.generateKey(
123 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
124 true,
125 ['encrypt', 'decrypt'],
126 );
127 STATE.clientPrivateKey = kp.privateKey;
128 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
129}
130
131/**
132 * Hybrid-encrypt a JS object using the server's RSA public key.
133 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
134 */
135async function hybridEncryptForServer (obj)
136{
137 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
138 {
139 return { plaintext: obj };
140 }
141
142 const serverPub = await crypto.subtle.importKey(
143 'jwk', STATE.serverPublicKeyJwk,
144 { name: 'RSA-OAEP', hash: 'SHA-256' },
145 false, ['encrypt'],
146 );
147
148 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
149 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
150 const iv = crypto.getRandomValues(new Uint8Array(12));
151 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
152
153 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
154 const gcmBytes = new Uint8Array(gcmResult);
155 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
156 const tag = gcmBytes.slice(gcmBytes.length - 16);
157
158 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
159 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
160
161 return {
162 encryptedKey: b64(encryptedKey),
163 iv: b64(iv),
164 ciphertext: b64(ciphertext),
165 tag: b64(tag),
166 };
167}
168
169/**
170 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
171 */
172async function hybridDecryptFromServer (payload)
173{
174 if (!payload) return null;
175 if (payload.token) return payload.token;
176 if (!hasWebCrypto()) return null;
177
178 const encryptedKey = unb64(payload.encryptedKey);
179 const iv = unb64(payload.iv);
180 const ciphertext = unb64(payload.ciphertext);
181 const tag = unb64(payload.tag);
182
183 const rawAes = await crypto.subtle.decrypt(
184 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
185 );
186
187 const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']);
188
189 // Recombine ciphertext + tag for AES-GCM
190 const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength);
191 combined.set(new Uint8Array(ciphertext));
192 combined.set(new Uint8Array(tag), ciphertext.byteLength);
193
194 const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined);
195 return new TextDecoder().decode(plain);
196}
197
198// ───────────────────────────────────────────────────────────────────────────
199// UTIL
200// ───────────────────────────────────────────────────────────────────────────
201
202function b64 (buf)
203{
204 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
205}
206
207function hasWebCrypto ()
208{
209 return !!(window.crypto && window.crypto.subtle);
210}
211
212function unb64 (str)
213{
214 const binary = atob(str);
215 const buf = new Uint8Array(binary.length);
216 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
217 return buf.buffer;
218}
219
220/** Stable browser fingerprint (not stored, derived fresh each load) */
221function getFingerprint ()
222{
223 const binding = getOrCreateClientBindingId();
224 const nav = navigator;
225
226 // Keep this stable: avoid viewport/screen metrics that can change when
227 // devtools opens, orientation changes, or window state changes.
228 return [
229 binding,
230 nav.userAgent || '',
231 nav.language,
232 nav.platform || nav.userAgentData?.platform || '',
233 Intl.DateTimeFormat().resolvedOptions().timeZone,
234 ].join('|');
235}
236
237function randomIdHex (bytes = 16)
238{
239 const arr = new Uint8Array(bytes);
240 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
241 {
242 window.crypto.getRandomValues(arr);
243 } else
244 {
245 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
246 }
247 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
248}
249
250function userVideoPrefsKey ()
251{
252 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
253 return VIDEO_PREFS_KEY_PREFIX + name;
254}
255
256function loadUserVideoPrefs ()
257{
258 try
259 {
260 const raw = localStorage.getItem(userVideoPrefsKey());
261 const parsed = raw ? JSON.parse(raw) : {};
262 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
263 return parsed;
264 } catch
265 {
266 return {};
267 }
268}
269
270function saveUserVideoPrefs (patch)
271{
272 try
273 {
274 const current = loadUserVideoPrefs();
275 localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) }));
276 } catch
277 {
278 // Ignore localStorage failures.
279 }
280}
281
282function userFolderViewPrefsKey ()
283{
284 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
285 return FOLDER_VIEW_PREFS_KEY_PREFIX + name;
286}
287
288function normaliseFolderViewPrefs (value)
289{
290 const input = value && typeof value === 'object' ? value : {};
291 const sortBy = ['alphabetical', 'fileType', 'lastChanged', 'timeUploaded', 'size'].includes(input.sortBy)
292 ? input.sortBy
293 : DEFAULT_FOLDER_VIEW_PREFS.sortBy;
294 const groupBy = ['none', 'alphabetical', 'fileType', 'lastChangedDate', 'timeUploadedDate', 'size'].includes(input.groupBy)
295 ? input.groupBy
296 : DEFAULT_FOLDER_VIEW_PREFS.groupBy;
297
298 return {
299 sortBy,
300 groupBy,
301 foldersFirst: input.foldersFirst !== undefined ? !!input.foldersFirst : DEFAULT_FOLDER_VIEW_PREFS.foldersFirst,
302 ascending: input.ascending !== undefined ? !!input.ascending : DEFAULT_FOLDER_VIEW_PREFS.ascending,
303 };
304}
305
306function loadFolderViewPrefsMap ()
307{
308 try
309 {
310 const raw = localStorage.getItem(userFolderViewPrefsKey());
311 const parsed = raw ? JSON.parse(raw) : {};
312 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
313
314 const out = {};
315 for (const [dirPath, prefs] of Object.entries(parsed))
316 {
317 out[String(dirPath)] = normaliseFolderViewPrefs(prefs);
318 }
319 return out;
320 } catch
321 {
322 return {};
323 }
324}
325
326function saveFolderViewPrefsMap (prefsByPath)
327{
328 try
329 {
330 localStorage.setItem(userFolderViewPrefsKey(), JSON.stringify(prefsByPath || {}));
331 } catch
332 {
333 // Ignore localStorage failures.
334 }
335}
336
337function folderViewPrefsForDir (dirPath)
338{
339 if (!dirPath) return { ...DEFAULT_FOLDER_VIEW_PREFS };
340 const prefsByPath = loadFolderViewPrefsMap();
341 return normaliseFolderViewPrefs(prefsByPath[String(dirPath)] || DEFAULT_FOLDER_VIEW_PREFS);
342}
343
344function saveFolderViewPrefsForDir (dirPath, patch)
345{
346 if (!dirPath) return;
347 const key = String(dirPath);
348 const prefsByPath = loadFolderViewPrefsMap();
349 const current = normaliseFolderViewPrefs(prefsByPath[key] || DEFAULT_FOLDER_VIEW_PREFS);
350 prefsByPath[key] = normaliseFolderViewPrefs({ ...current, ...(patch || {}) });
351 saveFolderViewPrefsMap(prefsByPath);
352}
353
354function buildAuthHeaders ()
355{
356 const headers = {};
357 if (STATE.token)
358 {
359 headers.Authorization = 'Bearer ' + STATE.token;
360 try
361 {
362 const fp = getFingerprint();
363 if (fp) headers['X-Fp'] = fp;
364 } catch
365 {
366 // Continue without a fingerprint header in constrained test/runtime contexts.
367 }
368 }
369 return headers;
370}
371
372function applyUserVideoTextTrackPrefs ()
373{
374 const shared = sharedVideoPlayer();
375 if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return;
376 shared.applyDefaultTextTrackPrefs();
377}
378
379function sharedVideoPlayer ()
380{
381 return window.FilemanagerSharedVideoPlayer || null;
382}
383
384function bindUserVideoTrackPrefs (player, prefs)
385{
386 const shared = sharedVideoPlayer();
387 if (!shared || typeof shared.bindTrackPrefs !== 'function')
388 {
389 return {
390 applySavedTracks: () => { },
391 captureSelectedTracks: () => { },
392 detach: () => { },
393 };
394 }
395 return shared.bindTrackPrefs(player, prefs, saveUserVideoPrefs);
396}
397
398function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
399{
400 const shared = sharedVideoPlayer();
401 if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
402
403 const sendSubtitleLogBatch = (entries) =>
404 {
405 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
406
407 const headers = {
408 ...buildAuthHeaders(),
409 'Content-Type': 'application/json',
410 };
411
412 return fetch('/api/files/video-stream-subtitle-log', {
413 method: 'POST',
414 headers,
415 credentials: 'same-origin',
416 keepalive: true,
417 body: JSON.stringify({
418 filePath: item.path,
419 sessionId: session.sessionId || null,
420 entries,
421 }),
422 }).catch(() => null);
423 };
424
425 return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
426 savePrefs: saveUserVideoPrefs,
427 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
428 sendSubtitleLogBatch,
429 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
430 url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
431 headers: buildAuthHeaders(),
432 credentials: 'same-origin',
433 }),
434 onError: () => toast('Image subtitles could not be rendered for this file.', 'err'),
435 });
436}
437
438function normaliseVideoDuration (player, durationSeconds)
439{
440 const shared = sharedVideoPlayer();
441 if (!shared || typeof shared.normaliseVideoDuration !== 'function') return;
442 shared.normaliseVideoDuration(player, durationSeconds);
443}
444
445function ensureVideoPlaybackUi (player, durationSeconds)
446{
447 const shared = sharedVideoPlayer();
448 if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return;
449 shared.ensureVideoPlaybackUi(player, durationSeconds);
450}
451
452async function reportWatchProgress (filePath, progress)
453{
454 if (!filePath || !Number.isFinite(progress)) return;
455 await api('POST', '/files/watch-progress', {
456 filePath,
457 progress,
458 }).catch(() => null);
459
460 const nextStatus = progress >= 0.7 ? 'fully' : progress >= 0.1 ? 'partway' : null;
461 if (!nextStatus) return;
462
463 const prev = STATE.watchedStatusByPath[filePath];
464 if (prev === 'fully') return;
465 STATE.watchedStatusByPath[filePath] = nextStatus;
466
467 const iconEl = findTileIconByPath(filePath);
468 renderWatchedOverlayOnIcon(iconEl, nextStatus);
469}
470
471function getOrCreateClientBindingId ()
472{
473 if (STATE.clientBindingId) return STATE.clientBindingId;
474
475 try
476 {
477 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
478 if (existing && typeof existing === 'string')
479 {
480 STATE.clientBindingId = existing;
481 return existing;
482 }
483 } catch
484 {
485 // Ignore storage read errors.
486 }
487
488 const created = randomIdHex(16);
489 STATE.clientBindingId = created;
490
491 try
492 {
493 localStorage.setItem(CLIENT_BINDING_KEY, created);
494 } catch
495 {
496 // Ignore storage write errors; in-memory fallback still keeps this stable
497 // for the current page session.
498 }
499
500 return created;
501}
502
503function formatBytes (bytes)
504{
505 if (bytes == null) return '—';
506 if (bytes < 1024) return bytes + ' B';
507 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
508 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
509 return (bytes / 1073741824).toFixed(2) + ' GB';
510}
511
512function parseHumanSize (input)
513{
514 const raw = String(input || '').trim();
515 if (!raw) return null;
516
517 const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i);
518 if (!m) return null;
519
520 const value = Number(m[1]);
521 if (!Number.isFinite(value) || value <= 0) return null;
522
523 const unit = String(m[2] || '').toLowerCase();
524 const multipliers = {
525 '': 1,
526 k: 1024,
527 m: 1024 * 1024,
528 g: 1024 * 1024 * 1024,
529 t: 1024 * 1024 * 1024 * 1024,
530 };
531 return Math.floor(value * (multipliers[unit] || 1));
532}
533
534function updateAdminSizeFeedback (rawValue)
535{
536 const feedback = document.getElementById('admin-user-size-feedback');
537 if (!feedback) return { bytes: null, valid: true };
538
539 const trimmed = String(rawValue || '').trim();
540 if (!trimmed)
541 {
542 feedback.textContent = '';
543 feedback.classList.add('hidden');
544 feedback.classList.remove('ok', 'err');
545 return { bytes: null, valid: true };
546 }
547
548 const bytes = parseHumanSize(trimmed);
549 feedback.classList.remove('hidden', 'ok', 'err');
550 if (bytes == null)
551 {
552 feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.';
553 feedback.classList.add('err');
554 return { bytes: null, valid: false };
555 }
556
557 feedback.textContent = `Valid size: ${formatBytes(bytes)}`;
558 feedback.classList.add('ok');
559 return { bytes, valid: true };
560}
561
562function extOf (name)
563{
564 const i = name.lastIndexOf('.');
565 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
566}
567
568function getPathSep (basePath)
569{
570 return basePath && basePath.includes('\\') ? '\\' : '/';
571}
572
573function joinServerPath (basePath, segment)
574{
575 const sep = getPathSep(basePath);
576 const base = String(basePath || '').replace(/[\\/]+$/, '');
577 return base + sep + segment;
578}
579
580function samePath (a, b)
581{
582 if (!a || !b) return false;
583 return String(a).toLowerCase() === String(b).toLowerCase();
584}
585
586function pathInside (child, root)
587{
588 if (!child || !root) return false;
589 if (samePath(child, root)) return true;
590 const sep = getPathSep(root);
591 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
592}
593
594function relativePathFromRoot (targetPath, rootPath)
595{
596 if (!targetPath || !rootPath) return String(targetPath || '');
597 if (samePath(targetPath, rootPath)) return '.';
598
599 const prefix = String(rootPath).replace(/[\\/]+$/, '');
600 const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, '');
601 if (!rel) return '.';
602 return rel;
603}
604
605function displayPathWithRootLabel (targetPath, rootPath, rootLabel)
606{
607 const rel = relativePathFromRoot(targetPath, rootPath);
608 const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, '');
609 if (!safeRoot) return '/';
610 if (rel === '.') return `/${safeRoot}`;
611 return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`;
612}
613
614function splitNameExt (name)
615{
616 const dot = String(name || '').lastIndexOf('.');
617 if (dot <= 0) return { stem: String(name || ''), ext: '' };
618 return {
619 stem: String(name).slice(0, dot),
620 ext: String(name).slice(dot),
621 };
622}
623
624function nextAvailableName (requestedName, existingNames)
625{
626 const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []);
627 if (!set.has(requestedName)) return requestedName;
628
629 const { stem, ext } = splitNameExt(requestedName);
630 let n = 1;
631 while (n <= 10000)
632 {
633 const candidate = `${stem || 'file'} (${n})${ext}`;
634 if (!set.has(candidate)) return candidate;
635 n++;
636 }
637
638 return requestedName;
639}
640
641async function listDirNameSet (dir)
642{
643 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`);
644 const names = new Set();
645 for (const it of ((data && data.items) || [])) names.add(it.name);
646 return names;
647}
648
649function cloneFileWithName (file, newName)
650{
651 return new File([file], newName, {
652 type: file.type,
653 lastModified: file.lastModified,
654 });
655}
656
657function saveSessionState ()
658{
659 if (!STATE.token) return;
660 const now = Date.now();
661 STATE.lastOperationAt = now;
662 const payload = {
663 token: STATE.token,
664 dir: STATE.currentDir || null,
665 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
666 lastOperationAt: STATE.lastOperationAt,
667 };
668 try
669 {
670 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
671 } catch
672 {
673 // Ignore storage errors (private mode/full quota).
674 }
675}
676
677function loadSessionState ()
678{
679 try
680 {
681 const raw = localStorage.getItem(SESSION_KEY);
682 if (!raw) return null;
683 const parsed = JSON.parse(raw);
684 if (!parsed || typeof parsed.token !== 'string') return null;
685 if (!Number.isFinite(parsed.lastOperationAt)) return null;
686
687 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
688 {
689 clearSessionState();
690 return null;
691 }
692
693 return parsed;
694 } catch
695 {
696 return null;
697 }
698}
699
700function clearSessionState ()
701{
702 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
703}
704
705// ───────────────────────────────────────────────────────────────────────────
706// API
707// ───────────────────────────────────────────────────────────────────────────
708
709async function api (method, path, body, opts = {})
710{
711 const headers = { 'Content-Type': 'application/json' };
712 const noAutoLogout = !!opts.noAutoLogout;
713 if (STATE.token)
714 {
715 headers['Authorization'] = 'Bearer ' + STATE.token;
716 try
717 {
718 const fp = getFingerprint();
719 if (fp) headers['X-Fp'] = fp;
720 } catch
721 {
722 // Continue without a fingerprint header in constrained test/runtime contexts.
723 }
724 }
725 const fetchOpts = { ...opts };
726 delete fetchOpts.noAutoLogout;
727 const res = await fetch('/api' + path, {
728 method,
729 headers,
730 body: body != null ? JSON.stringify(body) : undefined,
731 ...fetchOpts,
732 });
733 if (!res.ok)
734 {
735 const j = await res.json().catch(() => ({}));
736 // Session-expired → force re-login
737 if (res.status === 401)
738 {
739 if (!noAutoLogout) logout();
740 return null;
741 }
742 throw new Error(j.error || res.statusText);
743 }
744 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
745 {
746 saveSessionState();
747 }
748 return res.json();
749}
750
751// ───────────────────────────────────────────────────────────────────────────
752// TOAST
753// ───────────────────────────────────────────────────────────────────────────
754
755function toast (msg, type = '')
756{
757 const el = document.createElement('div');
758 el.className = 'toast-msg' + (type ? ' ' + type : '');
759 el.textContent = msg;
760 document.getElementById('toast').appendChild(el);
761 setTimeout(() => el.remove(), 3500);
762}
763
764// ───────────────────────────────────────────────────────────────────────────
765// DIALOG MODALS — centralised replacements for alert / confirm / prompt
766// ───────────────────────────────────────────────────────────────────────────
767
768/**
769 * Show a confirmation dialog.
770 * @param {string} title
771 * @param {string} message
772 * @returns {Promise<boolean>} true = OK, false = Cancel
773 */
774function showConfirm (title, message, { html = false, okLabel = null, modalClass = '' } = {})
775{
776 return new Promise((resolve) =>
777 {
778 const overlay = document.getElementById('confirm-modal');
779 const dialogEl = overlay ? overlay.querySelector('.modal') : null;
780 const className = typeof modalClass === 'string' ? modalClass.trim() : '';
781 document.getElementById('confirm-modal-title').textContent = title;
782 const msgEl = document.getElementById('confirm-modal-message');
783 if (html) msgEl.innerHTML = message;
784 else msgEl.textContent = message;
785 if (dialogEl && className) dialogEl.classList.add(className);
786 overlay.classList.remove('hidden');
787
788 const ok = document.getElementById('confirm-modal-ok');
789 const prevOkLabel = ok.textContent;
790 if (okLabel != null) ok.textContent = okLabel;
791
792 const cancel = document.getElementById('confirm-modal-cancel');
793
794 function finish (result)
795 {
796 overlay.classList.add('hidden');
797 if (dialogEl && className) dialogEl.classList.remove(className);
798 ok.textContent = prevOkLabel;
799 ok.removeEventListener('click', onOk);
800 cancel.removeEventListener('click', onCancel);
801 resolve(result);
802 }
803 function onOk () { finish(true); }
804 function onCancel () { finish(false); }
805
806 ok.addEventListener('click', onOk);
807 cancel.addEventListener('click', onCancel);
808 ok.focus();
809 });
810}
811
812function escHtml (s)
813{
814 return String(s || '')
815 .replace(/&/g, '&amp;')
816 .replace(/</g, '&lt;')
817 .replace(/>/g, '&gt;')
818 .replace(/"/g, '&quot;');
819}
820
821function normaliseUpdateCommits (commitsAhead)
822{
823 if (!Array.isArray(commitsAhead)) return [];
824
825 const out = [];
826 for (const raw of commitsAhead)
827 {
828 if (typeof raw === 'string')
829 {
830 const line = raw.trim();
831 if (!line) continue;
832 const match = line.match(/^([0-9a-f]{7,40})\s+(.+)$/i);
833 out.push({
834 hash: match ? match[1] : '',
835 subject: match ? match[2].trim() : line,
836 body: '',
837 });
838 continue;
839 }
840
841 if (!raw || typeof raw !== 'object') continue;
842 const subject = String(raw.subject || '').trim();
843 if (!subject) continue;
844 out.push({
845 hash: String(raw.hash || '').trim(),
846 subject,
847 body: String(raw.body || '').trim(),
848 });
849 }
850
851 return out;
852}
853
854function renderUpdateCommitListHtml (commitsAhead)
855{
856 const commits = normaliseUpdateCommits(commitsAhead);
857 if (!commits.length) return '';
858
859 const commitItems = commits.map((commit) =>
860 {
861 const hashLabel = commit.hash
862 ? `<span class="update-commit-hash">${escHtml(commit.hash.slice(0, 7))}</span>`
863 : '';
864 const subjectLabel = `<span class="update-commit-subject">${escHtml(commit.subject)}</span>`;
865
866 const bodyHtml = commit.body
867 ? `<p class="update-commit-body">${escHtml(commit.body).replace(/\n/g, '<br/>')}</p>`
868 : '';
869
870 return `<article class="update-commit-item"><h3>${hashLabel}${hashLabel ? ' ' : ''}${subjectLabel}</h3>${bodyHtml}</article>`;
871 }).join('');
872
873 return `<div class="update-commit-list">${commitItems}</div>`;
874}
875
876/**
877 * Show a text-input dialog.
878 * @param {string} title
879 * @param {string} [message] — optional helper text shown above the input
880 * @param {string} [defaultValue] — pre-filled value
881 * @returns {Promise<string|null>} string = submitted value, null = cancelled
882 */
883function showPrompt (title, message = '', defaultValue = '')
884{
885 return new Promise((resolve) =>
886 {
887 const overlay = document.getElementById('prompt-modal');
888 const msgEl = document.getElementById('prompt-modal-message');
889 const input = document.getElementById('prompt-modal-input');
890 const errorEl = document.getElementById('prompt-modal-error');
891 const form = document.getElementById('prompt-modal-form');
892 const cancel = document.getElementById('prompt-modal-cancel');
893
894 document.getElementById('prompt-modal-title').textContent = title;
895 msgEl.textContent = message;
896 msgEl.classList.toggle('hidden', !message);
897 input.value = defaultValue;
898 errorEl.classList.add('hidden');
899 overlay.classList.remove('hidden');
900 input.focus();
901 input.select();
902
903 function finish (result)
904 {
905 overlay.classList.add('hidden');
906 form.removeEventListener('submit', onSubmit);
907 cancel.removeEventListener('click', onCancel);
908 resolve(result);
909 }
910 function onSubmit (e)
911 {
912 e.preventDefault();
913 finish(input.value);
914 }
915 function onCancel () { finish(null); }
916
917 form.addEventListener('submit', onSubmit);
918 cancel.addEventListener('click', onCancel);
919 });
920}
921
922/**
923 * Show an overwrite-decision dialog for a single file conflict.
924 * @param {string} filename
925 * @returns {Promise<'yes'|'no'|'all'|'none'>}
926 */
927function showOverwrite (filename)
928{
929 return new Promise((resolve) =>
930 {
931 const overlay = document.getElementById('overwrite-modal');
932 document.getElementById('overwrite-modal-filename').textContent = filename;
933 overlay.classList.remove('hidden');
934
935 const btnYes = document.getElementById('overwrite-modal-yes');
936 const btnNo = document.getElementById('overwrite-modal-no');
937 const btnAll = document.getElementById('overwrite-modal-all');
938 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
939
940 function finish (result)
941 {
942 overlay.classList.add('hidden');
943 btnYes.removeEventListener('click', onYes);
944 btnNo.removeEventListener('click', onNo);
945 btnAll.removeEventListener('click', onAll);
946 btnSkipAll.removeEventListener('click', onSkipAll);
947 resolve(result);
948 }
949 function onYes () { finish('yes'); }
950 function onNo () { finish('no'); }
951 function onAll () { finish('all'); }
952 function onSkipAll () { finish('none'); }
953
954 btnYes.addEventListener('click', onYes);
955 btnNo.addEventListener('click', onNo);
956 btnAll.addEventListener('click', onAll);
957 btnSkipAll.addEventListener('click', onSkipAll);
958 btnNo.focus();
959 });
960}
961
962/**
963 * Show single-file conflict options.
964 * @param {string} filename
965 * @param {string} renameTo
966 * @param {string} mode - upload|move
967 * @returns {Promise<'overwrite'|'rename'|'cancel'>}
968 */
969function showFileConflictChoice (filename, renameTo, mode = 'upload')
970{
971 return new Promise((resolve) =>
972 {
973 const overlay = document.getElementById('file-conflict-modal');
974 const title = document.getElementById('file-conflict-title');
975 const fileEl = document.getElementById('file-conflict-filename');
976 const renameEl = document.getElementById('file-conflict-rename');
977 const btnOverwrite = document.getElementById('file-conflict-overwrite');
978 const btnRename = document.getElementById('file-conflict-rename-btn');
979 const btnCancel = document.getElementById('file-conflict-cancel');
980
981 title.textContent = mode === 'move' ? 'Move file' : 'Upload file';
982 fileEl.textContent = filename;
983 renameEl.textContent = renameTo;
984 btnRename.textContent = `Rename (${renameTo})`;
985
986 overlay.classList.remove('hidden');
987
988 function finish (result)
989 {
990 overlay.classList.add('hidden');
991 btnOverwrite.removeEventListener('click', onOverwrite);
992 btnRename.removeEventListener('click', onRename);
993 btnCancel.removeEventListener('click', onCancel);
994 resolve(result);
995 }
996
997 function onOverwrite () { finish('overwrite'); }
998 function onRename () { finish('rename'); }
999 function onCancel () { finish('cancel'); }
1000
1001 btnOverwrite.addEventListener('click', onOverwrite);
1002 btnRename.addEventListener('click', onRename);
1003 btnCancel.addEventListener('click', onCancel);
1004 btnCancel.focus();
1005 });
1006}
1007
1008// ───────────────────────────────────────────────────────────────────────────
1009// SHARE MODAL
1010// ───────────────────────────────────────────────────────────────────────────
1011
1012async function openShareModal (item)
1013{
1014 const overlay = document.getElementById('share-modal');
1015 const urlInput = document.getElementById('share-url-input');
1016 const copyBtn = document.getElementById('share-copy-btn');
1017 const okBtn = document.getElementById('share-modal-ok');
1018 const closeBtn = document.getElementById('share-modal-close');
1019 const msgEl = document.getElementById('share-modal-msg');
1020
1021 urlInput.value = 'Creating link...';
1022 copyBtn.disabled = true;
1023 msgEl.textContent = 'This link is valid for 24 hours.';
1024 overlay.classList.remove('hidden');
1025
1026 let data;
1027 try
1028 {
1029 data = await api('POST', '/share/create', { filePath: item.path });
1030 } catch (err)
1031 {
1032 msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.');
1033 urlInput.value = '';
1034 return;
1035 }
1036
1037 if (!data || !data.token)
1038 {
1039 msgEl.textContent = 'Unknown error while creating link.';
1040 urlInput.value = '';
1041 return;
1042 }
1043
1044 const shareUrl = `${location.origin}/share/${data.token}`;
1045 urlInput.value = shareUrl;
1046 copyBtn.disabled = false;
1047
1048 function close ()
1049 {
1050 overlay.classList.add('hidden');
1051 okBtn.removeEventListener('click', close);
1052 closeBtn.removeEventListener('click', close);
1053 copyBtn.removeEventListener('click', onCopy);
1054 }
1055
1056 function onCopy ()
1057 {
1058 navigator.clipboard.writeText(shareUrl).then(() =>
1059 {
1060 const orig = copyBtn.textContent;
1061 copyBtn.textContent = 'Copied!';
1062 setTimeout(() => { copyBtn.textContent = orig; }, 1500);
1063 }).catch(() =>
1064 {
1065 // Fallback: select the text
1066 urlInput.select();
1067 });
1068 }
1069
1070 okBtn.addEventListener('click', close);
1071 closeBtn.addEventListener('click', close);
1072 copyBtn.addEventListener('click', onCopy);
1073 okBtn.focus();
1074}
1075
1076// ───────────────────────────────────────────────────────────────────────────
1077// AUTH FLOW
1078// ───────────────────────────────────────────────────────────────────────────
1079
1080function showAuthOverlay (setupMode = false)
1081{
1082 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1083 closeDebugModal();
1084 document.getElementById('app').classList.add('hidden');
1085 const overlay = document.getElementById('auth-overlay');
1086 const usernameInput = document.getElementById('auth-username');
1087 const passwordInput = document.getElementById('auth-password');
1088 overlay.classList.remove('hidden');
1089 document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
1090 document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
1091 const submitBtn = document.getElementById('auth-submit');
1092 submitBtn.disabled = false;
1093 submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
1094 document.getElementById('auth-error').classList.add('hidden');
1095 usernameInput.value = '';
1096 passwordInput.value = '';
1097 usernameInput.autocomplete = 'username';
1098 passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password';
1099 usernameInput.focus();
1100 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
1101}
1102
1103function showApp ()
1104{
1105 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1106 document.getElementById('auth-overlay').classList.add('hidden');
1107 document.getElementById('app').classList.remove('hidden');
1108 if (isMobileViewport())
1109 {
1110 hideSidebarPanel();
1111 } else
1112 {
1113 openFolderSidebar();
1114 }
1115 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1116 document.getElementById('btn-debug').classList.toggle('hidden', !STATE.isAdmin);
1117 const userLabel = document.getElementById('user-menu-label');
1118 if (userLabel) userLabel.textContent = STATE.username || 'User';
1119 void refreshGlobalFavicon();
1120 if (STATE.isAdmin)
1121 {
1122 void refreshAdminUpdateStatus();
1123 }
1124 else
1125 {
1126 setAdminUpdateBadge(0);
1127 }
1128 startAutoRefresh();
1129}
1130
1131async function initAuth ()
1132{
1133 // Generate a fresh key pair in the background; login falls back gracefully
1134 // while this is still in progress.
1135 generateClientKeyPair().catch(() =>
1136 {
1137 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
1138 });
1139
1140 // Fetch server public key
1141 const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));
1142 if (publicKey) STATE.serverPublicKeyJwk = publicKey;
1143 if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }
1144 STATE.serverPublicKeyJwk = publicKey;
1145
1146 // Check whether first-run setup is needed
1147 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
1148
1149 if (!needed)
1150 {
1151 const saved = loadSessionState();
1152 if (saved && saved.token)
1153 {
1154 STATE.token = saved.token;
1155 STATE.restoreDir = saved.dir || null;
1156 STATE.restoreRootPath = saved.rootPath || null;
1157 STATE.lastOperationAt = saved.lastOperationAt;
1158
1159 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
1160 if (me)
1161 {
1162 STATE.username = me.username;
1163 STATE.isAdmin = me.isAdmin;
1164 STATE.permissions = me.permissions;
1165 showApp();
1166 await loadRoots({
1167 preferredDir: STATE.restoreDir,
1168 preferredRootPath: STATE.restoreRootPath,
1169 });
1170 return;
1171 }
1172
1173 STATE.token = null;
1174 clearSessionState();
1175 }
1176 }
1177
1178 showAuthOverlay(needed);
1179}
1180
1181async function doLogin (username, password, isSetup)
1182{
1183 const encrypted = await hybridEncryptForServer({ username, password });
1184 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
1185
1186 let data;
1187 try
1188 {
1189 data = await api('POST', endpoint, {
1190 encrypted,
1191 clientPublicKey: STATE.clientPublicKeyJwk,
1192 fingerprint: getFingerprint(),
1193 });
1194 } catch (err)
1195 {
1196 return err.message;
1197 }
1198
1199 if (!data) return 'Login failed.';
1200
1201 // Decrypt the token sent back by the server
1202 const token = await hybridDecryptFromServer(data.encrypted || data);
1203 if (!token) return 'Login failed.';
1204 STATE.token = token;
1205
1206 // Load user info
1207 const me = await api('GET', '/auth/me');
1208 if (!me) return 'Session error.';
1209
1210 STATE.username = me.username;
1211 STATE.isAdmin = me.isAdmin;
1212 STATE.permissions = me.permissions;
1213
1214 saveSessionState();
1215 showApp();
1216 await loadRoots();
1217 return null; // no error
1218}
1219
1220function logout ()
1221{
1222 void performLogout();
1223}
1224
1225function openChangePasswordModal ()
1226{
1227 const modal = document.getElementById('change-password-modal');
1228 const form = document.getElementById('change-password-form');
1229 const currentInput = document.getElementById('change-password-current');
1230 const nextInput = document.getElementById('change-password-next');
1231 const confirmInput = document.getElementById('change-password-confirm');
1232 const errorEl = document.getElementById('change-password-error');
1233
1234 function hide ()
1235 {
1236 modal.classList.add('hidden');
1237 form.onsubmit = null;
1238 }
1239
1240 currentInput.value = '';
1241 nextInput.value = '';
1242 confirmInput.value = '';
1243 errorEl.textContent = '';
1244 errorEl.classList.add('hidden');
1245 modal.classList.remove('hidden');
1246 currentInput.focus();
1247
1248 form.onsubmit = async (e) =>
1249 {
1250 e.preventDefault();
1251 const currentPassword = currentInput.value;
1252 const newPassword = nextInput.value;
1253 const confirmPassword = confirmInput.value;
1254
1255 if (newPassword !== confirmPassword)
1256 {
1257 errorEl.textContent = 'New passwords do not match.';
1258 errorEl.classList.remove('hidden');
1259 return;
1260 }
1261
1262 if (newPassword.length < 8)
1263 {
1264 errorEl.textContent = 'New password must be at least 8 characters.';
1265 errorEl.classList.remove('hidden');
1266 return;
1267 }
1268
1269 try
1270 {
1271 await api('POST', '/auth/change-password', {
1272 currentPassword,
1273 newPassword,
1274 });
1275 hide();
1276 toast('Password changed.', 'ok');
1277 }
1278 catch (err)
1279 {
1280 errorEl.textContent = err.message || 'Failed to change password.';
1281 errorEl.classList.remove('hidden');
1282 }
1283 };
1284}
1285
1286async function performLogout ()
1287{
1288 const tokenAtStart = STATE.token;
1289 stopAutoRefresh();
1290
1291 if (tokenAtStart)
1292 {
1293 try
1294 {
1295 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
1296 } catch
1297 {
1298 // Ignore network errors while logging out locally.
1299 }
1300 }
1301
1302 STATE.token = null;
1303 STATE.username = null;
1304 STATE.isAdmin = false;
1305 STATE.permissions = {};
1306 STATE.currentDir = null;
1307 STATE.currentRoot = null;
1308 STATE.items = [];
1309 STATE.restoreDir = null;
1310 STATE.restoreRootPath = null;
1311 STATE.lastOperationAt = null;
1312 _adminUpdateStatus = null;
1313 setAdminUpdateBadge(0);
1314 clearSessionState();
1315 closePreview({ force: true });
1316 closeSidebar();
1317 await initAuth();
1318}
1319
1320// ───────────────────────────────────────────────────────────────────────────
1321// NAVIGATION
1322// ───────────────────────────────────────────────────────────────────────────
1323
1324async function loadRoots (opts = {})
1325{
1326 const data = await api('GET', '/files/roots');
1327 if (!data) return;
1328 STATE.roots = data.roots;
1329
1330 const preferredDir = opts.preferredDir || null;
1331 const preferredRootPath = opts.preferredRootPath || null;
1332
1333 if (preferredDir && preferredRootPath)
1334 {
1335 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
1336 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1337 {
1338 try
1339 {
1340 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
1341 return;
1342 } catch
1343 {
1344 // Fall back to default root behavior.
1345 }
1346 }
1347 }
1348
1349 if (STATE.roots.length === 1)
1350 {
1351 // Single root → open it directly
1352 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
1353 } else
1354 {
1355 renderRootsView();
1356 }
1357}
1358
1359function renderRootsView ()
1360{
1361 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1362 disconnectThumbnailObserver();
1363 disconnectFolderIconObserver();
1364 revokeThumbnails();
1365
1366 STATE.currentDir = null;
1367 STATE.currentRoot = null;
1368 STATE.searchQuery = null;
1369 saveSessionState();
1370 renderBreadcrumb();
1371 const grid = document.getElementById('file-grid');
1372 grid.innerHTML = '';
1373 document.getElementById('empty-notice').classList.add('hidden');
1374 document.getElementById('folder-stats').classList.add('hidden');
1375 closeSidebar();
1376
1377 for (const root of STATE.roots)
1378 {
1379 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
1380 grid.appendChild(el);
1381 }
1382
1383 loadThumbnails();
1384}
1385
1386async function navigateTo (absPath, root, opts = {})
1387{
1388 STATE.searchQuery = null;
1389 if (root) STATE.currentRoot = root;
1390 STATE.currentDir = absPath;
1391
1392 const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`);
1393 if (!data) return;
1394
1395 STATE.items = data.items;
1396 saveSessionState();
1397 renderBreadcrumb();
1398 renderFileGrid();
1399 await refreshFolderStats();
1400 closeSidebar();
1401}
1402
1403async function runGlobalFileSearch ()
1404{
1405 const input = document.getElementById('top-search-input');
1406 if (!input) return;
1407
1408 const query = String(input.value || '').trim();
1409 if (!query)
1410 {
1411 toast('Enter a search term first.', 'err');
1412 return;
1413 }
1414
1415 let data;
1416 try
1417 {
1418 data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`);
1419 }
1420 catch (err)
1421 {
1422 toast('Search failed: ' + err.message, 'err');
1423 return;
1424 }
1425
1426 STATE.searchQuery = query;
1427 STATE.currentDir = null;
1428 STATE.currentRoot = null;
1429 STATE.items = Array.isArray(data && data.results)
1430 ? data.results.map((it) => ({
1431 name: it.name,
1432 path: it.path,
1433 dir: it.dir,
1434 isDir: false,
1435 size: it.size,
1436 mtime: it.mtime,
1437 }))
1438 : [];
1439
1440 renderBreadcrumb();
1441 renderFileGrid();
1442 closeSidebar();
1443
1444 const stats = document.getElementById('folder-stats');
1445 if (stats)
1446 {
1447 const n = STATE.items.length;
1448 stats.textContent = n === 1
1449 ? `1 file found for "${query}".`
1450 : `${n} files found for "${query}".`;
1451 stats.classList.remove('hidden');
1452 }
1453}
1454
1455function renderBreadcrumb ()
1456{
1457 if (typeof document === 'undefined') return;
1458 const nav = document.getElementById('breadcrumb');
1459 if (!nav) return;
1460 nav.innerHTML = '';
1461
1462 // "Home" crumb
1463 const home = document.createElement('span');
1464 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
1465 home.textContent = 'Home';
1466 home.addEventListener('click', () =>
1467 {
1468 if (STATE.roots.length === 1)
1469 {
1470 navigateTo(STATE.roots[0].path, STATE.roots[0]);
1471 } else
1472 {
1473 renderRootsView();
1474 }
1475 });
1476 nav.appendChild(home);
1477
1478 if (STATE.searchQuery)
1479 {
1480 const sep = document.createElement('span');
1481 sep.className = 'sep';
1482 sep.textContent = ' / ';
1483 nav.appendChild(sep);
1484
1485 const searchCrumb = document.createElement('span');
1486 searchCrumb.className = 'crumb active';
1487 searchCrumb.textContent = `Search: ${STATE.searchQuery}`;
1488 nav.appendChild(searchCrumb);
1489 return;
1490 }
1491
1492 if (!STATE.currentDir || !STATE.currentRoot) return;
1493
1494 // Build path segments relative to the root.
1495 const rootPath = STATE.currentRoot.path;
1496 const relative = relativePathFromRoot(STATE.currentDir, rootPath);
1497 const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean);
1498 const parts = [STATE.currentRoot.label, ...segments];
1499
1500 for (let i = 0; i < parts.length; i++)
1501 {
1502 const sep = document.createElement('span');
1503 sep.className = 'sep';
1504 sep.textContent = ' / ';
1505 nav.appendChild(sep);
1506
1507 const crumb = document.createElement('span');
1508 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1509 crumb.textContent = parts[i];
1510
1511 // Root crumb points to rootPath; segment crumbs point to their folder.
1512 const capturedPath = i === 0
1513 ? rootPath
1514 : joinServerPath(rootPath, segments.slice(0, i).join('/'));
1515 crumb.classList.add('crumb-drop-target');
1516 crumb.dataset.path = capturedPath;
1517 if (i < parts.length - 1)
1518 {
1519 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
1520 }
1521
1522 nav.appendChild(crumb);
1523 }
1524}
1525
1526async function refreshFolderStats ()
1527{
1528 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1529 const el = document.getElementById('folder-stats');
1530 if (!STATE.currentDir || STATE.searchQuery)
1531 {
1532 el.classList.add('hidden');
1533 return;
1534 }
1535
1536 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1537 if (!data)
1538 {
1539 el.classList.add('hidden');
1540 return;
1541 }
1542
1543 const used = formatBytes(data.usedBytes);
1544 if (data.userFreeBytes != null)
1545 {
1546 el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`;
1547 } else
1548 {
1549 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1550 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1551 }
1552 el.classList.remove('hidden');
1553}
1554
1555function itemsSignature (items)
1556{
1557 return JSON.stringify(
1558 (items || []).map(it => [it.path, it.mtime, it.uploadedAt, it.size, it.isDir])
1559 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
1560 );
1561}
1562
1563async function incrementalRefreshCurrentDir ()
1564{
1565 if (STATE.previewExpandState) return;
1566 if (STATE.searchQuery) return;
1567 if (!STATE.currentDir || STATE.uploadInProgress) return;
1568
1569 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1570 if (!data) return;
1571
1572 const oldSig = itemsSignature(STATE.items);
1573 const newSig = itemsSignature(data.items);
1574 if (oldSig !== newSig)
1575 {
1576 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
1577 STATE.items = data.items;
1578 renderFileGrid();
1579
1580 if (selectedPath)
1581 {
1582 const match = STATE.items.find(i => i.path === selectedPath);
1583 if (match)
1584 {
1585 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
1586 .find(el => el.dataset.path === selectedPath);
1587 if (selectedEl) selectItem(selectedEl, match);
1588 } else
1589 {
1590 closeSidebar();
1591 }
1592 }
1593 }
1594 else
1595 {
1596 loadThumbnails();
1597 void loadWatchedStatusesForCurrentDir();
1598 }
1599
1600 await refreshFolderStats();
1601}
1602
1603function startAutoRefresh ()
1604{
1605 stopAutoRefresh();
1606 STATE.autoRefreshTimer = setInterval(() =>
1607 {
1608 if (document.hidden) return;
1609 incrementalRefreshCurrentDir();
1610 }, 5000);
1611}
1612
1613function stopAutoRefresh ()
1614{
1615 if (STATE.autoRefreshTimer)
1616 {
1617 clearInterval(STATE.autoRefreshTimer);
1618 STATE.autoRefreshTimer = null;
1619 }
1620}
1621
1622// ───────────────────────────────────────────────────────────────────────────
1623// FILE GRID RENDERING
1624// ───────────────────────────────────────────────────────────────────────────
1625
1626function parseItemTimestampMs (value)
1627{
1628 if (value == null || value === '') return null;
1629 const asNumber = Number(value);
1630 if (Number.isFinite(asNumber) && asNumber > 0) return asNumber;
1631 const asDate = Date.parse(String(value));
1632 return Number.isFinite(asDate) ? asDate : null;
1633}
1634
1635function dayStartMsFromTimestamp (value)
1636{
1637 const ts = parseItemTimestampMs(value);
1638 if (!Number.isFinite(ts)) return null;
1639 const d = new Date(ts);
1640 return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
1641}
1642
1643function dayCountWord (count)
1644{
1645 const words = {
1646 2: 'two',
1647 3: 'three',
1648 4: 'four',
1649 5: 'five',
1650 6: 'six',
1651 };
1652 return words[count] || String(count);
1653}
1654
1655function groupDateLabel (dayStartMs)
1656{
1657 if (!Number.isFinite(dayStartMs)) return 'Unknown date';
1658
1659 const now = new Date();
1660 const todayStartMs = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
1661 const diffDays = Math.floor((todayStartMs - dayStartMs) / (24 * 60 * 60 * 1000));
1662
1663 if (diffDays === 0) return 'today';
1664 if (diffDays === 1) return 'yesterday';
1665 if (diffDays >= 2 && diffDays <= 6) return `${dayCountWord(diffDays)} days ago`;
1666 if (diffDays === 7) return 'one week ago';
1667
1668 return new Date(dayStartMs).toLocaleDateString('en-GB', {
1669 day: '2-digit',
1670 month: 'short',
1671 year: 'numeric',
1672 });
1673}
1674
1675function itemFileTypeLabel (item)
1676{
1677 if (item.isDir) return 'Folder';
1678 const ext = extOf(item.name);
1679 return ext ? `.${ext}` : 'No extension';
1680}
1681
1682function itemAlphabeticalGroupLabel (item)
1683{
1684 const first = String(item.name || '').trim().charAt(0).toUpperCase();
1685 if (!first) return '#';
1686 return /[A-Z0-9]/.test(first) ? first : '#';
1687}
1688
1689function itemSizeGroupInfo (item)
1690{
1691 if (item.isDir) return { id: 'folder', label: 'Folder', rank: -1 };
1692 const size = Number(item.size);
1693 if (!Number.isFinite(size) || size < 0) return { id: 'unknown', label: 'Unknown size', rank: 999 };
1694 if (size === 0) return { id: 'empty', label: 'Empty', rank: 0 };
1695 if (size < (1024 * 1024)) return { id: 'small', label: 'Smaller than 1 MB', rank: 1 };
1696 if (size < (100 * 1024 * 1024)) return { id: 'medium', label: '1 MB to 100 MB', rank: 2 };
1697 if (size < (1024 * 1024 * 1024)) return { id: 'large', label: '100 MB to 1 GB', rank: 3 };
1698 return { id: 'huge', label: 'Larger than 1 GB', rank: 4 };
1699}
1700
1701function itemGroupInfo (item, groupBy)
1702{
1703 if (groupBy === 'alphabetical')
1704 {
1705 const label = itemAlphabeticalGroupLabel(item);
1706 return { id: `alpha:${label}`, label, rank: label.charCodeAt(0) || 999 };
1707 }
1708
1709 if (groupBy === 'fileType')
1710 {
1711 const label = itemFileTypeLabel(item);
1712 return { id: `type:${label.toLowerCase()}`, label, rank: 0 };
1713 }
1714
1715 if (groupBy === 'lastChangedDate')
1716 {
1717 const dayStart = dayStartMsFromTimestamp(item.mtime);
1718 return {
1719 id: `mtime:${dayStart == null ? 'unknown' : dayStart}`,
1720 label: groupDateLabel(dayStart),
1721 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
1722 };
1723 }
1724
1725 if (groupBy === 'timeUploadedDate')
1726 {
1727 const dayStart = dayStartMsFromTimestamp(item.uploadedAt != null ? item.uploadedAt : item.mtime);
1728 return {
1729 id: `uploaded:${dayStart == null ? 'unknown' : dayStart}`,
1730 label: groupDateLabel(dayStart),
1731 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
1732 };
1733 }
1734
1735 if (groupBy === 'size')
1736 {
1737 const sizeGroup = itemSizeGroupInfo(item);
1738 return {
1739 id: `size:${sizeGroup.id}`,
1740 label: sizeGroup.label,
1741 rank: sizeGroup.rank,
1742 };
1743 }
1744
1745 return { id: 'none', label: '', rank: 0 };
1746}
1747
1748function compareText (a, b)
1749{
1750 return String(a || '').localeCompare(String(b || ''), undefined, { numeric: true, sensitivity: 'base' });
1751}
1752
1753function compareNullableNumber (a, b, ascending)
1754{
1755 const hasA = Number.isFinite(a);
1756 const hasB = Number.isFinite(b);
1757 if (!hasA && !hasB) return 0;
1758 if (!hasA) return 1;
1759 if (!hasB) return -1;
1760 const diff = a - b;
1761 return ascending ? diff : -diff;
1762}
1763
1764function compareBySortMode (a, b, sortBy, ascending)
1765{
1766 if (sortBy === 'fileType')
1767 {
1768 const extA = itemFileTypeLabel(a.item).toLowerCase();
1769 const extB = itemFileTypeLabel(b.item).toLowerCase();
1770 const byType = compareText(extA, extB);
1771 if (byType !== 0) return ascending ? byType : -byType;
1772 const byName = compareText(a.item.name, b.item.name);
1773 return ascending ? byName : -byName;
1774 }
1775
1776 if (sortBy === 'lastChanged')
1777 {
1778 return compareNullableNumber(parseItemTimestampMs(a.item.mtime), parseItemTimestampMs(b.item.mtime), ascending);
1779 }
1780
1781 if (sortBy === 'timeUploaded')
1782 {
1783 const uploadedA = parseItemTimestampMs(a.item.uploadedAt != null ? a.item.uploadedAt : a.item.mtime);
1784 const uploadedB = parseItemTimestampMs(b.item.uploadedAt != null ? b.item.uploadedAt : b.item.mtime);
1785 return compareNullableNumber(uploadedA, uploadedB, ascending);
1786 }
1787
1788 if (sortBy === 'size')
1789 {
1790 const sizeA = Number.isFinite(Number(a.item.size)) ? Number(a.item.size) : null;
1791 const sizeB = Number.isFinite(Number(b.item.size)) ? Number(b.item.size) : null;
1792 return compareNullableNumber(sizeA, sizeB, ascending);
1793 }
1794
1795 const byName = compareText(a.item.name, b.item.name);
1796 return ascending ? byName : -byName;
1797}
1798
1799function buildFileGridRows (items, prefs)
1800{
1801 const list = Array.isArray(items) ? items : [];
1802 const groupBy = prefs.groupBy || 'none';
1803 const sortBy = prefs.sortBy || 'alphabetical';
1804 const descriptors = list.map((item) => ({
1805 item,
1806 group: itemGroupInfo(item, groupBy),
1807 }));
1808
1809 descriptors.sort((a, b) =>
1810 {
1811 if (groupBy !== 'none')
1812 {
1813 const dateGrouping = groupBy === 'lastChangedDate' || groupBy === 'timeUploadedDate';
1814 if (a.group.rank !== b.group.rank)
1815 {
1816 const byRank = dateGrouping ? (b.group.rank - a.group.rank) : (a.group.rank - b.group.rank);
1817 if (byRank !== 0) return byRank;
1818 }
1819 const byGroupLabel = compareText(a.group.label, b.group.label);
1820 if (byGroupLabel !== 0) return dateGrouping ? byGroupLabel : (prefs.ascending ? byGroupLabel : -byGroupLabel);
1821 }
1822
1823 if (prefs.foldersFirst && a.item.isDir !== b.item.isDir)
1824 {
1825 return a.item.isDir ? -1 : 1;
1826 }
1827
1828 const bySort = compareBySortMode(a, b, sortBy, !!prefs.ascending);
1829 if (bySort !== 0) return bySort;
1830
1831 return compareText(a.item.name, b.item.name);
1832 });
1833
1834 const rows = [];
1835 let previousGroupId = null;
1836 for (const descriptor of descriptors)
1837 {
1838 if (groupBy !== 'none' && descriptor.group.id !== previousGroupId)
1839 {
1840 rows.push({ type: 'group', label: descriptor.group.label });
1841 previousGroupId = descriptor.group.id;
1842 }
1843 rows.push({ type: 'item', item: descriptor.item });
1844 }
1845
1846 return rows;
1847}
1848
1849function makeGroupSeparator (label)
1850{
1851 const el = document.createElement('div');
1852 el.className = 'file-group-separator';
1853
1854 const text = document.createElement('span');
1855 text.textContent = String(label || 'Other');
1856 el.appendChild(text);
1857 return el;
1858}
1859
1860function renderFileItemName (targetEl, fileName)
1861{
1862 if (!targetEl) return;
1863
1864 const rawName = String(fileName || '');
1865 targetEl.textContent = '';
1866 if (!rawName) return;
1867
1868 const segments = rawName.split(/([\-.,])/);
1869 for (const segment of segments)
1870 {
1871 if (!segment) continue;
1872 targetEl.appendChild(document.createTextNode(segment));
1873
1874 if (segment === '-' || segment === ',' || segment === '.')
1875 {
1876 targetEl.appendChild(document.createElement('wbr'));
1877 }
1878 }
1879}
1880
1881function renderFileGrid ()
1882{
1883 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1884 disconnectThumbnailObserver();
1885 disconnectFolderIconObserver();
1886 revokeThumbnails();
1887 const grid = document.getElementById('file-grid');
1888 grid.innerHTML = '';
1889 const empty = document.getElementById('empty-notice');
1890
1891 const prefs = (!STATE.searchQuery && STATE.currentDir)
1892 ? folderViewPrefsForDir(STATE.currentDir)
1893 : { ...DEFAULT_FOLDER_VIEW_PREFS };
1894 const rows = buildFileGridRows(STATE.items, prefs);
1895
1896 empty.classList.toggle('hidden', STATE.items.length > 0);
1897
1898 for (const row of rows)
1899 {
1900 if (row.type === 'group')
1901 {
1902 grid.appendChild(makeGroupSeparator(row.label));
1903 continue;
1904 }
1905 grid.appendChild(makeFileItem(row.item));
1906 }
1907
1908 loadThumbnails();
1909 void loadWatchedStatusesForCurrentDir();
1910}
1911
1912function makeFileItem (item)
1913{
1914 const el = document.createElement('div');
1915 el.className = 'file-item';
1916 el.dataset.path = item.path;
1917 if (item.isDir) el.dataset.isdir = '1';
1918
1919 const icon = document.createElement('div');
1920 icon.className = 'icon';
1921 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
1922 if (!item.isDir)
1923 {
1924 icon.dataset.previewPath = item.path;
1925 renderWatchedOverlayOnIcon(icon, watchStatusForTile(item));
1926 } else
1927 {
1928 icon.dataset.folderPath = item.path;
1929 }
1930 el.appendChild(icon);
1931
1932 const name = document.createElement('div');
1933 name.className = 'name';
1934 renderFileItemName(name, item.name);
1935 el.appendChild(name);
1936
1937 if (!item._root) makeDraggable(el, item);
1938 attachMobileLongPress(el, item);
1939
1940 el.addEventListener('contextmenu', (e) =>
1941 {
1942 e.preventDefault();
1943 e.stopPropagation();
1944
1945 if (isMobileViewport()) return;
1946 if (el.classList.contains('file-item--preview')) return;
1947
1948 document.querySelectorAll('.file-item.selected').forEach(node => node.classList.remove('selected'));
1949 el.classList.add('selected');
1950 STATE.selectedItem = item;
1951 openItemContextMenu(item, e.clientX, e.clientY);
1952 });
1953
1954 // Single-click: open sidebar
1955 el.addEventListener('click', (e) =>
1956 {
1957 e.stopPropagation();
1958 closeCustomContextMenu();
1959 if (el.classList.contains('file-item--preview')) return;
1960 if (isMobileViewport())
1961 {
1962 if (el.dataset.longPressTriggered === '1')
1963 {
1964 el.dataset.longPressTriggered = '0';
1965 return;
1966 }
1967
1968 if (item.isDir)
1969 {
1970 navigateTo(item.path, item._root || STATE.currentRoot);
1971 } else
1972 {
1973 downloadOrView(item, icon.querySelector('svg'));
1974 }
1975 return;
1976 }
1977
1978 selectItem(el, item);
1979 });
1980
1981 // Double-click: enter folder or view/download file
1982 el.addEventListener('dblclick', (e) =>
1983 {
1984 e.stopPropagation();
1985 if (el.classList.contains('file-item--preview')) return;
1986 if (item.isDir)
1987 {
1988 navigateTo(item.path, item._root || STATE.currentRoot);
1989 } else
1990 {
1991 downloadOrView(item, icon.querySelector('svg'));
1992 }
1993 });
1994
1995 return el;
1996}
1997
1998function attachMobileLongPress (el, item)
1999{
2000 if (item._root) return;
2001
2002 let pressTimer = null;
2003 let startX = 0;
2004 let startY = 0;
2005
2006 function clearPress ()
2007 {
2008 if (!pressTimer) return;
2009 clearTimeout(pressTimer);
2010 pressTimer = null;
2011 }
2012
2013 function cancelPress ()
2014 {
2015 clearPress();
2016 }
2017
2018 el.addEventListener('pointerdown', (e) =>
2019 {
2020 if (!isMobileViewport()) return;
2021 if (e.button !== undefined && e.button !== 0) return;
2022 if (e.pointerType && e.pointerType === 'mouse') return;
2023
2024 startX = e.clientX;
2025 startY = e.clientY;
2026 clearPress();
2027
2028 pressTimer = setTimeout(() =>
2029 {
2030 pressTimer = null;
2031 el.dataset.longPressTriggered = '1';
2032 selectItem(el, item);
2033 }, MOBILE_LONG_PRESS_MS);
2034 });
2035
2036 el.addEventListener('pointermove', (e) =>
2037 {
2038 if (!pressTimer) return;
2039 if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD)
2040 {
2041 clearPress();
2042 }
2043 });
2044
2045 el.addEventListener('pointerup', cancelPress);
2046 el.addEventListener('pointercancel', cancelPress);
2047 el.addEventListener('pointerleave', cancelPress);
2048}
2049
2050function selectItem (el, item)
2051{
2052 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2053 el.classList.add('selected');
2054 STATE.selectedItem = item;
2055 openSidebar(item);
2056}
2057
2058function isAbortError (err)
2059{
2060 if (!err) return false;
2061 return err.name === 'AbortError' || /abort/i.test(String(err.message || ''));
2062}
2063
2064function beginSidebarLoad ()
2065{
2066 if (STATE.sidebarAbortController && typeof STATE.sidebarAbortController.abort === 'function')
2067 {
2068 try { STATE.sidebarAbortController.abort(); } catch { /* ignore */ }
2069 }
2070
2071 STATE.sidebarLoadId += 1;
2072 STATE.sidebarAbortController = null;
2073
2074 return {
2075 id: STATE.sidebarLoadId,
2076 };
2077}
2078
2079function isSidebarLoadStale (item, sidebarLoadId)
2080{
2081 if (sidebarLoadId !== STATE.sidebarLoadId) return true;
2082 if (!STATE.selectedItem) return true;
2083 return STATE.selectedItem !== item && STATE.selectedItem.path !== item.path;
2084}
2085
2086// ───────────────────────────────────────────────────────────────────────────
2087// SIDEBAR
2088// ───────────────────────────────────────────────────────────────────────────
2089
2090/**
2091 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
2092 * @param {object|null} item — the item whose duplicates are shown; null = clear
2093 * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
2094 */
2095function renderSidebarDuplicates (item, duplicates)
2096{
2097 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
2098 const panel = document.getElementById('sidebar-duplicates');
2099 if (!panel) return;
2100
2101 // Clear / hide when no item or no duplicates.
2102 if (!item || (Array.isArray(duplicates) && duplicates.length === 0))
2103 {
2104 panel.classList.add('hidden');
2105 panel.innerHTML = '';
2106 return;
2107 }
2108
2109 // Loading state.
2110 if (duplicates === null)
2111 {
2112 panel.classList.add('hidden');
2113 panel.innerHTML = '';
2114 return;
2115 }
2116
2117 panel.innerHTML = '';
2118 const heading = document.createElement('p');
2119 heading.className = 'sidebar-duplicates-heading';
2120 heading.textContent = `Duplicates (${duplicates.length})`;
2121 panel.appendChild(heading);
2122
2123 const list = document.createElement('ul');
2124 list.className = 'sidebar-duplicates-list';
2125
2126 for (const dup of duplicates)
2127 {
2128 const li = document.createElement('li');
2129 const btn = document.createElement('button');
2130 btn.className = 'sidebar-duplicate-entry';
2131 btn.title = dup.path;
2132 // Show path relative to its root; keep absolute path in the tooltip.
2133 btn.textContent = dup.relativePath || dup.path;
2134 btn.addEventListener('click', () => navigateToDuplicate(dup));
2135 li.appendChild(btn);
2136 list.appendChild(li);
2137 }
2138
2139 panel.appendChild(list);
2140 panel.classList.remove('hidden');
2141}
2142
2143/**
2144 * Navigates to the folder containing a duplicate file and then auto-opens it.
2145 * @param {{ path: string, name: string, dir: string }} dup
2146 */
2147async function navigateToDuplicate (dup)
2148{
2149 // If the duplicate lives in the folder already shown, just select it.
2150 if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
2151 {
2152 const tile = Array.from(document.querySelectorAll('.file-item'))
2153 .find((el) => el.dataset.path === dup.path);
2154 const dupItem = STATE.items.find((i) => i.path === dup.path);
2155 if (tile && dupItem)
2156 {
2157 selectItem(tile, dupItem);
2158 }
2159 return;
2160 }
2161
2162 // Find the root that contains the duplicate.
2163 const root = STATE.roots.find(
2164 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
2165 );
2166 if (!root)
2167 {
2168 toast('Cannot navigate to duplicate: root not accessible.', 'err');
2169 return;
2170 }
2171
2172 await navigateTo(dup.dir, root);
2173
2174 // After navigation, find and select the file tile to open it.
2175 const tile = Array.from(document.querySelectorAll('.file-item'))
2176 .find((el) => el.dataset.path === dup.path);
2177 const dupItem = STATE.items.find((i) => i.path === dup.path);
2178
2179 if (tile && dupItem)
2180 {
2181 selectItem(tile, dupItem);
2182 }
2183}
2184
2185function renderItemActionButtons (actions, item)
2186{
2187 if (!actions || !item) return;
2188 actions.innerHTML = '';
2189
2190 if (!item.isDir)
2191 {
2192 const btnDl = document.createElement('button');
2193 btnDl.textContent = 'View / Download';
2194 btnDl.addEventListener('click', () =>
2195 {
2196 const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path);
2197 const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg');
2198 downloadOrView(item, source);
2199 });
2200 actions.appendChild(btnDl);
2201
2202 const btnShareFile = document.createElement('button');
2203 btnShareFile.textContent = 'Share';
2204 btnShareFile.addEventListener('click', () => openShareModal(item));
2205 actions.appendChild(btnShareFile);
2206 }
2207 else
2208 {
2209 const btnOpen = document.createElement('button');
2210 btnOpen.textContent = 'Open folder';
2211 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
2212 actions.appendChild(btnOpen);
2213
2214 const btnZip = document.createElement('button');
2215 btnZip.textContent = 'Download as zip';
2216 btnZip.addEventListener('click', () =>
2217 {
2218 btnZip.disabled = true;
2219 btnZip.textContent = 'Working...';
2220 const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`;
2221 const headers = {
2222 Authorization: 'Bearer ' + STATE.token,
2223 'X-Fp': getFingerprint(),
2224 };
2225 fetch(url, { headers })
2226 .then(res =>
2227 {
2228 if (!res.ok) throw new Error('Download mislukt');
2229 return res.blob();
2230 })
2231 .then(blob =>
2232 {
2233 const blobUrl = URL.createObjectURL(blob);
2234 const a = document.createElement('a');
2235 a.href = blobUrl;
2236 a.download = item.name + '.zip';
2237 a.click();
2238 setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
2239 })
2240 .catch((err) => toast(err.message || 'Download mislukt', 'err'))
2241 .finally(() =>
2242 {
2243 btnZip.disabled = false;
2244 btnZip.textContent = 'Download as zip';
2245 });
2246 });
2247 actions.appendChild(btnZip);
2248
2249 const btnShareFolder = document.createElement('button');
2250 btnShareFolder.textContent = 'Share';
2251 btnShareFolder.addEventListener('click', () => openShareModal(item));
2252 actions.appendChild(btnShareFolder);
2253 }
2254
2255 if (!canWrite(item)) return;
2256
2257 if (item.isDir)
2258 {
2259 const btnSetIcon = document.createElement('button');
2260 btnSetIcon.textContent = 'Set icon';
2261 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
2262 actions.appendChild(btnSetIcon);
2263 }
2264
2265 if (!item._root)
2266 {
2267 const btnMove = document.createElement('button');
2268 btnMove.textContent = 'Move to';
2269 btnMove.addEventListener('click', () => openMovePicker(item));
2270 actions.appendChild(btnMove);
2271
2272 if (!item.isDir)
2273 {
2274 const btnCopy = document.createElement('button');
2275 btnCopy.textContent = 'Copy to';
2276 btnCopy.addEventListener('click', () => openCopyPicker(item));
2277 actions.appendChild(btnCopy);
2278 }
2279 }
2280
2281 const btnRen = document.createElement('button');
2282 btnRen.textContent = 'Rename';
2283 btnRen.addEventListener('click', () => openRenameModal(item));
2284 actions.appendChild(btnRen);
2285
2286 if (!item._root)
2287 {
2288 const btnDel = document.createElement('button');
2289 btnDel.textContent = 'Delete';
2290 btnDel.className = 'danger';
2291 btnDel.addEventListener('click', () => deleteItem(item));
2292 actions.appendChild(btnDel);
2293 }
2294}
2295
2296function closeCustomContextMenu ()
2297{
2298 const menu = document.getElementById('custom-context-menu');
2299 if (!menu) return;
2300 menu.classList.add('hidden');
2301 menu.innerHTML = '';
2302}
2303
2304function ensureCustomContextMenu ()
2305{
2306 let menu = document.getElementById('custom-context-menu');
2307 if (menu) return menu;
2308
2309 menu = document.createElement('div');
2310 menu.id = 'custom-context-menu';
2311 menu.className = 'custom-context-menu hidden';
2312 menu.setAttribute('role', 'menu');
2313 menu.setAttribute('aria-label', 'Context menu');
2314 menu.addEventListener('click', (e) => e.stopPropagation());
2315 document.body.appendChild(menu);
2316 return menu;
2317}
2318
2319function openCustomContextMenuAt (x, y, build)
2320{
2321 const menu = ensureCustomContextMenu();
2322 menu.innerHTML = '';
2323 build(menu);
2324 if (!menu.childElementCount)
2325 {
2326 closeCustomContextMenu();
2327 return;
2328 }
2329
2330 menu.classList.remove('hidden');
2331 menu.style.left = '0px';
2332 menu.style.top = '0px';
2333
2334 const maxLeft = Math.max(6, window.innerWidth - menu.offsetWidth - 6);
2335 const maxTop = Math.max(6, window.innerHeight - menu.offsetHeight - 6);
2336 menu.style.left = `${Math.min(Math.max(6, x), maxLeft)}px`;
2337 menu.style.top = `${Math.min(Math.max(6, y), maxTop)}px`;
2338}
2339
2340function addContextMenuButton (menu, label, onClick, { danger = false, checked = null, hasSubmenu = false } = {})
2341{
2342 const btn = document.createElement('button');
2343 btn.type = 'button';
2344 btn.className = 'custom-context-menu-item';
2345 if (danger) btn.classList.add('danger');
2346 if (checked !== null) btn.classList.add('custom-context-menu-item--check');
2347 if (hasSubmenu) btn.classList.add('custom-context-menu-item--submenu');
2348
2349 const labelEl = document.createElement('span');
2350 if (checked === true) labelEl.textContent = '✓ ' + label;
2351 else if (checked === false) labelEl.textContent = '□ ' + label;
2352 else labelEl.textContent = label;
2353 btn.appendChild(labelEl);
2354
2355 if (hasSubmenu)
2356 {
2357 const arrow = document.createElement('span');
2358 arrow.textContent = '›';
2359 btn.appendChild(arrow);
2360 }
2361
2362 btn.addEventListener('click', async (e) =>
2363 {
2364 e.stopPropagation();
2365 await onClick();
2366 closeCustomContextMenu();
2367 });
2368 menu.appendChild(btn);
2369 return btn;
2370}
2371
2372function addContextMenuSeparator (menu)
2373{
2374 const sep = document.createElement('div');
2375 sep.className = 'custom-context-menu-separator';
2376 menu.appendChild(sep);
2377}
2378
2379function addContextMenuSubmenu (menu, label, options)
2380{
2381 const row = document.createElement('div');
2382 row.className = 'custom-context-menu-row';
2383 const trigger = addContextMenuButton(row, label, () => { }, { hasSubmenu: true });
2384 trigger.addEventListener('click', (e) => e.preventDefault());
2385
2386 const panel = document.createElement('div');
2387 panel.className = 'custom-context-submenu';
2388 for (const option of options)
2389 {
2390 addContextMenuButton(panel, option.label, option.onClick, {
2391 checked: option.checked,
2392 });
2393 }
2394 row.appendChild(panel);
2395 menu.appendChild(row);
2396}
2397
2398function openItemContextMenu (item, x, y)
2399{
2400 openCustomContextMenuAt(x, y, (menu) =>
2401 {
2402 renderItemActionButtons(menu, item);
2403 menu.querySelectorAll('button').forEach((btn) =>
2404 {
2405 if (btn.classList.contains('danger')) btn.classList.add('danger');
2406 btn.addEventListener('click', () => closeCustomContextMenu(), { once: true });
2407 });
2408 });
2409}
2410
2411function openFolderContextMenu (x, y)
2412{
2413 if (!STATE.currentDir)
2414 {
2415 closeCustomContextMenu();
2416 return;
2417 }
2418
2419 const prefs = folderViewPrefsForDir(STATE.currentDir);
2420 const makeOptionHandler = (patch) => async () =>
2421 {
2422 saveFolderViewPrefsForDir(STATE.currentDir, patch);
2423 renderFileGrid();
2424 };
2425
2426 openCustomContextMenuAt(x, y, (menu) =>
2427 {
2428 if (canWrite())
2429 {
2430 addContextMenuButton(menu, 'Create Folder', createFolderInCurrentDir);
2431 addContextMenuSeparator(menu);
2432 }
2433
2434 addContextMenuSubmenu(menu, 'Sort by', FOLDER_SORT_OPTIONS.map((option) => ({
2435 label: option.label,
2436 checked: prefs.sortBy === option.value,
2437 onClick: makeOptionHandler({ sortBy: option.value }),
2438 })));
2439
2440 addContextMenuSubmenu(menu, 'Group by', FOLDER_GROUP_OPTIONS.map((option) => ({
2441 label: option.label,
2442 checked: prefs.groupBy === option.value,
2443 onClick: makeOptionHandler({ groupBy: option.value }),
2444 })));
2445
2446 addContextMenuSeparator(menu);
2447 addContextMenuButton(menu, 'Always keep folders at the top', makeOptionHandler({ foldersFirst: !prefs.foldersFirst }), {
2448 checked: !!prefs.foldersFirst,
2449 });
2450 addContextMenuButton(menu, prefs.ascending ? 'Ascending' : 'Descending', makeOptionHandler({ ascending: !prefs.ascending }), {
2451 checked: !!prefs.ascending,
2452 });
2453 });
2454}
2455// ───────────────────────────────────────────────────────────────────────────
2456
2457async function openSidebar (item)
2458{
2459 const sidebarLoad = beginSidebarLoad();
2460
2461 const sidebar = document.getElementById('sidebar');
2462 sidebar.classList.remove('hidden');
2463 document.getElementById('app').classList.add('sidebar-open');
2464
2465 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
2466 if (item.isDir)
2467 {
2468 document.getElementById('sidebar-icon').dataset.folderPath = item.path;
2469 } else
2470 {
2471 delete document.getElementById('sidebar-icon').dataset.folderPath;
2472 }
2473 document.getElementById('sidebar-name').textContent = item.name;
2474
2475 // Load metadata
2476 const dl = document.getElementById('sidebar-meta');
2477 dl.innerHTML = '<dt>Loading…</dt><dd></dd>';
2478
2479 const actions = document.getElementById('sidebar-actions');
2480 actions.innerHTML = '';
2481
2482 // Reset duplicates panel whenever a new item is opened.
2483 renderSidebarDuplicates(null, null);
2484
2485 if (!item.isDir)
2486 {
2487 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch((err) =>
2488 {
2489 if (isAbortError(err)) return null;
2490 throw err;
2491 });
2492 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2493
2494 if (meta)
2495 {
2496 const watchedBy = VIDEO_EXTS.has(extOf(item.name))
2497 ? Object.entries(meta.watchedBy || {})
2498 .map(([user, status]) => `${String(user)}: ${String(status)}`)
2499 .sort((a, b) => a.localeCompare(b))
2500 : [];
2501
2502 dl.innerHTML = `
2503 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
2504 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
2505 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
2506 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
2507 ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''}
2508 `;
2509 }
2510
2511 // Fetch and render duplicate files.
2512 renderSidebarDuplicates(item, null); // show loading state
2513 const selectedPathAtRequest = item.path;
2514 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
2515 .then((data) =>
2516 {
2517 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2518 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
2519 renderSidebarDuplicates(item, data ? data.duplicates : []);
2520 })
2521 .catch((err) =>
2522 {
2523 if (isAbortError(err)) return;
2524 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2525 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
2526 renderSidebarDuplicates(item, []);
2527 });
2528
2529 } else
2530 {
2531 dl.innerHTML = `<dt>Type</dt><dd>${item._root ? 'Root folder' : 'Folder'}</dd>`;
2532
2533 if (item._root)
2534 {
2535 dl.innerHTML += `
2536 <dt>Alias</dt><dd>${item.name}</dd>
2537 <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd>
2538 `;
2539
2540 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch((err) =>
2541 {
2542 if (isAbortError(err)) return null;
2543 return null;
2544 });
2545 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2546
2547 if (space)
2548 {
2549 const used = formatBytes(space.usedBytes);
2550 const free = space.userFreeBytes != null
2551 ? formatBytes(space.userFreeBytes)
2552 : (space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes));
2553 const freeLabel = space.userFreeBytes != null ? 'Free space remaining' : 'Remaining';
2554 dl.innerHTML += `
2555 <dt>Used</dt><dd>${used}</dd>
2556 <dt>${freeLabel}</dt><dd>${free}</dd>
2557 `;
2558 }
2559
2560 if (item._root.isUserFolder)
2561 {
2562 dl.innerHTML += `
2563 <dt>Access</dt><dd>Private (your folder)</dd>
2564 `;
2565 } else
2566 {
2567 const accessUsers = await fetchRootAccessList(item.path);
2568 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2569 if (accessUsers)
2570 {
2571 dl.innerHTML += `
2572 <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>
2573 `;
2574 }
2575 }
2576 }
2577 }
2578
2579 renderItemActionButtons(actions, item);
2580
2581 if (item.isDir)
2582 {
2583 // Load folder icon thumbnail into the sidebar icon element.
2584 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
2585 }
2586}
2587
2588function openFolderSidebar ()
2589{
2590 beginSidebarLoad();
2591
2592 const sidebar = document.getElementById('sidebar');
2593 sidebar.classList.remove('hidden');
2594 document.getElementById('app').classList.add('sidebar-open');
2595
2596 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
2597
2598 const nameEl = document.getElementById('sidebar-name');
2599 const dl = document.getElementById('sidebar-meta');
2600 const actions = document.getElementById('sidebar-actions');
2601 actions.innerHTML = '';
2602 renderSidebarDuplicates(null, null);
2603
2604 if (!STATE.currentDir || !STATE.currentRoot)
2605 {
2606 nameEl.textContent = 'Storage Roots';
2607 dl.innerHTML = `
2608 <dt>Type</dt><dd>Root overview</dd>
2609 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
2610 `;
2611 return;
2612 }
2613
2614 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
2615 const fallback = STATE.currentRoot.label || 'Folder';
2616 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
2617
2618 const dirs = STATE.items.filter(i => i.isDir).length;
2619 const files = STATE.items.length - dirs;
2620 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
2621 const baseDetails = `
2622 <dt>Path</dt><dd>${displayPath}</dd>
2623 <dt>Folders</dt><dd>${dirs}</dd>
2624 <dt>Files</dt><dd>${files}</dd>
2625 `;
2626 dl.innerHTML = baseDetails;
2627 renderFolderViewControls(actions, STATE.currentDir);
2628
2629 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2630 {
2631 if (STATE.currentRoot.isUserFolder)
2632 {
2633 dl.innerHTML += '<dt>Access</dt><dd>Private (your folder)</dd>';
2634 return;
2635 }
2636
2637 dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>';
2638 const currentDirAtStart = STATE.currentDir;
2639 const currentRootPathAtStart = STATE.currentRoot.path;
2640 void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) =>
2641 {
2642 if (!accessUsers) return;
2643 if (!STATE.currentRoot) return;
2644 if (!samePath(STATE.currentDir, currentDirAtStart)) return;
2645 if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return;
2646 dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`;
2647 });
2648 }
2649}
2650
2651function renderFolderViewControls (actions, dirPath)
2652{
2653 if (!actions || !dirPath) return;
2654
2655 const prefs = folderViewPrefsForDir(dirPath);
2656
2657 const section = document.createElement('section');
2658 section.className = 'sidebar-view-options';
2659
2660 const heading = document.createElement('h3');
2661 heading.textContent = 'View options';
2662 section.appendChild(heading);
2663
2664 const sortLabel = document.createElement('label');
2665 sortLabel.className = 'sidebar-view-option-label';
2666 sortLabel.textContent = 'Sort by';
2667 const sortSelect = document.createElement('select');
2668 sortSelect.className = 'sidebar-view-option-control';
2669 sortSelect.dataset.viewOption = 'sort';
2670 for (const option of FOLDER_SORT_OPTIONS)
2671 {
2672 const optEl = document.createElement('option');
2673 optEl.value = option.value;
2674 optEl.textContent = option.label;
2675 sortSelect.appendChild(optEl);
2676 }
2677 sortSelect.value = prefs.sortBy;
2678 sortSelect.addEventListener('change', () =>
2679 {
2680 saveFolderViewPrefsForDir(dirPath, { sortBy: sortSelect.value });
2681 renderFileGrid();
2682 });
2683 sortLabel.appendChild(sortSelect);
2684 section.appendChild(sortLabel);
2685
2686 const groupLabel = document.createElement('label');
2687 groupLabel.className = 'sidebar-view-option-label';
2688 groupLabel.textContent = 'Group by';
2689 const groupSelect = document.createElement('select');
2690 groupSelect.className = 'sidebar-view-option-control';
2691 groupSelect.dataset.viewOption = 'group';
2692 for (const option of FOLDER_GROUP_OPTIONS)
2693 {
2694 const optEl = document.createElement('option');
2695 optEl.value = option.value;
2696 optEl.textContent = option.label;
2697 groupSelect.appendChild(optEl);
2698 }
2699 groupSelect.value = prefs.groupBy;
2700 groupSelect.addEventListener('change', () =>
2701 {
2702 saveFolderViewPrefsForDir(dirPath, { groupBy: groupSelect.value });
2703 renderFileGrid();
2704 });
2705 groupLabel.appendChild(groupSelect);
2706 section.appendChild(groupLabel);
2707
2708 const foldersTopLabel = document.createElement('label');
2709 foldersTopLabel.className = 'sidebar-view-toggle';
2710 const foldersTopInput = document.createElement('input');
2711 foldersTopInput.type = 'checkbox';
2712 foldersTopInput.dataset.viewOption = 'folders-first';
2713 foldersTopInput.checked = !!prefs.foldersFirst;
2714 foldersTopInput.addEventListener('change', () =>
2715 {
2716 saveFolderViewPrefsForDir(dirPath, { foldersFirst: foldersTopInput.checked });
2717 renderFileGrid();
2718 });
2719 const foldersTopText = document.createElement('span');
2720 foldersTopText.textContent = 'Always keep folders at the top';
2721 foldersTopLabel.appendChild(foldersTopInput);
2722 foldersTopLabel.appendChild(foldersTopText);
2723 section.appendChild(foldersTopLabel);
2724
2725 const ascLabel = document.createElement('label');
2726 ascLabel.className = 'sidebar-view-toggle';
2727 const ascInput = document.createElement('input');
2728 ascInput.type = 'checkbox';
2729 ascInput.dataset.viewOption = 'ascending';
2730 ascInput.checked = !!prefs.ascending;
2731 ascInput.addEventListener('change', () =>
2732 {
2733 saveFolderViewPrefsForDir(dirPath, { ascending: ascInput.checked });
2734 renderFileGrid();
2735 });
2736 const ascText = document.createElement('span');
2737 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2738 ascInput.addEventListener('change', () =>
2739 {
2740 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2741 });
2742 ascLabel.appendChild(ascInput);
2743 ascLabel.appendChild(ascText);
2744 section.appendChild(ascLabel);
2745
2746 actions.appendChild(section);
2747}
2748
2749function closeSidebar ()
2750{
2751 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
2752 beginSidebarLoad();
2753 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2754 STATE.selectedItem = null;
2755
2756 if (isMobileViewport())
2757 {
2758 hideSidebarPanel();
2759 return;
2760 }
2761
2762 openFolderSidebar();
2763}
2764
2765function isMobileViewport ()
2766{
2767 return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
2768}
2769
2770function hideSidebarPanel ()
2771{
2772 const sidebar = document.getElementById('sidebar');
2773 const app = document.getElementById('app');
2774 sidebar.classList.add('hidden');
2775 app.classList.remove('sidebar-open');
2776}
2777
2778function basenameOfPath (p)
2779{
2780 const parts = String(p || '').split(/[\\/]/).filter(Boolean);
2781 return parts.length ? parts[parts.length - 1] : String(p || '');
2782}
2783
2784async function fetchRootAccessList (rootPath)
2785{
2786 if (!rootPath) return null;
2787 const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch((err) =>
2788 {
2789 if (isAbortError(err)) return null;
2790 return null;
2791 });
2792 if (!data || !Array.isArray(data.users)) return null;
2793 return data.users;
2794}
2795
2796function formatRootAccessList (users)
2797{
2798 if (!Array.isArray(users) || users.length === 0) return 'No users';
2799
2800 const sorted = [...users].sort((a, b) =>
2801 {
2802 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
2803 const byMode = modeRank(a.mode) - modeRank(b.mode);
2804 if (byMode !== 0) return byMode;
2805 return String(a.username).localeCompare(String(b.username));
2806 });
2807
2808 const items = sorted
2809 .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`)
2810 .join('');
2811 return `<ul class="root-access-list">${items}</ul>`;
2812}
2813
2814function rootPermissionLabel (root)
2815{
2816 if (root && root.isUserFolder) return 'My Folder';
2817 return (root && (root.originalName || root.label)) || '';
2818}
2819
2820function resolveRootForPath (targetPath)
2821{
2822 if (!targetPath) return null;
2823 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
2824}
2825
2826function writableRoots ()
2827{
2828 if (STATE.isAdmin) return STATE.roots.slice();
2829 return STATE.roots.filter((r) =>
2830 {
2831 if (r.isUserFolder) return true;
2832 const perm = STATE.permissions[rootPermissionLabel(r)];
2833 return !!(perm && perm.write);
2834 });
2835}
2836
2837async function moveWithConflictResolution (item, targetDir)
2838{
2839 try
2840 {
2841 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
2842 }
2843 catch (err)
2844 {
2845 if (!/already exists/i.test(err.message || '')) throw err;
2846
2847 const existingNames = await listDirNameSet(targetDir);
2848 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2849 const suggestedName = nextAvailableName(desiredName, existingNames);
2850 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
2851 if (decision === 'cancel') return null;
2852
2853 if (decision === 'overwrite')
2854 {
2855 return api('POST', '/files/move', {
2856 from: item.path,
2857 toDir: targetDir,
2858 conflict: 'overwrite',
2859 });
2860 }
2861
2862 return api('POST', '/files/move', {
2863 from: item.path,
2864 toDir: targetDir,
2865 conflict: 'rename',
2866 targetName: suggestedName,
2867 });
2868 }
2869}
2870
2871async function copyWithConflictResolution (item, targetDir)
2872{
2873 try
2874 {
2875 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2876 }
2877 catch (err)
2878 {
2879 if (!/already exists/i.test(err.message || '')) throw err;
2880
2881 const existingNames = await listDirNameSet(targetDir);
2882 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2883 const suggestedName = nextAvailableName(desiredName, existingNames);
2884 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2885 if (decision === 'cancel') return null;
2886
2887 if (decision === 'overwrite')
2888 {
2889 return api('POST', '/files/copy', {
2890 from: item.path,
2891 toDir: targetDir,
2892 conflict: 'overwrite',
2893 });
2894 }
2895
2896 return api('POST', '/files/copy', {
2897 from: item.path,
2898 toDir: targetDir,
2899 conflict: 'rename',
2900 targetName: suggestedName,
2901 });
2902 }
2903}
2904
2905function ensureMoveModal ()
2906{
2907 let overlay = document.getElementById('move-modal');
2908 if (overlay) return overlay;
2909
2910 overlay = document.createElement('div');
2911 overlay.id = 'move-modal';
2912 overlay.className = 'modal-overlay hidden';
2913 overlay.innerHTML = `
2914 <div class="modal move-modal">
2915 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
2916 <h2>Move To</h2>
2917 <p id="move-modal-caption" class="muted"></p>
2918 <div id="move-tree" class="move-tree"></div>
2919 <p id="move-selected" class="muted"></p>
2920 <div class="dialog-actions">
2921 <button id="move-modal-cancel">Cancel</button>
2922 <button id="move-modal-confirm" class="primary">Move</button>
2923 </div>
2924 </div>
2925 `;
2926 document.body.appendChild(overlay);
2927
2928 const closeBtn = overlay.querySelector('#move-modal-close');
2929 const cancelBtn = overlay.querySelector('#move-modal-cancel');
2930 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2931
2932 function hide ()
2933 {
2934 overlay.classList.add('hidden');
2935 STATE.movePicker = null;
2936 }
2937
2938 closeBtn.addEventListener('click', hide);
2939 cancelBtn.addEventListener('click', hide);
2940 overlay.addEventListener('click', (e) =>
2941 {
2942 if (e.target === overlay) hide();
2943 });
2944
2945 confirmBtn.addEventListener('click', async () =>
2946 {
2947 const st = STATE.movePicker;
2948 if (!st || !st.item || !st.selectedPath)
2949 {
2950 toast('Select a destination folder first.', 'err');
2951 return;
2952 }
2953
2954 try
2955 {
2956 if (st.mode === 'copy')
2957 {
2958 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2959 if (!copied) return;
2960 }
2961 else
2962 {
2963 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2964 if (!moved) return;
2965 }
2966 }
2967 catch (err)
2968 {
2969 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2970 toast(`${action} failed: ${err.message}`, 'err');
2971 return;
2972 }
2973
2974 hide();
2975 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2976 navigateTo(STATE.currentDir, STATE.currentRoot);
2977 });
2978
2979 return overlay;
2980}
2981
2982function setMoveSelection (path, buttonEl)
2983{
2984 if (!STATE.movePicker) return;
2985 STATE.movePicker.selectedPath = path;
2986
2987 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
2988 if (buttonEl) buttonEl.classList.add('selected');
2989
2990 const selectedEl = document.getElementById('move-selected');
2991 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
2992}
2993
2994async function loadMoveChildren (containerEl, dirPath)
2995{
2996 if (containerEl.dataset.loaded === '1') return;
2997 containerEl.dataset.loaded = '1';
2998
2999 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
3000 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
3001
3002 if (!folders.length)
3003 {
3004 const empty = document.createElement('div');
3005 empty.className = 'move-empty';
3006 empty.textContent = 'No subfolders';
3007 containerEl.appendChild(empty);
3008 return;
3009 }
3010
3011 for (const child of folders)
3012 {
3013 containerEl.appendChild(createMoveNode(child.path, child.name));
3014 }
3015}
3016
3017function createMoveNode (folderPath, label)
3018{
3019 const node = document.createElement('div');
3020 node.className = 'move-node';
3021
3022 const row = document.createElement('div');
3023 row.className = 'move-node-row';
3024
3025 const toggle = document.createElement('button');
3026 toggle.type = 'button';
3027 toggle.className = 'move-toggle';
3028 toggle.textContent = '▸';
3029
3030 const selectBtn = document.createElement('button');
3031 selectBtn.type = 'button';
3032 selectBtn.className = 'move-node-label';
3033 selectBtn.textContent = label;
3034 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
3035
3036 const children = document.createElement('div');
3037 children.className = 'move-children hidden';
3038
3039 toggle.addEventListener('click', async () =>
3040 {
3041 if (children.classList.contains('hidden'))
3042 {
3043 await loadMoveChildren(children, folderPath);
3044 children.classList.remove('hidden');
3045 toggle.textContent = '▾';
3046 } else
3047 {
3048 children.classList.add('hidden');
3049 toggle.textContent = '▸';
3050 }
3051 });
3052
3053 row.appendChild(toggle);
3054 row.appendChild(selectBtn);
3055 node.appendChild(row);
3056 node.appendChild(children);
3057 return node;
3058}
3059
3060function openDestinationPicker (item, mode)
3061{
3062 if (!canWrite())
3063 {
3064 toast('No write access.', 'err');
3065 return;
3066 }
3067
3068 const roots = writableRoots();
3069 if (!roots.length)
3070 {
3071 toast('No writable destination roots available.', 'err');
3072 return;
3073 }
3074
3075 const overlay = ensureMoveModal();
3076 const tree = overlay.querySelector('#move-tree');
3077 const caption = overlay.querySelector('#move-modal-caption');
3078 const titleEl = overlay.querySelector('h2');
3079 const confirmBtn = overlay.querySelector('#move-modal-confirm');
3080
3081 const op = mode === 'copy' ? 'copy' : 'move';
3082 STATE.movePicker = { item, selectedPath: null, mode: op };
3083 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
3084 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
3085 caption.textContent = `Select destination folder for: ${item.name}`;
3086 tree.innerHTML = '';
3087
3088 for (const root of roots)
3089 {
3090 tree.appendChild(createMoveNode(root.path, root.label));
3091 }
3092
3093 setMoveSelection(null, null);
3094 overlay.classList.remove('hidden');
3095}
3096
3097function openMovePicker (item)
3098{
3099 openDestinationPicker(item, 'move');
3100}
3101
3102function openCopyPicker (item)
3103{
3104 openDestinationPicker(item, 'copy');
3105}
3106
3107// ───────────────────────────────────────────────────────────────────────────
3108// FOLDER ICON PICKER
3109// ───────────────────────────────────────────────────────────────────────────
3110
3111function globalFaviconFallbackMarkup ()
3112{
3113 return iconFile('favicon.png', 18);
3114}
3115
3116function applyGlobalFaviconPreview (hasFavicon)
3117{
3118 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
3119 const preview = document.getElementById('global-favicon-preview');
3120 if (!preview) return;
3121
3122 if (!hasFavicon)
3123 {
3124 preview.innerHTML = globalFaviconFallbackMarkup();
3125 return;
3126 }
3127
3128 const img = document.createElement('img');
3129 img.alt = 'Current favicon';
3130 img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
3131 img.addEventListener('error', () =>
3132 {
3133 preview.innerHTML = globalFaviconFallbackMarkup();
3134 }, { once: true });
3135 preview.innerHTML = '';
3136 preview.appendChild(img);
3137}
3138
3139function applyGlobalFaviconLink (hasFavicon)
3140{
3141 if (typeof document === 'undefined' || typeof document.getElementById !== 'function' || !document.head) return;
3142 let link = document.getElementById('global-favicon-link');
3143 if (!link)
3144 {
3145 link = document.createElement('link');
3146 link.id = 'global-favicon-link';
3147 link.rel = 'icon';
3148 document.head.appendChild(link);
3149 }
3150
3151 if (!hasFavicon)
3152 {
3153 link.removeAttribute('href');
3154 return;
3155 }
3156
3157 link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
3158}
3159
3160async function refreshGlobalFavicon ()
3161{
3162 const data = await api('GET', '/files/global-favicon').catch(() => null);
3163 const hasFavicon = !!(data && data.favicon && data.favicon.filePath);
3164 applyGlobalFaviconPreview(hasFavicon);
3165 applyGlobalFaviconLink(hasFavicon);
3166}
3167
3168async function openIconPickerModal ({
3169 dirPath,
3170 titleText,
3171 subtitleText,
3172 emptyText,
3173 confirmLabel,
3174 clearLabel,
3175 onSelect,
3176 onClear,
3177})
3178{
3179 if (!dirPath)
3180 {
3181 toast('Open a folder first.', 'err');
3182 return;
3183 }
3184
3185 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
3186 const images = data ? data.images : [];
3187
3188 const existingIconOverlay = document.getElementById('folder-icon-picker');
3189 if (existingIconOverlay) existingIconOverlay.remove();
3190
3191 const overlay = document.createElement('div');
3192 overlay.id = 'folder-icon-picker';
3193 overlay.className = 'modal-overlay';
3194
3195 const modal = document.createElement('div');
3196 modal.className = 'modal folder-icon-modal';
3197
3198 const closeBtn = document.createElement('button');
3199 closeBtn.className = 'modal-close';
3200 closeBtn.setAttribute('aria-label', 'Close');
3201 closeBtn.textContent = '✕';
3202
3203 const title = document.createElement('h2');
3204 title.textContent = titleText;
3205
3206 const filterInput = document.createElement('input');
3207 filterInput.type = 'text';
3208 filterInput.className = 'folder-icon-filter';
3209 filterInput.placeholder = 'Search icons';
3210 filterInput.setAttribute('aria-label', 'Search icons');
3211
3212 const subtitle = document.createElement('p');
3213 subtitle.className = 'muted';
3214 subtitle.textContent = images.length ? subtitleText : emptyText;
3215
3216 const grid = document.createElement('div');
3217 grid.className = 'folder-icon-grid';
3218
3219 for (const { filePath } of images)
3220 {
3221 const name = filePath.split('/').pop();
3222 const cell = document.createElement('div');
3223 cell.className = 'folder-icon-cell';
3224 cell.dataset.path = filePath;
3225 cell.dataset.name = String(name || '').toLowerCase();
3226
3227 const imgEl = document.createElement('img');
3228 imgEl.alt = name;
3229 imgEl.className = 'folder-icon-thumb';
3230 imgEl.dataset.src = filePath;
3231
3232 const label = document.createElement('div');
3233 label.className = 'folder-icon-label';
3234 label.textContent = name;
3235
3236 cell.appendChild(imgEl);
3237 cell.appendChild(label);
3238
3239 cell.addEventListener('click', () =>
3240 {
3241 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3242 cell.classList.add('selected');
3243 confirmBtn.disabled = false;
3244 });
3245
3246 grid.appendChild(cell);
3247 }
3248
3249 function applyFilter ()
3250 {
3251 const needle = String(filterInput.value || '').trim().toLowerCase();
3252 let visible = 0;
3253 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3254 {
3255 const name = cell.dataset.name || '';
3256 const show = !needle || name.includes(needle);
3257 cell.classList.toggle('hidden', !show);
3258 if (show) visible += 1;
3259 }
3260 subtitle.textContent = visible
3261 ? subtitleText
3262 : 'No matching thumbnails were found.';
3263 }
3264
3265 filterInput.addEventListener('input', applyFilter);
3266
3267 const dialogActions = document.createElement('div');
3268 dialogActions.className = 'dialog-actions';
3269
3270 const clearBtn = document.createElement('button');
3271 clearBtn.textContent = clearLabel;
3272 clearBtn.addEventListener('click', async () =>
3273 {
3274 try
3275 {
3276 await onClear();
3277 }
3278 catch (err)
3279 {
3280 toast('Failed to clear icon: ' + err.message, 'err');
3281 return;
3282 }
3283 hide();
3284 });
3285
3286 const cancelBtn = document.createElement('button');
3287 cancelBtn.textContent = 'Cancel';
3288 cancelBtn.addEventListener('click', () => hide());
3289
3290 const confirmBtn = document.createElement('button');
3291 confirmBtn.className = 'primary';
3292 confirmBtn.textContent = confirmLabel;
3293 confirmBtn.disabled = true;
3294 confirmBtn.addEventListener('click', async () =>
3295 {
3296 const selected = grid.querySelector('.folder-icon-cell.selected');
3297 if (!selected) return;
3298
3299 try
3300 {
3301 await onSelect(selected.dataset.path);
3302 }
3303 catch (err)
3304 {
3305 toast('Failed to set icon: ' + err.message, 'err');
3306 return;
3307 }
3308
3309 hide();
3310 });
3311
3312 dialogActions.appendChild(clearBtn);
3313 dialogActions.appendChild(cancelBtn);
3314 dialogActions.appendChild(confirmBtn);
3315
3316 modal.appendChild(closeBtn);
3317 modal.appendChild(title);
3318 modal.appendChild(filterInput);
3319 modal.appendChild(subtitle);
3320 modal.appendChild(grid);
3321 modal.appendChild(dialogActions);
3322 overlay.appendChild(modal);
3323 document.body.appendChild(overlay);
3324
3325 function hide ()
3326 {
3327 overlay.remove();
3328 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3329 {
3330 URL.revokeObjectURL(img.src);
3331 });
3332 }
3333
3334 closeBtn.addEventListener('click', hide);
3335 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3336
3337 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3338 {
3339 const imgEl = cell.querySelector('.folder-icon-thumb');
3340 const filePath = imgEl.dataset.src;
3341 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3342 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3343 }).then(async (r) =>
3344 {
3345 if (!r.ok || !overlay.isConnected) return;
3346 const blob = await r.blob();
3347 const url = URL.createObjectURL(blob);
3348 imgEl.src = url;
3349 }).catch(() => { });
3350 }
3351
3352 filterInput.focus();
3353}
3354
3355async function openFolderIconPicker (item)
3356{
3357 if (!canWrite(item))
3358 {
3359 toast('No write access.', 'err');
3360 return;
3361 }
3362
3363 await openIconPickerModal({
3364 dirPath: item.path,
3365 titleText: 'Set folder icon',
3366 subtitleText: 'Select a file thumbnail to use as the folder icon.',
3367 emptyText: 'No files with cached thumbnails were found inside this folder.',
3368 confirmLabel: 'Set icon',
3369 clearLabel: 'Clear icon',
3370 onSelect: async (imagePath) =>
3371 {
3372 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
3373 refreshAfterIconChange(item);
3374 },
3375 onClear: async () =>
3376 {
3377 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
3378 refreshAfterIconChange(item);
3379 },
3380 });
3381}
3382
3383async function openGlobalFaviconPicker ()
3384{
3385 if (!STATE.isAdmin)
3386 {
3387 toast('Admin access required.', 'err');
3388 return;
3389 }
3390
3391 const existingIconOverlay = document.getElementById('folder-icon-picker');
3392 if (existingIconOverlay) existingIconOverlay.remove();
3393
3394 const overlay = document.createElement('div');
3395 overlay.id = 'folder-icon-picker';
3396 overlay.className = 'modal-overlay';
3397
3398 const modal = document.createElement('div');
3399 modal.className = 'modal folder-icon-modal';
3400
3401 const closeBtn = document.createElement('button');
3402 closeBtn.className = 'modal-close';
3403 closeBtn.setAttribute('aria-label', 'Close');
3404 closeBtn.textContent = '✕';
3405
3406 const title = document.createElement('h2');
3407 title.textContent = 'Set global favicon';
3408
3409 const filterInput = document.createElement('input');
3410 filterInput.type = 'text';
3411 filterInput.className = 'folder-icon-filter';
3412 filterInput.placeholder = 'Search images across all folders';
3413 filterInput.setAttribute('aria-label', 'Search images');
3414
3415 const subtitle = document.createElement('p');
3416 subtitle.className = 'muted';
3417 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3418
3419 const grid = document.createElement('div');
3420 grid.className = 'folder-icon-grid';
3421
3422 const dialogActions = document.createElement('div');
3423 dialogActions.className = 'dialog-actions';
3424
3425 const clearBtn = document.createElement('button');
3426 clearBtn.textContent = 'Clear favicon';
3427 clearBtn.addEventListener('click', async () =>
3428 {
3429 try
3430 {
3431 await api('POST', '/files/global-favicon', { imagePath: null });
3432 STATE.faviconVersion = Date.now();
3433 await refreshGlobalFavicon();
3434 }
3435 catch (err)
3436 {
3437 toast('Failed to clear icon: ' + err.message, 'err');
3438 return;
3439 }
3440 hide();
3441 });
3442
3443 const cancelBtn = document.createElement('button');
3444 cancelBtn.textContent = 'Cancel';
3445 cancelBtn.addEventListener('click', () => hide());
3446
3447 const confirmBtn = document.createElement('button');
3448 confirmBtn.className = 'primary';
3449 confirmBtn.textContent = 'Set favicon';
3450 confirmBtn.disabled = true;
3451
3452 let selectedPath = null;
3453 let searchToken = 0;
3454 let searchTimer = null;
3455
3456 confirmBtn.addEventListener('click', async () =>
3457 {
3458 if (!selectedPath) return;
3459 try
3460 {
3461 await api('POST', '/files/global-favicon', { imagePath: selectedPath });
3462 STATE.faviconVersion = Date.now();
3463 await refreshGlobalFavicon();
3464 }
3465 catch (err)
3466 {
3467 toast('Failed to set icon: ' + err.message, 'err');
3468 return;
3469 }
3470 hide();
3471 });
3472
3473 function revokeCellThumbs ()
3474 {
3475 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3476 {
3477 URL.revokeObjectURL(img.src);
3478 });
3479 }
3480
3481 function renderResults (items)
3482 {
3483 selectedPath = null;
3484 confirmBtn.disabled = true;
3485 revokeCellThumbs();
3486 grid.innerHTML = '';
3487
3488 for (const { path: filePath, name } of (items || []))
3489 {
3490 const cell = document.createElement('div');
3491 cell.className = 'folder-icon-cell';
3492 cell.dataset.path = filePath;
3493
3494 const imgEl = document.createElement('img');
3495 imgEl.alt = name;
3496 imgEl.className = 'folder-icon-thumb';
3497
3498 const label = document.createElement('div');
3499 label.className = 'folder-icon-label';
3500 label.textContent = name;
3501
3502 cell.appendChild(imgEl);
3503 cell.appendChild(label);
3504
3505 cell.addEventListener('click', () =>
3506 {
3507 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3508 cell.classList.add('selected');
3509 selectedPath = filePath;
3510 confirmBtn.disabled = false;
3511 });
3512
3513 grid.appendChild(cell);
3514
3515 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3516 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3517 }).then(async (r) =>
3518 {
3519 if (!r.ok || !overlay.isConnected) return;
3520 const blob = await r.blob();
3521 const url = URL.createObjectURL(blob);
3522 imgEl.src = url;
3523 }).catch(() => { });
3524 }
3525 }
3526
3527 async function runSearchNow ()
3528 {
3529 const query = String(filterInput.value || '').trim();
3530 searchToken += 1;
3531 const token = searchToken;
3532
3533 if (query.length < 2)
3534 {
3535 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3536 renderResults([]);
3537 return;
3538 }
3539
3540 subtitle.textContent = 'Searching…';
3541 const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null);
3542 if (!overlay.isConnected || token !== searchToken) return;
3543
3544 const results = Array.isArray(data && data.results) ? data.results : [];
3545 renderResults(results);
3546
3547 if (!results.length)
3548 {
3549 subtitle.textContent = 'No matching thumbnails were found.';
3550 return;
3551 }
3552
3553 const suffix = data && data.truncated
3554 ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.`
3555 : '';
3556 subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`;
3557 }
3558
3559 filterInput.addEventListener('input', () =>
3560 {
3561 if (searchTimer) clearTimeout(searchTimer);
3562 searchTimer = setTimeout(() =>
3563 {
3564 void runSearchNow();
3565 }, 240);
3566 });
3567
3568 dialogActions.appendChild(clearBtn);
3569 dialogActions.appendChild(cancelBtn);
3570 dialogActions.appendChild(confirmBtn);
3571
3572 modal.appendChild(closeBtn);
3573 modal.appendChild(title);
3574 modal.appendChild(filterInput);
3575 modal.appendChild(subtitle);
3576 modal.appendChild(grid);
3577 modal.appendChild(dialogActions);
3578 overlay.appendChild(modal);
3579 document.body.appendChild(overlay);
3580
3581 function hide ()
3582 {
3583 if (searchTimer) clearTimeout(searchTimer);
3584 overlay.remove();
3585 revokeCellThumbs();
3586 }
3587
3588 closeBtn.addEventListener('click', hide);
3589 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3590 filterInput.focus();
3591}
3592
3593function refreshAfterIconChange (item)
3594{
3595 // Reset and reload icon in grid tiles.
3596 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
3597 .find(el => el.dataset.folderPath === item.path);
3598 if (gridTile)
3599 {
3600 const svg = gridTile.querySelector('svg');
3601 if (svg)
3602 {
3603 // Rebuild to plain folder SVG, then reload.
3604 gridTile.innerHTML = iconFolder();
3605 delete gridTile.dataset.thumbReady;
3606 gridTile.dataset.folderPath = item.path;
3607 void loadOneFolderIcon(gridTile);
3608 }
3609 }
3610
3611 // Also reset the sidebar icon if it's showing the same folder.
3612 const sidebarIcon = document.getElementById('sidebar-icon');
3613 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
3614 {
3615 sidebarIcon.innerHTML = iconFolder(64);
3616 delete sidebarIcon.dataset.thumbReady;
3617 void loadOneFolderIcon(sidebarIcon);
3618 }
3619}
3620
3621// ───────────────────────────────────────────────────────────────────────────
3622// DOWNLOAD / VIEW
3623// ───────────────────────────────────────────────────────────────────────────
3624
3625function isInlinePreviewableBlob (blob, name)
3626{
3627 const mime = String(blob.type || '').toLowerCase();
3628 if (/^(image|video|audio)\//.test(mime)) return true;
3629 if (/^text\//.test(mime)) return true;
3630 if (mime === 'application/pdf') return true;
3631 if (mime === 'application/json') return true;
3632 if (mime === 'application/xml') return true;
3633 if (mime === 'application/javascript') return true;
3634
3635 // Fallback by extension when MIME is missing or generic.
3636 const ext = extOf(name || '');
3637 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
3638 if (MODEL_EXTS.has(ext)) return true;
3639 if (MODEL_EXTS.has(ext)) return true;
3640 if (CODE_EXTS.has(ext)) return true;
3641 return false;
3642}
3643
3644function isTextLikeBlob (blob, name)
3645{
3646 const mime = String(blob.type || '').toLowerCase();
3647 if (/^text\//.test(mime)) return true;
3648 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
3649 const ext = extOf(name || '');
3650 return CODE_EXTS.has(ext);
3651}
3652
3653function detectCodeLanguage (name, mime)
3654{
3655 const ext = extOf(name || '');
3656 const m = String(mime || '').toLowerCase();
3657 if (m.includes('json') || ext === 'json') return 'json';
3658 if (m.includes('xml') || ext === 'xml') return 'xml';
3659 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
3660 if (m.includes('css') || ext === 'css') return 'css';
3661 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
3662 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
3663 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
3664 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
3665 return CODE_EXTS.has(ext) ? 'js' : 'plain';
3666}
3667
3668function prettyPrintMarkup (raw)
3669{
3670 const src = String(raw || '')
3671 .replace(/>\s+</g, '><')
3672 .replace(/\r\n/g, '\n');
3673
3674 const lines = src.replace(/></g, '>\n<').split('\n');
3675 let indent = 0;
3676 const out = [];
3677
3678 for (const ln of lines)
3679 {
3680 const line = ln.trim();
3681 if (!line) continue;
3682 const isClose = /^<\//.test(line);
3683 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
3684 const isOpen = /^<[^!?/][^>]*>$/.test(line);
3685
3686 if (isClose) indent = Math.max(0, indent - 1);
3687 out.push(' '.repeat(indent) + line);
3688 if (isOpen && !isSelf) indent += 1;
3689 }
3690
3691 return out.join('\n');
3692}
3693
3694function prettyPrintBraces (raw)
3695{
3696 const lines = String(raw || '')
3697 .replace(/\r\n/g, '\n')
3698 .split('\n');
3699 let indent = 0;
3700 const out = [];
3701
3702 for (const ln of lines)
3703 {
3704 const line = ln.trim();
3705 if (!line)
3706 {
3707 out.push('');
3708 continue;
3709 }
3710 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
3711 out.push(' '.repeat(indent) + line);
3712 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
3713 }
3714 return out.join('\n');
3715}
3716
3717function prettyPrintCode (raw, lang)
3718{
3719 const text = String(raw || '').replace(/\r\n/g, '\n');
3720 if (lang === 'json')
3721 {
3722 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
3723 }
3724 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
3725 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
3726 return text;
3727}
3728
3729function escapeHtml (s)
3730{
3731 return String(s)
3732 .replace(/&/g, '&amp;')
3733 .replace(/</g, '&lt;')
3734 .replace(/>/g, '&gt;');
3735}
3736
3737function highlightCode (raw, lang)
3738{
3739 if (lang === 'plain') return escapeHtml(raw);
3740
3741 let html = escapeHtml(raw);
3742 const stash = [];
3743 const keep = (regex, cls) =>
3744 {
3745 html = html.replace(regex, (m) =>
3746 {
3747 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
3748 return `@@TOK${idx}@@`;
3749 });
3750 };
3751
3752 if (lang === 'json')
3753 {
3754 html = html
3755 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
3756 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
3757 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
3758 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
3759 return html;
3760 }
3761
3762 if (lang === 'xml' || lang === 'html')
3763 {
3764 html = html
3765 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
3766 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
3767 return html;
3768 }
3769
3770 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
3771 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
3772 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
3773
3774 html = html
3775 .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>')
3776 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
3777
3778 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
3779 return html;
3780}
3781
3782function clearPreviewObjectUrl ()
3783{
3784 if (typeof STATE.previewCleanup === 'function')
3785 {
3786 try { STATE.previewCleanup(); } catch { /* ignore */ }
3787 }
3788 STATE.previewCleanup = null;
3789 STATE.previewDownloadAction = null;
3790 if (!STATE.previewObjectUrl) return;
3791 if (String(STATE.previewObjectUrl).startsWith('blob:'))
3792 {
3793 URL.revokeObjectURL(STATE.previewObjectUrl);
3794 }
3795 STATE.previewObjectUrl = null;
3796}
3797
3798function ensureStylesheet (id, href)
3799{
3800 let link = document.getElementById(id);
3801 if (link) return Promise.resolve(link);
3802
3803 link = document.createElement('link');
3804 link.id = id;
3805 link.rel = 'stylesheet';
3806 link.href = href;
3807
3808 return new Promise((resolve, reject) =>
3809 {
3810 link.addEventListener('load', () => resolve(link), { once: true });
3811 link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });
3812 document.head.appendChild(link);
3813 });
3814}
3815
3816function ensureScript (id, src)
3817{
3818 let script = document.getElementById(id);
3819 if (script && window.videojs) return Promise.resolve(window.videojs);
3820
3821 if (!script)
3822 {
3823 script = document.createElement('script');
3824 script.id = id;
3825 script.src = src;
3826 }
3827
3828 return new Promise((resolve, reject) =>
3829 {
3830 script.addEventListener('load', () => resolve(window.videojs), { once: true });
3831 script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });
3832 if (!script.isConnected) document.head.appendChild(script);
3833 });
3834}
3835
3836async function ensureVideoJsLoaded ()
3837{
3838 if (window.videojs)
3839 {
3840 configureVideoJsBuffering(window.videojs);
3841 return window.videojs;
3842 }
3843 if (!videoJsLoaderPromise)
3844 {
3845 videoJsLoaderPromise = Promise.all([
3846 ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),
3847 ensureScript('videojs-script', '/vendor/video.js/video.min.js'),
3848 ]).then(() =>
3849 {
3850 configureVideoJsBuffering(window.videojs);
3851 return window.videojs;
3852 });
3853 }
3854 return videoJsLoaderPromise;
3855}
3856
3857function configureVideoJsBuffering (videojs)
3858{
3859 const shared = sharedVideoPlayer();
3860 if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return;
3861 shared.configureVideoJsBuffering(videojs, {
3862 enabled: VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED,
3863 seconds: VIDEO_FORWARD_BUFFER_SECONDS,
3864 });
3865}
3866
3867async function createVideoStreamSessionForItem (item)
3868{
3869 return api('POST', '/files/video-stream', { filePath: item.path });
3870}
3871
3872async function releaseVideoStreamSession (sessionId, opts = {})
3873{
3874 const id = String(sessionId || '').trim();
3875 if (!id) return;
3876
3877 await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {
3878 keepalive: !!opts.keepalive,
3879 noAutoLogout: true,
3880 }).catch(() => null);
3881}
3882
3883function releaseActivePreviewVideoStreamSession (opts = {})
3884{
3885 const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();
3886 if (!sessionId) return;
3887 STATE.previewVideoStreamSessionId = null;
3888 void releaseVideoStreamSession(sessionId, opts);
3889}
3890
3891async function preparePreviewDownload (item)
3892{
3893 const blob = await fetchFileBlob(item);
3894 if (!blob)
3895 {
3896 toast('Download failed.', 'err');
3897 return;
3898 }
3899
3900 const objectUrl = URL.createObjectURL(blob);
3901 triggerDownload(item.name, objectUrl);
3902 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
3903}
3904
3905async function renderStreamedVideoPreview (item, targetEl)
3906{
3907 const videojs = await ensureVideoJsLoaded();
3908 const session = await createVideoStreamSessionForItem(item);
3909 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3910 const prefs = loadUserVideoPrefs();
3911 applyUserVideoTextTrackPrefs();
3912
3913 if ((session.subtitleSummary && session.subtitleSummary.skipped > 0))
3914 {
3915 toast('Some subtitle tracks could not be converted for web playback.', 'err');
3916 }
3917
3918 STATE.previewDownloadAction = () => preparePreviewDownload(item);
3919
3920 const video = document.createElement('video');
3921 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
3922 video.controls = true;
3923 video.preload = 'auto';
3924 video.playsInline = true;
3925 targetEl.classList.add('preview-expand-content--video');
3926 targetEl.appendChild(video);
3927
3928 const player = videojs(video, {
3929 controls: true,
3930 fluid: false,
3931 fill: true,
3932 responsive: false,
3933 preload: 'auto',
3934 controlBar: {
3935 currentTimeDisplay: true,
3936 timeDivider: true,
3937 durationDisplay: true,
3938 remainingTimeDisplay: false,
3939 },
3940 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
3941 tracks: (session.subtitleTracks || []).map((track) => ({
3942 kind: 'subtitles',
3943 src: track.src,
3944 srclang: track.language || 'und',
3945 label: track.label,
3946 default: !!track.default,
3947 })),
3948 });
3949
3950 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
3951
3952 ensureVideoPlaybackUi(player, session.durationSeconds);
3953 const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item);
3954
3955 // -------------------------------------------------------------------------
3956
3957 let sentPartway = false;
3958 let sentFully = false;
3959 const markWatch = async () =>
3960 {
3961 let ratio = 0;
3962 try
3963 {
3964 const duration = Number(player.duration());
3965 const current = Number(player.currentTime());
3966 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
3967 {
3968 ratio = current / duration;
3969 }
3970 } catch
3971 {
3972 return;
3973 }
3974
3975 if (ratio >= 0.7)
3976 {
3977 if (sentFully) return;
3978 sentPartway = true;
3979 sentFully = true;
3980 void reportWatchProgress(item.path, ratio);
3981 return;
3982 }
3983
3984 if (ratio >= 0.05)
3985 {
3986 if (sentPartway) return;
3987 sentPartway = true;
3988 void reportWatchProgress(item.path, ratio);
3989 }
3990 };
3991
3992 player.ready(() =>
3993 {
3994 const volume = Number(prefs.volume);
3995 if (Number.isFinite(volume))
3996 {
3997 player.volume(Math.max(0, Math.min(1, volume)));
3998 }
3999
4000 const settings = player && player.textTrackSettings;
4001 if (settings && typeof settings.setValues === 'function' && typeof settings.updateDisplay === 'function')
4002 {
4003 settings.setValues({
4004 backgroundColor: '#000',
4005 backgroundOpacity: '0',
4006 edgeStyle: 'uniform',
4007 });
4008 settings.updateDisplay();
4009 }
4010
4011 trackPrefs.applySavedTracks();
4012 });
4013
4014 player.on('loadedmetadata', trackPrefs.applySavedTracks);
4015 player.on('loadedplaylist', trackPrefs.applySavedTracks);
4016 player.on('timeupdate', markWatch);
4017 player.on('ended', () =>
4018 {
4019 sentPartway = true;
4020 sentFully = true;
4021 void reportWatchProgress(item.path, 1);
4022 });
4023 player.on('volumechange', () =>
4024 {
4025 const v = Number(player.volume());
4026 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
4027 });
4028
4029 STATE.previewCleanup = () =>
4030 {
4031 if (imageSubtitleController)
4032 {
4033 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4034 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4035 }
4036 releaseActivePreviewVideoStreamSession();
4037 try { markWatch(); } catch { /* ignore */ }
4038 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
4039 try { trackPrefs.detach(); } catch { /* ignore */ }
4040 try { player.dispose(); } catch { /* ignore */ }
4041 };
4042}
4043
4044function fileAccentColor (name)
4045{
4046 const ext = extOf(name || '');
4047 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
4048 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
4049 if (AUDIO_EXTS.has(ext)) return '#c084fc';
4050 if (MODEL_EXTS.has(ext)) return '#2f6dff';
4051 if (DOC_EXTS.has(ext)) return '#f97316';
4052 if (CODE_EXTS.has(ext)) return '#38bdf8';
4053 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
4054 return '#7880a0';
4055}
4056
4057function animateRect (el, fromRect, toRect, opts = {})
4058{
4059 const duration = opts.duration == null ? 260 : opts.duration;
4060 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
4061
4062 el.style.left = `${fromRect.left}px`;
4063 el.style.top = `${fromRect.top}px`;
4064 el.style.width = `${fromRect.width}px`;
4065 el.style.height = `${fromRect.height}px`;
4066
4067 return new Promise((resolve) =>
4068 {
4069 const t0 = performance.now();
4070
4071 function frame (now)
4072 {
4073 const raw = Math.min((now - t0) / duration, 1);
4074 const t = easeOut(raw);
4075
4076 const left = fromRect.left + (toRect.left - fromRect.left) * t;
4077 const top = fromRect.top + (toRect.top - fromRect.top) * t;
4078 const width = fromRect.width + (toRect.width - fromRect.width) * t;
4079 const height = fromRect.height + (toRect.height - fromRect.height) * t;
4080
4081 el.style.left = `${left}px`;
4082 el.style.top = `${top}px`;
4083 el.style.width = `${width}px`;
4084 el.style.height = `${height}px`;
4085
4086 if (raw < 1)
4087 {
4088 requestAnimationFrame(frame);
4089 } else
4090 {
4091 resolve();
4092 }
4093 }
4094
4095 requestAnimationFrame(frame);
4096 });
4097}
4098
4099async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
4100{
4101 if (!tileEl || !sourceSvgEl) return false;
4102
4103 if (STATE.previewExpandState)
4104 {
4105 await closeExpandedTilePreview();
4106 }
4107
4108 const iconEl = tileEl.querySelector('.icon');
4109 const nameEl = tileEl.querySelector('.name');
4110 if (!iconEl) return false;
4111
4112 const startRect = tileEl.getBoundingClientRect();
4113 const targetW = Math.min(window.innerWidth * 0.94, 1100);
4114 const targetH = Math.min(window.innerHeight * 0.9, 860);
4115 const targetRect = {
4116 left: (window.innerWidth - targetW) / 2,
4117 top: (window.innerHeight - targetH) / 2,
4118 width: targetW,
4119 height: targetH,
4120 };
4121
4122 const backdrop = document.createElement('div');
4123 backdrop.className = 'preview-backdrop';
4124 document.body.appendChild(backdrop);
4125
4126 const parent = tileEl.parentNode;
4127 const nextSibling = tileEl.nextSibling;
4128 const iconHtml = iconEl.innerHTML;
4129 const originalIconSvg = iconEl.querySelector('svg');
4130 const placeholder = document.createElement('div');
4131 placeholder.className = 'file-item file-item--preview-placeholder';
4132 placeholder.style.width = `${startRect.width}px`;
4133 placeholder.style.height = `${startRect.height}px`;
4134
4135 if (parent)
4136 {
4137 parent.insertBefore(placeholder, tileEl);
4138 }
4139
4140 tileEl.remove();
4141 document.body.appendChild(tileEl);
4142 tileEl.classList.add('file-item--preview');
4143 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
4144 tileEl.style.position = 'fixed';
4145 tileEl.style.left = `${startRect.left}px`;
4146 tileEl.style.top = `${startRect.top}px`;
4147 tileEl.style.width = `${startRect.width}px`;
4148 tileEl.style.height = `${startRect.height}px`;
4149 tileEl.style.margin = '0';
4150 tileEl.style.zIndex = '10000';
4151
4152 if (nameEl) nameEl.style.display = 'none';
4153
4154 const titleEl = document.createElement('div');
4155 titleEl.className = 'preview-expand-title';
4156 titleEl.textContent = item.name;
4157
4158 const closeBtn = document.createElement('button');
4159 closeBtn.className = 'preview-expand-close';
4160 closeBtn.type = 'button';
4161 closeBtn.textContent = '×';
4162 closeBtn.setAttribute('aria-label', 'Close preview');
4163
4164 const dlBtn = document.createElement('button');
4165 dlBtn.className = 'preview-expand-download';
4166 dlBtn.type = 'button';
4167 dlBtn.textContent = 'Download';
4168 dlBtn.addEventListener('click', async (e) =>
4169 {
4170 e.stopPropagation();
4171 if (STATE.previewDownloadAction)
4172 {
4173 await STATE.previewDownloadAction();
4174 return;
4175 }
4176 if (!STATE.previewObjectUrl)
4177 {
4178 toast('Preview still loading.', 'err');
4179 return;
4180 }
4181 triggerDownload(item.name, STATE.previewObjectUrl);
4182 });
4183
4184 const shareBtn = document.createElement('button');
4185 shareBtn.className = 'preview-expand-share';
4186 shareBtn.type = 'button';
4187 shareBtn.textContent = 'Share';
4188 shareBtn.addEventListener('click', (e) =>
4189 {
4190 e.stopPropagation();
4191 openShareModal(item);
4192 });
4193
4194 const actionsEl = document.createElement('div');
4195 actionsEl.className = 'preview-expand-actions';
4196 actionsEl.appendChild(shareBtn);
4197 actionsEl.appendChild(dlBtn);
4198
4199 iconEl.innerHTML = '';
4200
4201 if (originalIconSvg)
4202 {
4203 const outline = originalIconSvg.cloneNode(true);
4204 outline.classList.add('preview-expand-outline');
4205 iconEl.appendChild(outline);
4206 }
4207
4208 const previewMount = document.createElement('div');
4209 previewMount.className = 'preview-expand-content';
4210 iconEl.appendChild(previewMount);
4211
4212 // Show spinner during expansion animation; content loads after it finishes
4213 const spinner = document.createElement('div');
4214 spinner.className = 'preview-loading-spinner';
4215 previewMount.appendChild(spinner);
4216
4217 tileEl.insertBefore(titleEl, tileEl.firstChild);
4218 tileEl.appendChild(closeBtn);
4219 tileEl.appendChild(actionsEl);
4220
4221 STATE.previewExpandState = {
4222 item,
4223 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
4224 tileEl,
4225 sourceSvgEl,
4226 parent,
4227 nextSibling,
4228 iconEl,
4229 iconHtml,
4230 nameEl,
4231 backdrop,
4232 placeholder,
4233 closeBtn,
4234 dlBtn,
4235 shareBtn,
4236 actionsEl,
4237 titleEl,
4238 previewMount,
4239 startRect,
4240 };
4241
4242 const onBackdrop = (e) =>
4243 {
4244 if (e.target === backdrop) closePreview();
4245 };
4246 const onClose = () => closePreview({ force: true });
4247 backdrop.addEventListener('click', onBackdrop);
4248 closeBtn.addEventListener('click', onClose);
4249 STATE.previewExpandState.onBackdrop = onBackdrop;
4250 STATE.previewExpandState.onClose = onClose;
4251
4252 requestAnimationFrame(() => backdrop.classList.add('visible'));
4253 await animateRect(tileEl, startRect, targetRect);
4254
4255 tileEl.style.left = `${targetRect.left}px`;
4256 tileEl.style.top = `${targetRect.top}px`;
4257 tileEl.style.width = `${targetRect.width}px`;
4258 tileEl.style.height = `${targetRect.height}px`;
4259
4260 try
4261 {
4262 await loadPreviewContent(previewMount);
4263 } catch
4264 {
4265 if (previewMount.isConnected)
4266 {
4267 previewMount.innerHTML = '';
4268 const msg = document.createElement('p');
4269 msg.className = 'preview-unsupported';
4270 msg.textContent = 'Preview failed to load. You can try again.';
4271 previewMount.appendChild(msg);
4272 }
4273 }
4274
4275 return true;
4276}
4277
4278async function closeExpandedTilePreview ()
4279{
4280 const st = STATE.previewExpandState;
4281 if (!st) return;
4282
4283 st.backdrop.classList.remove('visible');
4284 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
4285 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
4286
4287 const fromRect = st.tileEl.getBoundingClientRect();
4288 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
4289
4290 st.tileEl.classList.remove('file-item--preview');
4291 st.tileEl.style.position = '';
4292 st.tileEl.style.left = '';
4293 st.tileEl.style.top = '';
4294 st.tileEl.style.width = '';
4295 st.tileEl.style.height = '';
4296 st.tileEl.style.margin = '';
4297 st.tileEl.style.zIndex = '';
4298
4299 if (st.titleEl) st.titleEl.remove();
4300 if (st.closeBtn) st.closeBtn.remove();
4301 if (st.actionsEl) st.actionsEl.remove();
4302 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
4303 if (st.nameEl) st.nameEl.style.display = '';
4304
4305 if (st.placeholder && st.placeholder.parentNode)
4306 {
4307 st.placeholder.parentNode.insertBefore(st.tileEl, st.placeholder);
4308 st.placeholder.remove();
4309 } else if (st.parent)
4310 {
4311 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
4312 {
4313 st.parent.insertBefore(st.tileEl, st.nextSibling);
4314 } else
4315 {
4316 st.parent.appendChild(st.tileEl);
4317 }
4318 }
4319
4320 if (st.backdrop) st.backdrop.remove();
4321 STATE.previewExpandState = null;
4322}
4323
4324async function closePreview (opts = {})
4325{
4326 if (STATE.previewClosing) return;
4327 if (STATE.previewExpandState)
4328 {
4329 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
4330 {
4331 return;
4332 }
4333
4334 STATE.previewClosing = true;
4335 clearPreviewObjectUrl();
4336 try
4337 {
4338 await closeExpandedTilePreview();
4339 STATE.previewSourceEl = null;
4340 } finally
4341 {
4342 STATE.previewClosing = false;
4343 }
4344 }
4345}
4346
4347async function fetchFileBlob (item)
4348{
4349 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
4350 try
4351 {
4352 const res = await fetch(url, {
4353 headers: {
4354 Authorization: 'Bearer ' + STATE.token,
4355 'X-Fp': getFingerprint(),
4356 },
4357 });
4358 if (!res.ok) throw new Error('Download failed.');
4359 return await res.blob();
4360 } catch
4361 {
4362 return null;
4363 }
4364}
4365
4366function triggerDownload (filename, objectUrl)
4367{
4368 const a = document.createElement('a');
4369 a.href = objectUrl;
4370 a.download = filename;
4371 a.click();
4372}
4373
4374function modelPreviewType (name)
4375{
4376 const ext = extOf(name || '');
4377 if (MODEL_EXTS.has(ext)) return ext;
4378 return null;
4379}
4380
4381async function loadThreePreviewModules ()
4382{
4383 if (!threePreviewModulesPromise)
4384 {
4385 threePreviewModulesPromise = Promise.all([
4386 import('/vendor/three/three.module.js'),
4387 import('/vendor/three/addons/controls/OrbitControls.js'),
4388 import('/vendor/three/addons/loaders/STLLoader.js'),
4389 import('/vendor/three/addons/loaders/OBJLoader.js'),
4390 ]).then(([THREE, controlsMod, stlMod, objMod]) =>
4391 {
4392 return {
4393 THREE,
4394 OrbitControls: controlsMod.OrbitControls,
4395 STLLoader: stlMod.STLLoader,
4396 OBJLoader: objMod.OBJLoader,
4397 };
4398 });
4399 }
4400
4401 return threePreviewModulesPromise;
4402}
4403
4404function disposeObject3D (root)
4405{
4406 if (!root || typeof root.traverse !== 'function') return;
4407 root.traverse((node) =>
4408 {
4409 if (node.geometry && typeof node.geometry.dispose === 'function')
4410 {
4411 node.geometry.dispose();
4412 }
4413
4414 if (!node.material) return;
4415 if (Array.isArray(node.material))
4416 {
4417 node.material.forEach((material) =>
4418 {
4419 if (material && typeof material.dispose === 'function') material.dispose();
4420 });
4421 return;
4422 }
4423
4424 if (typeof node.material.dispose === 'function') node.material.dispose();
4425 });
4426}
4427
4428async function buildModelObjectFromBlob (blob, type, modules)
4429{
4430 const { THREE, STLLoader, OBJLoader } = modules;
4431 const sharedMaterial = new THREE.MeshStandardMaterial({
4432 color: 0x2f6dff,
4433 metalness: 0.08,
4434 roughness: 0.72,
4435 });
4436
4437 if (type === 'stl')
4438 {
4439 const arr = await blob.arrayBuffer();
4440 const geometry = new STLLoader().parse(arr);
4441 geometry.computeVertexNormals();
4442 return new THREE.Mesh(geometry, sharedMaterial);
4443 }
4444
4445 if (type === 'obj')
4446 {
4447 const text = await blob.text();
4448 const obj = new OBJLoader().parse(text);
4449 obj.traverse((node) =>
4450 {
4451 if (!node || !node.isMesh) return;
4452 node.material = sharedMaterial.clone();
4453 });
4454 sharedMaterial.dispose();
4455 return obj;
4456 }
4457
4458 throw new Error('Unsupported 3D model format.');
4459}
4460
4461function setModelPreviewMessage (wrap, text)
4462{
4463 wrap.innerHTML = '';
4464 const msg = document.createElement('p');
4465 msg.className = 'preview-unsupported';
4466 msg.textContent = text;
4467 wrap.appendChild(msg);
4468}
4469
4470async function renderModelPreview (item, blob, targetEl)
4471{
4472 const type = modelPreviewType(item && item.name);
4473 if (!type)
4474 {
4475 const msg = document.createElement('p');
4476 msg.className = 'preview-unsupported';
4477 msg.textContent = 'This 3D file type is not supported yet.';
4478 targetEl.appendChild(msg);
4479 return;
4480 }
4481
4482 const wrap = document.createElement('div');
4483 wrap.className = 'preview-model-wrap';
4484 targetEl.appendChild(wrap);
4485
4486 const canvas = document.createElement('canvas');
4487 canvas.className = 'preview-model-canvas';
4488 canvas.style.touchAction = 'none';
4489 wrap.appendChild(canvas);
4490
4491 const hint = document.createElement('p');
4492 hint.className = 'preview-model-hint';
4493 hint.textContent = 'Drag to rotate. Use the scroll wheel to zoom.';
4494 wrap.appendChild(hint);
4495
4496 const gl =
4497 canvas.getContext('webgl2', { antialias: true, alpha: true }) ||
4498 canvas.getContext('webgl', { antialias: true, alpha: true });
4499 if (!gl)
4500 {
4501 setModelPreviewMessage(wrap, '3D preview is not available in this browser. You can still download this file.');
4502 return;
4503 }
4504
4505 let modules;
4506 try
4507 {
4508 modules = await loadThreePreviewModules();
4509 } catch
4510 {
4511 setModelPreviewMessage(wrap, '3D preview dependencies failed to load. You can still download this file.');
4512 return;
4513 }
4514
4515 if (!wrap.isConnected) return;
4516
4517 const { THREE, OrbitControls } = modules;
4518 const scene = new THREE.Scene();
4519 scene.background = new THREE.Color(0x0d111a);
4520
4521 const camera = new THREE.PerspectiveCamera(50, 1, 0.01, 5000);
4522 const renderer = new THREE.WebGLRenderer({ canvas, context: gl, antialias: true, alpha: true });
4523 renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
4524
4525 const ambient = new THREE.AmbientLight(0xffffff, 0.9);
4526 const key = new THREE.DirectionalLight(0xffffff, 0.95);
4527 key.position.set(1.2, 1.6, 1.1);
4528 scene.add(ambient);
4529 scene.add(key);
4530
4531 let modelRoot;
4532 try
4533 {
4534 modelRoot = await buildModelObjectFromBlob(blob, type, modules);
4535 } catch
4536 {
4537 renderer.dispose();
4538 setModelPreviewMessage(wrap, 'This 3D file could not be parsed. You can still download it.');
4539 return;
4540 }
4541
4542 if (!wrap.isConnected)
4543 {
4544 disposeObject3D(modelRoot);
4545 renderer.dispose();
4546 return;
4547 }
4548
4549 scene.add(modelRoot);
4550
4551 const box = new THREE.Box3().setFromObject(modelRoot);
4552 if (box.isEmpty())
4553 {
4554 disposeObject3D(modelRoot);
4555 renderer.dispose();
4556 setModelPreviewMessage(wrap, 'This 3D file has no visible geometry to preview.');
4557 return;
4558 }
4559
4560 const size = new THREE.Vector3();
4561 const center = new THREE.Vector3();
4562 box.getSize(size);
4563 box.getCenter(center);
4564 modelRoot.position.sub(center);
4565
4566 const maxDim = Math.max(size.x, size.y, size.z) || 1;
4567 const camDistance = maxDim * 1.8;
4568 camera.position.set(camDistance, camDistance * 0.75, camDistance);
4569 camera.near = Math.max(0.001, maxDim / 2000);
4570 camera.far = Math.max(1000, maxDim * 2000);
4571 camera.updateProjectionMatrix();
4572
4573 const controls = new OrbitControls(camera, renderer.domElement);
4574 controls.enableDamping = true;
4575 controls.dampingFactor = 0.08;
4576 controls.target.set(0, 0, 0);
4577 controls.minDistance = maxDim * 0.2;
4578 controls.maxDistance = maxDim * 25;
4579 controls.update();
4580
4581 const resize = () =>
4582 {
4583 const w = Math.max(160, Math.floor(wrap.clientWidth || 0));
4584 const h = Math.max(160, Math.floor((wrap.clientHeight || 0) - (hint.offsetHeight || 0) - 6));
4585 renderer.setSize(w, h, false);
4586 camera.aspect = w / h;
4587 camera.updateProjectionMatrix();
4588 };
4589 resize();
4590
4591 let stop = false;
4592 let rafId = 0;
4593 const frame = () =>
4594 {
4595 if (stop) return;
4596 controls.update();
4597 renderer.render(scene, camera);
4598 rafId = requestAnimationFrame(frame);
4599 };
4600 frame();
4601
4602 const resizeObserver = typeof ResizeObserver === 'function'
4603 ? new ResizeObserver(() => resize())
4604 : null;
4605 if (resizeObserver) resizeObserver.observe(wrap);
4606
4607 STATE.previewCleanup = () =>
4608 {
4609 stop = true;
4610 if (rafId) cancelAnimationFrame(rafId);
4611 if (resizeObserver) resizeObserver.disconnect();
4612 try { controls.dispose(); } catch { /* ignore */ }
4613 try { disposeObject3D(modelRoot); } catch { /* ignore */ }
4614 try { renderer.dispose(); } catch { /* ignore */ }
4615 };
4616}
4617
4618async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
4619{
4620 const body = targetEl || document.getElementById('preview-body');
4621 body.innerHTML = '';
4622
4623 const mime = String(blob.type || '').toLowerCase();
4624 const previewable = isInlinePreviewableBlob(blob, item.name);
4625
4626 if (!previewable)
4627 {
4628 const msg = document.createElement('p');
4629 msg.className = 'preview-unsupported';
4630 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
4631 body.appendChild(msg);
4632 return;
4633 }
4634
4635 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
4636 {
4637 const img = document.createElement('img');
4638 img.className = 'preview-media';
4639 img.src = objectUrl;
4640 img.alt = item.name;
4641 body.appendChild(img);
4642 return;
4643 }
4644
4645 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
4646 {
4647 const video = document.createElement('video');
4648 video.className = 'preview-media';
4649 video.src = objectUrl;
4650 video.controls = true;
4651 video.preload = 'metadata';
4652 body.appendChild(video);
4653 return;
4654 }
4655
4656 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
4657 {
4658 const audio = document.createElement('audio');
4659 audio.className = 'preview-audio';
4660 audio.src = objectUrl;
4661 audio.controls = true;
4662 body.appendChild(audio);
4663 return;
4664 }
4665
4666 if (modelPreviewType(item.name))
4667 {
4668 await renderModelPreview(item, blob, body);
4669 return;
4670 }
4671
4672 if (mime === 'application/pdf')
4673 {
4674 const frame = document.createElement('iframe');
4675 frame.className = 'preview-frame';
4676 frame.src = objectUrl;
4677 frame.title = item.name;
4678 body.appendChild(frame);
4679 return;
4680 }
4681
4682 if (isTextLikeBlob(blob, item.name))
4683 {
4684 const text = await blob.text();
4685 const lang = detectCodeLanguage(item.name, mime);
4686 const formatted = prettyPrintCode(text, lang);
4687 const pre = document.createElement('pre');
4688 pre.className = 'preview-text preview-code';
4689 pre.innerHTML = highlightCode(formatted, lang);
4690 body.appendChild(pre);
4691 return;
4692 }
4693
4694 const msg = document.createElement('p');
4695 msg.className = 'preview-unsupported';
4696 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
4697 body.appendChild(msg);
4698}
4699
4700async function downloadOrView (item, sourceSvgEl = null)
4701{
4702 if (STATE.previewExpandState)
4703 {
4704 await closePreview({ force: true });
4705 }
4706
4707 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
4708 if (sourceTileEl)
4709 {
4710 STATE.previewSourceEl = sourceSvgEl;
4711 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
4712 {
4713 if (VIDEO_EXTS.has(extOf(item.name)))
4714 {
4715 clearPreviewObjectUrl();
4716 previewMount.innerHTML = '';
4717 await renderStreamedVideoPreview(item, previewMount);
4718 return;
4719 }
4720
4721 const blob = await fetchFileBlob(item);
4722 if (!blob) throw new Error('Download failed');
4723
4724 clearPreviewObjectUrl();
4725 const objectUrl = URL.createObjectURL(blob);
4726 STATE.previewObjectUrl = objectUrl;
4727
4728 if (!previewMount.isConnected) return;
4729
4730 previewMount.innerHTML = '';
4731 await renderPreviewBody(item, blob, objectUrl, previewMount);
4732 });
4733 if (expanded) return;
4734 }
4735
4736 toast('Preview unavailable — no source tile found.', 'err');
4737}
4738
4739// ───────────────────────────────────────────────────────────────────────────
4740// UPLOAD
4741// ───────────────────────────────────────────────────────────────────────────
4742
4743async function createFolderInCurrentDir ()
4744{
4745 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4746 if (!canWrite()) { toast('No write access.', 'err'); return; }
4747
4748 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
4749 if (name == null) return;
4750 const folderName = name.trim();
4751 if (!folderName)
4752 {
4753 toast('Folder name is required.', 'err');
4754 return;
4755 }
4756
4757 try
4758 {
4759 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
4760 toast('Folder created.', 'ok');
4761 await navigateTo(STATE.currentDir, STATE.currentRoot);
4762 } catch (err)
4763 {
4764 toast(err.message, 'err');
4765 }
4766}
4767
4768function canWrite (item = null)
4769{
4770 if (STATE.isAdmin) return true;
4771 const root = item && item._root
4772 ? item._root
4773 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
4774 if (!root) return false;
4775 if (root.isUserFolder) return true;
4776 const p = STATE.permissions[rootPermissionLabel(root)];
4777 return p && p.write;
4778}
4779
4780async function uploadFiles (fileList)
4781{
4782 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4783 if (!canWrite()) { toast('No write access.', 'err'); return; }
4784
4785 const files = Array.from(fileList || []);
4786 if (!files.length) return;
4787
4788 // Show upload bar
4789 const wrap = document.createElement('div');
4790 wrap.className = 'upload-bar-wrap';
4791 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
4792 document.body.appendChild(wrap);
4793 STATE.uploadInProgress = true;
4794
4795 try
4796 {
4797 const existingNames = await listDirNameSet(STATE.currentDir);
4798 let done = 0;
4799 let uploaded = 0;
4800
4801 for (const original of files)
4802 {
4803 let fileToUpload = original;
4804
4805 if (existingNames.has(original.name))
4806 {
4807 const suggested = nextAvailableName(original.name, existingNames);
4808 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
4809 if (decision === 'cancel')
4810 {
4811 done++;
4812 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
4813 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
4814 continue;
4815 }
4816
4817 if (decision === 'rename')
4818 {
4819 fileToUpload = cloneFileWithName(original, suggested);
4820 }
4821 }
4822
4823 await uploadSingleFile(fileToUpload, STATE.currentDir);
4824 existingNames.add(fileToUpload.name);
4825 done++;
4826 uploaded++;
4827 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
4828 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
4829 }
4830
4831 toast(`Uploaded ${uploaded} file(s).`, 'ok');
4832 await navigateTo(STATE.currentDir, STATE.currentRoot);
4833 } catch (err)
4834 {
4835 toast(err.message, 'err');
4836 } finally
4837 {
4838 STATE.uploadInProgress = false;
4839 wrap.remove();
4840 }
4841}
4842
4843async function uploadSingleFile (file, targetDir)
4844{
4845 const formData = new FormData();
4846 formData.append('files', file);
4847
4848 await new Promise((resolve, reject) =>
4849 {
4850 const xhr = new XMLHttpRequest();
4851 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
4852 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
4853 xhr.setRequestHeader('X-Fp', getFingerprint());
4854 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
4855 xhr.onload = () => xhr.status === 200
4856 ? resolve()
4857 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
4858 xhr.onerror = () => reject(new Error('Network error'));
4859 xhr.send(formData);
4860 });
4861}
4862
4863async function ensureServerDir (baseDir, relativeDir)
4864{
4865 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
4866 let current = baseDir;
4867 for (const part of parts)
4868 {
4869 try
4870 {
4871 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
4872 current = resp && resp.path ? resp.path : joinServerPath(current, part);
4873 } catch (err)
4874 {
4875 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
4876 current = joinServerPath(current, part);
4877 }
4878 }
4879 return current;
4880}
4881
4882async function uploadFolderInputFiles (fileList)
4883{
4884 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4885 if (!canWrite()) { toast('No write access.', 'err'); return; }
4886 if (!fileList || !fileList.length) return;
4887
4888 const files = Array.from(fileList);
4889 const total = files.length;
4890 let done = 0;
4891
4892 const wrap = document.createElement('div');
4893 wrap.className = 'upload-bar-wrap';
4894 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
4895 document.body.appendChild(wrap);
4896 STATE.uploadInProgress = true;
4897
4898 try
4899 {
4900 const dirCache = new Map();
4901 dirCache.set('', STATE.currentDir);
4902
4903 for (const file of files)
4904 {
4905 const rel = file.webkitRelativePath || file.name;
4906 const relParts = rel.split(/[\\/]/).filter(Boolean);
4907 const relDir = relParts.slice(0, -1).join('/');
4908
4909 if (!dirCache.has(relDir))
4910 {
4911 const parentRel = relParts.slice(0, -2).join('/');
4912 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
4913 const thisName = relParts[relParts.length - 2];
4914
4915 try
4916 {
4917 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
4918 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
4919 } catch (err)
4920 {
4921 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
4922 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
4923 }
4924 }
4925
4926 const targetDir = dirCache.get(relDir) || STATE.currentDir;
4927 await uploadSingleFile(file, targetDir);
4928 done++;
4929 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
4930 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
4931 }
4932
4933 toast(`Uploaded ${total} file(s).`, 'ok');
4934 await navigateTo(STATE.currentDir, STATE.currentRoot);
4935 } catch (err)
4936 {
4937 toast(err.message, 'err');
4938 } finally
4939 {
4940 STATE.uploadInProgress = false;
4941 wrap.remove();
4942 }
4943}
4944
4945// ───────────────────────────────────────────────────────────────────────────
4946// FOLDER DRAG-AND-DROP (recursive)
4947// ───────────────────────────────────────────────────────────────────────────
4948
4949/**
4950 * Reads all readEntries batches from a DirectoryReader (browsers may return
4951 * results in chunks; we must keep calling until we get an empty array).
4952 */
4953function readAllEntries (reader)
4954{
4955 return new Promise((resolve, reject) =>
4956 {
4957 const all = [];
4958 function next ()
4959 {
4960 reader.readEntries(batch =>
4961 {
4962 if (!batch.length) { resolve(all); return; }
4963 all.push(...batch);
4964 next();
4965 }, reject);
4966 }
4967 next();
4968 });
4969}
4970
4971/**
4972 * Recursively walk a FileSystemEntry tree, creating server-side directories
4973 * on the fly and collecting { file, targetDir } pairs for upload.
4974 */
4975async function collectEntries (entry, serverDir, toUpload)
4976{
4977 if (entry.isFile)
4978 {
4979 const file = await new Promise((res, rej) => entry.file(res, rej));
4980 toUpload.push({ file, targetDir: serverDir });
4981 } else if (entry.isDirectory)
4982 {
4983 // Ask the server to create the directory; it returns the canonical path.
4984 let newServerDir;
4985 try
4986 {
4987 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
4988 newServerDir = resp.path;
4989 } catch
4990 {
4991 // Directory may already exist — reconstruct path from what we know.
4992 // The server always returns JSON with {error} on failure, so we can
4993 // still continue by falling back to a best-effort path join.
4994 // We rely on the fact that the server separator is consistent within
4995 // a session (the list/browse API already returned paths in that format).
4996 const sep = serverDir.includes('\\') ? '\\' : '/';
4997 newServerDir = serverDir + sep + entry.name;
4998 }
4999 const reader = entry.createReader();
5000 const subEntries = await readAllEntries(reader);
5001 for (const sub of subEntries)
5002 {
5003 await collectEntries(sub, newServerDir, toUpload);
5004 }
5005 }
5006}
5007
5008async function uploadEntries (entries)
5009{
5010 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5011 if (!canWrite()) { toast('No write access.', 'err'); return; }
5012
5013 const wrap = document.createElement('div');
5014 wrap.className = 'upload-bar-wrap';
5015 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
5016 document.body.appendChild(wrap);
5017 STATE.uploadInProgress = true;
5018
5019 try
5020 {
5021 const toUpload = [];
5022 for (const entry of entries)
5023 {
5024 await collectEntries(entry, STATE.currentDir, toUpload);
5025 }
5026
5027 if (!toUpload.length) { toast('No files found.', 'err'); return; }
5028
5029 let done = 0;
5030 const total = toUpload.length;
5031 const updateBar = () =>
5032 {
5033 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
5034 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
5035 };
5036 updateBar();
5037
5038 for (const { file, targetDir } of toUpload)
5039 {
5040 await uploadSingleFile(file, targetDir);
5041 done++;
5042 updateBar();
5043 }
5044
5045 toast(`Uploaded ${total} file(s).`, 'ok');
5046 await navigateTo(STATE.currentDir, STATE.currentRoot);
5047 } catch (err)
5048 {
5049 toast(err.message, 'err');
5050 } finally
5051 {
5052 STATE.uploadInProgress = false;
5053 wrap.remove();
5054 }
5055}
5056
5057// DRAG-AND-DROP
5058// ───────────────────────────────────────────────────────────────────────────
5059
5060function initDragDrop ()
5061{
5062 const main = document.getElementById('main-content');
5063 const dropOvl = document.getElementById('drop-overlay');
5064 let dragDepth = 0;
5065
5066 main.addEventListener('dragenter', e =>
5067 {
5068 e.preventDefault();
5069 dragDepth++;
5070 dropOvl.classList.remove('hidden');
5071 });
5072 main.addEventListener('dragleave', () =>
5073 {
5074 dragDepth--;
5075 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
5076 });
5077 main.addEventListener('dragover', e => e.preventDefault());
5078 main.addEventListener('drop', async e =>
5079 {
5080 e.preventDefault();
5081 dragDepth = 0;
5082 dropOvl.classList.add('hidden');
5083 if (!canWrite()) { toast('No write access.', 'err'); return; }
5084
5085 const items = Array.from(e.dataTransfer.items || []);
5086 // Use the FileSystem Entry API when available so we can handle folders.
5087 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
5088 {
5089 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
5090 if (entries.some(en => en.isDirectory))
5091 {
5092 await uploadEntries(entries);
5093 return;
5094 }
5095 }
5096 // Plain files only — use the fast batch path.
5097 const files = e.dataTransfer.files;
5098 if (files.length) await uploadFiles(files);
5099 });
5100}
5101
5102// ───────────────────────────────────────────────────────────────────────────
5103// RENAME
5104// ───────────────────────────────────────────────────────────────────────────
5105
5106function openRenameModal (item)
5107{
5108 const modal = document.getElementById('rename-modal');
5109 modal.classList.remove('hidden');
5110 const input = document.getElementById('rename-input');
5111 input.value = item.name;
5112 input.focus();
5113 input.select();
5114 document.getElementById('rename-error').classList.add('hidden');
5115 document.getElementById('rename-form').onsubmit = async (e) =>
5116 {
5117 e.preventDefault();
5118 const newName = input.value.trim();
5119 if (!newName) return;
5120 try
5121 {
5122 if (item._root)
5123 {
5124 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
5125 } else
5126 {
5127 await api('POST', '/files/rename', { from: item.path, to: newName });
5128 }
5129 modal.classList.add('hidden');
5130 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
5131 if (item._root)
5132 {
5133 await loadRoots({
5134 preferredDir: STATE.currentDir,
5135 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
5136 });
5137 } else
5138 {
5139 await navigateTo(STATE.currentDir, STATE.currentRoot);
5140 }
5141 } catch (err)
5142 {
5143 document.getElementById('rename-error').textContent = err.message;
5144 document.getElementById('rename-error').classList.remove('hidden');
5145 }
5146 };
5147}
5148
5149// ───────────────────────────────────────────────────────────────────────────
5150// DELETE
5151// ───────────────────────────────────────────────────────────────────────────
5152
5153async function deleteItem (item)
5154{
5155 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
5156 try
5157 {
5158 await api('POST', '/files/delete', { path: item.path });
5159 toast('Deleted.', 'ok');
5160 closeSidebar();
5161 await navigateTo(STATE.currentDir, STATE.currentRoot);
5162 } catch (err)
5163 {
5164 toast(err.message, 'err');
5165 }
5166}
5167
5168// ───────────────────────────────────────────────────────────────────────────
5169// ADMIN PANEL
5170// ───────────────────────────────────────────────────────────────────────────
5171
5172let _adminUpdateStatus = null;
5173let _debugRefreshTimer = null;
5174let _debugLatestData = null;
5175
5176function formatTimestamp (ms)
5177{
5178 const value = Number(ms || 0);
5179 if (!Number.isFinite(value) || value <= 0) return '—';
5180 try
5181 {
5182 return new Date(value).toLocaleString();
5183 } catch
5184 {
5185 return '—';
5186 }
5187}
5188
5189function renderDebugTable (containerId, columns, rows)
5190{
5191 const container = document.getElementById(containerId);
5192 if (!container) return;
5193
5194 if (!Array.isArray(rows) || rows.length === 0)
5195 {
5196 container.innerHTML = '<div class="muted" style="padding:0.7rem">No data.</div>';
5197 return;
5198 }
5199
5200 const headHtml = columns.map((col) => `<th>${escapeHtml(col.label)}</th>`).join('');
5201 const bodyHtml = rows.map((row) =>
5202 `<tr>${columns.map((col) => `<td>${col.render(row)}</td>`).join('')}</tr>`).join('');
5203
5204 container.innerHTML = `<table class="debug-table"><thead><tr>${headHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>`;
5205}
5206
5207function renderDebugDashboardData (data)
5208{
5209 _debugLatestData = data;
5210
5211 const generatedAt = document.getElementById('debug-generated-at');
5212 if (generatedAt) generatedAt.textContent = `Last update: ${formatTimestamp(data.generatedAt)}`;
5213
5214 const usersEl = document.getElementById('debug-users');
5215 if (usersEl)
5216 {
5217 const users = Array.isArray(data.loggedInUsers) ? data.loggedInUsers : [];
5218 usersEl.innerHTML = users.length
5219 ? users.map((user) => `<span class="debug-chip">${escapeHtml(user.username || 'Unknown')} · ${escapeHtml(formatTimestamp(user.lastSeenAt))}</span>`).join('')
5220 : '<span class="muted">No active sessions.</span>';
5221 }
5222
5223 const summary = document.getElementById('debug-storage-summary');
5224 if (summary)
5225 {
5226 const storage = data.storage || {};
5227 const memory = data.memory || {};
5228 const roots = Array.isArray(storage.roots) ? storage.roots.length : 0;
5229 const activeStreams = Number(data.videoStream && data.videoStream.activeSessionCount) || 0;
5230 const activeLeases = Number(data.videoStream && data.videoStream.activeLeaseCount) || 0;
5231 const segmentRetention = Number(data.videoStream && data.videoStream.streamSegmentRetentionCount) || 0;
5232 summary.innerHTML = [
5233 ['Configured roots', String(roots)],
5234 ['Total used', formatBytes(storage.totalBytes || 0)],
5235 ['Total files', String(storage.totalFiles || 0)],
5236 ['RAM used', `${formatBytes(memory.usedBytes || 0)} / ${formatBytes(memory.totalBytes || 0)} (${Number(memory.usedPercent || 0).toFixed(1)}%)`],
5237 ['Process RSS', formatBytes(memory.processRssBytes || 0)],
5238 ['Active streams', String(activeStreams)],
5239 ['Active viewers', String(activeLeases)],
5240 ['Segment retention', String(segmentRetention)],
5241 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5242 }
5243
5244 renderDebugTable(
5245 'debug-roots',
5246 [
5247 { label: 'Root', render: (row) => `<span class="debug-path">${escapeHtml(row.path || '')}</span>` },
5248 { label: 'Exists', render: (row) => row.exists ? 'Yes' : 'No' },
5249 { label: 'Used', render: (row) => escapeHtml(formatBytes(row.bytes || 0)) },
5250 { label: 'Files', render: (row) => escapeHtml(String(row.files || 0)) },
5251 { label: 'Folders', render: (row) => escapeHtml(String(row.directories || 0)) },
5252 ],
5253 Array.isArray(data.storage && data.storage.roots) ? data.storage.roots : [],
5254 );
5255
5256 renderDebugTable(
5257 'debug-video-files',
5258 [
5259 { label: 'Video file', render: (row) => `<span class="debug-path">${escapeHtml(row.filePath || '')}</span>` },
5260 { label: 'Viewers', render: (row) => escapeHtml(String(row.viewers || 0)) },
5261 { label: 'Segments', render: (row) => escapeHtml(String(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0)) },
5262 { label: 'Segment bytes', render: (row) => escapeHtml(formatBytes(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0)) },
5263 { label: 'Event cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.eventEntries : 0)) },
5264 { label: 'Event bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventBytes : 0)) },
5265 { label: 'Event PNG bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0)) },
5266 { label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },
5267 { label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },
5268 { label: 'Retention', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentRetentionCount : 0)) },
5269 { label: 'Slowest seg', render: (row) => { const v = row.stream ? row.stream.slowestViewerSegmentIndex : -1; return escapeHtml(v === -1 ? '\u2014' : String(v)); } },
5270 { label: 'Pruned until', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentPrunedUntil : 0)) },
5271 { label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },
5272 ],
5273 Array.isArray(data.videoFiles) ? data.videoFiles : [],
5274 );
5275
5276 renderDebugTable(
5277 'debug-orphaned-streams',
5278 [
5279 { label: 'Output directory', render: (row) => `<span class="debug-path">${escapeHtml(row.outputDir || '')}</span>` },
5280 { label: 'Files', render: (row) => escapeHtml(String(row.output && row.output.totalFiles || 0)) },
5281 { label: 'Bytes', render: (row) => escapeHtml(formatBytes(row.output && row.output.totalBytes || 0)) },
5282 { label: 'Segments', render: (row) => escapeHtml(String(row.output && row.output.segmentFiles || 0)) },
5283 ],
5284 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5285 );
5286
5287 const subtitleSection = document.getElementById('debug-subtitle-log-section');
5288 const subtitlePath = document.getElementById('debug-subtitle-log-path');
5289 const subtitleMeta = document.getElementById('debug-subtitle-log-meta');
5290 const subtitleOpen = document.getElementById('debug-open-subtitle-log-folder');
5291 const subtitleLog = data.subtitleDebugLog || {};
5292
5293 if (subtitleSection && subtitlePath && subtitleMeta && subtitleOpen)
5294 {
5295 if (!subtitleLog.exists)
5296 {
5297 subtitleSection.classList.add('hidden');
5298 } else
5299 {
5300 subtitleSection.classList.remove('hidden');
5301 subtitlePath.textContent = subtitleLog.path || 'Unknown path';
5302 const fileCount = Number(subtitleLog.files || 0);
5303 subtitleMeta.textContent = `${fileCount} log file${fileCount === 1 ? '' : 's'} · ${formatBytes(subtitleLog.bytes || 0)}`;
5304 subtitleOpen.dataset.subtitleLogPath = subtitleLog.path || '';
5305 subtitleOpen.disabled = !subtitleLog.path;
5306 }
5307 }
5308}
5309
5310function csvEscape (value)
5311{
5312 const raw = String(value == null ? '' : value);
5313 if (/[,"\n\r]/.test(raw)) return `"${raw.replace(/"/g, '""')}"`;
5314 return raw;
5315}
5316
5317function toCsv (rows, columns)
5318{
5319 const header = columns.join(',');
5320 const body = rows.map((row) => columns.map((col) => csvEscape(row[col])).join(',')).join('\n');
5321 return `${header}\n${body}`;
5322}
5323
5324async function copyDebugText (text, successMessage)
5325{
5326 const payload = String(text || '');
5327 if (!payload.trim())
5328 {
5329 toast('No debug data to copy yet.', 'err');
5330 return;
5331 }
5332
5333 try
5334 {
5335 await navigator.clipboard.writeText(payload);
5336 toast(successMessage, 'ok');
5337 } catch
5338 {
5339 toast('Could not copy to clipboard.', 'err');
5340 }
5341}
5342
5343function copyDebugUsersJson ()
5344{
5345 const users = Array.isArray(_debugLatestData && _debugLatestData.loggedInUsers)
5346 ? _debugLatestData.loggedInUsers
5347 : [];
5348 void copyDebugText(JSON.stringify(users, null, 2), 'Copied users JSON.');
5349}
5350
5351function copyDebugStorageJson ()
5352{
5353 const payload = {
5354 generatedAt: _debugLatestData && _debugLatestData.generatedAt,
5355 storage: _debugLatestData && _debugLatestData.storage,
5356 memory: _debugLatestData && _debugLatestData.memory,
5357 };
5358 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied storage JSON.');
5359}
5360
5361function copyDebugVideoFilesCsv ()
5362{
5363 const files = Array.isArray(_debugLatestData && _debugLatestData.videoFiles)
5364 ? _debugLatestData.videoFiles
5365 : [];
5366
5367 const rows = files.map((row) => ({
5368 filePath: row.filePath || '',
5369 viewers: Number(row.viewers || 0),
5370 segmentFiles: Number(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0),
5371 segmentBytes: Number(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0),
5372 eventEntries: Number(row.subtitleCache ? row.subtitleCache.eventEntries : 0),
5373 eventBytes: Number(row.subtitleCache ? row.subtitleCache.eventBytes : 0),
5374 eventPngBytes: Number(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0),
5375 frameEntries: Number(row.subtitleCache ? row.subtitleCache.frameEntries : 0),
5376 frameBytes: Number(row.subtitleCache ? row.subtitleCache.frameBytes : 0),
5377 segmentRetentionCount: Number(row.stream ? row.stream.segmentRetentionCount : 0),
5378 slowestViewerSegmentIndex: row.stream ? row.stream.slowestViewerSegmentIndex : -1,
5379 segmentPrunedUntil: Number(row.stream ? row.stream.segmentPrunedUntil : 0),
5380 sessionIds: Array.isArray(row.activeSessionIds) ? row.activeSessionIds.join(';') : '',
5381 }));
5382
5383 const csv = toCsv(rows, [
5384 'filePath',
5385 'viewers',
5386 'segmentFiles',
5387 'segmentBytes',
5388 'eventEntries',
5389 'eventBytes',
5390 'eventPngBytes',
5391 'frameEntries',
5392 'frameBytes',
5393 'segmentRetentionCount',
5394 'slowestViewerSegmentIndex',
5395 'segmentPrunedUntil',
5396 'sessionIds',
5397 ]);
5398 void copyDebugText(csv, 'Copied video/cache CSV.');
5399}
5400
5401function copyDebugOrphanedCsv ()
5402{
5403 const rowsRaw = Array.isArray(_debugLatestData && _debugLatestData.videoStream && _debugLatestData.videoStream.orphanedOutputDirs)
5404 ? _debugLatestData.videoStream.orphanedOutputDirs
5405 : [];
5406
5407 const rows = rowsRaw.map((row) => ({
5408 outputDir: row.outputDir || '',
5409 totalFiles: Number(row.output && row.output.totalFiles || 0),
5410 totalBytes: Number(row.output && row.output.totalBytes || 0),
5411 segmentFiles: Number(row.output && row.output.segmentFiles || 0),
5412 segmentBytes: Number(row.output && row.output.segmentBytes || 0),
5413 }));
5414
5415 const csv = toCsv(rows, ['outputDir', 'totalFiles', 'totalBytes', 'segmentFiles', 'segmentBytes']);
5416 void copyDebugText(csv, 'Copied orphaned output CSV.');
5417}
5418
5419async function openSubtitleDebugLogFolder ()
5420{
5421 const button = document.getElementById('debug-open-subtitle-log-folder');
5422 const targetPath = String(button && button.dataset && button.dataset.subtitleLogPath || '').trim();
5423 if (!targetPath) return;
5424
5425 try
5426 {
5427 await navigateTo(targetPath, {
5428 label: 'Subtitle Logs',
5429 originalName: 'Subtitle Logs',
5430 alias: null,
5431 path: targetPath,
5432 isUserFolder: false,
5433 isDebugLogFolder: true,
5434 });
5435 closeDebugModal();
5436 } catch (err)
5437 {
5438 toast(err.message || 'Failed to open subtitle log folder.', 'err');
5439 }
5440}
5441
5442async function refreshDebugDashboard ()
5443{
5444 const data = await api('GET', '/admin/debug/stream-stats');
5445 if (!data) return;
5446 renderDebugDashboardData(data);
5447}
5448
5449async function openDebugModal ()
5450{
5451 const modal = document.getElementById('debug-modal');
5452 if (!modal) return;
5453 modal.classList.remove('hidden');
5454 await refreshDebugDashboard();
5455
5456 if (_debugRefreshTimer) clearInterval(_debugRefreshTimer);
5457 _debugRefreshTimer = setInterval(() =>
5458 {
5459 void refreshDebugDashboard();
5460 }, 5000);
5461}
5462
5463function closeDebugModal ()
5464{
5465 const modal = document.getElementById('debug-modal');
5466 if (modal) modal.classList.add('hidden');
5467 if (_debugRefreshTimer)
5468 {
5469 clearInterval(_debugRefreshTimer);
5470 _debugRefreshTimer = null;
5471 }
5472}
5473
5474function animateBadgeToTarget (targetEl)
5475{
5476 const badge = document.getElementById('admin-update-badge');
5477 if (!badge || !targetEl) return;
5478 if (badge.parentElement === targetEl) return;
5479
5480 const from = badge.getBoundingClientRect();
5481 targetEl.appendChild(badge);
5482 const to = badge.getBoundingClientRect();
5483
5484 const dx = from.left - to.left;
5485 const dy = from.top - to.top;
5486
5487 badge.style.transition = 'none';
5488 badge.style.transform = `translate(${dx}px, ${dy}px)`;
5489 badge.style.willChange = 'transform';
5490
5491 requestAnimationFrame(() =>
5492 {
5493 badge.style.transition = 'transform 240ms cubic-bezier(0.22, 1, 0.36, 1)';
5494 badge.style.transform = 'translate(0, 0)';
5495 });
5496
5497 const cleanup = () =>
5498 {
5499 badge.style.transition = '';
5500 badge.style.transform = '';
5501 badge.style.willChange = '';
5502 badge.removeEventListener('transitionend', cleanup);
5503 };
5504 badge.addEventListener('transitionend', cleanup);
5505}
5506
5507function moveBadgeToTarget (targetEl)
5508{
5509 const badge = document.getElementById('admin-update-badge');
5510 if (!badge || !targetEl) return;
5511 if (badge.parentElement === targetEl) return;
5512
5513 badge.style.transition = '';
5514 badge.style.transform = '';
5515 badge.style.willChange = '';
5516 targetEl.appendChild(badge);
5517}
5518
5519function syncAdminUpdateBadgeAnchor ({ animate = true, forceUserAnchor = false } = {})
5520{
5521 const badge = document.getElementById('admin-update-badge');
5522 const userMenuBtn = document.getElementById('btn-user-menu');
5523 const adminBtn = document.getElementById('btn-admin');
5524 if (!badge || !userMenuBtn || !adminBtn) return;
5525
5526 const userDropdown = userMenuBtn.closest('.topbar-dropdown');
5527 const userMenuOpen = !!(userDropdown && userDropdown.classList.contains('open'));
5528 const target = forceUserAnchor ? userMenuBtn : (userMenuOpen ? adminBtn : userMenuBtn);
5529
5530 if (badge.classList.contains('hidden'))
5531 {
5532 moveBadgeToTarget(userMenuBtn);
5533 return;
5534 }
5535
5536 if (animate) animateBadgeToTarget(target);
5537 else moveBadgeToTarget(target);
5538}
5539
5540function setAdminUpdateBadge (count)
5541{
5542 const badge = document.getElementById('admin-update-badge');
5543 const userMenuBtn = document.getElementById('btn-user-menu');
5544 if (!badge || !userMenuBtn) return;
5545
5546 if (!STATE.isAdmin || !Number.isFinite(count) || count <= 0)
5547 {
5548 badge.classList.add('hidden');
5549 badge.textContent = '';
5550 if (badge.parentElement !== userMenuBtn) userMenuBtn.appendChild(badge);
5551 userMenuBtn.removeAttribute('data-update-count');
5552 return;
5553 }
5554
5555 const whole = Math.floor(count);
5556 const capped = Math.min(whole, 99);
5557 badge.textContent = capped >= 99 ? '99+' : String(capped);
5558 badge.classList.remove('hidden');
5559 userMenuBtn.dataset.updateCount = String(whole);
5560 syncAdminUpdateBadgeAnchor();
5561}
5562
5563function pulseAdminUpdateButton ()
5564{
5565 const btn = document.getElementById('admin-shutdown-btn');
5566 if (!btn) return;
5567
5568 if (typeof btn.scrollIntoView === 'function')
5569 {
5570 btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
5571 }
5572
5573 btn.classList.remove('admin-update-highlight');
5574 // Force reflow so repeated openings can replay the pulse animation.
5575 void btn.offsetWidth;
5576 btn.classList.add('admin-update-highlight');
5577
5578 setTimeout(() =>
5579 {
5580 btn.classList.remove('admin-update-highlight');
5581 }, 1800);
5582}
5583
5584async function openAdminModal ()
5585{
5586 document.getElementById('admin-modal').classList.remove('hidden');
5587 await refreshGlobalFavicon();
5588 await refreshAdminConfig();
5589 await refreshAdminUsers();
5590 await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true });
5591}
5592
5593async function refreshAdminConfig ()
5594{
5595 const data = await api('GET', '/admin/config');
5596 if (!data) return;
5597
5598 const userPathInput = document.getElementById('admin-user-path');
5599 const sizeInput = document.getElementById('admin-user-size-limit');
5600 if (userPathInput) userPathInput.value = data.userPath || '';
5601 if (sizeInput)
5602 {
5603 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
5604 updateAdminSizeFeedback(sizeInput.value);
5605 }
5606
5607 const container = document.getElementById('admin-paths');
5608 container.innerHTML = '';
5609 for (const p of data.paths)
5610 {
5611 const row = document.createElement('div');
5612 row.className = 'path-row';
5613 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
5614 row.querySelector('button').addEventListener('click', () =>
5615 {
5616 row.remove();
5617 });
5618 container.appendChild(row);
5619 }
5620}
5621
5622async function refreshAdminUsers ()
5623{
5624 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
5625 const data = await api('GET', '/admin/users');
5626 if (!data) return;
5627 const container = document.getElementById('admin-users-list');
5628 if (!container) return;
5629 container.innerHTML = '';
5630
5631 // Need paths for permission rows
5632 const cfg = await api('GET', '/admin/config');
5633 const paths = cfg ? (cfg.effectivePaths || []) : [];
5634
5635 for (const u of data.users)
5636 {
5637 const row = document.createElement('div');
5638 row.className = 'user-row';
5639 row.innerHTML = `
5640 <span class="user-name">${u.username}</span>
5641 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
5642 <button data-id="${u.id}" data-action="edit">Edit</button>
5643 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
5644 `;
5645 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
5646 openUserModal(u, paths));
5647 const deleteBtn = row.querySelector('[data-action="delete"]');
5648 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
5649 {
5650 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
5651 try
5652 {
5653 await api('DELETE', `/admin/users/${u.id}`);
5654 toast('User deleted.', 'ok');
5655 await refreshAdminUsers();
5656 } catch (err) { toast(err.message, 'err'); }
5657 });
5658 container.appendChild(row);
5659 }
5660
5661 await refreshAdminOrphanUserFolders();
5662}
5663
5664async function refreshAdminOrphanUserFolders ()
5665{
5666 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
5667 const section = document.getElementById('admin-orphan-userfolders-section');
5668 const list = document.getElementById('admin-orphan-userfolders-list');
5669 if (!section || !list) return;
5670
5671 let data = null;
5672 try
5673 {
5674 data = await api('GET', '/admin/orphan-userfolders');
5675 } catch
5676 {
5677 section.classList.add('hidden');
5678 list.innerHTML = '';
5679 return;
5680 }
5681
5682 const folders = Array.isArray(data && data.folders) ? data.folders : [];
5683 if (!folders.length)
5684 {
5685 section.classList.add('hidden');
5686 list.innerHTML = '';
5687 return;
5688 }
5689
5690 section.classList.remove('hidden');
5691 list.innerHTML = '';
5692
5693 for (const folder of folders)
5694 {
5695 const row = document.createElement('div');
5696 row.className = 'user-row orphan-folder-row';
5697
5698 const name = document.createElement('span');
5699 name.className = 'user-name';
5700 name.textContent = folder.folderName || 'Unknown folder';
5701
5702 const info = document.createElement('span');
5703 info.className = 'orphan-folder-meta';
5704 const itemCount = Number(folder.itemCount) || 0;
5705 info.textContent = `${itemCount} item${itemCount === 1 ? '' : 's'}`;
5706
5707 const openBtn = document.createElement('button');
5708 openBtn.dataset.action = 'open-orphan-folder';
5709 openBtn.textContent = 'Open folder';
5710 openBtn.addEventListener('click', async () =>
5711 {
5712 const targetPath = String(folder.path || '').trim();
5713 if (!targetPath) return;
5714
5715 try
5716 {
5717 const syntheticRoot = {
5718 label: name.textContent,
5719 originalName: name.textContent,
5720 alias: null,
5721 path: targetPath,
5722 isUserFolder: true,
5723 isOrphanUserFolder: true,
5724 };
5725 await navigateTo(targetPath, syntheticRoot);
5726 document.getElementById('admin-modal').classList.add('hidden');
5727 } catch (err)
5728 {
5729 toast(err.message || 'Failed to open folder.', 'err');
5730 }
5731 });
5732
5733 row.appendChild(name);
5734 row.appendChild(info);
5735 row.appendChild(openBtn);
5736 list.appendChild(row);
5737 }
5738}
5739
5740async function refreshAdminUpdateStatus (opts = {})
5741{
5742 const pulseIfUpdateAvailable = !!opts.pulseIfUpdateAvailable;
5743 const btn = document.getElementById('admin-shutdown-btn');
5744 _adminUpdateStatus = null;
5745 btn.textContent = 'Shut down server';
5746 setAdminUpdateBadge(0);
5747
5748 try
5749 {
5750 const data = await api('GET', '/admin/update-status');
5751 if (!data) return;
5752 _adminUpdateStatus = data;
5753
5754 const updateCount = (data.underSystemd && Array.isArray(data.commitsAhead))
5755 ? data.commitsAhead.length
5756 : 0;
5757 setAdminUpdateBadge(updateCount);
5758
5759 if (!data.underSystemd)
5760 {
5761 btn.textContent = 'Shut down server';
5762 }
5763 else if (data.commitsAhead.length === 0)
5764 {
5765 btn.textContent = 'Restart Server';
5766 }
5767 else
5768 {
5769 btn.textContent = 'Restart & Update';
5770 if (pulseIfUpdateAvailable) pulseAdminUpdateButton();
5771 }
5772 }
5773 catch
5774 {
5775 // Not critical; button stays as "Shut down server".
5776 }
5777}
5778
5779function openUserModal (user, paths)
5780{
5781 const modal = document.getElementById('user-modal');
5782 modal.classList.remove('hidden');
5783 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
5784 document.getElementById('user-error').classList.add('hidden');
5785
5786 const usernameInput = document.getElementById('user-username');
5787 usernameInput.value = user ? user.username : '';
5788 usernameInput.readOnly = !!user;
5789
5790 document.getElementById('user-password').value = '';
5791 const adminChk = document.getElementById('user-is-admin');
5792 const editingOwnAccount = !!(user
5793 && String(user.username || '').toLowerCase() === String(STATE.username || '').toLowerCase());
5794 adminChk.checked = user ? user.isAdmin : false;
5795 adminChk.disabled = editingOwnAccount;
5796 adminChk.title = editingOwnAccount
5797 ? 'You cannot remove admin privileges from your own account.'
5798 : '';
5799
5800 // Password placeholder
5801 document.getElementById('user-password').placeholder =
5802 user ? 'Leave blank to keep current' : 'Min 8 characters';
5803
5804 // Build permissions grid
5805 const permDiv = document.getElementById('user-permissions');
5806 permDiv.innerHTML = '';
5807 if (paths.length)
5808 {
5809 const heading = document.createElement('h4');
5810 heading.textContent = 'Path Permissions';
5811 permDiv.appendChild(heading);
5812
5813 const isAdminUser = !!(user && user.isAdmin);
5814 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
5815 const rebuildPermRows = (admin) =>
5816 {
5817 permDiv.querySelectorAll('.perm-row').forEach(r =>
5818 {
5819 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
5820 {
5821 cb.disabled = admin;
5822 if (admin) cb.checked = true;
5823 });
5824 r.title = admin ? 'Admins always have full access' : '';
5825 });
5826 };
5827 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
5828
5829 const syncReadWriteConstraints = (row, admin = false) =>
5830 {
5831 const readCb = row.querySelector('input[data-type="read"]');
5832 const writeCb = row.querySelector('input[data-type="write"]');
5833 if (!readCb || !writeCb) return;
5834
5835 if (admin)
5836 {
5837 readCb.checked = true;
5838 writeCb.checked = true;
5839 readCb.disabled = true;
5840 writeCb.disabled = true;
5841 return;
5842 }
5843
5844 readCb.disabled = false;
5845 if (!readCb.checked)
5846 {
5847 writeCb.checked = false;
5848 writeCb.disabled = true;
5849 }
5850 else
5851 {
5852 writeCb.disabled = false;
5853 }
5854 };
5855
5856 const syncAllReadWriteConstraints = () =>
5857 {
5858 const admin = adminChk.checked;
5859 permDiv.querySelectorAll('.perm-row').forEach((row) =>
5860 {
5861 syncReadWriteConstraints(row, admin);
5862 });
5863 };
5864
5865 for (const p of paths)
5866 {
5867 const label = p.split(/[\\/]/).pop();
5868 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
5869 const row = document.createElement('div');
5870 row.className = 'perm-row';
5871 const readChecked = isAdminUser || perms.read;
5872 const writeChecked = isAdminUser || perms.write;
5873 row.innerHTML = `
5874 <span class="perm-label">${label}</span>
5875 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
5876 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
5877 `;
5878 if (isAdminUser) row.title = 'Admins always have full access';
5879 const readCb = row.querySelector('input[data-type="read"]');
5880 if (readCb)
5881 {
5882 readCb.addEventListener('change', () =>
5883 {
5884 syncReadWriteConstraints(row, adminChk.checked);
5885 });
5886 }
5887 permDiv.appendChild(row);
5888 }
5889
5890 syncAllReadWriteConstraints();
5891 adminChk.addEventListener('change', syncAllReadWriteConstraints);
5892 }
5893
5894 document.getElementById('user-form').onsubmit = async (e) =>
5895 {
5896 e.preventDefault();
5897 const password = document.getElementById('user-password').value;
5898 const isAdmin = document.getElementById('user-is-admin').checked;
5899 const permissions = {};
5900 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
5901 {
5902 const lbl = cb.dataset.label;
5903 if (!permissions[lbl]) permissions[lbl] = {};
5904 permissions[lbl][cb.dataset.type] = cb.checked;
5905 });
5906
5907 try
5908 {
5909 if (user)
5910 {
5911 const body = { isAdmin, permissions };
5912 if (password) body.password = password;
5913 await api('PATCH', `/admin/users/${user.id}`, body);
5914 } else
5915 {
5916 const uname = document.getElementById('user-username').value.trim();
5917 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
5918 }
5919 modal.classList.add('hidden');
5920 toast('User saved.', 'ok');
5921 await refreshAdminUsers();
5922 } catch (err)
5923 {
5924 document.getElementById('user-error').textContent = err.message;
5925 document.getElementById('user-error').classList.remove('hidden');
5926 }
5927 };
5928}
5929
5930// ───────────────────────────────────────────────────────────────────────────
5931// SVG ICONS
5932// ───────────────────────────────────────────────────────────────────────────
5933
5934const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
5935const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
5936const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
5937const MODEL_EXTS = new Set(['stl', 'obj']);
5938const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
5939const 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']);
5940const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
5941const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
5942
5943function iconFolder (size = 52)
5944{
5945 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
5946 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
5947 <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"/>
5948 </svg>`;
5949}
5950
5951function iconFile (name, size = 52)
5952{
5953 const color = fileAccentColor(name);
5954 let symbol = '';
5955
5956 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
5957 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
5958 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
5959 <polyline points="14 2 14 8 20 8"/>
5960 </svg>`;
5961}
5962
5963function watchStatusForTile (item)
5964{
5965 if (!item || item.isDir) return null;
5966 if (!VIDEO_EXTS.has(extOf(item.name || ''))) return null;
5967
5968 const cached = STATE.watchedStatusByPath[item.path];
5969 if (cached === 'fully' || cached === 'partway') return cached;
5970
5971 const currentUser = String(STATE.username || '').trim();
5972 if (!currentUser) return null;
5973
5974 const watchedBy = item.watchedBy && typeof item.watchedBy === 'object' ? item.watchedBy : {};
5975 const statusRaw = watchedBy[currentUser];
5976 const status = String(statusRaw || '').toLowerCase();
5977 if (status === 'fully' || status === 'partway') return status;
5978 return null;
5979}
5980
5981function renderWatchedOverlayOnIcon (iconEl, watchStatus)
5982{
5983 if (!iconEl) return;
5984
5985 const existing = iconEl.querySelector('.watched-overlay');
5986 if (existing) existing.remove();
5987 if (watchStatus !== 'fully' && watchStatus !== 'partway') return;
5988
5989 const overlay = document.createElement('div');
5990 overlay.className = `watched-overlay watched-overlay--${watchStatus}`;
5991 overlay.innerHTML = watchedEyeFilledSvg();
5992 iconEl.appendChild(overlay);
5993}
5994
5995function findTileIconByPath (filePath)
5996{
5997 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return null;
5998 const tile = Array.from(document.querySelectorAll('.file-item')).find((el) => el.dataset.path === filePath);
5999 if (!tile) return null;
6000 return tile.querySelector('.icon');
6001}
6002
6003function watchStatusFromWatchedBy (watchedBy)
6004{
6005 const currentUser = String(STATE.username || '').trim();
6006 if (!currentUser) return null;
6007
6008 const map = watchedBy && typeof watchedBy === 'object' ? watchedBy : {};
6009 const statusRaw = map[currentUser];
6010 const status = String(statusRaw || '').toLowerCase();
6011 if (status === 'fully' || status === 'partway') return status;
6012 return null;
6013}
6014
6015async function loadWatchedStatusesForCurrentDir ()
6016{
6017 const dirAtStart = STATE.currentDir;
6018 if (!dirAtStart) return;
6019
6020 const videoItems = (STATE.items || []).filter((item) =>
6021 item && !item.isDir && VIDEO_EXTS.has(extOf(item.name || ''))
6022 );
6023 if (!videoItems.length) return;
6024
6025 const loadId = ++STATE.watchedLoadId;
6026
6027 let statusMap = null;
6028 const filePaths = videoItems.map((item) => item.path);
6029
6030 const bulk = await api('POST', '/files/watched-statuses', { filePaths }).catch(() => null);
6031 if (bulk && bulk.statuses && typeof bulk.statuses === 'object')
6032 {
6033 statusMap = {};
6034 for (const item of videoItems)
6035 {
6036 const status = String(bulk.statuses[item.path] || '').toLowerCase();
6037 statusMap[item.path] = status === 'fully' || status === 'partway' ? status : null;
6038 }
6039 }
6040
6041 // Compatibility fallback for older servers that do not expose bulk statuses yet.
6042 if (!statusMap)
6043 {
6044 statusMap = {};
6045 const statuses = await Promise.all(videoItems.map(async (item) =>
6046 {
6047 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch(() => null);
6048 return {
6049 path: item.path,
6050 status: watchStatusFromWatchedBy(meta && meta.watchedBy),
6051 };
6052 }));
6053
6054 for (const entry of statuses)
6055 {
6056 statusMap[entry.path] = entry.status;
6057 }
6058 }
6059
6060 if (loadId !== STATE.watchedLoadId) return;
6061 if (!samePath(STATE.currentDir, dirAtStart)) return;
6062 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
6063
6064 for (const item of videoItems)
6065 {
6066 const status = statusMap[item.path] || null;
6067 if (status) STATE.watchedStatusByPath[item.path] = status;
6068 else delete STATE.watchedStatusByPath[item.path];
6069
6070 const iconEl = findTileIconByPath(item.path);
6071 renderWatchedOverlayOnIcon(iconEl, status);
6072 }
6073}
6074
6075function watchedEyeFilledSvg ()
6076{
6077 return `<svg class="watched-overlay-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path fill="#ffffff" d="M651.669528 512c0-14.5903-2.084475-28.290323-6.251378-41.395806-11.019984 24.423249-35.143405 41.395806-63.733557 41.395806l-7.440459-0.593518-5.957689 0.593518c-30.973432 0-56.285934-25.607214-56.285934-56.882522l0.297782-5.952572-0.297782-7.447623c0-28.290323 16.97665-52.709479 41.097-63.727417-13.104459-4.172019-26.802436-6.252401-41.097-6.252401-77.132728 0-139.67311 62.834071-139.67311 140.263557 0 77.428464 62.540382 139.971915 139.67311 139.971915S651.669528 589.428464 651.669528 512L651.669528 512zM958.70846 512c0 0-153.36904-297.80564-448.198905-297.80564-293.63669 0-445.219037 297.80564-445.219037 297.80564s164.385954 297.804616 447.306582 297.804616C805.038568 809.80564 958.70846 512 958.70846 512L958.70846 512zM304.725748 512c0-114.954125 92.619444-208.164017 207.27374-208.164017 114.657366 0 207.27067 93.209892 207.27067 208.164017 0 114.953102-92.613304 208.167087-207.27067 208.167087C397.345192 720.167087 304.725748 626.953102 304.725748 512L304.725748 512zM304.725748 512"/></svg>`;
6078}
6079
6080// ───────────────────────────────────────────────────────────────────────────
6081// EVENT WIRING
6082// ───────────────────────────────────────────────────────────────────────────
6083
6084// ───────────────────────────────────────────────────────────────────────────
6085// THUMBNAIL PREVIEWS
6086// ───────────────────────────────────────────────────────────────────────────
6087
6088function revokeThumbnails ()
6089{
6090 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
6091 STATE.thumbnailUrls = [];
6092}
6093
6094function disconnectThumbnailObserver ()
6095{
6096 if (!STATE.thumbnailObserver) return;
6097 STATE.thumbnailObserver.disconnect();
6098 STATE.thumbnailObserver = null;
6099}
6100
6101function disconnectFolderIconObserver ()
6102{
6103 if (!STATE.folderIconObserver) return;
6104 STATE.folderIconObserver.disconnect();
6105 STATE.folderIconObserver = null;
6106}
6107
6108function setThumbnailPending (iconEl, pending)
6109{
6110 if (!iconEl) return;
6111 if (pending)
6112 {
6113 iconEl.classList.add('thumb-pending');
6114 iconEl.dataset.thumbPending = '1';
6115 return;
6116 }
6117
6118 iconEl.classList.remove('thumb-pending');
6119 delete iconEl.dataset.thumbPending;
6120}
6121
6122function getThumbnailKind (name)
6123{
6124 const ext = extOf(name || '');
6125 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image';
6126 if (CODE_EXTS.has(ext)) return 'text';
6127 return 'badge';
6128}
6129
6130function maxThumbBytesForKind (kind)
6131{
6132 if (kind === 'image') return 15 * 1024 * 1024;
6133 if (kind === 'text') return 1024 * 1024;
6134 return 0;
6135}
6136
6137function drawTokenizedLine (ctx, line, x, y)
6138{
6139 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;
6140 let last = 0;
6141 let cursor = x;
6142 for (const m of line.matchAll(tokenRe))
6143 {
6144 const i = m.index == null ? 0 : m.index;
6145 if (i > last)
6146 {
6147 const plain = line.slice(last, i);
6148 ctx.fillStyle = '#dce4ff';
6149 ctx.fillText(plain, cursor, y);
6150 cursor += ctx.measureText(plain).width;
6151 }
6152
6153 const tok = m[0];
6154 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
6155 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
6156 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
6157 else ctx.fillStyle = '#8bb4ff';
6158
6159 ctx.fillText(tok, cursor, y);
6160 cursor += ctx.measureText(tok).width;
6161 last = i + tok.length;
6162 }
6163
6164 if (last < line.length)
6165 {
6166 const tail = line.slice(last);
6167 ctx.fillStyle = '#dce4ff';
6168 ctx.fillText(tail, cursor, y);
6169 }
6170}
6171
6172function textThumbnailDataUrl (text)
6173{
6174 const canvas = document.createElement('canvas');
6175 canvas.width = 160;
6176 canvas.height = 200;
6177 const ctx = canvas.getContext('2d');
6178 if (!ctx) return null;
6179
6180 ctx.fillStyle = '#0d111a';
6181 ctx.fillRect(0, 0, canvas.width, canvas.height);
6182 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
6183 ctx.textBaseline = 'top';
6184
6185 const lines = String(text || '')
6186 .replace(/\r\n/g, '\n')
6187 .split('\n')
6188 .slice(0, 17);
6189
6190 let y = 8;
6191 for (const line of lines)
6192 {
6193 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
6194 y += 11;
6195 if (y > 190) break;
6196 }
6197 return canvas.toDataURL('image/png');
6198}
6199
6200function badgeThumbnailDataUrl (name, kind)
6201{
6202 const canvas = document.createElement('canvas');
6203 canvas.width = 160;
6204 canvas.height = 200;
6205 const ctx = canvas.getContext('2d');
6206 if (!ctx) return null;
6207
6208 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
6209 const color = '#5b7fff';
6210
6211 ctx.fillStyle = '#111826';
6212 ctx.fillRect(0, 0, 160, 200);
6213 ctx.fillStyle = color;
6214 ctx.fillRect(0, 0, 160, 28);
6215 ctx.fillStyle = '#ffffff';
6216 ctx.font = 'bold 12px sans-serif';
6217 ctx.textAlign = 'center';
6218 ctx.fillText(ext, 80, 8);
6219 ctx.textAlign = 'left';
6220 ctx.fillStyle = '#9fb1d8';
6221 ctx.font = '10px sans-serif';
6222 ctx.fillText('Preview', 8, 48);
6223 ctx.fillStyle = '#dce4ff';
6224 ctx.font = 'bold 11px sans-serif';
6225 ctx.fillText(ext, 8, 66);
6226 return canvas.toDataURL('image/png');
6227}
6228
6229async function buildThumbnailSource (item, blob, kind)
6230{
6231 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
6232 return badgeThumbnailDataUrl(item.name, kind);
6233}
6234
6235function observeThumbnailIcon (iconEl)
6236{
6237 if (!iconEl || !iconEl.isConnected) return;
6238 if (iconEl.dataset.thumbReady === '1') return;
6239
6240 if (!('IntersectionObserver' in window))
6241 {
6242 void loadOneThumbnail(iconEl);
6243 return;
6244 }
6245
6246 if (!STATE.thumbnailObserver)
6247 {
6248 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
6249 {
6250 for (const entry of entries)
6251 {
6252 if (!entry.isIntersecting) continue;
6253 const icon = entry.target;
6254 STATE.thumbnailObserver.unobserve(icon);
6255 void loadOneThumbnail(icon);
6256 }
6257 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
6258 }
6259
6260 STATE.thumbnailObserver.observe(iconEl);
6261}
6262
6263async function loadThumbnails ()
6264{
6265 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
6266 for (const icon of icons)
6267 {
6268 observeThumbnailIcon(icon);
6269 }
6270
6271 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
6272 for (const icon of folderIcons)
6273 {
6274 observeFolderIcon(icon);
6275 }
6276}
6277
6278async function loadOneThumbnail (iconEl)
6279{
6280 if (!iconEl.isConnected || !STATE.token) return;
6281 if (iconEl.dataset.thumbReady === '1') return;
6282 const filePath = iconEl.dataset.previewPath;
6283 const item = STATE.items.find(i => i.path === filePath);
6284 if (!item) return;
6285
6286 const kind = getThumbnailKind(item.name);
6287 let srcUrl = null;
6288
6289 if (kind === 'badge')
6290 {
6291 setThumbnailPending(iconEl, false);
6292 srcUrl = badgeThumbnailDataUrl(item.name, kind);
6293 }
6294 else if (kind === 'image')
6295 {
6296 const ext = extOf(item.name || '');
6297 const useDirectSource =
6298 ext === 'ico' ||
6299 (
6300 ext === 'svg' &&
6301 typeof item.size === 'number' &&
6302 item.size > 0 &&
6303 item.size <= MAX_DIRECT_SVG_THUMB_BYTES
6304 );
6305
6306 const url = useDirectSource
6307 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
6308 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
6309
6310 let res;
6311 try
6312 {
6313 res = await fetch(url, {
6314 headers: {
6315 Authorization: `Bearer ${STATE.token}`,
6316 'X-Fp': getFingerprint(),
6317 },
6318 });
6319 } catch
6320 {
6321 return;
6322 }
6323
6324 if (!useDirectSource && res.status === 404)
6325 {
6326 setThumbnailPending(iconEl, true);
6327 return;
6328 }
6329
6330 if (!res.ok || !iconEl.isConnected) return;
6331 setThumbnailPending(iconEl, false);
6332
6333 const blob = await res.blob();
6334 srcUrl = URL.createObjectURL(blob);
6335 STATE.thumbnailUrls.push(srcUrl);
6336 }
6337 else
6338 {
6339 setThumbnailPending(iconEl, false);
6340 const maxBytes = maxThumbBytesForKind(kind);
6341 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
6342 {
6343 srcUrl = badgeThumbnailDataUrl(item.name, kind);
6344 } else
6345 {
6346 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
6347
6348 let res;
6349 try
6350 {
6351 res = await fetch(url, {
6352 headers: {
6353 Authorization: `Bearer ${STATE.token}`,
6354 'X-Fp': getFingerprint(),
6355 },
6356 });
6357 } catch { return; }
6358 if (!res.ok || !iconEl.isConnected) return;
6359
6360 const blob = await res.blob();
6361 srcUrl = await buildThumbnailSource(item, blob, kind);
6362 }
6363 }
6364 if (!srcUrl || !iconEl.isConnected) return;
6365
6366 const svg = iconEl.querySelector('svg');
6367 if (!svg)
6368 {
6369 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
6370 return;
6371 }
6372
6373 const NS = 'http://www.w3.org/2000/svg';
6374 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
6375
6376 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
6377 const defs = document.createElementNS(NS, 'defs');
6378 const clipPath = document.createElementNS(NS, 'clipPath');
6379 clipPath.setAttribute('id', id);
6380 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
6381 const clipShape = document.createElementNS(NS, 'path');
6382 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
6383 clipPath.appendChild(clipShape);
6384 defs.appendChild(clipPath);
6385
6386 // Image fills the file bounding box; clip keeps it inside the outline
6387 const img = document.createElementNS(NS, 'image');
6388 img.setAttribute('href', srcUrl);
6389 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
6390 img.setAttribute('x', '4');
6391 img.setAttribute('y', '2');
6392 img.setAttribute('width', '16');
6393 img.setAttribute('height', '20');
6394 img.setAttribute('clip-path', `url(#${id})`);
6395 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
6396
6397 // Prepend so existing path/polyline elements (the outline) render on top
6398 svg.prepend(img);
6399 svg.prepend(defs);
6400 iconEl.dataset.thumbReady = '1';
6401}
6402
6403// ───────────────────────────────────────────────────────────────────────────
6404// FOLDER ICON THUMBNAILS
6405// ───────────────────────────────────────────────────────────────────────────
6406
6407function observeFolderIcon (iconEl)
6408{
6409 if (!iconEl || !iconEl.isConnected) return;
6410 if (iconEl.dataset.thumbReady === '1') return;
6411
6412 if (!('IntersectionObserver' in window))
6413 {
6414 void loadOneFolderIcon(iconEl);
6415 return;
6416 }
6417
6418 if (!STATE.folderIconObserver)
6419 {
6420 STATE.folderIconObserver = new IntersectionObserver((entries) =>
6421 {
6422 for (const entry of entries)
6423 {
6424 if (!entry.isIntersecting) continue;
6425 const icon = entry.target;
6426 STATE.folderIconObserver.unobserve(icon);
6427 void loadOneFolderIcon(icon);
6428 }
6429 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
6430 }
6431
6432 STATE.folderIconObserver.observe(iconEl);
6433}
6434
6435async function loadOneFolderIcon (iconEl)
6436{
6437 if (!iconEl.isConnected || !STATE.token) return;
6438 if (iconEl.dataset.thumbReady === '1') return;
6439
6440 const folderPath = iconEl.dataset.folderPath;
6441 if (!folderPath) return;
6442
6443 let res;
6444 try
6445 {
6446 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
6447 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
6448 });
6449 } catch { return; }
6450
6451 if (!res.ok || !iconEl.isConnected) return;
6452
6453 const data = await res.json();
6454 if (!data.icon) return; // No icon available — keep plain folder SVG.
6455
6456 // Fetch the thumbnail through the auth-gated endpoint.
6457 let thumbRes;
6458 try
6459 {
6460 thumbRes = await fetch(
6461 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
6462 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } }
6463… afgekapt