BlueGit

timfa filemanager

Merge feature/folder-view-sorting-grouping

timfa Tim Falken · pushed by timfa

Authored 2026-05-18 · 6 months ago

Hash
1e6b4bc9693031f972d235038c5007894b90ede5
5 files changed +593 −9
.github/technical-reference.md +3 −0
@@ -77,6 +77,7 @@
77 77 - GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
78 78 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
79 79 - GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
80 - GET /api/files/list - Returns directory items including name/path/isDir plus size, mtime, and uploadedAt (creation-time approximation) used by client folder sorting/grouping.
80 81 - GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
81 82 - GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
82 83 - GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
@@ -248,6 +249,8 @@
248 249 - formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
249 250 - openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
250 251 - openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
252 - openFolderSidebar() / renderFolderViewControls(actions, dirPath) - In folder overview mode, renders per-folder view controls (Sort by, Group by, folders-first, ascending) and persists them per user+folder in localStorage.
253 - renderFileGrid() / buildFileGridRows(items, prefs) - Applies folder view ordering as Group option > folders-first option > sort option, and inserts labelled separator rows when grouping is enabled.
251 254 - openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
252 255 - uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
253 256 - openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
@@ -77,6 +77,7 @@
77- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
77- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
78- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
78- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
79- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
79- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
80- GET /api/files/list - Returns directory items including name/path/isDir plus size, mtime, and uploadedAt (creation-time approximation) used by client folder sorting/grouping.
80- GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
81- GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
81- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
82- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
82- GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
83- GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
@@ -248,6 +249,8 @@
248- formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
249- formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
249- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
250- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
250- openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
251- openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
252- openFolderSidebar() / renderFolderViewControls(actions, dirPath) - In folder overview mode, renders per-folder view controls (Sort by, Group by, folders-first, ascending) and persists them per user+folder in localStorage.
253- renderFileGrid() / buildFileGridRows(items, prefs) - Applies folder view ordering as Group option > folders-first option > sort option, and inserts labelled separator rows when grouping is enabled.
251- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
254- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
252- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
255- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
253- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
256- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
public/app.js +418 −9
@@ -79,11 +79,18 @@ const MOBILE_LONG_PRESS_MS = 420;
79 79 const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
80 80 const THUMB_OBSERVER_ROOT_MARGIN = '120px';
81 81 const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
82 const FOLDER_VIEW_PREFS_KEY_PREFIX = 'filemanager.folder-view-prefs.v1.';
82 83 const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
83 84 const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
84 85 backgroundOpacity: '0',
85 86 edgeStyle: 'uniform',
86 87 });
88 const DEFAULT_FOLDER_VIEW_PREFS = {
89 sortBy: 'alphabetical',
90 groupBy: 'none',
91 foldersFirst: true,
92 ascending: true,
93 };
87 94 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
88 95 const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
89 96 let videoJsLoaderPromise = null;
@@ -256,6 +263,78 @@ function saveUserVideoPrefs (patch)
256 263 }
257 264 }
258 265
266 function userFolderViewPrefsKey ()
267 {
268 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
269 return FOLDER_VIEW_PREFS_KEY_PREFIX + name;
270 }
271
272 function normaliseFolderViewPrefs (value)
273 {
274 const input = value && typeof value === 'object' ? value : {};
275 const sortBy = ['alphabetical', 'fileType', 'lastChanged', 'timeUploaded', 'size'].includes(input.sortBy)
276 ? input.sortBy
277 : DEFAULT_FOLDER_VIEW_PREFS.sortBy;
278 const groupBy = ['none', 'alphabetical', 'fileType', 'lastChangedDate', 'timeUploadedDate', 'size'].includes(input.groupBy)
279 ? input.groupBy
280 : DEFAULT_FOLDER_VIEW_PREFS.groupBy;
281
282 return {
283 sortBy,
284 groupBy,
285 foldersFirst: input.foldersFirst !== undefined ? !!input.foldersFirst : DEFAULT_FOLDER_VIEW_PREFS.foldersFirst,
286 ascending: input.ascending !== undefined ? !!input.ascending : DEFAULT_FOLDER_VIEW_PREFS.ascending,
287 };
288 }
289
290 function loadFolderViewPrefsMap ()
291 {
292 try
293 {
294 const raw = localStorage.getItem(userFolderViewPrefsKey());
295 const parsed = raw ? JSON.parse(raw) : {};
296 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
297
298 const out = {};
299 for (const [dirPath, prefs] of Object.entries(parsed))
300 {
301 out[String(dirPath)] = normaliseFolderViewPrefs(prefs);
302 }
303 return out;
304 } catch
305 {
306 return {};
307 }
308 }
309
310 function saveFolderViewPrefsMap (prefsByPath)
311 {
312 try
313 {
314 localStorage.setItem(userFolderViewPrefsKey(), JSON.stringify(prefsByPath || {}));
315 } catch
316 {
317 // Ignore localStorage failures.
318 }
319 }
320
321 function folderViewPrefsForDir (dirPath)
322 {
323 if (!dirPath) return { ...DEFAULT_FOLDER_VIEW_PREFS };
324 const prefsByPath = loadFolderViewPrefsMap();
325 return normaliseFolderViewPrefs(prefsByPath[String(dirPath)] || DEFAULT_FOLDER_VIEW_PREFS);
326 }
327
328 function saveFolderViewPrefsForDir (dirPath, patch)
329 {
330 if (!dirPath) return;
331 const key = String(dirPath);
332 const prefsByPath = loadFolderViewPrefsMap();
333 const current = normaliseFolderViewPrefs(prefsByPath[key] || DEFAULT_FOLDER_VIEW_PREFS);
334 prefsByPath[key] = normaliseFolderViewPrefs({ ...current, ...(patch || {}) });
335 saveFolderViewPrefsMap(prefsByPath);
336 }
337
259 338 function buildAuthHeaders ()
260 339 {
261 340 const headers = {};
@@ -1922,7 +2001,7 @@ async function refreshFolderStats ()
1922 2001 function itemsSignature (items)
1923 2002 {
1924 2003 return JSON.stringify(
1925 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
2004 (items || []).map(it => [it.path, it.mtime, it.uploadedAt, it.size, it.isDir])
1926 2005 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
1927 2006 );
1928 2007 }
@@ -1990,6 +2069,218 @@ function stopAutoRefresh ()
1990 2069 // FILE GRID RENDERING
1991 2070 // ───────────────────────────────────────────────────────────────────────────
1992 2071
2072 function parseItemTimestampMs (value)
2073 {
2074 if (value == null || value === '') return null;
2075 const asNumber = Number(value);
2076 if (Number.isFinite(asNumber) && asNumber > 0) return asNumber;
2077 const asDate = Date.parse(String(value));
2078 return Number.isFinite(asDate) ? asDate : null;
2079 }
2080
2081 function dayStartMsFromTimestamp (value)
2082 {
2083 const ts = parseItemTimestampMs(value);
2084 if (!Number.isFinite(ts)) return null;
2085 const d = new Date(ts);
2086 return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
2087 }
2088
2089 function groupDateLabel (dayStartMs)
2090 {
2091 if (!Number.isFinite(dayStartMs)) return 'Unknown date';
2092 return new Date(dayStartMs).toLocaleDateString('en-GB', {
2093 day: '2-digit',
2094 month: 'short',
2095 year: 'numeric',
2096 });
2097 }
2098
2099 function itemFileTypeLabel (item)
2100 {
2101 if (item.isDir) return 'Folder';
2102 const ext = extOf(item.name);
2103 return ext ? `.${ext}` : 'No extension';
2104 }
2105
2106 function itemAlphabeticalGroupLabel (item)
2107 {
2108 const first = String(item.name || '').trim().charAt(0).toUpperCase();
2109 if (!first) return '#';
2110 return /[A-Z0-9]/.test(first) ? first : '#';
2111 }
2112
2113 function itemSizeGroupInfo (item)
2114 {
2115 if (item.isDir) return { id: 'folder', label: 'Folder', rank: -1 };
2116 const size = Number(item.size);
2117 if (!Number.isFinite(size) || size < 0) return { id: 'unknown', label: 'Unknown size', rank: 999 };
2118 if (size === 0) return { id: 'empty', label: 'Empty', rank: 0 };
2119 if (size < (1024 * 1024)) return { id: 'small', label: 'Smaller than 1 MB', rank: 1 };
2120 if (size < (100 * 1024 * 1024)) return { id: 'medium', label: '1 MB to 100 MB', rank: 2 };
2121 if (size < (1024 * 1024 * 1024)) return { id: 'large', label: '100 MB to 1 GB', rank: 3 };
2122 return { id: 'huge', label: 'Larger than 1 GB', rank: 4 };
2123 }
2124
2125 function itemGroupInfo (item, groupBy)
2126 {
2127 if (groupBy === 'alphabetical')
2128 {
2129 const label = itemAlphabeticalGroupLabel(item);
2130 return { id: `alpha:${label}`, label, rank: label.charCodeAt(0) || 999 };
2131 }
2132
2133 if (groupBy === 'fileType')
2134 {
2135 const label = itemFileTypeLabel(item);
2136 return { id: `type:${label.toLowerCase()}`, label, rank: 0 };
2137 }
2138
2139 if (groupBy === 'lastChangedDate')
2140 {
2141 const dayStart = dayStartMsFromTimestamp(item.mtime);
2142 return {
2143 id: `mtime:${dayStart == null ? 'unknown' : dayStart}`,
2144 label: groupDateLabel(dayStart),
2145 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
2146 };
2147 }
2148
2149 if (groupBy === 'timeUploadedDate')
2150 {
2151 const dayStart = dayStartMsFromTimestamp(item.uploadedAt != null ? item.uploadedAt : item.mtime);
2152 return {
2153 id: `uploaded:${dayStart == null ? 'unknown' : dayStart}`,
2154 label: groupDateLabel(dayStart),
2155 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
2156 };
2157 }
2158
2159 if (groupBy === 'size')
2160 {
2161 const sizeGroup = itemSizeGroupInfo(item);
2162 return {
2163 id: `size:${sizeGroup.id}`,
2164 label: sizeGroup.label,
2165 rank: sizeGroup.rank,
2166 };
2167 }
2168
2169 return { id: 'none', label: '', rank: 0 };
2170 }
2171
2172 function compareText (a, b)
2173 {
2174 return String(a || '').localeCompare(String(b || ''), undefined, { numeric: true, sensitivity: 'base' });
2175 }
2176
2177 function compareNullableNumber (a, b, ascending)
2178 {
2179 const hasA = Number.isFinite(a);
2180 const hasB = Number.isFinite(b);
2181 if (!hasA && !hasB) return 0;
2182 if (!hasA) return 1;
2183 if (!hasB) return -1;
2184 const diff = a - b;
2185 return ascending ? diff : -diff;
2186 }
2187
2188 function compareBySortMode (a, b, sortBy, ascending)
2189 {
2190 if (sortBy === 'fileType')
2191 {
2192 const extA = itemFileTypeLabel(a.item).toLowerCase();
2193 const extB = itemFileTypeLabel(b.item).toLowerCase();
2194 const byType = compareText(extA, extB);
2195 if (byType !== 0) return ascending ? byType : -byType;
2196 const byName = compareText(a.item.name, b.item.name);
2197 return ascending ? byName : -byName;
2198 }
2199
2200 if (sortBy === 'lastChanged')
2201 {
2202 return compareNullableNumber(parseItemTimestampMs(a.item.mtime), parseItemTimestampMs(b.item.mtime), ascending);
2203 }
2204
2205 if (sortBy === 'timeUploaded')
2206 {
2207 const uploadedA = parseItemTimestampMs(a.item.uploadedAt != null ? a.item.uploadedAt : a.item.mtime);
2208 const uploadedB = parseItemTimestampMs(b.item.uploadedAt != null ? b.item.uploadedAt : b.item.mtime);
2209 return compareNullableNumber(uploadedA, uploadedB, ascending);
2210 }
2211
2212 if (sortBy === 'size')
2213 {
2214 const sizeA = Number.isFinite(Number(a.item.size)) ? Number(a.item.size) : null;
2215 const sizeB = Number.isFinite(Number(b.item.size)) ? Number(b.item.size) : null;
2216 return compareNullableNumber(sizeA, sizeB, ascending);
2217 }
2218
2219 const byName = compareText(a.item.name, b.item.name);
2220 return ascending ? byName : -byName;
2221 }
2222
2223 function buildFileGridRows (items, prefs)
2224 {
2225 const list = Array.isArray(items) ? items : [];
2226 const groupBy = prefs.groupBy || 'none';
2227 const sortBy = prefs.sortBy || 'alphabetical';
2228 const descriptors = list.map((item) => ({
2229 item,
2230 group: itemGroupInfo(item, groupBy),
2231 }));
2232
2233 descriptors.sort((a, b) =>
2234 {
2235 if (groupBy !== 'none')
2236 {
2237 const dateGrouping = groupBy === 'lastChangedDate' || groupBy === 'timeUploadedDate';
2238 if (a.group.rank !== b.group.rank)
2239 {
2240 const byRank = dateGrouping ? (b.group.rank - a.group.rank) : (a.group.rank - b.group.rank);
2241 if (byRank !== 0) return byRank;
2242 }
2243 const byGroupLabel = compareText(a.group.label, b.group.label);
2244 if (byGroupLabel !== 0) return dateGrouping ? byGroupLabel : (prefs.ascending ? byGroupLabel : -byGroupLabel);
2245 }
2246
2247 if (prefs.foldersFirst && a.item.isDir !== b.item.isDir)
2248 {
2249 return a.item.isDir ? -1 : 1;
2250 }
2251
2252 const bySort = compareBySortMode(a, b, sortBy, !!prefs.ascending);
2253 if (bySort !== 0) return bySort;
2254
2255 return compareText(a.item.name, b.item.name);
2256 });
2257
2258 const rows = [];
2259 let previousGroupId = null;
2260 for (const descriptor of descriptors)
2261 {
2262 if (groupBy !== 'none' && descriptor.group.id !== previousGroupId)
2263 {
2264 rows.push({ type: 'group', label: descriptor.group.label });
2265 previousGroupId = descriptor.group.id;
2266 }
2267 rows.push({ type: 'item', item: descriptor.item });
2268 }
2269
2270 return rows;
2271 }
2272
2273 function makeGroupSeparator (label)
2274 {
2275 const el = document.createElement('div');
2276 el.className = 'file-group-separator';
2277
2278 const text = document.createElement('span');
2279 text.textContent = String(label || 'Other');
2280 el.appendChild(text);
2281 return el;
2282 }
2283
1993 2284 function renderFileGrid ()
1994 2285 {
1995 2286 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
@@ -2000,17 +2291,21 @@ function renderFileGrid ()
2000 2291 grid.innerHTML = '';
2001 2292 const empty = document.getElementById('empty-notice');
2002 2293
2003 const sorted = [...STATE.items].sort((a, b) =>
2004 {
2005 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
2006 return a.name.localeCompare(b.name);
2007 });
2294 const prefs = (!STATE.searchQuery && STATE.currentDir)
2295 ? folderViewPrefsForDir(STATE.currentDir)
2296 : { ...DEFAULT_FOLDER_VIEW_PREFS };
2297 const rows = buildFileGridRows(STATE.items, prefs);
2008 2298
2009 empty.classList.toggle('hidden', sorted.length > 0);
2299 empty.classList.toggle('hidden', STATE.items.length > 0);
2010 2300
2011 for (const item of sorted)
2301 for (const row of rows)
2012 2302 {
2013 grid.appendChild(makeFileItem(item));
2303 if (row.type === 'group')
2304 {
2305 grid.appendChild(makeGroupSeparator(row.label));
2306 continue;
2307 }
2308 grid.appendChild(makeFileItem(row.item));
2014 2309 }
2015 2310
2016 2311 loadThumbnails();
@@ -2553,6 +2848,7 @@ function openFolderSidebar ()
2553 2848 <dt>Files</dt><dd>${files}</dd>
2554 2849 `;
2555 2850 dl.innerHTML = baseDetails;
2851 renderFolderViewControls(actions, STATE.currentDir);
2556 2852
2557 2853 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2558 2854 {
@@ -2576,6 +2872,119 @@ function openFolderSidebar ()
2576 2872 }
2577 2873 }
2578 2874
2875 function renderFolderViewControls (actions, dirPath)
2876 {
2877 if (!actions || !dirPath) return;
2878
2879 const prefs = folderViewPrefsForDir(dirPath);
2880
2881 const section = document.createElement('section');
2882 section.className = 'sidebar-view-options';
2883
2884 const heading = document.createElement('h3');
2885 heading.textContent = 'View options';
2886 section.appendChild(heading);
2887
2888 const sortLabel = document.createElement('label');
2889 sortLabel.className = 'sidebar-view-option-label';
2890 sortLabel.textContent = 'Sort by';
2891 const sortSelect = document.createElement('select');
2892 sortSelect.className = 'sidebar-view-option-control';
2893 sortSelect.dataset.viewOption = 'sort';
2894 const sortOptions = [
2895 { value: 'alphabetical', label: 'Alphabetically' },
2896 { value: 'fileType', label: 'File type' },
2897 { value: 'lastChanged', label: 'Last changed' },
2898 { value: 'timeUploaded', label: 'Time uploaded' },
2899 { value: 'size', label: 'Size' },
2900 ];
2901 for (const option of sortOptions)
2902 {
2903 const optEl = document.createElement('option');
2904 optEl.value = option.value;
2905 optEl.textContent = option.label;
2906 sortSelect.appendChild(optEl);
2907 }
2908 sortSelect.value = prefs.sortBy;
2909 sortSelect.addEventListener('change', () =>
2910 {
2911 saveFolderViewPrefsForDir(dirPath, { sortBy: sortSelect.value });
2912 renderFileGrid();
2913 });
2914 sortLabel.appendChild(sortSelect);
2915 section.appendChild(sortLabel);
2916
2917 const groupLabel = document.createElement('label');
2918 groupLabel.className = 'sidebar-view-option-label';
2919 groupLabel.textContent = 'Group by';
2920 const groupSelect = document.createElement('select');
2921 groupSelect.className = 'sidebar-view-option-control';
2922 groupSelect.dataset.viewOption = 'group';
2923 const groupOptions = [
2924 { value: 'none', label: 'None' },
2925 { value: 'alphabetical', label: 'Alphabetically' },
2926 { value: 'fileType', label: 'File type' },
2927 { value: 'lastChangedDate', label: 'Last changed date' },
2928 { value: 'timeUploadedDate', label: 'Upload date' },
2929 { value: 'size', label: 'Size' },
2930 ];
2931 for (const option of groupOptions)
2932 {
2933 const optEl = document.createElement('option');
2934 optEl.value = option.value;
2935 optEl.textContent = option.label;
2936 groupSelect.appendChild(optEl);
2937 }
2938 groupSelect.value = prefs.groupBy;
2939 groupSelect.addEventListener('change', () =>
2940 {
2941 saveFolderViewPrefsForDir(dirPath, { groupBy: groupSelect.value });
2942 renderFileGrid();
2943 });
2944 groupLabel.appendChild(groupSelect);
2945 section.appendChild(groupLabel);
2946
2947 const foldersTopLabel = document.createElement('label');
2948 foldersTopLabel.className = 'sidebar-view-toggle';
2949 const foldersTopInput = document.createElement('input');
2950 foldersTopInput.type = 'checkbox';
2951 foldersTopInput.dataset.viewOption = 'folders-first';
2952 foldersTopInput.checked = !!prefs.foldersFirst;
2953 foldersTopInput.addEventListener('change', () =>
2954 {
2955 saveFolderViewPrefsForDir(dirPath, { foldersFirst: foldersTopInput.checked });
2956 renderFileGrid();
2957 });
2958 const foldersTopText = document.createElement('span');
2959 foldersTopText.textContent = 'Always keep folders at the top';
2960 foldersTopLabel.appendChild(foldersTopInput);
2961 foldersTopLabel.appendChild(foldersTopText);
2962 section.appendChild(foldersTopLabel);
2963
2964 const ascLabel = document.createElement('label');
2965 ascLabel.className = 'sidebar-view-toggle';
2966 const ascInput = document.createElement('input');
2967 ascInput.type = 'checkbox';
2968 ascInput.dataset.viewOption = 'ascending';
2969 ascInput.checked = !!prefs.ascending;
2970 ascInput.addEventListener('change', () =>
2971 {
2972 saveFolderViewPrefsForDir(dirPath, { ascending: ascInput.checked });
2973 renderFileGrid();
2974 });
2975 const ascText = document.createElement('span');
2976 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2977 ascInput.addEventListener('change', () =>
2978 {
2979 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2980 });
2981 ascLabel.appendChild(ascInput);
2982 ascLabel.appendChild(ascText);
2983 section.appendChild(ascLabel);
2984
2985 actions.appendChild(section);
2986 }
2987
2579 2988 function closeSidebar ()
2580 2989 {
2581 2990 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
@@ -79,11 +79,18 @@ const MOBILE_LONG_PRESS_MS = 420;
79const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
79const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
80const THUMB_OBSERVER_ROOT_MARGIN = '120px';
80const THUMB_OBSERVER_ROOT_MARGIN = '120px';
81const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
81const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
82const FOLDER_VIEW_PREFS_KEY_PREFIX = 'filemanager.folder-view-prefs.v1.';
82const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
83const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
83const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
84const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
84 backgroundOpacity: '0',
85 backgroundOpacity: '0',
85 edgeStyle: 'uniform',
86 edgeStyle: 'uniform',
86});
87});
88const DEFAULT_FOLDER_VIEW_PREFS = {
89 sortBy: 'alphabetical',
90 groupBy: 'none',
91 foldersFirst: true,
92 ascending: true,
93};
87const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
94const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
88const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
95const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
89let videoJsLoaderPromise = null;
96let videoJsLoaderPromise = null;
@@ -256,6 +263,78 @@ function saveUserVideoPrefs (patch)
256 }
263 }
257}
264}
258
265
266function userFolderViewPrefsKey ()
267{
268 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
269 return FOLDER_VIEW_PREFS_KEY_PREFIX + name;
270}
271
272function normaliseFolderViewPrefs (value)
273{
274 const input = value && typeof value === 'object' ? value : {};
275 const sortBy = ['alphabetical', 'fileType', 'lastChanged', 'timeUploaded', 'size'].includes(input.sortBy)
276 ? input.sortBy
277 : DEFAULT_FOLDER_VIEW_PREFS.sortBy;
278 const groupBy = ['none', 'alphabetical', 'fileType', 'lastChangedDate', 'timeUploadedDate', 'size'].includes(input.groupBy)
279 ? input.groupBy
280 : DEFAULT_FOLDER_VIEW_PREFS.groupBy;
281
282 return {
283 sortBy,
284 groupBy,
285 foldersFirst: input.foldersFirst !== undefined ? !!input.foldersFirst : DEFAULT_FOLDER_VIEW_PREFS.foldersFirst,
286 ascending: input.ascending !== undefined ? !!input.ascending : DEFAULT_FOLDER_VIEW_PREFS.ascending,
287 };
288}
289
290function loadFolderViewPrefsMap ()
291{
292 try
293 {
294 const raw = localStorage.getItem(userFolderViewPrefsKey());
295 const parsed = raw ? JSON.parse(raw) : {};
296 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
297
298 const out = {};
299 for (const [dirPath, prefs] of Object.entries(parsed))
300 {
301 out[String(dirPath)] = normaliseFolderViewPrefs(prefs);
302 }
303 return out;
304 } catch
305 {
306 return {};
307 }
308}
309
310function saveFolderViewPrefsMap (prefsByPath)
311{
312 try
313 {
314 localStorage.setItem(userFolderViewPrefsKey(), JSON.stringify(prefsByPath || {}));
315 } catch
316 {
317 // Ignore localStorage failures.
318 }
319}
320
321function folderViewPrefsForDir (dirPath)
322{
323 if (!dirPath) return { ...DEFAULT_FOLDER_VIEW_PREFS };
324 const prefsByPath = loadFolderViewPrefsMap();
325 return normaliseFolderViewPrefs(prefsByPath[String(dirPath)] || DEFAULT_FOLDER_VIEW_PREFS);
326}
327
328function saveFolderViewPrefsForDir (dirPath, patch)
329{
330 if (!dirPath) return;
331 const key = String(dirPath);
332 const prefsByPath = loadFolderViewPrefsMap();
333 const current = normaliseFolderViewPrefs(prefsByPath[key] || DEFAULT_FOLDER_VIEW_PREFS);
334 prefsByPath[key] = normaliseFolderViewPrefs({ ...current, ...(patch || {}) });
335 saveFolderViewPrefsMap(prefsByPath);
336}
337
259function buildAuthHeaders ()
338function buildAuthHeaders ()
260{
339{
261 const headers = {};
340 const headers = {};
@@ -1922,7 +2001,7 @@ async function refreshFolderStats ()
1922function itemsSignature (items)
2001function itemsSignature (items)
1923{
2002{
1924 return JSON.stringify(
2003 return JSON.stringify(
1925 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
2004 (items || []).map(it => [it.path, it.mtime, it.uploadedAt, it.size, it.isDir])
1926 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
2005 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
1927 );
2006 );
1928}
2007}
@@ -1990,6 +2069,218 @@ function stopAutoRefresh ()
1990// FILE GRID RENDERING
2069// FILE GRID RENDERING
1991// ───────────────────────────────────────────────────────────────────────────
2070// ───────────────────────────────────────────────────────────────────────────
1992
2071
2072function parseItemTimestampMs (value)
2073{
2074 if (value == null || value === '') return null;
2075 const asNumber = Number(value);
2076 if (Number.isFinite(asNumber) && asNumber > 0) return asNumber;
2077 const asDate = Date.parse(String(value));
2078 return Number.isFinite(asDate) ? asDate : null;
2079}
2080
2081function dayStartMsFromTimestamp (value)
2082{
2083 const ts = parseItemTimestampMs(value);
2084 if (!Number.isFinite(ts)) return null;
2085 const d = new Date(ts);
2086 return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
2087}
2088
2089function groupDateLabel (dayStartMs)
2090{
2091 if (!Number.isFinite(dayStartMs)) return 'Unknown date';
2092 return new Date(dayStartMs).toLocaleDateString('en-GB', {
2093 day: '2-digit',
2094 month: 'short',
2095 year: 'numeric',
2096 });
2097}
2098
2099function itemFileTypeLabel (item)
2100{
2101 if (item.isDir) return 'Folder';
2102 const ext = extOf(item.name);
2103 return ext ? `.${ext}` : 'No extension';
2104}
2105
2106function itemAlphabeticalGroupLabel (item)
2107{
2108 const first = String(item.name || '').trim().charAt(0).toUpperCase();
2109 if (!first) return '#';
2110 return /[A-Z0-9]/.test(first) ? first : '#';
2111}
2112
2113function itemSizeGroupInfo (item)
2114{
2115 if (item.isDir) return { id: 'folder', label: 'Folder', rank: -1 };
2116 const size = Number(item.size);
2117 if (!Number.isFinite(size) || size < 0) return { id: 'unknown', label: 'Unknown size', rank: 999 };
2118 if (size === 0) return { id: 'empty', label: 'Empty', rank: 0 };
2119 if (size < (1024 * 1024)) return { id: 'small', label: 'Smaller than 1 MB', rank: 1 };
2120 if (size < (100 * 1024 * 1024)) return { id: 'medium', label: '1 MB to 100 MB', rank: 2 };
2121 if (size < (1024 * 1024 * 1024)) return { id: 'large', label: '100 MB to 1 GB', rank: 3 };
2122 return { id: 'huge', label: 'Larger than 1 GB', rank: 4 };
2123}
2124
2125function itemGroupInfo (item, groupBy)
2126{
2127 if (groupBy === 'alphabetical')
2128 {
2129 const label = itemAlphabeticalGroupLabel(item);
2130 return { id: `alpha:${label}`, label, rank: label.charCodeAt(0) || 999 };
2131 }
2132
2133 if (groupBy === 'fileType')
2134 {
2135 const label = itemFileTypeLabel(item);
2136 return { id: `type:${label.toLowerCase()}`, label, rank: 0 };
2137 }
2138
2139 if (groupBy === 'lastChangedDate')
2140 {
2141 const dayStart = dayStartMsFromTimestamp(item.mtime);
2142 return {
2143 id: `mtime:${dayStart == null ? 'unknown' : dayStart}`,
2144 label: groupDateLabel(dayStart),
2145 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
2146 };
2147 }
2148
2149 if (groupBy === 'timeUploadedDate')
2150 {
2151 const dayStart = dayStartMsFromTimestamp(item.uploadedAt != null ? item.uploadedAt : item.mtime);
2152 return {
2153 id: `uploaded:${dayStart == null ? 'unknown' : dayStart}`,
2154 label: groupDateLabel(dayStart),
2155 rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart,
2156 };
2157 }
2158
2159 if (groupBy === 'size')
2160 {
2161 const sizeGroup = itemSizeGroupInfo(item);
2162 return {
2163 id: `size:${sizeGroup.id}`,
2164 label: sizeGroup.label,
2165 rank: sizeGroup.rank,
2166 };
2167 }
2168
2169 return { id: 'none', label: '', rank: 0 };
2170}
2171
2172function compareText (a, b)
2173{
2174 return String(a || '').localeCompare(String(b || ''), undefined, { numeric: true, sensitivity: 'base' });
2175}
2176
2177function compareNullableNumber (a, b, ascending)
2178{
2179 const hasA = Number.isFinite(a);
2180 const hasB = Number.isFinite(b);
2181 if (!hasA && !hasB) return 0;
2182 if (!hasA) return 1;
2183 if (!hasB) return -1;
2184 const diff = a - b;
2185 return ascending ? diff : -diff;
2186}
2187
2188function compareBySortMode (a, b, sortBy, ascending)
2189{
2190 if (sortBy === 'fileType')
2191 {
2192 const extA = itemFileTypeLabel(a.item).toLowerCase();
2193 const extB = itemFileTypeLabel(b.item).toLowerCase();
2194 const byType = compareText(extA, extB);
2195 if (byType !== 0) return ascending ? byType : -byType;
2196 const byName = compareText(a.item.name, b.item.name);
2197 return ascending ? byName : -byName;
2198 }
2199
2200 if (sortBy === 'lastChanged')
2201 {
2202 return compareNullableNumber(parseItemTimestampMs(a.item.mtime), parseItemTimestampMs(b.item.mtime), ascending);
2203 }
2204
2205 if (sortBy === 'timeUploaded')
2206 {
2207 const uploadedA = parseItemTimestampMs(a.item.uploadedAt != null ? a.item.uploadedAt : a.item.mtime);
2208 const uploadedB = parseItemTimestampMs(b.item.uploadedAt != null ? b.item.uploadedAt : b.item.mtime);
2209 return compareNullableNumber(uploadedA, uploadedB, ascending);
2210 }
2211
2212 if (sortBy === 'size')
2213 {
2214 const sizeA = Number.isFinite(Number(a.item.size)) ? Number(a.item.size) : null;
2215 const sizeB = Number.isFinite(Number(b.item.size)) ? Number(b.item.size) : null;
2216 return compareNullableNumber(sizeA, sizeB, ascending);
2217 }
2218
2219 const byName = compareText(a.item.name, b.item.name);
2220 return ascending ? byName : -byName;
2221}
2222
2223function buildFileGridRows (items, prefs)
2224{
2225 const list = Array.isArray(items) ? items : [];
2226 const groupBy = prefs.groupBy || 'none';
2227 const sortBy = prefs.sortBy || 'alphabetical';
2228 const descriptors = list.map((item) => ({
2229 item,
2230 group: itemGroupInfo(item, groupBy),
2231 }));
2232
2233 descriptors.sort((a, b) =>
2234 {
2235 if (groupBy !== 'none')
2236 {
2237 const dateGrouping = groupBy === 'lastChangedDate' || groupBy === 'timeUploadedDate';
2238 if (a.group.rank !== b.group.rank)
2239 {
2240 const byRank = dateGrouping ? (b.group.rank - a.group.rank) : (a.group.rank - b.group.rank);
2241 if (byRank !== 0) return byRank;
2242 }
2243 const byGroupLabel = compareText(a.group.label, b.group.label);
2244 if (byGroupLabel !== 0) return dateGrouping ? byGroupLabel : (prefs.ascending ? byGroupLabel : -byGroupLabel);
2245 }
2246
2247 if (prefs.foldersFirst && a.item.isDir !== b.item.isDir)
2248 {
2249 return a.item.isDir ? -1 : 1;
2250 }
2251
2252 const bySort = compareBySortMode(a, b, sortBy, !!prefs.ascending);
2253 if (bySort !== 0) return bySort;
2254
2255 return compareText(a.item.name, b.item.name);
2256 });
2257
2258 const rows = [];
2259 let previousGroupId = null;
2260 for (const descriptor of descriptors)
2261 {
2262 if (groupBy !== 'none' && descriptor.group.id !== previousGroupId)
2263 {
2264 rows.push({ type: 'group', label: descriptor.group.label });
2265 previousGroupId = descriptor.group.id;
2266 }
2267 rows.push({ type: 'item', item: descriptor.item });
2268 }
2269
2270 return rows;
2271}
2272
2273function makeGroupSeparator (label)
2274{
2275 const el = document.createElement('div');
2276 el.className = 'file-group-separator';
2277
2278 const text = document.createElement('span');
2279 text.textContent = String(label || 'Other');
2280 el.appendChild(text);
2281 return el;
2282}
2283
1993function renderFileGrid ()
2284function renderFileGrid ()
1994{
2285{
1995 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
2286 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
@@ -2000,17 +2291,21 @@ function renderFileGrid ()
2000 grid.innerHTML = '';
2291 grid.innerHTML = '';
2001 const empty = document.getElementById('empty-notice');
2292 const empty = document.getElementById('empty-notice');
2002
2293
2003 const sorted = [...STATE.items].sort((a, b) =>
2294 const prefs = (!STATE.searchQuery && STATE.currentDir)
2004 {
2295 ? folderViewPrefsForDir(STATE.currentDir)
2005 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
2296 : { ...DEFAULT_FOLDER_VIEW_PREFS };
2006 return a.name.localeCompare(b.name);
2297 const rows = buildFileGridRows(STATE.items, prefs);
2007 });
2008
2298
2009 empty.classList.toggle('hidden', sorted.length > 0);
2299 empty.classList.toggle('hidden', STATE.items.length > 0);
2010
2300
2011 for (const item of sorted)
2301 for (const row of rows)
2012 {
2302 {
2013 grid.appendChild(makeFileItem(item));
2303 if (row.type === 'group')
2304 {
2305 grid.appendChild(makeGroupSeparator(row.label));
2306 continue;
2307 }
2308 grid.appendChild(makeFileItem(row.item));
2014 }
2309 }
2015
2310
2016 loadThumbnails();
2311 loadThumbnails();
@@ -2553,6 +2848,7 @@ function openFolderSidebar ()
2553 <dt>Files</dt><dd>${files}</dd>
2848 <dt>Files</dt><dd>${files}</dd>
2554 `;
2849 `;
2555 dl.innerHTML = baseDetails;
2850 dl.innerHTML = baseDetails;
2851 renderFolderViewControls(actions, STATE.currentDir);
2556
2852
2557 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2853 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2558 {
2854 {
@@ -2576,6 +2872,119 @@ function openFolderSidebar ()
2576 }
2872 }
2577}
2873}
2578
2874
2875function renderFolderViewControls (actions, dirPath)
2876{
2877 if (!actions || !dirPath) return;
2878
2879 const prefs = folderViewPrefsForDir(dirPath);
2880
2881 const section = document.createElement('section');
2882 section.className = 'sidebar-view-options';
2883
2884 const heading = document.createElement('h3');
2885 heading.textContent = 'View options';
2886 section.appendChild(heading);
2887
2888 const sortLabel = document.createElement('label');
2889 sortLabel.className = 'sidebar-view-option-label';
2890 sortLabel.textContent = 'Sort by';
2891 const sortSelect = document.createElement('select');
2892 sortSelect.className = 'sidebar-view-option-control';
2893 sortSelect.dataset.viewOption = 'sort';
2894 const sortOptions = [
2895 { value: 'alphabetical', label: 'Alphabetically' },
2896 { value: 'fileType', label: 'File type' },
2897 { value: 'lastChanged', label: 'Last changed' },
2898 { value: 'timeUploaded', label: 'Time uploaded' },
2899 { value: 'size', label: 'Size' },
2900 ];
2901 for (const option of sortOptions)
2902 {
2903 const optEl = document.createElement('option');
2904 optEl.value = option.value;
2905 optEl.textContent = option.label;
2906 sortSelect.appendChild(optEl);
2907 }
2908 sortSelect.value = prefs.sortBy;
2909 sortSelect.addEventListener('change', () =>
2910 {
2911 saveFolderViewPrefsForDir(dirPath, { sortBy: sortSelect.value });
2912 renderFileGrid();
2913 });
2914 sortLabel.appendChild(sortSelect);
2915 section.appendChild(sortLabel);
2916
2917 const groupLabel = document.createElement('label');
2918 groupLabel.className = 'sidebar-view-option-label';
2919 groupLabel.textContent = 'Group by';
2920 const groupSelect = document.createElement('select');
2921 groupSelect.className = 'sidebar-view-option-control';
2922 groupSelect.dataset.viewOption = 'group';
2923 const groupOptions = [
2924 { value: 'none', label: 'None' },
2925 { value: 'alphabetical', label: 'Alphabetically' },
2926 { value: 'fileType', label: 'File type' },
2927 { value: 'lastChangedDate', label: 'Last changed date' },
2928 { value: 'timeUploadedDate', label: 'Upload date' },
2929 { value: 'size', label: 'Size' },
2930 ];
2931 for (const option of groupOptions)
2932 {
2933 const optEl = document.createElement('option');
2934 optEl.value = option.value;
2935 optEl.textContent = option.label;
2936 groupSelect.appendChild(optEl);
2937 }
2938 groupSelect.value = prefs.groupBy;
2939 groupSelect.addEventListener('change', () =>
2940 {
2941 saveFolderViewPrefsForDir(dirPath, { groupBy: groupSelect.value });
2942 renderFileGrid();
2943 });
2944 groupLabel.appendChild(groupSelect);
2945 section.appendChild(groupLabel);
2946
2947 const foldersTopLabel = document.createElement('label');
2948 foldersTopLabel.className = 'sidebar-view-toggle';
2949 const foldersTopInput = document.createElement('input');
2950 foldersTopInput.type = 'checkbox';
2951 foldersTopInput.dataset.viewOption = 'folders-first';
2952 foldersTopInput.checked = !!prefs.foldersFirst;
2953 foldersTopInput.addEventListener('change', () =>
2954 {
2955 saveFolderViewPrefsForDir(dirPath, { foldersFirst: foldersTopInput.checked });
2956 renderFileGrid();
2957 });
2958 const foldersTopText = document.createElement('span');
2959 foldersTopText.textContent = 'Always keep folders at the top';
2960 foldersTopLabel.appendChild(foldersTopInput);
2961 foldersTopLabel.appendChild(foldersTopText);
2962 section.appendChild(foldersTopLabel);
2963
2964 const ascLabel = document.createElement('label');
2965 ascLabel.className = 'sidebar-view-toggle';
2966 const ascInput = document.createElement('input');
2967 ascInput.type = 'checkbox';
2968 ascInput.dataset.viewOption = 'ascending';
2969 ascInput.checked = !!prefs.ascending;
2970 ascInput.addEventListener('change', () =>
2971 {
2972 saveFolderViewPrefsForDir(dirPath, { ascending: ascInput.checked });
2973 renderFileGrid();
2974 });
2975 const ascText = document.createElement('span');
2976 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2977 ascInput.addEventListener('change', () =>
2978 {
2979 ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending';
2980 });
2981 ascLabel.appendChild(ascInput);
2982 ascLabel.appendChild(ascText);
2983 section.appendChild(ascLabel);
2984
2985 actions.appendChild(section);
2986}
2987
2579function closeSidebar ()
2988function closeSidebar ()
2580{
2989{
2581 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
2990 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
public/style.css +70 −0
@@ -432,6 +432,34 @@ button.danger.admin-update-highlight {
432 432 gap: 0.75rem;
433 433 }
434 434
435 .file-group-separator {
436 grid-column: 1 / -1;
437 display: flex;
438 align-items: center;
439 gap: 0.55rem;
440 margin-top: 0.1rem;
441 margin-bottom: 0.1rem;
442 color: var(--text-muted);
443 font-size: 0.76rem;
444 letter-spacing: 0.02em;
445 }
446
447 .file-group-separator::before,
448 .file-group-separator::after {
449 content: '';
450 height: 1px;
451 background: var(--border);
452 flex: 1;
453 }
454
455 .file-group-separator span {
456 padding: 0.12rem 0.45rem;
457 border: 1px solid var(--border);
458 border-radius: 999px;
459 background: rgba(255, 255, 255, 0.02);
460 white-space: nowrap;
461 }
462
435 463 .file-item {
436 464 display: flex;
437 465 flex-direction: column;
@@ -640,6 +668,48 @@ button.danger.admin-update-highlight {
640 668 color: var(--danger);
641 669 }
642 670
671 .sidebar-view-options {
672 display: flex;
673 flex-direction: column;
674 gap: 0.5rem;
675 border-top: 1px solid var(--border);
676 padding-top: 0.7rem;
677 margin-top: 0.2rem;
678 }
679
680 .sidebar-view-options h3 {
681 margin: 0;
682 font-size: 0.82rem;
683 color: var(--text-muted);
684 text-transform: uppercase;
685 letter-spacing: 0.04em;
686 }
687
688 .sidebar-view-option-label {
689 display: flex;
690 flex-direction: column;
691 gap: 0.28rem;
692 font-size: 0.8rem;
693 color: var(--text-muted);
694 }
695
696 .sidebar-view-option-control {
697 width: 100%;
698 background: var(--surface2);
699 border: 1px solid var(--border);
700 border-radius: var(--radius);
701 color: var(--text);
702 padding: 0.42rem 0.5rem;
703 }
704
705 .sidebar-view-toggle {
706 display: flex;
707 align-items: center;
708 gap: 0.45rem;
709 font-size: 0.8rem;
710 color: var(--text);
711 }
712
643 713 /* ─── Duplicates panel ─────────────────────────────────── */
644 714 #sidebar-duplicates {
645 715 margin-top: 1rem;
@@ -432,6 +432,34 @@ button.danger.admin-update-highlight {
432 gap: 0.75rem;
432 gap: 0.75rem;
433}
433}
434
434
435.file-group-separator {
436 grid-column: 1 / -1;
437 display: flex;
438 align-items: center;
439 gap: 0.55rem;
440 margin-top: 0.1rem;
441 margin-bottom: 0.1rem;
442 color: var(--text-muted);
443 font-size: 0.76rem;
444 letter-spacing: 0.02em;
445}
446
447.file-group-separator::before,
448.file-group-separator::after {
449 content: '';
450 height: 1px;
451 background: var(--border);
452 flex: 1;
453}
454
455.file-group-separator span {
456 padding: 0.12rem 0.45rem;
457 border: 1px solid var(--border);
458 border-radius: 999px;
459 background: rgba(255, 255, 255, 0.02);
460 white-space: nowrap;
461}
462
435.file-item {
463.file-item {
436 display: flex;
464 display: flex;
437 flex-direction: column;
465 flex-direction: column;
@@ -640,6 +668,48 @@ button.danger.admin-update-highlight {
640 color: var(--danger);
668 color: var(--danger);
641}
669}
642
670
671.sidebar-view-options {
672 display: flex;
673 flex-direction: column;
674 gap: 0.5rem;
675 border-top: 1px solid var(--border);
676 padding-top: 0.7rem;
677 margin-top: 0.2rem;
678}
679
680.sidebar-view-options h3 {
681 margin: 0;
682 font-size: 0.82rem;
683 color: var(--text-muted);
684 text-transform: uppercase;
685 letter-spacing: 0.04em;
686}
687
688.sidebar-view-option-label {
689 display: flex;
690 flex-direction: column;
691 gap: 0.28rem;
692 font-size: 0.8rem;
693 color: var(--text-muted);
694}
695
696.sidebar-view-option-control {
697 width: 100%;
698 background: var(--surface2);
699 border: 1px solid var(--border);
700 border-radius: var(--radius);
701 color: var(--text);
702 padding: 0.42rem 0.5rem;
703}
704
705.sidebar-view-toggle {
706 display: flex;
707 align-items: center;
708 gap: 0.45rem;
709 font-size: 0.8rem;
710 color: var(--text);
711}
712
643/* ─── Duplicates panel ─────────────────────────────────── */
713/* ─── Duplicates panel ─────────────────────────────────── */
644#sidebar-duplicates {
714#sidebar-duplicates {
645 margin-top: 1rem;
715 margin-top: 1rem;
server/routes/files.js +7 −0
@@ -1014,11 +1014,17 @@ router.get('/list', requireAuth, (req, res) =>
1014 1014 const fullPath = path.join(dir, e.name);
1015 1015 let size = null;
1016 1016 let mtime = null;
1017 let uploadedAt = null;
1017 1018 try
1018 1019 {
1019 1020 const stat = fs.statSync(fullPath);
1020 1021 size = stat.size;
1021 1022 mtime = stat.mtime.toISOString();
1023 // Approximate upload time from file creation metadata when available.
1024 const uploadDate = (stat.birthtime && Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0)
1025 ? stat.birthtime
1026 : stat.ctime;
1027 uploadedAt = uploadDate instanceof Date ? uploadDate.toISOString() : null;
1022 1028 } catch { /* ignore */ }
1023 1029
1024 1030 return {
@@ -1026,6 +1032,7 @@ router.get('/list', requireAuth, (req, res) =>
1026 1032 isDir: e.isDirectory(),
1027 1033 size,
1028 1034 mtime,
1035 uploadedAt,
1029 1036 path: fullPath,
1030 1037 };
1031 1038 });
@@ -1014,11 +1014,17 @@ router.get('/list', requireAuth, (req, res) =>
1014 const fullPath = path.join(dir, e.name);
1014 const fullPath = path.join(dir, e.name);
1015 let size = null;
1015 let size = null;
1016 let mtime = null;
1016 let mtime = null;
1017 let uploadedAt = null;
1017 try
1018 try
1018 {
1019 {
1019 const stat = fs.statSync(fullPath);
1020 const stat = fs.statSync(fullPath);
1020 size = stat.size;
1021 size = stat.size;
1021 mtime = stat.mtime.toISOString();
1022 mtime = stat.mtime.toISOString();
1023 // Approximate upload time from file creation metadata when available.
1024 const uploadDate = (stat.birthtime && Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0)
1025 ? stat.birthtime
1026 : stat.ctime;
1027 uploadedAt = uploadDate instanceof Date ? uploadDate.toISOString() : null;
1022 } catch { /* ignore */ }
1028 } catch { /* ignore */ }
1023
1029
1024 return {
1030 return {
@@ -1026,6 +1032,7 @@ router.get('/list', requireAuth, (req, res) =>
1026 isDir: e.isDirectory(),
1032 isDir: e.isDirectory(),
1027 size,
1033 size,
1028 mtime,
1034 mtime,
1035 uploadedAt,
1029 path: fullPath,
1036 path: fullPath,
1030 };
1037 };
1031 });
1038 });
tests/page.load.test.js +95 −0
@@ -704,6 +704,101 @@ describe('page load smoke test', () =>
704 704 dom.window.close();
705 705 });
706 706
707 test('folder sidebar view options apply grouping/sorting and persist per folder', async () =>
708 {
709 listFixture = {
710 '/data': [
711 {
712 name: 'sub',
713 path: '/data/sub',
714 isDir: true,
715 size: 0,
716 mtime: '2026-05-10T08:00:00.000Z',
717 uploadedAt: '2026-05-09T08:00:00.000Z',
718 },
719 {
720 name: 'small.txt',
721 path: '/data/small.txt',
722 isDir: false,
723 size: 20,
724 mtime: '2026-05-15T10:00:00.000Z',
725 uploadedAt: '2026-05-15T10:00:00.000Z',
726 },
727 {
728 name: 'big.txt',
729 path: '/data/big.txt',
730 isDir: false,
731 size: 100,
732 mtime: '2026-05-11T10:00:00.000Z',
733 uploadedAt: '2026-05-11T10:00:00.000Z',
734 },
735 {
736 name: 'clip.mp4',
737 path: '/data/clip.mp4',
738 isDir: false,
739 size: 50,
740 mtime: '2026-05-12T10:00:00.000Z',
741 uploadedAt: '2026-05-12T10:00:00.000Z',
742 },
743 ],
744 '/data/sub': [
745 {
746 name: 'inside.txt',
747 path: '/data/sub/inside.txt',
748 isDir: false,
749 size: 1,
750 mtime: '2026-05-01T00:00:00.000Z',
751 uploadedAt: '2026-05-01T00:00:00.000Z',
752 },
753 ],
754 };
755
756 const { dom, runtimeErrors } = await bootClient();
757 expect(runtimeErrors).toEqual([]);
758
759 await waitFor(dom, () => dom.window.document.querySelectorAll('.file-item').length === 4);
760 await waitFor(dom, () => !!dom.window.document.querySelector('select[data-view-option="sort"]'));
761 const sortSelect = dom.window.document.querySelector('select[data-view-option="sort"]');
762 const groupSelect = dom.window.document.querySelector('select[data-view-option="group"]');
763 const ascInput = dom.window.document.querySelector('input[data-view-option="ascending"]');
764 expect(sortSelect).toBeTruthy();
765 expect(groupSelect).toBeTruthy();
766 expect(ascInput).toBeTruthy();
767
768 sortSelect.value = 'size';
769 sortSelect.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
770 ascInput.checked = false;
771 ascInput.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
772
773 await waitFor(dom, () =>
774 {
775 const names = Array.from(dom.window.document.querySelectorAll('.file-item .name')).map((el) => el.textContent);
776 const bigIdx = names.indexOf('big.txt');
777 const clipIdx = names.indexOf('clip.mp4');
778 const smallIdx = names.indexOf('small.txt');
779 return names[0] === 'sub' && bigIdx > -1 && clipIdx > -1 && smallIdx > -1 && bigIdx < clipIdx && clipIdx < smallIdx;
780 });
781
782 groupSelect.value = 'fileType';
783 groupSelect.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
784 await waitFor(dom, () => dom.window.document.querySelectorAll('.file-group-separator').length >= 2);
785
786 const subTile = dom.window.document.querySelector('.file-item[data-path="/data/sub"]');
787 subTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
788 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub/inside.txt"]'));
789
790 const homeCrumb = dom.window.document.querySelector('#breadcrumb .crumb');
791 homeCrumb.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
792
793 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub"]'));
794 await waitFor(dom, () => !!dom.window.document.querySelector('select[data-view-option="group"]'));
795 expect(dom.window.document.querySelector('select[data-view-option="sort"]').value).toBe('size');
796 expect(dom.window.document.querySelector('select[data-view-option="group"]').value).toBe('fileType');
797 expect(dom.window.document.querySelectorAll('.file-group-separator').length).toBeGreaterThanOrEqual(2);
798
799 dom.window.close();
800 });
801
707 802 test('shows pending icon spinner when image thumbnail cache is not ready', async () =>
708 803 {
709 804 listFixture = {
@@ -704,6 +704,101 @@ describe('page load smoke test', () =>
704 dom.window.close();
704 dom.window.close();
705 });
705 });
706
706
707 test('folder sidebar view options apply grouping/sorting and persist per folder', async () =>
708 {
709 listFixture = {
710 '/data': [
711 {
712 name: 'sub',
713 path: '/data/sub',
714 isDir: true,
715 size: 0,
716 mtime: '2026-05-10T08:00:00.000Z',
717 uploadedAt: '2026-05-09T08:00:00.000Z',
718 },
719 {
720 name: 'small.txt',
721 path: '/data/small.txt',
722 isDir: false,
723 size: 20,
724 mtime: '2026-05-15T10:00:00.000Z',
725 uploadedAt: '2026-05-15T10:00:00.000Z',
726 },
727 {
728 name: 'big.txt',
729 path: '/data/big.txt',
730 isDir: false,
731 size: 100,
732 mtime: '2026-05-11T10:00:00.000Z',
733 uploadedAt: '2026-05-11T10:00:00.000Z',
734 },
735 {
736 name: 'clip.mp4',
737 path: '/data/clip.mp4',
738 isDir: false,
739 size: 50,
740 mtime: '2026-05-12T10:00:00.000Z',
741 uploadedAt: '2026-05-12T10:00:00.000Z',
742 },
743 ],
744 '/data/sub': [
745 {
746 name: 'inside.txt',
747 path: '/data/sub/inside.txt',
748 isDir: false,
749 size: 1,
750 mtime: '2026-05-01T00:00:00.000Z',
751 uploadedAt: '2026-05-01T00:00:00.000Z',
752 },
753 ],
754 };
755
756 const { dom, runtimeErrors } = await bootClient();
757 expect(runtimeErrors).toEqual([]);
758
759 await waitFor(dom, () => dom.window.document.querySelectorAll('.file-item').length === 4);
760 await waitFor(dom, () => !!dom.window.document.querySelector('select[data-view-option="sort"]'));
761 const sortSelect = dom.window.document.querySelector('select[data-view-option="sort"]');
762 const groupSelect = dom.window.document.querySelector('select[data-view-option="group"]');
763 const ascInput = dom.window.document.querySelector('input[data-view-option="ascending"]');
764 expect(sortSelect).toBeTruthy();
765 expect(groupSelect).toBeTruthy();
766 expect(ascInput).toBeTruthy();
767
768 sortSelect.value = 'size';
769 sortSelect.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
770 ascInput.checked = false;
771 ascInput.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
772
773 await waitFor(dom, () =>
774 {
775 const names = Array.from(dom.window.document.querySelectorAll('.file-item .name')).map((el) => el.textContent);
776 const bigIdx = names.indexOf('big.txt');
777 const clipIdx = names.indexOf('clip.mp4');
778 const smallIdx = names.indexOf('small.txt');
779 return names[0] === 'sub' && bigIdx > -1 && clipIdx > -1 && smallIdx > -1 && bigIdx < clipIdx && clipIdx < smallIdx;
780 });
781
782 groupSelect.value = 'fileType';
783 groupSelect.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
784 await waitFor(dom, () => dom.window.document.querySelectorAll('.file-group-separator').length >= 2);
785
786 const subTile = dom.window.document.querySelector('.file-item[data-path="/data/sub"]');
787 subTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
788 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub/inside.txt"]'));
789
790 const homeCrumb = dom.window.document.querySelector('#breadcrumb .crumb');
791 homeCrumb.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
792
793 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub"]'));
794 await waitFor(dom, () => !!dom.window.document.querySelector('select[data-view-option="group"]'));
795 expect(dom.window.document.querySelector('select[data-view-option="sort"]').value).toBe('size');
796 expect(dom.window.document.querySelector('select[data-view-option="group"]').value).toBe('fileType');
797 expect(dom.window.document.querySelectorAll('.file-group-separator').length).toBeGreaterThanOrEqual(2);
798
799 dom.window.close();
800 });
801
707 test('shows pending icon spinner when image thumbnail cache is not ready', async () =>
802 test('shows pending icon spinner when image thumbnail cache is not ready', async () =>
708 {
803 {
709 listFixture = {
804 listFixture = {