BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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