BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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