BlueGit

timfa filemanager

Merge feature: topbar search and global favicon

timfa Tim Falken · pushed by timfa

Authored 2026-05-17 · 6 months ago

Hash
7fc9586925fa8f23fbb162c1686fb5fba78a172c
7 files changed +714 −51
.github/technical-reference.md +11 −0
@@ -72,6 +72,10 @@
72 72 - GET /api/files/folder-images - Returns files inside a directory (recursive) that already have a cached thumbnail (including video thumbnails when cached).
73 73 - 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.
74 74 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
75 - GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
76 - GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
77 - GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
78 - POST /api/files/global-favicon - Admin-only route that sets or clears the global favicon source image; image must have a cached thumbnail.
75 79 - GET /api/files/download-zip?dir=<absolute-path> - Authenticated. Streams the directory as a zip archive; caches the zip for up to 1 day in zip-cache/.
76 80 - makeTempUploadPath(dir, originalName) - Builds a hidden per-upload staging filename in the target directory for multipart uploads.
77 81 - unlinkIfExists(targetPath, cb) - Removes a file during upload cleanup while ignoring already-missing temp files.
@@ -128,6 +132,7 @@
128 132
129 133 ## public/index.html
130 134 - Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
135 - Top bar - Includes global file search input/button controls plus an admin-only global favicon button.
131 136 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
132 137 - Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
133 138
@@ -154,6 +159,7 @@
154 159 - updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
155 160 - relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
156 161 - displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
162 - runGlobalFileSearch() - Executes cross-root fuzzy file search via `/files/search`, swaps the grid into search-results mode, and updates breadcrumb/folder-stats text.
157 163 - openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
158 164 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
159 165 - loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
@@ -163,6 +169,9 @@
163 169 - loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
164 170 - applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
165 171 - openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
172 - openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
173 - openGlobalFaviconPicker() - Opens the shared icon picker for the current folder and sets/clears global favicon via `/files/global-favicon`.
174 - refreshGlobalFavicon() - Reads `/files/global-favicon`, updates topbar preview button, and applies/removes the page `<link rel="icon">` URL.
166 175 - refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
167 176 - disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
168 177 - getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
@@ -254,6 +263,8 @@
254 263 ## public/style.css
255 264 - #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
256 265 - .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
266 - .top-search* + .global-favicon-preview - Topbar file search controls and global favicon preview button styling.
267 - .folder-icon-filter - Search input styling for live filtering in the icon-picker modal.
257 268
258 269 ## tests/auth.routes.test.js
259 270 - session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
@@ -72,6 +72,10 @@
72- GET /api/files/folder-images - Returns files inside a directory (recursive) that already have a cached thumbnail (including video thumbnails when cached).
72- GET /api/files/folder-images - Returns files inside a directory (recursive) that already have a cached thumbnail (including video thumbnails when cached).
73- 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.
73- 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.
74- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
74- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
75- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
76- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
77- GET /api/files/global-favicon - Returns the configured global favicon source file path ({favicon:{filePath}} or {favicon:null}).
78- POST /api/files/global-favicon - Admin-only route that sets or clears the global favicon source image; image must have a cached thumbnail.
75- GET /api/files/download-zip?dir=<absolute-path> - Authenticated. Streams the directory as a zip archive; caches the zip for up to 1 day in zip-cache/.
79- GET /api/files/download-zip?dir=<absolute-path> - Authenticated. Streams the directory as a zip archive; caches the zip for up to 1 day in zip-cache/.
76- makeTempUploadPath(dir, originalName) - Builds a hidden per-upload staging filename in the target directory for multipart uploads.
80- makeTempUploadPath(dir, originalName) - Builds a hidden per-upload staging filename in the target directory for multipart uploads.
77- unlinkIfExists(targetPath, cb) - Removes a file during upload cleanup while ignoring already-missing temp files.
81- unlinkIfExists(targetPath, cb) - Removes a file during upload cleanup while ignoring already-missing temp files.
@@ -128,6 +132,7 @@
128
132
129## public/index.html
133## public/index.html
130- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
134- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
135- Top bar - Includes global file search input/button controls plus an admin-only global favicon button.
131- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
136- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
132- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
137- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
133
138
@@ -154,6 +159,7 @@
154- updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
159- updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
155- relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
160- relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
156- displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
161- displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
162- runGlobalFileSearch() - Executes cross-root fuzzy file search via `/files/search`, swaps the grid into search-results mode, and updates breadcrumb/folder-stats text.
157- openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
163- openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
158- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
164- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
159- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
165- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
@@ -163,6 +169,9 @@
163- loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
169- loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
164- applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
170- applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
165- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
171- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
172- openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
173- openGlobalFaviconPicker() - Opens the shared icon picker for the current folder and sets/clears global favicon via `/files/global-favicon`.
174- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates topbar preview button, and applies/removes the page `<link rel="icon">` URL.
166- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
175- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
167- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
176- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
168- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
177- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
@@ -254,6 +263,8 @@
254## public/style.css
263## public/style.css
255- #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
264- #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
256- .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
265- .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
266- .top-search* + .global-favicon-preview - Topbar file search controls and global favicon preview button styling.
267- .folder-icon-filter - Search input styling for live filtering in the icon-picker modal.
257
268
258## tests/auth.routes.test.js
269## tests/auth.routes.test.js
259- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
270- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
.github/tests.md +2 −3
@@ -44,6 +44,8 @@
44 44 - `GET /api/files/thumbnail`
45 45 - `GET /api/files/root-access`
46 46 - `folder icon endpoints`
47 - `file search endpoint`
48 - `global favicon endpoints`
47 49 - `GET /api/files/download-zip`
48 50 - `video streaming routes`
49 51 - `SHA-256 hashing and duplicate detection`
@@ -52,7 +54,6 @@
52 54
53 55 ## `test/image-subtitles.test.js`
54 56 - `image subtitle option parsing`
55 - `prune calculates drop threshold as end plus duration plus 30 seconds`
56 57
57 58 ---
58 59
@@ -84,7 +85,5 @@
84 85
85 86 ## `test/video-stream.test.js`
86 87 - `video stream bootstrap`
87 - `sendVideoStreamAsset prunes old segment files after playback moves far ahead`
88 - `createVideoStreamSession reuses one transcode for concurrent viewers of the same file`
89 88
90 89 ---
@@ -44,6 +44,8 @@
44- `GET /api/files/thumbnail`
44- `GET /api/files/thumbnail`
45- `GET /api/files/root-access`
45- `GET /api/files/root-access`
46- `folder icon endpoints`
46- `folder icon endpoints`
47- `file search endpoint`
48- `global favicon endpoints`
47- `GET /api/files/download-zip`
49- `GET /api/files/download-zip`
48- `video streaming routes`
50- `video streaming routes`
49- `SHA-256 hashing and duplicate detection`
51- `SHA-256 hashing and duplicate detection`
@@ -52,7 +54,6 @@
52
54
53## `test/image-subtitles.test.js`
55## `test/image-subtitles.test.js`
54- `image subtitle option parsing`
56- `image subtitle option parsing`
55- `prune calculates drop threshold as end plus duration plus 30 seconds`
56
57
57---
58---
58
59
@@ -84,7 +85,5 @@
84
85
85## `test/video-stream.test.js`
86## `test/video-stream.test.js`
86- `video stream bootstrap`
87- `video stream bootstrap`
87- `sendVideoStreamAsset prunes old segment files after playback moves far ahead`
88- `createVideoStreamSession reuses one transcode for concurrent viewers of the same file`
89
88
90---
89---
public/app.js +286 −47
@@ -63,6 +63,12 @@ const STATE = {
63 63 // Watched overlays are resolved asynchronously from /files/meta responses.
64 64 watchedStatusByPath: {},
65 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(),
66 72 };
67 73
68 74 const SESSION_KEY = 'filemanager.session.v1';
@@ -1536,6 +1542,8 @@ function showApp ()
1536 1542 openFolderSidebar();
1537 1543 }
1538 1544 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1545 document.getElementById('btn-global-favicon').classList.toggle('hidden', !STATE.isAdmin);
1546 void refreshGlobalFavicon();
1539 1547 if (STATE.isAdmin)
1540 1548 {
1541 1549 void refreshAdminUpdateStatus();
@@ -1723,6 +1731,7 @@ function renderRootsView ()
1723 1731
1724 1732 STATE.currentDir = null;
1725 1733 STATE.currentRoot = null;
1734 STATE.searchQuery = null;
1726 1735 saveSessionState();
1727 1736 renderBreadcrumb();
1728 1737 const grid = document.getElementById('file-grid');
@@ -1742,6 +1751,7 @@ function renderRootsView ()
1742 1751
1743 1752 async function navigateTo (absPath, root, opts = {})
1744 1753 {
1754 STATE.searchQuery = null;
1745 1755 if (root) STATE.currentRoot = root;
1746 1756 STATE.currentDir = absPath;
1747 1757
@@ -1756,6 +1766,58 @@ async function navigateTo (absPath, root, opts = {})
1756 1766 closeSidebar();
1757 1767 }
1758 1768
1769 async function runGlobalFileSearch ()
1770 {
1771 const input = document.getElementById('top-search-input');
1772 if (!input) return;
1773
1774 const query = String(input.value || '').trim();
1775 if (!query)
1776 {
1777 toast('Enter a search term first.', 'err');
1778 return;
1779 }
1780
1781 let data;
1782 try
1783 {
1784 data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`);
1785 }
1786 catch (err)
1787 {
1788 toast('Search failed: ' + err.message, 'err');
1789 return;
1790 }
1791
1792 STATE.searchQuery = query;
1793 STATE.currentDir = null;
1794 STATE.currentRoot = null;
1795 STATE.items = Array.isArray(data && data.results)
1796 ? data.results.map((it) => ({
1797 name: it.name,
1798 path: it.path,
1799 dir: it.dir,
1800 isDir: false,
1801 size: it.size,
1802 mtime: it.mtime,
1803 }))
1804 : [];
1805
1806 renderBreadcrumb();
1807 renderFileGrid();
1808 closeSidebar();
1809
1810 const stats = document.getElementById('folder-stats');
1811 if (stats)
1812 {
1813 const n = STATE.items.length;
1814 stats.textContent = n === 1
1815 ? `1 file found for "${query}".`
1816 : `${n} files found for "${query}".`;
1817 stats.classList.remove('hidden');
1818 }
1819 }
1820
1759 1821 function renderBreadcrumb ()
1760 1822 {
1761 1823 if (typeof document === 'undefined') return;
@@ -1779,6 +1841,20 @@ function renderBreadcrumb ()
1779 1841 });
1780 1842 nav.appendChild(home);
1781 1843
1844 if (STATE.searchQuery)
1845 {
1846 const sep = document.createElement('span');
1847 sep.className = 'sep';
1848 sep.textContent = ' / ';
1849 nav.appendChild(sep);
1850
1851 const searchCrumb = document.createElement('span');
1852 searchCrumb.className = 'crumb active';
1853 searchCrumb.textContent = `Search: ${STATE.searchQuery}`;
1854 nav.appendChild(searchCrumb);
1855 return;
1856 }
1857
1782 1858 if (!STATE.currentDir || !STATE.currentRoot) return;
1783 1859
1784 1860 // Build path segments relative to the root.
@@ -1817,7 +1893,7 @@ async function refreshFolderStats ()
1817 1893 {
1818 1894 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1819 1895 const el = document.getElementById('folder-stats');
1820 if (!STATE.currentDir)
1896 if (!STATE.currentDir || STATE.searchQuery)
1821 1897 {
1822 1898 el.classList.add('hidden');
1823 1899 return;
@@ -1853,6 +1929,7 @@ function itemsSignature (items)
1853 1929 async function incrementalRefreshCurrentDir ()
1854 1930 {
1855 1931 if (STATE.previewExpandState) return;
1932 if (STATE.searchQuery) return;
1856 1933 if (!STATE.currentDir || STATE.uploadInProgress) return;
1857 1934
1858 1935 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
@@ -2860,19 +2937,82 @@ function openCopyPicker (item)
2860 2937 // FOLDER ICON PICKER
2861 2938 // ───────────────────────────────────────────────────────────────────────────
2862 2939
2863 async function openFolderIconPicker (item)
2940 function globalFaviconFallbackMarkup ()
2864 2941 {
2865 if (!canWrite(item))
2942 return iconFile('favicon.png', 18);
2943 }
2944
2945 function applyGlobalFaviconPreview (hasFavicon)
2946 {
2947 const preview = document.getElementById('global-favicon-preview');
2948 if (!preview) return;
2949
2950 if (!hasFavicon)
2866 2951 {
2867 toast('No write access.', 'err');
2952 preview.innerHTML = globalFaviconFallbackMarkup();
2953 return;
2954 }
2955
2956 const img = document.createElement('img');
2957 img.alt = 'Current favicon';
2958 img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2959 img.addEventListener('error', () =>
2960 {
2961 preview.innerHTML = globalFaviconFallbackMarkup();
2962 }, { once: true });
2963 preview.innerHTML = '';
2964 preview.appendChild(img);
2965 }
2966
2967 function applyGlobalFaviconLink (hasFavicon)
2968 {
2969 let link = document.getElementById('global-favicon-link');
2970 if (!link)
2971 {
2972 link = document.createElement('link');
2973 link.id = 'global-favicon-link';
2974 link.rel = 'icon';
2975 document.head.appendChild(link);
2976 }
2977
2978 if (!hasFavicon)
2979 {
2980 link.removeAttribute('href');
2868 2981 return;
2869 2982 }
2870 2983
2871 // Fetch the list of available files (only those with cached thumbnails).
2872 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
2984 link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2985 }
2986
2987 async function refreshGlobalFavicon ()
2988 {
2989 const data = await api('GET', '/files/global-favicon').catch(() => null);
2990 const hasFavicon = !!(data && data.favicon && data.favicon.filePath);
2991 applyGlobalFaviconPreview(hasFavicon);
2992 applyGlobalFaviconLink(hasFavicon);
2993 }
2994
2995 async function openIconPickerModal ({
2996 dirPath,
2997 titleText,
2998 subtitleText,
2999 emptyText,
3000 confirmLabel,
3001 clearLabel,
3002 onSelect,
3003 onClear,
3004 })
3005 {
3006 if (!dirPath)
3007 {
3008 toast('Open a folder first.', 'err');
3009 return;
3010 }
3011
3012 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
2873 3013 const images = data ? data.images : [];
2874 3014
2875 let existingIconOverlay = document.getElementById('folder-icon-picker');
3015 const existingIconOverlay = document.getElementById('folder-icon-picker');
2876 3016 if (existingIconOverlay) existingIconOverlay.remove();
2877 3017
2878 3018 const overlay = document.createElement('div');
@@ -2888,68 +3028,86 @@ async function openFolderIconPicker (item)
2888 3028 closeBtn.textContent = '✕';
2889 3029
2890 3030 const title = document.createElement('h2');
2891 title.textContent = 'Set folder icon';
3031 title.textContent = titleText;
3032
3033 const filterInput = document.createElement('input');
3034 filterInput.type = 'text';
3035 filterInput.className = 'folder-icon-filter';
3036 filterInput.placeholder = 'Search icons';
3037 filterInput.setAttribute('aria-label', 'Search icons');
2892 3038
2893 3039 const subtitle = document.createElement('p');
2894 3040 subtitle.className = 'muted';
3041 subtitle.textContent = images.length ? subtitleText : emptyText;
2895 3042
2896 3043 const grid = document.createElement('div');
2897 3044 grid.className = 'folder-icon-grid';
2898 3045
2899 if (!images.length)
2900 {
2901 subtitle.textContent = 'No files with cached thumbnails were found inside this folder.';
2902 } else
3046 for (const { filePath } of images)
2903 3047 {
2904 subtitle.textContent = 'Select a file thumbnail to use as the folder icon.';
3048 const name = filePath.split('/').pop();
3049 const cell = document.createElement('div');
3050 cell.className = 'folder-icon-cell';
3051 cell.dataset.path = filePath;
3052 cell.dataset.name = String(name || '').toLowerCase();
2905 3053
2906 for (const { filePath } of images)
2907 {
2908 const cell = document.createElement('div');
2909 cell.className = 'folder-icon-cell';
2910 cell.dataset.path = filePath;
3054 const imgEl = document.createElement('img');
3055 imgEl.alt = name;
3056 imgEl.className = 'folder-icon-thumb';
3057 imgEl.dataset.src = filePath;
2911 3058
2912 const imgEl = document.createElement('img');
2913 imgEl.alt = filePath.split('/').pop();
2914 imgEl.className = 'folder-icon-thumb';
2915 // Lazy-load via IntersectionObserver on the cell.
2916 imgEl.dataset.src = filePath;
3059 const label = document.createElement('div');
3060 label.className = 'folder-icon-label';
3061 label.textContent = name;
2917 3062
2918 const label = document.createElement('div');
2919 label.className = 'folder-icon-label';
2920 label.textContent = filePath.split('/').pop();
3063 cell.appendChild(imgEl);
3064 cell.appendChild(label);
2921 3065
2922 cell.appendChild(imgEl);
2923 cell.appendChild(label);
3066 cell.addEventListener('click', () =>
3067 {
3068 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3069 cell.classList.add('selected');
3070 confirmBtn.disabled = false;
3071 });
2924 3072
2925 cell.addEventListener('click', () =>
2926 {
2927 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
2928 cell.classList.add('selected');
2929 confirmBtn.disabled = false;
2930 });
3073 grid.appendChild(cell);
3074 }
2931 3075
2932 grid.appendChild(cell);
3076 function applyFilter ()
3077 {
3078 const needle = String(filterInput.value || '').trim().toLowerCase();
3079 let visible = 0;
3080 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3081 {
3082 const name = cell.dataset.name || '';
3083 const show = !needle || name.includes(needle);
3084 cell.classList.toggle('hidden', !show);
3085 if (show) visible += 1;
2933 3086 }
3087 subtitle.textContent = visible
3088 ? subtitleText
3089 : 'No matching thumbnails were found.';
2934 3090 }
2935 3091
3092 filterInput.addEventListener('input', applyFilter);
3093
2936 3094 const dialogActions = document.createElement('div');
2937 3095 dialogActions.className = 'dialog-actions';
2938 3096
2939 3097 const clearBtn = document.createElement('button');
2940 clearBtn.textContent = 'Clear icon';
3098 clearBtn.textContent = clearLabel;
2941 3099 clearBtn.addEventListener('click', async () =>
2942 3100 {
2943 3101 try
2944 3102 {
2945 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
2946 } catch (err)
3103 await onClear();
3104 }
3105 catch (err)
2947 3106 {
2948 3107 toast('Failed to clear icon: ' + err.message, 'err');
2949 3108 return;
2950 3109 }
2951 3110 hide();
2952 refreshAfterIconChange(item);
2953 3111 });
2954 3112
2955 3113 const cancelBtn = document.createElement('button');
@@ -2958,23 +3116,24 @@ async function openFolderIconPicker (item)
2958 3116
2959 3117 const confirmBtn = document.createElement('button');
2960 3118 confirmBtn.className = 'primary';
2961 confirmBtn.textContent = 'Set icon';
3119 confirmBtn.textContent = confirmLabel;
2962 3120 confirmBtn.disabled = true;
2963 3121 confirmBtn.addEventListener('click', async () =>
2964 3122 {
2965 3123 const selected = grid.querySelector('.folder-icon-cell.selected');
2966 3124 if (!selected) return;
2967 const imagePath = selected.dataset.path;
3125
2968 3126 try
2969 3127 {
2970 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
2971 } catch (err)
3128 await onSelect(selected.dataset.path);
3129 }
3130 catch (err)
2972 3131 {
2973 3132 toast('Failed to set icon: ' + err.message, 'err');
2974 3133 return;
2975 3134 }
3135
2976 3136 hide();
2977 refreshAfterIconChange(item);
2978 3137 });
2979 3138
2980 3139 dialogActions.appendChild(clearBtn);
@@ -2983,6 +3142,7 @@ async function openFolderIconPicker (item)
2983 3142
2984 3143 modal.appendChild(closeBtn);
2985 3144 modal.appendChild(title);
3145 modal.appendChild(filterInput);
2986 3146 modal.appendChild(subtitle);
2987 3147 modal.appendChild(grid);
2988 3148 modal.appendChild(dialogActions);
@@ -2992,8 +3152,7 @@ async function openFolderIconPicker (item)
2992 3152 function hide ()
2993 3153 {
2994 3154 overlay.remove();
2995 // Revoke any blob URLs we created for the picker thumbnails.
2996 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
3155 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
2997 3156 {
2998 3157 URL.revokeObjectURL(img.src);
2999 3158 });
@@ -3002,7 +3161,6 @@ async function openFolderIconPicker (item)
3002 3161 closeBtn.addEventListener('click', hide);
3003 3162 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3004 3163
3005 // Eagerly load thumbnails for all cells (picker is small, fetch all).
3006 3164 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3007 3165 {
3008 3166 const imgEl = cell.querySelector('.folder-icon-thumb');
@@ -3017,6 +3175,67 @@ async function openFolderIconPicker (item)
3017 3175 imgEl.src = url;
3018 3176 }).catch(() => { });
3019 3177 }
3178
3179 filterInput.focus();
3180 }
3181
3182 async function openFolderIconPicker (item)
3183 {
3184 if (!canWrite(item))
3185 {
3186 toast('No write access.', 'err');
3187 return;
3188 }
3189
3190 await openIconPickerModal({
3191 dirPath: item.path,
3192 titleText: 'Set folder icon',
3193 subtitleText: 'Select a file thumbnail to use as the folder icon.',
3194 emptyText: 'No files with cached thumbnails were found inside this folder.',
3195 confirmLabel: 'Set icon',
3196 clearLabel: 'Clear icon',
3197 onSelect: async (imagePath) =>
3198 {
3199 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
3200 refreshAfterIconChange(item);
3201 },
3202 onClear: async () =>
3203 {
3204 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
3205 refreshAfterIconChange(item);
3206 },
3207 });
3208 }
3209
3210 async function openGlobalFaviconPicker ()
3211 {
3212 if (!STATE.isAdmin)
3213 {
3214 toast('Admin access required.', 'err');
3215 return;
3216 }
3217
3218 const dirPath = STATE.currentDir || (STATE.currentRoot ? STATE.currentRoot.path : null);
3219 await openIconPickerModal({
3220 dirPath,
3221 titleText: 'Set global favicon',
3222 subtitleText: 'Select a file thumbnail to use as the global favicon.',
3223 emptyText: 'No files with cached thumbnails were found inside this folder.',
3224 confirmLabel: 'Set favicon',
3225 clearLabel: 'Clear favicon',
3226 onSelect: async (imagePath) =>
3227 {
3228 await api('POST', '/files/global-favicon', { imagePath });
3229 STATE.faviconVersion = Date.now();
3230 await refreshGlobalFavicon();
3231 },
3232 onClear: async () =>
3233 {
3234 await api('POST', '/files/global-favicon', { imagePath: null });
3235 STATE.faviconVersion = Date.now();
3236 await refreshGlobalFavicon();
3237 },
3238 });
3020 3239 }
3021 3240
3022 3241 function refreshAfterIconChange (item)
@@ -5506,6 +5725,22 @@ function wireEvents ()
5506 5725 location.reload();
5507 5726 });
5508 5727
5728 const topSearchInput = document.getElementById('top-search-input');
5729 const topSearchBtn = document.getElementById('btn-search');
5730 if (topSearchInput && topSearchBtn)
5731 {
5732 topSearchInput.addEventListener('keydown', (e) =>
5733 {
5734 if (e.key !== 'Enter') return;
5735 e.preventDefault();
5736 void runGlobalFileSearch();
5737 });
5738 topSearchBtn.addEventListener('click', () =>
5739 {
5740 void runGlobalFileSearch();
5741 });
5742 }
5743
5509 5744 // Upload button
5510 5745 document.getElementById('btn-upload').addEventListener('click', () =>
5511 5746 {
@@ -5592,6 +5827,10 @@ function wireEvents ()
5592 5827
5593 5828 // Admin panel
5594 5829 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
5830 document.getElementById('btn-global-favicon').addEventListener('click', () =>
5831 {
5832 void openGlobalFaviconPicker();
5833 });
5595 5834 document.getElementById('admin-modal-close').addEventListener('click', () =>
5596 5835 document.getElementById('admin-modal').classList.add('hidden'));
5597 5836
@@ -63,6 +63,12 @@ const STATE = {
63 // Watched overlays are resolved asynchronously from /files/meta responses.
63 // Watched overlays are resolved asynchronously from /files/meta responses.
64 watchedStatusByPath: {},
64 watchedStatusByPath: {},
65 watchedLoadId: 0,
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(),
66};
72};
67
73
68const SESSION_KEY = 'filemanager.session.v1';
74const SESSION_KEY = 'filemanager.session.v1';
@@ -1536,6 +1542,8 @@ function showApp ()
1536 openFolderSidebar();
1542 openFolderSidebar();
1537 }
1543 }
1538 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1544 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1545 document.getElementById('btn-global-favicon').classList.toggle('hidden', !STATE.isAdmin);
1546 void refreshGlobalFavicon();
1539 if (STATE.isAdmin)
1547 if (STATE.isAdmin)
1540 {
1548 {
1541 void refreshAdminUpdateStatus();
1549 void refreshAdminUpdateStatus();
@@ -1723,6 +1731,7 @@ function renderRootsView ()
1723
1731
1724 STATE.currentDir = null;
1732 STATE.currentDir = null;
1725 STATE.currentRoot = null;
1733 STATE.currentRoot = null;
1734 STATE.searchQuery = null;
1726 saveSessionState();
1735 saveSessionState();
1727 renderBreadcrumb();
1736 renderBreadcrumb();
1728 const grid = document.getElementById('file-grid');
1737 const grid = document.getElementById('file-grid');
@@ -1742,6 +1751,7 @@ function renderRootsView ()
1742
1751
1743async function navigateTo (absPath, root, opts = {})
1752async function navigateTo (absPath, root, opts = {})
1744{
1753{
1754 STATE.searchQuery = null;
1745 if (root) STATE.currentRoot = root;
1755 if (root) STATE.currentRoot = root;
1746 STATE.currentDir = absPath;
1756 STATE.currentDir = absPath;
1747
1757
@@ -1756,6 +1766,58 @@ async function navigateTo (absPath, root, opts = {})
1756 closeSidebar();
1766 closeSidebar();
1757}
1767}
1758
1768
1769async function runGlobalFileSearch ()
1770{
1771 const input = document.getElementById('top-search-input');
1772 if (!input) return;
1773
1774 const query = String(input.value || '').trim();
1775 if (!query)
1776 {
1777 toast('Enter a search term first.', 'err');
1778 return;
1779 }
1780
1781 let data;
1782 try
1783 {
1784 data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`);
1785 }
1786 catch (err)
1787 {
1788 toast('Search failed: ' + err.message, 'err');
1789 return;
1790 }
1791
1792 STATE.searchQuery = query;
1793 STATE.currentDir = null;
1794 STATE.currentRoot = null;
1795 STATE.items = Array.isArray(data && data.results)
1796 ? data.results.map((it) => ({
1797 name: it.name,
1798 path: it.path,
1799 dir: it.dir,
1800 isDir: false,
1801 size: it.size,
1802 mtime: it.mtime,
1803 }))
1804 : [];
1805
1806 renderBreadcrumb();
1807 renderFileGrid();
1808 closeSidebar();
1809
1810 const stats = document.getElementById('folder-stats');
1811 if (stats)
1812 {
1813 const n = STATE.items.length;
1814 stats.textContent = n === 1
1815 ? `1 file found for "${query}".`
1816 : `${n} files found for "${query}".`;
1817 stats.classList.remove('hidden');
1818 }
1819}
1820
1759function renderBreadcrumb ()
1821function renderBreadcrumb ()
1760{
1822{
1761 if (typeof document === 'undefined') return;
1823 if (typeof document === 'undefined') return;
@@ -1779,6 +1841,20 @@ function renderBreadcrumb ()
1779 });
1841 });
1780 nav.appendChild(home);
1842 nav.appendChild(home);
1781
1843
1844 if (STATE.searchQuery)
1845 {
1846 const sep = document.createElement('span');
1847 sep.className = 'sep';
1848 sep.textContent = ' / ';
1849 nav.appendChild(sep);
1850
1851 const searchCrumb = document.createElement('span');
1852 searchCrumb.className = 'crumb active';
1853 searchCrumb.textContent = `Search: ${STATE.searchQuery}`;
1854 nav.appendChild(searchCrumb);
1855 return;
1856 }
1857
1782 if (!STATE.currentDir || !STATE.currentRoot) return;
1858 if (!STATE.currentDir || !STATE.currentRoot) return;
1783
1859
1784 // Build path segments relative to the root.
1860 // Build path segments relative to the root.
@@ -1817,7 +1893,7 @@ async function refreshFolderStats ()
1817{
1893{
1818 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1894 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1819 const el = document.getElementById('folder-stats');
1895 const el = document.getElementById('folder-stats');
1820 if (!STATE.currentDir)
1896 if (!STATE.currentDir || STATE.searchQuery)
1821 {
1897 {
1822 el.classList.add('hidden');
1898 el.classList.add('hidden');
1823 return;
1899 return;
@@ -1853,6 +1929,7 @@ function itemsSignature (items)
1853async function incrementalRefreshCurrentDir ()
1929async function incrementalRefreshCurrentDir ()
1854{
1930{
1855 if (STATE.previewExpandState) return;
1931 if (STATE.previewExpandState) return;
1932 if (STATE.searchQuery) return;
1856 if (!STATE.currentDir || STATE.uploadInProgress) return;
1933 if (!STATE.currentDir || STATE.uploadInProgress) return;
1857
1934
1858 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1935 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
@@ -2860,19 +2937,82 @@ function openCopyPicker (item)
2860// FOLDER ICON PICKER
2937// FOLDER ICON PICKER
2861// ───────────────────────────────────────────────────────────────────────────
2938// ───────────────────────────────────────────────────────────────────────────
2862
2939
2863async function openFolderIconPicker (item)
2940function globalFaviconFallbackMarkup ()
2864{
2941{
2865 if (!canWrite(item))
2942 return iconFile('favicon.png', 18);
2943}
2944
2945function applyGlobalFaviconPreview (hasFavicon)
2946{
2947 const preview = document.getElementById('global-favicon-preview');
2948 if (!preview) return;
2949
2950 if (!hasFavicon)
2866 {
2951 {
2867 toast('No write access.', 'err');
2952 preview.innerHTML = globalFaviconFallbackMarkup();
2953 return;
2954 }
2955
2956 const img = document.createElement('img');
2957 img.alt = 'Current favicon';
2958 img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2959 img.addEventListener('error', () =>
2960 {
2961 preview.innerHTML = globalFaviconFallbackMarkup();
2962 }, { once: true });
2963 preview.innerHTML = '';
2964 preview.appendChild(img);
2965}
2966
2967function applyGlobalFaviconLink (hasFavicon)
2968{
2969 let link = document.getElementById('global-favicon-link');
2970 if (!link)
2971 {
2972 link = document.createElement('link');
2973 link.id = 'global-favicon-link';
2974 link.rel = 'icon';
2975 document.head.appendChild(link);
2976 }
2977
2978 if (!hasFavicon)
2979 {
2980 link.removeAttribute('href');
2868 return;
2981 return;
2869 }
2982 }
2870
2983
2871 // Fetch the list of available files (only those with cached thumbnails).
2984 link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2872 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
2985}
2986
2987async function refreshGlobalFavicon ()
2988{
2989 const data = await api('GET', '/files/global-favicon').catch(() => null);
2990 const hasFavicon = !!(data && data.favicon && data.favicon.filePath);
2991 applyGlobalFaviconPreview(hasFavicon);
2992 applyGlobalFaviconLink(hasFavicon);
2993}
2994
2995async function openIconPickerModal ({
2996 dirPath,
2997 titleText,
2998 subtitleText,
2999 emptyText,
3000 confirmLabel,
3001 clearLabel,
3002 onSelect,
3003 onClear,
3004})
3005{
3006 if (!dirPath)
3007 {
3008 toast('Open a folder first.', 'err');
3009 return;
3010 }
3011
3012 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
2873 const images = data ? data.images : [];
3013 const images = data ? data.images : [];
2874
3014
2875 let existingIconOverlay = document.getElementById('folder-icon-picker');
3015 const existingIconOverlay = document.getElementById('folder-icon-picker');
2876 if (existingIconOverlay) existingIconOverlay.remove();
3016 if (existingIconOverlay) existingIconOverlay.remove();
2877
3017
2878 const overlay = document.createElement('div');
3018 const overlay = document.createElement('div');
@@ -2888,68 +3028,86 @@ async function openFolderIconPicker (item)
2888 closeBtn.textContent = '✕';
3028 closeBtn.textContent = '✕';
2889
3029
2890 const title = document.createElement('h2');
3030 const title = document.createElement('h2');
2891 title.textContent = 'Set folder icon';
3031 title.textContent = titleText;
3032
3033 const filterInput = document.createElement('input');
3034 filterInput.type = 'text';
3035 filterInput.className = 'folder-icon-filter';
3036 filterInput.placeholder = 'Search icons';
3037 filterInput.setAttribute('aria-label', 'Search icons');
2892
3038
2893 const subtitle = document.createElement('p');
3039 const subtitle = document.createElement('p');
2894 subtitle.className = 'muted';
3040 subtitle.className = 'muted';
3041 subtitle.textContent = images.length ? subtitleText : emptyText;
2895
3042
2896 const grid = document.createElement('div');
3043 const grid = document.createElement('div');
2897 grid.className = 'folder-icon-grid';
3044 grid.className = 'folder-icon-grid';
2898
3045
2899 if (!images.length)
3046 for (const { filePath } of images)
2900 {
2901 subtitle.textContent = 'No files with cached thumbnails were found inside this folder.';
2902 } else
2903 {
3047 {
2904 subtitle.textContent = 'Select a file thumbnail to use as the folder icon.';
3048 const name = filePath.split('/').pop();
3049 const cell = document.createElement('div');
3050 cell.className = 'folder-icon-cell';
3051 cell.dataset.path = filePath;
3052 cell.dataset.name = String(name || '').toLowerCase();
2905
3053
2906 for (const { filePath } of images)
3054 const imgEl = document.createElement('img');
2907 {
3055 imgEl.alt = name;
2908 const cell = document.createElement('div');
3056 imgEl.className = 'folder-icon-thumb';
2909 cell.className = 'folder-icon-cell';
3057 imgEl.dataset.src = filePath;
2910 cell.dataset.path = filePath;
2911
3058
2912 const imgEl = document.createElement('img');
3059 const label = document.createElement('div');
2913 imgEl.alt = filePath.split('/').pop();
3060 label.className = 'folder-icon-label';
2914 imgEl.className = 'folder-icon-thumb';
3061 label.textContent = name;
2915 // Lazy-load via IntersectionObserver on the cell.
2916 imgEl.dataset.src = filePath;
2917
3062
2918 const label = document.createElement('div');
3063 cell.appendChild(imgEl);
2919 label.className = 'folder-icon-label';
3064 cell.appendChild(label);
2920 label.textContent = filePath.split('/').pop();
2921
3065
2922 cell.appendChild(imgEl);
3066 cell.addEventListener('click', () =>
2923 cell.appendChild(label);
3067 {
3068 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3069 cell.classList.add('selected');
3070 confirmBtn.disabled = false;
3071 });
2924
3072
2925 cell.addEventListener('click', () =>
3073 grid.appendChild(cell);
2926 {
3074 }
2927 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
2928 cell.classList.add('selected');
2929 confirmBtn.disabled = false;
2930 });
2931
3075
2932 grid.appendChild(cell);
3076 function applyFilter ()
3077 {
3078 const needle = String(filterInput.value || '').trim().toLowerCase();
3079 let visible = 0;
3080 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3081 {
3082 const name = cell.dataset.name || '';
3083 const show = !needle || name.includes(needle);
3084 cell.classList.toggle('hidden', !show);
3085 if (show) visible += 1;
2933 }
3086 }
3087 subtitle.textContent = visible
3088 ? subtitleText
3089 : 'No matching thumbnails were found.';
2934 }
3090 }
2935
3091
3092 filterInput.addEventListener('input', applyFilter);
3093
2936 const dialogActions = document.createElement('div');
3094 const dialogActions = document.createElement('div');
2937 dialogActions.className = 'dialog-actions';
3095 dialogActions.className = 'dialog-actions';
2938
3096
2939 const clearBtn = document.createElement('button');
3097 const clearBtn = document.createElement('button');
2940 clearBtn.textContent = 'Clear icon';
3098 clearBtn.textContent = clearLabel;
2941 clearBtn.addEventListener('click', async () =>
3099 clearBtn.addEventListener('click', async () =>
2942 {
3100 {
2943 try
3101 try
2944 {
3102 {
2945 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
3103 await onClear();
2946 } catch (err)
3104 }
3105 catch (err)
2947 {
3106 {
2948 toast('Failed to clear icon: ' + err.message, 'err');
3107 toast('Failed to clear icon: ' + err.message, 'err');
2949 return;
3108 return;
2950 }
3109 }
2951 hide();
3110 hide();
2952 refreshAfterIconChange(item);
2953 });
3111 });
2954
3112
2955 const cancelBtn = document.createElement('button');
3113 const cancelBtn = document.createElement('button');
@@ -2958,23 +3116,24 @@ async function openFolderIconPicker (item)
2958
3116
2959 const confirmBtn = document.createElement('button');
3117 const confirmBtn = document.createElement('button');
2960 confirmBtn.className = 'primary';
3118 confirmBtn.className = 'primary';
2961 confirmBtn.textContent = 'Set icon';
3119 confirmBtn.textContent = confirmLabel;
2962 confirmBtn.disabled = true;
3120 confirmBtn.disabled = true;
2963 confirmBtn.addEventListener('click', async () =>
3121 confirmBtn.addEventListener('click', async () =>
2964 {
3122 {
2965 const selected = grid.querySelector('.folder-icon-cell.selected');
3123 const selected = grid.querySelector('.folder-icon-cell.selected');
2966 if (!selected) return;
3124 if (!selected) return;
2967 const imagePath = selected.dataset.path;
3125
2968 try
3126 try
2969 {
3127 {
2970 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
3128 await onSelect(selected.dataset.path);
2971 } catch (err)
3129 }
3130 catch (err)
2972 {
3131 {
2973 toast('Failed to set icon: ' + err.message, 'err');
3132 toast('Failed to set icon: ' + err.message, 'err');
2974 return;
3133 return;
2975 }
3134 }
3135
2976 hide();
3136 hide();
2977 refreshAfterIconChange(item);
2978 });
3137 });
2979
3138
2980 dialogActions.appendChild(clearBtn);
3139 dialogActions.appendChild(clearBtn);
@@ -2983,6 +3142,7 @@ async function openFolderIconPicker (item)
2983
3142
2984 modal.appendChild(closeBtn);
3143 modal.appendChild(closeBtn);
2985 modal.appendChild(title);
3144 modal.appendChild(title);
3145 modal.appendChild(filterInput);
2986 modal.appendChild(subtitle);
3146 modal.appendChild(subtitle);
2987 modal.appendChild(grid);
3147 modal.appendChild(grid);
2988 modal.appendChild(dialogActions);
3148 modal.appendChild(dialogActions);
@@ -2992,8 +3152,7 @@ async function openFolderIconPicker (item)
2992 function hide ()
3152 function hide ()
2993 {
3153 {
2994 overlay.remove();
3154 overlay.remove();
2995 // Revoke any blob URLs we created for the picker thumbnails.
3155 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
2996 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
2997 {
3156 {
2998 URL.revokeObjectURL(img.src);
3157 URL.revokeObjectURL(img.src);
2999 });
3158 });
@@ -3002,7 +3161,6 @@ async function openFolderIconPicker (item)
3002 closeBtn.addEventListener('click', hide);
3161 closeBtn.addEventListener('click', hide);
3003 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3162 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3004
3163
3005 // Eagerly load thumbnails for all cells (picker is small, fetch all).
3006 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3164 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3007 {
3165 {
3008 const imgEl = cell.querySelector('.folder-icon-thumb');
3166 const imgEl = cell.querySelector('.folder-icon-thumb');
@@ -3017,6 +3175,67 @@ async function openFolderIconPicker (item)
3017 imgEl.src = url;
3175 imgEl.src = url;
3018 }).catch(() => { });
3176 }).catch(() => { });
3019 }
3177 }
3178
3179 filterInput.focus();
3180}
3181
3182async function openFolderIconPicker (item)
3183{
3184 if (!canWrite(item))
3185 {
3186 toast('No write access.', 'err');
3187 return;
3188 }
3189
3190 await openIconPickerModal({
3191 dirPath: item.path,
3192 titleText: 'Set folder icon',
3193 subtitleText: 'Select a file thumbnail to use as the folder icon.',
3194 emptyText: 'No files with cached thumbnails were found inside this folder.',
3195 confirmLabel: 'Set icon',
3196 clearLabel: 'Clear icon',
3197 onSelect: async (imagePath) =>
3198 {
3199 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
3200 refreshAfterIconChange(item);
3201 },
3202 onClear: async () =>
3203 {
3204 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
3205 refreshAfterIconChange(item);
3206 },
3207 });
3208}
3209
3210async function openGlobalFaviconPicker ()
3211{
3212 if (!STATE.isAdmin)
3213 {
3214 toast('Admin access required.', 'err');
3215 return;
3216 }
3217
3218 const dirPath = STATE.currentDir || (STATE.currentRoot ? STATE.currentRoot.path : null);
3219 await openIconPickerModal({
3220 dirPath,
3221 titleText: 'Set global favicon',
3222 subtitleText: 'Select a file thumbnail to use as the global favicon.',
3223 emptyText: 'No files with cached thumbnails were found inside this folder.',
3224 confirmLabel: 'Set favicon',
3225 clearLabel: 'Clear favicon',
3226 onSelect: async (imagePath) =>
3227 {
3228 await api('POST', '/files/global-favicon', { imagePath });
3229 STATE.faviconVersion = Date.now();
3230 await refreshGlobalFavicon();
3231 },
3232 onClear: async () =>
3233 {
3234 await api('POST', '/files/global-favicon', { imagePath: null });
3235 STATE.faviconVersion = Date.now();
3236 await refreshGlobalFavicon();
3237 },
3238 });
3020}
3239}
3021
3240
3022function refreshAfterIconChange (item)
3241function refreshAfterIconChange (item)
@@ -5506,6 +5725,22 @@ function wireEvents ()
5506 location.reload();
5725 location.reload();
5507 });
5726 });
5508
5727
5728 const topSearchInput = document.getElementById('top-search-input');
5729 const topSearchBtn = document.getElementById('btn-search');
5730 if (topSearchInput && topSearchBtn)
5731 {
5732 topSearchInput.addEventListener('keydown', (e) =>
5733 {
5734 if (e.key !== 'Enter') return;
5735 e.preventDefault();
5736 void runGlobalFileSearch();
5737 });
5738 topSearchBtn.addEventListener('click', () =>
5739 {
5740 void runGlobalFileSearch();
5741 });
5742 }
5743
5509 // Upload button
5744 // Upload button
5510 document.getElementById('btn-upload').addEventListener('click', () =>
5745 document.getElementById('btn-upload').addEventListener('click', () =>
5511 {
5746 {
@@ -5592,6 +5827,10 @@ function wireEvents ()
5592
5827
5593 // Admin panel
5828 // Admin panel
5594 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
5829 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
5830 document.getElementById('btn-global-favicon').addEventListener('click', () =>
5831 {
5832 void openGlobalFaviconPicker();
5833 });
5595 document.getElementById('admin-modal-close').addEventListener('click', () =>
5834 document.getElementById('admin-modal-close').addEventListener('click', () =>
5596 document.getElementById('admin-modal').classList.add('hidden'));
5835 document.getElementById('admin-modal').classList.add('hidden'));
5597
5836
public/index.html +23 −0
@@ -55,6 +55,18 @@
55 55 Refresh
56 56 </button>
57 57
58 <div id="top-search" class="top-search" role="search">
59 <input id="top-search-input" type="text" placeholder="Search files" aria-label="Search files" />
60 <button id="btn-search" class="icon-btn" title="Search files" aria-label="Search files">
61 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
62 stroke-linecap="round" stroke-linejoin="round">
63 <circle cx="11" cy="11" r="8" />
64 <line x1="21" y1="21" x2="16.65" y2="16.65" />
65 </svg>
66 Search
67 </button>
68 </div>
69
58 70 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
59 71 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
60 72 stroke-linecap="round" stroke-linejoin="round">
@@ -97,6 +109,17 @@
97 109 <span id="admin-update-badge" class="topbar-badge hidden" aria-hidden="true"></span>
98 110 </button>
99 111
112 <button id="btn-global-favicon" class="icon-btn hidden" title="Set global favicon" aria-label="Set global favicon">
113 <span id="global-favicon-preview" class="global-favicon-preview" aria-hidden="true">
114 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
115 stroke-linecap="round" stroke-linejoin="round">
116 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
117 <polyline points="14 2 14 8 20 8" />
118 </svg>
119 </span>
120 Favicon
121 </button>
122
100 123 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
101 124 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
102 125 stroke-linecap="round" stroke-linejoin="round">
@@ -55,6 +55,18 @@
55 Refresh
55 Refresh
56 </button>
56 </button>
57
57
58 <div id="top-search" class="top-search" role="search">
59 <input id="top-search-input" type="text" placeholder="Search files" aria-label="Search files" />
60 <button id="btn-search" class="icon-btn" title="Search files" aria-label="Search files">
61 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
62 stroke-linecap="round" stroke-linejoin="round">
63 <circle cx="11" cy="11" r="8" />
64 <line x1="21" y1="21" x2="16.65" y2="16.65" />
65 </svg>
66 Search
67 </button>
68 </div>
69
58 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
70 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
59 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
71 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
60 stroke-linecap="round" stroke-linejoin="round">
72 stroke-linecap="round" stroke-linejoin="round">
@@ -97,6 +109,17 @@
97 <span id="admin-update-badge" class="topbar-badge hidden" aria-hidden="true"></span>
109 <span id="admin-update-badge" class="topbar-badge hidden" aria-hidden="true"></span>
98 </button>
110 </button>
99
111
112 <button id="btn-global-favicon" class="icon-btn hidden" title="Set global favicon" aria-label="Set global favicon">
113 <span id="global-favicon-preview" class="global-favicon-preview" aria-hidden="true">
114 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
115 stroke-linecap="round" stroke-linejoin="round">
116 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
117 <polyline points="14 2 14 8 20 8" />
118 </svg>
119 </span>
120 Favicon
121 </button>
122
100 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
123 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
101 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
124 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
102 stroke-linecap="round" stroke-linejoin="round">
125 stroke-linecap="round" stroke-linejoin="round">
public/style.css +73 −0
@@ -271,6 +271,52 @@ button.danger.admin-update-highlight {
271 271 flex-shrink: 0;
272 272 }
273 273
274 .top-search {
275 display: flex;
276 align-items: center;
277 gap: 0.35rem;
278 margin-right: 0.2rem;
279 }
280
281 .top-search input {
282 width: min(34vw, 300px);
283 min-width: 150px;
284 background: var(--bg);
285 border: 1px solid var(--border);
286 border-radius: 6px;
287 color: var(--text);
288 font-size: 0.88rem;
289 padding: 0.42rem 0.6rem;
290 outline: none;
291 }
292
293 .top-search input:focus {
294 border-color: var(--accent);
295 }
296
297 #btn-search {
298 padding: 0.36rem 0.62rem;
299 }
300
301 .global-favicon-preview {
302 width: 18px;
303 height: 18px;
304 display: inline-flex;
305 align-items: center;
306 justify-content: center;
307 border-radius: 4px;
308 overflow: hidden;
309 color: #fff;
310 }
311
312 .global-favicon-preview svg,
313 .global-favicon-preview img {
314 width: 100%;
315 height: 100%;
316 display: block;
317 object-fit: cover;
318 }
319
274 320 /* =========================================================
275 321 MAIN + SIDEBAR LAYOUT
276 322 ========================================================= */
@@ -665,6 +711,21 @@ button.danger.admin-update-highlight {
665 711 border-radius: var(--radius);
666 712 }
667 713
714 .folder-icon-filter {
715 width: 100%;
716 background: var(--bg);
717 border: 1px solid var(--border);
718 border-radius: 6px;
719 color: var(--text);
720 font-size: 0.9rem;
721 padding: 0.48rem 0.68rem;
722 outline: none;
723 }
724
725 .folder-icon-filter:focus {
726 border-color: var(--accent);
727 }
728
668 729 .folder-icon-cell {
669 730 display: flex;
670 731 flex-direction: column;
@@ -1091,6 +1152,18 @@ button.danger.admin-update-highlight {
1091 1152 gap: 0.15rem;
1092 1153 }
1093 1154
1155 .top-search {
1156 order: -1;
1157 width: 100%;
1158 margin-right: 0;
1159 }
1160
1161 .top-search input {
1162 flex: 1;
1163 min-width: 0;
1164 width: auto;
1165 }
1166
1094 1167 .icon-btn {
1095 1168 padding: 0.4rem 0.55rem;
1096 1169 font-size: 0.82rem;
@@ -271,6 +271,52 @@ button.danger.admin-update-highlight {
271 flex-shrink: 0;
271 flex-shrink: 0;
272}
272}
273
273
274.top-search {
275 display: flex;
276 align-items: center;
277 gap: 0.35rem;
278 margin-right: 0.2rem;
279}
280
281.top-search input {
282 width: min(34vw, 300px);
283 min-width: 150px;
284 background: var(--bg);
285 border: 1px solid var(--border);
286 border-radius: 6px;
287 color: var(--text);
288 font-size: 0.88rem;
289 padding: 0.42rem 0.6rem;
290 outline: none;
291}
292
293.top-search input:focus {
294 border-color: var(--accent);
295}
296
297#btn-search {
298 padding: 0.36rem 0.62rem;
299}
300
301.global-favicon-preview {
302 width: 18px;
303 height: 18px;
304 display: inline-flex;
305 align-items: center;
306 justify-content: center;
307 border-radius: 4px;
308 overflow: hidden;
309 color: #fff;
310}
311
312.global-favicon-preview svg,
313.global-favicon-preview img {
314 width: 100%;
315 height: 100%;
316 display: block;
317 object-fit: cover;
318}
319
274/* =========================================================
320/* =========================================================
275 MAIN + SIDEBAR LAYOUT
321 MAIN + SIDEBAR LAYOUT
276 ========================================================= */
322 ========================================================= */
@@ -665,6 +711,21 @@ button.danger.admin-update-highlight {
665 border-radius: var(--radius);
711 border-radius: var(--radius);
666}
712}
667
713
714.folder-icon-filter {
715 width: 100%;
716 background: var(--bg);
717 border: 1px solid var(--border);
718 border-radius: 6px;
719 color: var(--text);
720 font-size: 0.9rem;
721 padding: 0.48rem 0.68rem;
722 outline: none;
723}
724
725.folder-icon-filter:focus {
726 border-color: var(--accent);
727}
728
668.folder-icon-cell {
729.folder-icon-cell {
669 display: flex;
730 display: flex;
670 flex-direction: column;
731 flex-direction: column;
@@ -1091,6 +1152,18 @@ button.danger.admin-update-highlight {
1091 gap: 0.15rem;
1152 gap: 0.15rem;
1092 }
1153 }
1093
1154
1155 .top-search {
1156 order: -1;
1157 width: 100%;
1158 margin-right: 0;
1159 }
1160
1161 .top-search input {
1162 flex: 1;
1163 min-width: 0;
1164 width: auto;
1165 }
1166
1094 .icon-btn {
1167 .icon-btn {
1095 padding: 0.4rem 0.55rem;
1168 padding: 0.4rem 0.55rem;
1096 font-size: 0.82rem;
1169 font-size: 0.82rem;
server/routes/files.js +236 −0
@@ -211,6 +211,138 @@ function isAccessiblePath (absPath, roots, user, config)
211 211 return resolveRootForUser(absPath, roots, user, config) !== null;
212 212 }
213 213
214 function readableSearchRootsForUser (user, config, roots)
215 {
216 const out = [];
217 for (const root of roots)
218 {
219 const label = path.basename(root);
220 if (canRead(user, label)) out.push(root);
221 }
222
223 const personal = getUserFolderPath(config, user && user.username);
224 if (personal) out.push(personal);
225
226 // Deduplicate by resolved path.
227 const seen = new Set();
228 return out.filter((p) =>
229 {
230 const key = path.resolve(p);
231 if (seen.has(key)) return false;
232 seen.add(key);
233 return true;
234 });
235 }
236
237 function fuzzyMatchScore (needle, haystack)
238 {
239 const q = String(needle || '').trim().toLowerCase();
240 const t = String(haystack || '').toLowerCase();
241 if (!q || !t) return null;
242
243 // Strong boost for contiguous substring matches.
244 const idx = t.indexOf(q);
245 if (idx >= 0)
246 {
247 const compactBonus = Math.max(0, 200 - idx);
248 const lengthBonus = Math.max(0, 120 - (t.length - q.length));
249 return 1200 + compactBonus + lengthBonus;
250 }
251
252 // Fallback: subsequence fuzzy match.
253 let qPos = 0;
254 let firstHit = -1;
255 let lastHit = -1;
256 let gaps = 0;
257
258 for (let i = 0; i < t.length && qPos < q.length; i++)
259 {
260 if (t[i] !== q[qPos]) continue;
261 if (firstHit === -1) firstHit = i;
262 if (lastHit >= 0) gaps += Math.max(0, i - lastHit - 1);
263 lastHit = i;
264 qPos += 1;
265 }
266
267 if (qPos !== q.length) return null;
268
269 const span = lastHit - firstHit + 1;
270 const compactness = Math.max(0, 300 - span);
271 const gapPenalty = Math.min(180, gaps * 3);
272 const startBonus = Math.max(0, 120 - firstHit);
273 return 700 + compactness + startBonus - gapPenalty;
274 }
275
276 function searchFilesInRoots (query, roots, maxResults)
277 {
278 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
279 const results = [];
280 const visitedDirs = new Set();
281
282 for (const root of roots)
283 {
284 const rootPath = path.resolve(root);
285 const stack = [rootPath];
286
287 while (stack.length)
288 {
289 const dir = stack.pop();
290 if (!dir) continue;
291 const dirKey = path.resolve(dir);
292 if (visitedDirs.has(dirKey)) continue;
293 visitedDirs.add(dirKey);
294
295 let entries;
296 try
297 {
298 entries = fs.readdirSync(dir, { withFileTypes: true });
299 } catch
300 {
301 continue;
302 }
303
304 for (const entry of entries)
305 {
306 const fullPath = path.join(dir, entry.name);
307 if (entry.isDirectory())
308 {
309 stack.push(fullPath);
310 continue;
311 }
312 if (!entry.isFile()) continue;
313
314 const relativePath = path.relative(rootPath, fullPath);
315 const score = fuzzyMatchScore(query, entry.name)
316 ?? fuzzyMatchScore(query, relativePath);
317 if (score == null) continue;
318
319 let stat = null;
320 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
321
322 results.push({
323 name: entry.name,
324 path: fullPath,
325 dir: path.dirname(fullPath),
326 rootPath,
327 relativePath,
328 size: stat ? stat.size : null,
329 mtime: stat ? stat.mtime.toISOString() : null,
330 score,
331 });
332
333 if (results.length > limit * 4)
334 {
335 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
336 results.length = limit * 2;
337 }
338 }
339 }
340 }
341
342 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
343 return results.slice(0, limit);
344 }
345
214 346 function rootAliasesFromConfig (config)
215 347 {
216 348 if (!config || typeof config !== 'object') return {};
@@ -759,6 +891,35 @@ router.get('/list', requireAuth, (req, res) =>
759 891 res.json({ items });
760 892 });
761 893
894 // ---------------------------------------------------------------------------
895 // GET /api/files/search?query=<text>&limit=<number>
896 // Fuzzy-searches all readable roots for files.
897 // ---------------------------------------------------------------------------
898 router.get('/search', requireAuth, (req, res) =>
899 {
900 const query = String(req.query.query || '').trim();
901 if (!query) return res.status(400).json({ error: 'query is required.' });
902
903 const { config, roots } = loadConfigAndRoots();
904 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
905 .filter((rootPath) =>
906 {
907 try
908 {
909 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
910 } catch
911 {
912 return false;
913 }
914 });
915
916 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
917 res.json({
918 query,
919 results,
920 });
921 });
922
762 923 // ---------------------------------------------------------------------------
763 924 // GET /api/files/meta?file=<absolute-path>
764 925 // Returns file metadata from the DB. Lazily computes SHA-256 when missing.
@@ -1663,6 +1824,81 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1663 1824 res.json({ ok: true });
1664 1825 });
1665 1826
1827 // ---------------------------------------------------------------------------
1828 // GET /api/files/global-favicon-image
1829 // Serves the configured global favicon thumbnail file (cache-backed).
1830 // Public so <link rel="icon"> can fetch it without auth headers.
1831 // ---------------------------------------------------------------------------
1832 router.get('/global-favicon-image', async (req, res) =>
1833 {
1834 const config = loadConfig();
1835 const filePath = config && typeof config.globalFaviconPath === 'string'
1836 ? config.globalFaviconPath.trim()
1837 : '';
1838 if (!filePath) return res.status(404).end();
1839
1840 const thumb = await getCachedThumbnailInfo(filePath);
1841 if (!thumb || !thumb.thumbPath) return res.status(404).end();
1842 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
1843
1844 res.type(thumb.contentType || 'image/webp');
1845 res.sendFile(thumb.thumbPath);
1846 });
1847
1848 // ---------------------------------------------------------------------------
1849 // GET /api/files/global-favicon
1850 // Returns the configured global favicon source file path, if any.
1851 // ---------------------------------------------------------------------------
1852 router.get('/global-favicon', requireAuth, async (req, res) =>
1853 {
1854 const config = loadConfig();
1855 const filePath = config && typeof config.globalFaviconPath === 'string'
1856 ? config.globalFaviconPath.trim()
1857 : '';
1858 if (!filePath) return res.json({ favicon: null });
1859
1860 const thumb = await getCachedThumbnailInfo(filePath);
1861 if (!thumb) return res.json({ favicon: null });
1862
1863 res.json({ favicon: { filePath } });
1864 });
1865
1866 // ---------------------------------------------------------------------------
1867 // POST /api/files/global-favicon
1868 // Body: { imagePath } where imagePath may be null to clear.
1869 // Admin-only route for setting the global favicon source image.
1870 // ---------------------------------------------------------------------------
1871 router.post('/global-favicon', requireAuth, async (req, res) =>
1872 {
1873 if (!req.user || !req.user.isAdmin)
1874 {
1875 return res.status(403).json({ error: 'Admin access required.' });
1876 }
1877
1878 const rawImage = req.body && req.body.imagePath != null
1879 ? String(req.body.imagePath).trim()
1880 : null;
1881
1882 const config = loadConfig();
1883 const roots = getEffectivePaths(config.paths || []);
1884
1885 if (rawImage !== null)
1886 {
1887 const info = resolveRootForUser(rawImage, roots, req.user, config);
1888 if (!info || !canReadInfo(req.user, info))
1889 {
1890 return res.status(403).json({ error: 'Image not accessible.' });
1891 }
1892
1893 const thumb = await getCachedThumbnailInfo(rawImage);
1894 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1895 }
1896
1897 config.globalFaviconPath = rawImage;
1898 saveConfig(config);
1899 res.json({ ok: true });
1900 });
1901
1666 1902 // ---------------------------------------------------------------------------
1667 1903 // POST /api/files/copy
1668 1904 // Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
@@ -211,6 +211,138 @@ function isAccessiblePath (absPath, roots, user, config)
211 return resolveRootForUser(absPath, roots, user, config) !== null;
211 return resolveRootForUser(absPath, roots, user, config) !== null;
212}
212}
213
213
214function readableSearchRootsForUser (user, config, roots)
215{
216 const out = [];
217 for (const root of roots)
218 {
219 const label = path.basename(root);
220 if (canRead(user, label)) out.push(root);
221 }
222
223 const personal = getUserFolderPath(config, user && user.username);
224 if (personal) out.push(personal);
225
226 // Deduplicate by resolved path.
227 const seen = new Set();
228 return out.filter((p) =>
229 {
230 const key = path.resolve(p);
231 if (seen.has(key)) return false;
232 seen.add(key);
233 return true;
234 });
235}
236
237function fuzzyMatchScore (needle, haystack)
238{
239 const q = String(needle || '').trim().toLowerCase();
240 const t = String(haystack || '').toLowerCase();
241 if (!q || !t) return null;
242
243 // Strong boost for contiguous substring matches.
244 const idx = t.indexOf(q);
245 if (idx >= 0)
246 {
247 const compactBonus = Math.max(0, 200 - idx);
248 const lengthBonus = Math.max(0, 120 - (t.length - q.length));
249 return 1200 + compactBonus + lengthBonus;
250 }
251
252 // Fallback: subsequence fuzzy match.
253 let qPos = 0;
254 let firstHit = -1;
255 let lastHit = -1;
256 let gaps = 0;
257
258 for (let i = 0; i < t.length && qPos < q.length; i++)
259 {
260 if (t[i] !== q[qPos]) continue;
261 if (firstHit === -1) firstHit = i;
262 if (lastHit >= 0) gaps += Math.max(0, i - lastHit - 1);
263 lastHit = i;
264 qPos += 1;
265 }
266
267 if (qPos !== q.length) return null;
268
269 const span = lastHit - firstHit + 1;
270 const compactness = Math.max(0, 300 - span);
271 const gapPenalty = Math.min(180, gaps * 3);
272 const startBonus = Math.max(0, 120 - firstHit);
273 return 700 + compactness + startBonus - gapPenalty;
274}
275
276function searchFilesInRoots (query, roots, maxResults)
277{
278 const limit = Math.max(1, Math.min(500, Number(maxResults) || 200));
279 const results = [];
280 const visitedDirs = new Set();
281
282 for (const root of roots)
283 {
284 const rootPath = path.resolve(root);
285 const stack = [rootPath];
286
287 while (stack.length)
288 {
289 const dir = stack.pop();
290 if (!dir) continue;
291 const dirKey = path.resolve(dir);
292 if (visitedDirs.has(dirKey)) continue;
293 visitedDirs.add(dirKey);
294
295 let entries;
296 try
297 {
298 entries = fs.readdirSync(dir, { withFileTypes: true });
299 } catch
300 {
301 continue;
302 }
303
304 for (const entry of entries)
305 {
306 const fullPath = path.join(dir, entry.name);
307 if (entry.isDirectory())
308 {
309 stack.push(fullPath);
310 continue;
311 }
312 if (!entry.isFile()) continue;
313
314 const relativePath = path.relative(rootPath, fullPath);
315 const score = fuzzyMatchScore(query, entry.name)
316 ?? fuzzyMatchScore(query, relativePath);
317 if (score == null) continue;
318
319 let stat = null;
320 try { stat = fs.statSync(fullPath); } catch { /* ignore disappearing files */ }
321
322 results.push({
323 name: entry.name,
324 path: fullPath,
325 dir: path.dirname(fullPath),
326 rootPath,
327 relativePath,
328 size: stat ? stat.size : null,
329 mtime: stat ? stat.mtime.toISOString() : null,
330 score,
331 });
332
333 if (results.length > limit * 4)
334 {
335 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
336 results.length = limit * 2;
337 }
338 }
339 }
340 }
341
342 results.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
343 return results.slice(0, limit);
344}
345
214function rootAliasesFromConfig (config)
346function rootAliasesFromConfig (config)
215{
347{
216 if (!config || typeof config !== 'object') return {};
348 if (!config || typeof config !== 'object') return {};
@@ -759,6 +891,35 @@ router.get('/list', requireAuth, (req, res) =>
759 res.json({ items });
891 res.json({ items });
760});
892});
761
893
894// ---------------------------------------------------------------------------
895// GET /api/files/search?query=<text>&limit=<number>
896// Fuzzy-searches all readable roots for files.
897// ---------------------------------------------------------------------------
898router.get('/search', requireAuth, (req, res) =>
899{
900 const query = String(req.query.query || '').trim();
901 if (!query) return res.status(400).json({ error: 'query is required.' });
902
903 const { config, roots } = loadConfigAndRoots();
904 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
905 .filter((rootPath) =>
906 {
907 try
908 {
909 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
910 } catch
911 {
912 return false;
913 }
914 });
915
916 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
917 res.json({
918 query,
919 results,
920 });
921});
922
762// ---------------------------------------------------------------------------
923// ---------------------------------------------------------------------------
763// GET /api/files/meta?file=<absolute-path>
924// GET /api/files/meta?file=<absolute-path>
764// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
925// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
@@ -1663,6 +1824,81 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1663 res.json({ ok: true });
1824 res.json({ ok: true });
1664});
1825});
1665
1826
1827// ---------------------------------------------------------------------------
1828// GET /api/files/global-favicon-image
1829// Serves the configured global favicon thumbnail file (cache-backed).
1830// Public so <link rel="icon"> can fetch it without auth headers.
1831// ---------------------------------------------------------------------------
1832router.get('/global-favicon-image', async (req, res) =>
1833{
1834 const config = loadConfig();
1835 const filePath = config && typeof config.globalFaviconPath === 'string'
1836 ? config.globalFaviconPath.trim()
1837 : '';
1838 if (!filePath) return res.status(404).end();
1839
1840 const thumb = await getCachedThumbnailInfo(filePath);
1841 if (!thumb || !thumb.thumbPath) return res.status(404).end();
1842 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
1843
1844 res.type(thumb.contentType || 'image/webp');
1845 res.sendFile(thumb.thumbPath);
1846});
1847
1848// ---------------------------------------------------------------------------
1849// GET /api/files/global-favicon
1850// Returns the configured global favicon source file path, if any.
1851// ---------------------------------------------------------------------------
1852router.get('/global-favicon', requireAuth, async (req, res) =>
1853{
1854 const config = loadConfig();
1855 const filePath = config && typeof config.globalFaviconPath === 'string'
1856 ? config.globalFaviconPath.trim()
1857 : '';
1858 if (!filePath) return res.json({ favicon: null });
1859
1860 const thumb = await getCachedThumbnailInfo(filePath);
1861 if (!thumb) return res.json({ favicon: null });
1862
1863 res.json({ favicon: { filePath } });
1864});
1865
1866// ---------------------------------------------------------------------------
1867// POST /api/files/global-favicon
1868// Body: { imagePath } where imagePath may be null to clear.
1869// Admin-only route for setting the global favicon source image.
1870// ---------------------------------------------------------------------------
1871router.post('/global-favicon', requireAuth, async (req, res) =>
1872{
1873 if (!req.user || !req.user.isAdmin)
1874 {
1875 return res.status(403).json({ error: 'Admin access required.' });
1876 }
1877
1878 const rawImage = req.body && req.body.imagePath != null
1879 ? String(req.body.imagePath).trim()
1880 : null;
1881
1882 const config = loadConfig();
1883 const roots = getEffectivePaths(config.paths || []);
1884
1885 if (rawImage !== null)
1886 {
1887 const info = resolveRootForUser(rawImage, roots, req.user, config);
1888 if (!info || !canReadInfo(req.user, info))
1889 {
1890 return res.status(403).json({ error: 'Image not accessible.' });
1891 }
1892
1893 const thumb = await getCachedThumbnailInfo(rawImage);
1894 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1895 }
1896
1897 config.globalFaviconPath = rawImage;
1898 saveConfig(config);
1899 res.json({ ok: true });
1900});
1901
1666// ---------------------------------------------------------------------------
1902// ---------------------------------------------------------------------------
1667// POST /api/files/copy
1903// POST /api/files/copy
1668// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1904// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
tests/files.routes.test.js +83 −1
@@ -10,6 +10,7 @@ const { once } = require('events');
10 10 let mockPaths = [];
11 11 let mockUserPath = null;
12 12 let mockRootAliases = {};
13 let mockGlobalFaviconPath = null;
13 14 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14 15 let mockThumbPath = null;
15 16 let mockFolderImages = [];
@@ -54,11 +55,18 @@ jest.mock('../server/db', () =>
54 55 });
55 56
56 57 jest.mock('../server/config', () => ({
57 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
58 loadConfig: () => ({
59 port: 3000,
60 paths: [...mockPaths],
61 userPath: mockUserPath,
62 rootAliases: { ...mockRootAliases },
63 globalFaviconPath: mockGlobalFaviconPath,
64 }),
58 65 saveConfig: (config) =>
59 66 {
60 67 mockPaths = [...(config.paths || [])];
61 68 mockRootAliases = { ...(config.rootAliases || {}) };
69 mockGlobalFaviconPath = config.globalFaviconPath || null;
62 70 },
63 71 getEffectivePaths: (paths) => paths,
64 72 getAllowedRoot: (targetPath, roots) =>
@@ -163,6 +171,7 @@ beforeEach(() =>
163 171 fs.mkdirSync(mockUserPath, { recursive: true });
164 172 }
165 173 mockRootAliases = {};
174 mockGlobalFaviconPath = null;
166 175 mockUserPath = null;
167 176 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
168 177 mockThumbPath = null;
@@ -724,6 +733,79 @@ describe('folder icon endpoints', () =>
724 733 });
725 734 });
726 735
736 describe('file search endpoint', () =>
737 {
738 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
739 {
740 const movieDir = path.join(rootDir, 'Movies');
741 const docsDir = path.join(rootDir, 'Docs');
742 fs.mkdirSync(movieDir, { recursive: true });
743 fs.mkdirSync(docsDir, { recursive: true });
744 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
745 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
746
747 const { status, body } = await req('GET', '/api/files/search?query=dbs');
748 expect(status).toBe(200);
749 expect(body.query).toBe('dbs');
750 expect(body.results.length).toBeGreaterThan(0);
751 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
752 });
753
754 test('GET /api/files/search returns 400 when query is missing', async () =>
755 {
756 const { status } = await req('GET', '/api/files/search');
757 expect(status).toBe(400);
758 });
759 });
760
761 describe('global favicon endpoints', () =>
762 {
763 test('GET /api/files/global-favicon returns null when unset', async () =>
764 {
765 const { status, body } = await req('GET', '/api/files/global-favicon');
766 expect(status).toBe(200);
767 expect(body.favicon).toBeNull();
768 });
769
770 test('POST /api/files/global-favicon stores selected image path', async () =>
771 {
772 const imgPath = path.join(rootDir, 'cover.jpg');
773 const thumbPath = path.join(rootDir, 'cover.webp');
774 fs.writeFileSync(imgPath, 'img');
775 fs.writeFileSync(thumbPath, 'thumb');
776 mockThumbPath = thumbPath;
777
778 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
779 expect(status).toBe(200);
780 expect(body.ok).toBe(true);
781 expect(mockGlobalFaviconPath).toBe(imgPath);
782
783 const fetched = await req('GET', '/api/files/global-favicon');
784 expect(fetched.status).toBe(200);
785 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
786 });
787
788 test('POST /api/files/global-favicon clears the configured favicon', async () =>
789 {
790 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
791
792 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
793 expect(status).toBe(200);
794 expect(body.ok).toBe(true);
795 expect(mockGlobalFaviconPath).toBeNull();
796 });
797
798 test('POST /api/files/global-favicon is admin-only', async () =>
799 {
800 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
801 const imgPath = path.join(rootDir, 'cover.jpg');
802 fs.writeFileSync(imgPath, 'img');
803
804 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
805 expect(status).toBe(403);
806 });
807 });
808
727 809 // ---------------------------------------------------------------------------
728 810 // GET /api/files/download-zip
729 811 // ---------------------------------------------------------------------------
@@ -10,6 +10,7 @@ const { once } = require('events');
10let mockPaths = [];
10let mockPaths = [];
11let mockUserPath = null;
11let mockUserPath = null;
12let mockRootAliases = {};
12let mockRootAliases = {};
13let mockGlobalFaviconPath = null;
13let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockThumbPath = null;
15let mockThumbPath = null;
15let mockFolderImages = [];
16let mockFolderImages = [];
@@ -54,11 +55,18 @@ jest.mock('../server/db', () =>
54});
55});
55
56
56jest.mock('../server/config', () => ({
57jest.mock('../server/config', () => ({
57 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
58 loadConfig: () => ({
59 port: 3000,
60 paths: [...mockPaths],
61 userPath: mockUserPath,
62 rootAliases: { ...mockRootAliases },
63 globalFaviconPath: mockGlobalFaviconPath,
64 }),
58 saveConfig: (config) =>
65 saveConfig: (config) =>
59 {
66 {
60 mockPaths = [...(config.paths || [])];
67 mockPaths = [...(config.paths || [])];
61 mockRootAliases = { ...(config.rootAliases || {}) };
68 mockRootAliases = { ...(config.rootAliases || {}) };
69 mockGlobalFaviconPath = config.globalFaviconPath || null;
62 },
70 },
63 getEffectivePaths: (paths) => paths,
71 getEffectivePaths: (paths) => paths,
64 getAllowedRoot: (targetPath, roots) =>
72 getAllowedRoot: (targetPath, roots) =>
@@ -163,6 +171,7 @@ beforeEach(() =>
163 fs.mkdirSync(mockUserPath, { recursive: true });
171 fs.mkdirSync(mockUserPath, { recursive: true });
164 }
172 }
165 mockRootAliases = {};
173 mockRootAliases = {};
174 mockGlobalFaviconPath = null;
166 mockUserPath = null;
175 mockUserPath = null;
167 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
176 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
168 mockThumbPath = null;
177 mockThumbPath = null;
@@ -724,6 +733,79 @@ describe('folder icon endpoints', () =>
724 });
733 });
725});
734});
726
735
736describe('file search endpoint', () =>
737{
738 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
739 {
740 const movieDir = path.join(rootDir, 'Movies');
741 const docsDir = path.join(rootDir, 'Docs');
742 fs.mkdirSync(movieDir, { recursive: true });
743 fs.mkdirSync(docsDir, { recursive: true });
744 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
745 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
746
747 const { status, body } = await req('GET', '/api/files/search?query=dbs');
748 expect(status).toBe(200);
749 expect(body.query).toBe('dbs');
750 expect(body.results.length).toBeGreaterThan(0);
751 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
752 });
753
754 test('GET /api/files/search returns 400 when query is missing', async () =>
755 {
756 const { status } = await req('GET', '/api/files/search');
757 expect(status).toBe(400);
758 });
759});
760
761describe('global favicon endpoints', () =>
762{
763 test('GET /api/files/global-favicon returns null when unset', async () =>
764 {
765 const { status, body } = await req('GET', '/api/files/global-favicon');
766 expect(status).toBe(200);
767 expect(body.favicon).toBeNull();
768 });
769
770 test('POST /api/files/global-favicon stores selected image path', async () =>
771 {
772 const imgPath = path.join(rootDir, 'cover.jpg');
773 const thumbPath = path.join(rootDir, 'cover.webp');
774 fs.writeFileSync(imgPath, 'img');
775 fs.writeFileSync(thumbPath, 'thumb');
776 mockThumbPath = thumbPath;
777
778 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
779 expect(status).toBe(200);
780 expect(body.ok).toBe(true);
781 expect(mockGlobalFaviconPath).toBe(imgPath);
782
783 const fetched = await req('GET', '/api/files/global-favicon');
784 expect(fetched.status).toBe(200);
785 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
786 });
787
788 test('POST /api/files/global-favicon clears the configured favicon', async () =>
789 {
790 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
791
792 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
793 expect(status).toBe(200);
794 expect(body.ok).toBe(true);
795 expect(mockGlobalFaviconPath).toBeNull();
796 });
797
798 test('POST /api/files/global-favicon is admin-only', async () =>
799 {
800 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
801 const imgPath = path.join(rootDir, 'cover.jpg');
802 fs.writeFileSync(imgPath, 'img');
803
804 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
805 expect(status).toBe(403);
806 });
807});
808
727// ---------------------------------------------------------------------------
809// ---------------------------------------------------------------------------
728// GET /api/files/download-zip
810// GET /api/files/download-zip
729// ---------------------------------------------------------------------------
811// ---------------------------------------------------------------------------