BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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