BlueGit

timfa filemanager

feat: folder icon — set thumbnail as folder icon from cached images

timfa Tim Falken · pushed by timfa

Authored 2026-05-04 · 6 months ago

Hash
8b75bfe41fcaba1d5f1da2ff4f6d8bf1073edcb7
Parent
ed7af91f
8 files changed +756 −26
.github/technical-reference.md +13 −1
@@ -11,6 +11,9 @@
11 11 - getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12 12 - getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
13 13 - getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
14 - getImagesWithThumbnailsInDir(dirPath) - Returns [{filePath, thumbRelPath}] for all images inside dirPath (recursive) that have a cached thumbnail; sorted by filePath.
15 - getFolderIconSourceFile(folderPath) - Returns the source image path for a folder's icon: explicit assignment first, then auto-first cached image, null if none.
16 - setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
14 17
15 18 ## server/db.js
16 19 - initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
@@ -43,6 +46,9 @@
43 46 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
44 47 - GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
45 48 - GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
49 - GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
50 - 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.
51 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
46 52
47 53 ## public/app.js
48 54 - showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -56,8 +62,14 @@
56 62 - showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
57 63 - showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
58 64 - showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
59 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading; retries missing cache thumbnails during incremental refresh.
65 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
60 66 - 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.
67 - observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
68 - loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
69 - applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
70 - openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail images from the folder; allows selection, clearing, and cancellation.
71 - refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
72 - disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
61 73 - getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
62 74 - observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
63 75 - disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
@@ -11,6 +11,9 @@
11- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
11- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12- getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
12- getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
13- getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
13- getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
14- getImagesWithThumbnailsInDir(dirPath) - Returns [{filePath, thumbRelPath}] for all images inside dirPath (recursive) that have a cached thumbnail; sorted by filePath.
15- getFolderIconSourceFile(folderPath) - Returns the source image path for a folder's icon: explicit assignment first, then auto-first cached image, null if none.
16- setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
14
17
15## server/db.js
18## server/db.js
16- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
19- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
@@ -43,6 +46,9 @@
43- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
46- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
44- GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
47- GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
45- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
48- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
49- GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
50- 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.
51- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
46
52
47## public/app.js
53## public/app.js
48- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
54- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -56,8 +62,14 @@
56- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
62- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
57- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
63- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
58- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
64- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
59- loadThumbnails() - Registers visible file icons for lazy thumbnail loading; retries missing cache thumbnails during incremental refresh.
65- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
60- 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.
66- 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.
67- observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
68- loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
69- applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
70- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail images from the folder; allows selection, clearing, and cancellation.
71- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
72- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
61- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
73- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
62- observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
74- observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
63- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
75- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
.github/tests.md +5 −24
@@ -13,8 +13,6 @@
13 13 - `GET /api/admin/config`
14 14 - `PUT /api/admin/config`
15 15 - `POST /api/admin/shutdown`
16 - `normalizes permissions so write implies read on create`
17 - `normalizes permissions so write implies read on update`
18 16
19 17 ---
20 18
@@ -41,35 +39,18 @@
41 39 ## `test/files.routes.test.js`
42 40 - `POST /api/files/move`
43 41 - `root alias endpoints`
44 - `GET /api/files/roots returns alias label and original name`
45 - `POST /api/files/root-alias stores alias without renaming filesystem path`
46 - `POST /api/files/root-alias rejects non-root paths`
47 42 - `GET /api/files/thumbnail`
48 - `returns 404 while cached thumbnail is not ready`
49 - `serves cached thumbnail file when available`
50 43 - `GET /api/files/root-access`
51 - `returns users with R/R+W modes for an exact root path`
52 - `rejects non-exact nested root paths`
44 - `folder icon endpoints`
53 45
54 46 ---
55 47
56 ## `test/thumbnail-cache.test.js`
57 - `thumbnail cache worker`
58 - `creates cached thumbnail with dimensions smaller than 100px`
59 - `removes cached thumbnail when source file is deleted`
48 ## `test/page.load.test.js`
49 - `page load smoke test`
60 50
61 51 ---
62 52
63 ## `test/page.load.test.js`
64 - `page load smoke test`
65 - `requests / and boots the client without runtime errors`
66 - `keeps sidebar folded on initial mobile boot`
67 - `suppresses default context menu on mobile file long-press`
68 - `in Home, root tiles single-click focus and double-click open`
69 - `root sidebar shows alias and original name, and excludes Move to action`
70 - `base-level root sidebar shows access list with no item selected`
71 - `shows pending icon spinner when image thumbnail cache is not ready`
72 - `admin user modal locks write checkbox while read is unchecked`
73 - `uses direct svg thumbnail when svg file is under 1MB`
53 ## `test/thumbnail-cache.test.js`
54 - `thumbnail cache worker`
74 55
75 56 ---
@@ -13,8 +13,6 @@
13- `GET /api/admin/config`
13- `GET /api/admin/config`
14- `PUT /api/admin/config`
14- `PUT /api/admin/config`
15- `POST /api/admin/shutdown`
15- `POST /api/admin/shutdown`
16- `normalizes permissions so write implies read on create`
17- `normalizes permissions so write implies read on update`
18
16
19---
17---
20
18
@@ -41,35 +39,18 @@
41## `test/files.routes.test.js`
39## `test/files.routes.test.js`
42- `POST /api/files/move`
40- `POST /api/files/move`
43- `root alias endpoints`
41- `root alias endpoints`
44- `GET /api/files/roots returns alias label and original name`
45- `POST /api/files/root-alias stores alias without renaming filesystem path`
46- `POST /api/files/root-alias rejects non-root paths`
47- `GET /api/files/thumbnail`
42- `GET /api/files/thumbnail`
48- `returns 404 while cached thumbnail is not ready`
49- `serves cached thumbnail file when available`
50- `GET /api/files/root-access`
43- `GET /api/files/root-access`
51- `returns users with R/R+W modes for an exact root path`
44- `folder icon endpoints`
52- `rejects non-exact nested root paths`
53
45
54---
46---
55
47
56## `test/thumbnail-cache.test.js`
48## `test/page.load.test.js`
57- `thumbnail cache worker`
49- `page load smoke test`
58- `creates cached thumbnail with dimensions smaller than 100px`
59- `removes cached thumbnail when source file is deleted`
60
50
61---
51---
62
52
63## `test/page.load.test.js`
53## `test/thumbnail-cache.test.js`
64- `page load smoke test`
54- `thumbnail cache worker`
65- `requests / and boots the client without runtime errors`
66- `keeps sidebar folded on initial mobile boot`
67- `suppresses default context menu on mobile file long-press`
68- `in Home, root tiles single-click focus and double-click open`
69- `root sidebar shows alias and original name, and excludes Move to action`
70- `base-level root sidebar shows access list with no item selected`
71- `shows pending icon spinner when image thumbnail cache is not ready`
72- `admin user modal locks write checkbox while read is unchecked`
73- `uses direct svg thumbnail when svg file is under 1MB`
74
55
75---
56---
public/app.js +343 −0
@@ -44,6 +44,7 @@ const STATE = {
44 44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 45 thumbnailUrls: [],
46 46 thumbnailObserver: null,
47 folderIconObserver: null,
47 48
48 49 // Preview overlay state
49 50 previewObjectUrl: null,
@@ -888,6 +889,7 @@ function stopAutoRefresh ()
888 889 function renderFileGrid ()
889 890 {
890 891 disconnectThumbnailObserver();
892 disconnectFolderIconObserver();
891 893 revokeThumbnails();
892 894 const grid = document.getElementById('file-grid');
893 895 grid.innerHTML = '';
@@ -922,6 +924,9 @@ function makeFileItem (item)
922 924 if (!item.isDir)
923 925 {
924 926 icon.dataset.previewPath = item.path;
927 } else
928 {
929 icon.dataset.folderPath = item.path;
925 930 }
926 931 el.appendChild(icon);
927 932
@@ -1052,6 +1057,13 @@ async function openSidebar (item)
1052 1057 document.getElementById('app').classList.add('sidebar-open');
1053 1058
1054 1059 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
1060 if (item.isDir)
1061 {
1062 document.getElementById('sidebar-icon').dataset.folderPath = item.path;
1063 } else
1064 {
1065 delete document.getElementById('sidebar-icon').dataset.folderPath;
1066 }
1055 1067 document.getElementById('sidebar-name').textContent = item.name;
1056 1068
1057 1069 // Load metadata
@@ -1119,11 +1131,22 @@ async function openSidebar (item)
1119 1131 btnOpen.textContent = 'Open folder';
1120 1132 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
1121 1133 actions.appendChild(btnOpen);
1134
1135 // Load folder icon thumbnail into the sidebar icon element.
1136 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
1122 1137 }
1123 1138
1124 1139 // Rename button (write access required)
1125 1140 if (canWrite(item))
1126 1141 {
1142 if (item.isDir)
1143 {
1144 const btnSetIcon = document.createElement('button');
1145 btnSetIcon.textContent = 'Set icon';
1146 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
1147 actions.appendChild(btnSetIcon);
1148 }
1149
1127 1150 if (!item._root)
1128 1151 {
1129 1152 const btnMove = document.createElement('button');
@@ -1457,6 +1480,197 @@ function openMovePicker (item)
1457 1480 overlay.classList.remove('hidden');
1458 1481 }
1459 1482
1483 // ───────────────────────────────────────────────────────────────────────────
1484 // FOLDER ICON PICKER
1485 // ───────────────────────────────────────────────────────────────────────────
1486
1487 async function openFolderIconPicker (item)
1488 {
1489 if (!canWrite(item))
1490 {
1491 toast('No write access.', 'err');
1492 return;
1493 }
1494
1495 // Fetch the list of available images (only those with cached thumbnails).
1496 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1497 const images = data ? data.images : [];
1498
1499 let existingIconOverlay = document.getElementById('folder-icon-picker');
1500 if (existingIconOverlay) existingIconOverlay.remove();
1501
1502 const overlay = document.createElement('div');
1503 overlay.id = 'folder-icon-picker';
1504 overlay.className = 'modal-overlay';
1505
1506 const modal = document.createElement('div');
1507 modal.className = 'modal folder-icon-modal';
1508
1509 const closeBtn = document.createElement('button');
1510 closeBtn.className = 'modal-close';
1511 closeBtn.setAttribute('aria-label', 'Close');
1512 closeBtn.textContent = '✕';
1513
1514 const title = document.createElement('h2');
1515 title.textContent = 'Set folder icon';
1516
1517 const subtitle = document.createElement('p');
1518 subtitle.className = 'muted';
1519
1520 const grid = document.createElement('div');
1521 grid.className = 'folder-icon-grid';
1522
1523 if (!images.length)
1524 {
1525 subtitle.textContent = 'No images with cached thumbnails were found inside this folder.';
1526 } else
1527 {
1528 subtitle.textContent = 'Select an image to use as the folder icon.';
1529
1530 for (const { filePath } of images)
1531 {
1532 const cell = document.createElement('div');
1533 cell.className = 'folder-icon-cell';
1534 cell.dataset.path = filePath;
1535
1536 const imgEl = document.createElement('img');
1537 imgEl.alt = filePath.split('/').pop();
1538 imgEl.className = 'folder-icon-thumb';
1539 // Lazy-load via IntersectionObserver on the cell.
1540 imgEl.dataset.src = filePath;
1541
1542 const label = document.createElement('div');
1543 label.className = 'folder-icon-label';
1544 label.textContent = filePath.split('/').pop();
1545
1546 cell.appendChild(imgEl);
1547 cell.appendChild(label);
1548
1549 cell.addEventListener('click', () =>
1550 {
1551 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
1552 cell.classList.add('selected');
1553 confirmBtn.disabled = false;
1554 });
1555
1556 grid.appendChild(cell);
1557 }
1558 }
1559
1560 const dialogActions = document.createElement('div');
1561 dialogActions.className = 'dialog-actions';
1562
1563 const clearBtn = document.createElement('button');
1564 clearBtn.textContent = 'Clear icon';
1565 clearBtn.addEventListener('click', async () =>
1566 {
1567 try
1568 {
1569 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
1570 } catch (err)
1571 {
1572 toast('Failed to clear icon: ' + err.message, 'err');
1573 return;
1574 }
1575 hide();
1576 refreshAfterIconChange(item);
1577 });
1578
1579 const cancelBtn = document.createElement('button');
1580 cancelBtn.textContent = 'Cancel';
1581 cancelBtn.addEventListener('click', () => hide());
1582
1583 const confirmBtn = document.createElement('button');
1584 confirmBtn.className = 'primary';
1585 confirmBtn.textContent = 'Set icon';
1586 confirmBtn.disabled = true;
1587 confirmBtn.addEventListener('click', async () =>
1588 {
1589 const selected = grid.querySelector('.folder-icon-cell.selected');
1590 if (!selected) return;
1591 const imagePath = selected.dataset.path;
1592 try
1593 {
1594 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
1595 } catch (err)
1596 {
1597 toast('Failed to set icon: ' + err.message, 'err');
1598 return;
1599 }
1600 hide();
1601 refreshAfterIconChange(item);
1602 });
1603
1604 dialogActions.appendChild(clearBtn);
1605 dialogActions.appendChild(cancelBtn);
1606 dialogActions.appendChild(confirmBtn);
1607
1608 modal.appendChild(closeBtn);
1609 modal.appendChild(title);
1610 modal.appendChild(subtitle);
1611 modal.appendChild(grid);
1612 modal.appendChild(dialogActions);
1613 overlay.appendChild(modal);
1614 document.body.appendChild(overlay);
1615
1616 function hide ()
1617 {
1618 overlay.remove();
1619 // Revoke any blob URLs we created for the picker thumbnails.
1620 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
1621 {
1622 URL.revokeObjectURL(img.src);
1623 });
1624 }
1625
1626 closeBtn.addEventListener('click', hide);
1627 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
1628
1629 // Eagerly load thumbnails for all cells (picker is small, fetch all).
1630 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
1631 {
1632 const imgEl = cell.querySelector('.folder-icon-thumb');
1633 const filePath = imgEl.dataset.src;
1634 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
1635 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
1636 }).then(async (r) =>
1637 {
1638 if (!r.ok || !overlay.isConnected) return;
1639 const blob = await r.blob();
1640 const url = URL.createObjectURL(blob);
1641 imgEl.src = url;
1642 }).catch(() => {});
1643 }
1644 }
1645
1646 function refreshAfterIconChange (item)
1647 {
1648 // Reset and reload icon in grid tiles.
1649 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
1650 .find(el => el.dataset.folderPath === item.path);
1651 if (gridTile)
1652 {
1653 const svg = gridTile.querySelector('svg');
1654 if (svg)
1655 {
1656 // Rebuild to plain folder SVG, then reload.
1657 gridTile.innerHTML = iconFolder();
1658 delete gridTile.dataset.thumbReady;
1659 gridTile.dataset.folderPath = item.path;
1660 void loadOneFolderIcon(gridTile);
1661 }
1662 }
1663
1664 // Also reset the sidebar icon if it's showing the same folder.
1665 const sidebarIcon = document.getElementById('sidebar-icon');
1666 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
1667 {
1668 sidebarIcon.innerHTML = iconFolder(64);
1669 delete sidebarIcon.dataset.thumbReady;
1670 void loadOneFolderIcon(sidebarIcon);
1671 }
1672 }
1673
1460 1674 // ───────────────────────────────────────────────────────────────────────────
1461 1675 // DOWNLOAD / VIEW
1462 1676 // ───────────────────────────────────────────────────────────────────────────
@@ -2669,6 +2883,13 @@ function disconnectThumbnailObserver ()
2669 2883 STATE.thumbnailObserver = null;
2670 2884 }
2671 2885
2886 function disconnectFolderIconObserver ()
2887 {
2888 if (!STATE.folderIconObserver) return;
2889 STATE.folderIconObserver.disconnect();
2890 STATE.folderIconObserver = null;
2891 }
2892
2672 2893 function setThumbnailPending (iconEl, pending)
2673 2894 {
2674 2895 if (!iconEl) return;
@@ -2833,6 +3054,12 @@ async function loadThumbnails ()
2833 3054 {
2834 3055 observeThumbnailIcon(icon);
2835 3056 }
3057
3058 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
3059 for (const icon of folderIcons)
3060 {
3061 observeFolderIcon(icon);
3062 }
2836 3063 }
2837 3064
2838 3065 async function loadOneThumbnail (iconEl)
@@ -2957,6 +3184,122 @@ async function loadOneThumbnail (iconEl)
2957 3184 iconEl.dataset.thumbReady = '1';
2958 3185 }
2959 3186
3187 // ───────────────────────────────────────────────────────────────────────────
3188 // FOLDER ICON THUMBNAILS
3189 // ───────────────────────────────────────────────────────────────────────────
3190
3191 function observeFolderIcon (iconEl)
3192 {
3193 if (!iconEl || !iconEl.isConnected) return;
3194 if (iconEl.dataset.thumbReady === '1') return;
3195
3196 if (!('IntersectionObserver' in window))
3197 {
3198 void loadOneFolderIcon(iconEl);
3199 return;
3200 }
3201
3202 if (!STATE.folderIconObserver)
3203 {
3204 STATE.folderIconObserver = new IntersectionObserver((entries) =>
3205 {
3206 for (const entry of entries)
3207 {
3208 if (!entry.isIntersecting) continue;
3209 const icon = entry.target;
3210 STATE.folderIconObserver.unobserve(icon);
3211 void loadOneFolderIcon(icon);
3212 }
3213 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
3214 }
3215
3216 STATE.folderIconObserver.observe(iconEl);
3217 }
3218
3219 async function loadOneFolderIcon (iconEl)
3220 {
3221 if (!iconEl.isConnected || !STATE.token) return;
3222 if (iconEl.dataset.thumbReady === '1') return;
3223
3224 const folderPath = iconEl.dataset.folderPath;
3225 if (!folderPath) return;
3226
3227 let res;
3228 try
3229 {
3230 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
3231 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3232 });
3233 } catch { return; }
3234
3235 if (!res.ok || !iconEl.isConnected) return;
3236
3237 const data = await res.json();
3238 if (!data.icon) return; // No icon available — keep plain folder SVG.
3239
3240 // Fetch the thumbnail through the auth-gated endpoint.
3241 let thumbRes;
3242 try
3243 {
3244 thumbRes = await fetch(
3245 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
3246 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
3247 );
3248 } catch { return; }
3249
3250 if (!thumbRes.ok || !iconEl.isConnected) return;
3251
3252 const blob = await thumbRes.blob();
3253 const srcUrl = URL.createObjectURL(blob);
3254 STATE.thumbnailUrls.push(srcUrl);
3255
3256 applyFolderThumbnail(iconEl, srcUrl);
3257 }
3258
3259 /**
3260 * Overlays a thumbnail image inside the folder SVG outline.
3261 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
3262 */
3263 function applyFolderThumbnail (iconEl, srcUrl)
3264 {
3265 if (!iconEl.isConnected) return;
3266 const svg = iconEl.querySelector('svg');
3267 if (!svg)
3268 {
3269 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
3270 return;
3271 }
3272
3273 const NS = 'http://www.w3.org/2000/svg';
3274 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
3275
3276 const defs = document.createElementNS(NS, 'defs');
3277 const clipPath = document.createElementNS(NS, 'clipPath');
3278 clipPath.setAttribute('id', id);
3279 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
3280 const clipShape = document.createElementNS(NS, 'path');
3281 // Folder outline path (same as iconFolder SVG path)
3282 clipShape.setAttribute('d', 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z');
3283 clipPath.appendChild(clipShape);
3284 defs.appendChild(clipPath);
3285
3286 // Image covers the folder body area; clip keeps it inside the outline.
3287 const img = document.createElementNS(NS, 'image');
3288 img.setAttribute('href', srcUrl);
3289 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
3290 img.setAttribute('x', '2');
3291 img.setAttribute('y', '3');
3292 img.setAttribute('width', '20');
3293 img.setAttribute('height', '18');
3294 img.setAttribute('clip-path', `url(#${id})`);
3295 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
3296
3297 // Prepend so the folder outline strokes render on top.
3298 svg.prepend(img);
3299 svg.prepend(defs);
3300 iconEl.dataset.thumbReady = '1';
3301 }
3302
2960 3303 function wireEvents ()
2961 3304 {
2962 3305 // Auth form
@@ -44,6 +44,7 @@ const STATE = {
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 thumbnailUrls: [],
45 thumbnailUrls: [],
46 thumbnailObserver: null,
46 thumbnailObserver: null,
47 folderIconObserver: null,
47
48
48 // Preview overlay state
49 // Preview overlay state
49 previewObjectUrl: null,
50 previewObjectUrl: null,
@@ -888,6 +889,7 @@ function stopAutoRefresh ()
888function renderFileGrid ()
889function renderFileGrid ()
889{
890{
890 disconnectThumbnailObserver();
891 disconnectThumbnailObserver();
892 disconnectFolderIconObserver();
891 revokeThumbnails();
893 revokeThumbnails();
892 const grid = document.getElementById('file-grid');
894 const grid = document.getElementById('file-grid');
893 grid.innerHTML = '';
895 grid.innerHTML = '';
@@ -922,6 +924,9 @@ function makeFileItem (item)
922 if (!item.isDir)
924 if (!item.isDir)
923 {
925 {
924 icon.dataset.previewPath = item.path;
926 icon.dataset.previewPath = item.path;
927 } else
928 {
929 icon.dataset.folderPath = item.path;
925 }
930 }
926 el.appendChild(icon);
931 el.appendChild(icon);
927
932
@@ -1052,6 +1057,13 @@ async function openSidebar (item)
1052 document.getElementById('app').classList.add('sidebar-open');
1057 document.getElementById('app').classList.add('sidebar-open');
1053
1058
1054 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
1059 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
1060 if (item.isDir)
1061 {
1062 document.getElementById('sidebar-icon').dataset.folderPath = item.path;
1063 } else
1064 {
1065 delete document.getElementById('sidebar-icon').dataset.folderPath;
1066 }
1055 document.getElementById('sidebar-name').textContent = item.name;
1067 document.getElementById('sidebar-name').textContent = item.name;
1056
1068
1057 // Load metadata
1069 // Load metadata
@@ -1119,11 +1131,22 @@ async function openSidebar (item)
1119 btnOpen.textContent = 'Open folder';
1131 btnOpen.textContent = 'Open folder';
1120 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
1132 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
1121 actions.appendChild(btnOpen);
1133 actions.appendChild(btnOpen);
1134
1135 // Load folder icon thumbnail into the sidebar icon element.
1136 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
1122 }
1137 }
1123
1138
1124 // Rename button (write access required)
1139 // Rename button (write access required)
1125 if (canWrite(item))
1140 if (canWrite(item))
1126 {
1141 {
1142 if (item.isDir)
1143 {
1144 const btnSetIcon = document.createElement('button');
1145 btnSetIcon.textContent = 'Set icon';
1146 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
1147 actions.appendChild(btnSetIcon);
1148 }
1149
1127 if (!item._root)
1150 if (!item._root)
1128 {
1151 {
1129 const btnMove = document.createElement('button');
1152 const btnMove = document.createElement('button');
@@ -1457,6 +1480,197 @@ function openMovePicker (item)
1457 overlay.classList.remove('hidden');
1480 overlay.classList.remove('hidden');
1458}
1481}
1459
1482
1483// ───────────────────────────────────────────────────────────────────────────
1484// FOLDER ICON PICKER
1485// ───────────────────────────────────────────────────────────────────────────
1486
1487async function openFolderIconPicker (item)
1488{
1489 if (!canWrite(item))
1490 {
1491 toast('No write access.', 'err');
1492 return;
1493 }
1494
1495 // Fetch the list of available images (only those with cached thumbnails).
1496 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1497 const images = data ? data.images : [];
1498
1499 let existingIconOverlay = document.getElementById('folder-icon-picker');
1500 if (existingIconOverlay) existingIconOverlay.remove();
1501
1502 const overlay = document.createElement('div');
1503 overlay.id = 'folder-icon-picker';
1504 overlay.className = 'modal-overlay';
1505
1506 const modal = document.createElement('div');
1507 modal.className = 'modal folder-icon-modal';
1508
1509 const closeBtn = document.createElement('button');
1510 closeBtn.className = 'modal-close';
1511 closeBtn.setAttribute('aria-label', 'Close');
1512 closeBtn.textContent = '✕';
1513
1514 const title = document.createElement('h2');
1515 title.textContent = 'Set folder icon';
1516
1517 const subtitle = document.createElement('p');
1518 subtitle.className = 'muted';
1519
1520 const grid = document.createElement('div');
1521 grid.className = 'folder-icon-grid';
1522
1523 if (!images.length)
1524 {
1525 subtitle.textContent = 'No images with cached thumbnails were found inside this folder.';
1526 } else
1527 {
1528 subtitle.textContent = 'Select an image to use as the folder icon.';
1529
1530 for (const { filePath } of images)
1531 {
1532 const cell = document.createElement('div');
1533 cell.className = 'folder-icon-cell';
1534 cell.dataset.path = filePath;
1535
1536 const imgEl = document.createElement('img');
1537 imgEl.alt = filePath.split('/').pop();
1538 imgEl.className = 'folder-icon-thumb';
1539 // Lazy-load via IntersectionObserver on the cell.
1540 imgEl.dataset.src = filePath;
1541
1542 const label = document.createElement('div');
1543 label.className = 'folder-icon-label';
1544 label.textContent = filePath.split('/').pop();
1545
1546 cell.appendChild(imgEl);
1547 cell.appendChild(label);
1548
1549 cell.addEventListener('click', () =>
1550 {
1551 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
1552 cell.classList.add('selected');
1553 confirmBtn.disabled = false;
1554 });
1555
1556 grid.appendChild(cell);
1557 }
1558 }
1559
1560 const dialogActions = document.createElement('div');
1561 dialogActions.className = 'dialog-actions';
1562
1563 const clearBtn = document.createElement('button');
1564 clearBtn.textContent = 'Clear icon';
1565 clearBtn.addEventListener('click', async () =>
1566 {
1567 try
1568 {
1569 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
1570 } catch (err)
1571 {
1572 toast('Failed to clear icon: ' + err.message, 'err');
1573 return;
1574 }
1575 hide();
1576 refreshAfterIconChange(item);
1577 });
1578
1579 const cancelBtn = document.createElement('button');
1580 cancelBtn.textContent = 'Cancel';
1581 cancelBtn.addEventListener('click', () => hide());
1582
1583 const confirmBtn = document.createElement('button');
1584 confirmBtn.className = 'primary';
1585 confirmBtn.textContent = 'Set icon';
1586 confirmBtn.disabled = true;
1587 confirmBtn.addEventListener('click', async () =>
1588 {
1589 const selected = grid.querySelector('.folder-icon-cell.selected');
1590 if (!selected) return;
1591 const imagePath = selected.dataset.path;
1592 try
1593 {
1594 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
1595 } catch (err)
1596 {
1597 toast('Failed to set icon: ' + err.message, 'err');
1598 return;
1599 }
1600 hide();
1601 refreshAfterIconChange(item);
1602 });
1603
1604 dialogActions.appendChild(clearBtn);
1605 dialogActions.appendChild(cancelBtn);
1606 dialogActions.appendChild(confirmBtn);
1607
1608 modal.appendChild(closeBtn);
1609 modal.appendChild(title);
1610 modal.appendChild(subtitle);
1611 modal.appendChild(grid);
1612 modal.appendChild(dialogActions);
1613 overlay.appendChild(modal);
1614 document.body.appendChild(overlay);
1615
1616 function hide ()
1617 {
1618 overlay.remove();
1619 // Revoke any blob URLs we created for the picker thumbnails.
1620 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
1621 {
1622 URL.revokeObjectURL(img.src);
1623 });
1624 }
1625
1626 closeBtn.addEventListener('click', hide);
1627 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
1628
1629 // Eagerly load thumbnails for all cells (picker is small, fetch all).
1630 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
1631 {
1632 const imgEl = cell.querySelector('.folder-icon-thumb');
1633 const filePath = imgEl.dataset.src;
1634 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
1635 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
1636 }).then(async (r) =>
1637 {
1638 if (!r.ok || !overlay.isConnected) return;
1639 const blob = await r.blob();
1640 const url = URL.createObjectURL(blob);
1641 imgEl.src = url;
1642 }).catch(() => {});
1643 }
1644}
1645
1646function refreshAfterIconChange (item)
1647{
1648 // Reset and reload icon in grid tiles.
1649 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
1650 .find(el => el.dataset.folderPath === item.path);
1651 if (gridTile)
1652 {
1653 const svg = gridTile.querySelector('svg');
1654 if (svg)
1655 {
1656 // Rebuild to plain folder SVG, then reload.
1657 gridTile.innerHTML = iconFolder();
1658 delete gridTile.dataset.thumbReady;
1659 gridTile.dataset.folderPath = item.path;
1660 void loadOneFolderIcon(gridTile);
1661 }
1662 }
1663
1664 // Also reset the sidebar icon if it's showing the same folder.
1665 const sidebarIcon = document.getElementById('sidebar-icon');
1666 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
1667 {
1668 sidebarIcon.innerHTML = iconFolder(64);
1669 delete sidebarIcon.dataset.thumbReady;
1670 void loadOneFolderIcon(sidebarIcon);
1671 }
1672}
1673
1460// ───────────────────────────────────────────────────────────────────────────
1674// ───────────────────────────────────────────────────────────────────────────
1461// DOWNLOAD / VIEW
1675// DOWNLOAD / VIEW
1462// ───────────────────────────────────────────────────────────────────────────
1676// ───────────────────────────────────────────────────────────────────────────
@@ -2669,6 +2883,13 @@ function disconnectThumbnailObserver ()
2669 STATE.thumbnailObserver = null;
2883 STATE.thumbnailObserver = null;
2670}
2884}
2671
2885
2886function disconnectFolderIconObserver ()
2887{
2888 if (!STATE.folderIconObserver) return;
2889 STATE.folderIconObserver.disconnect();
2890 STATE.folderIconObserver = null;
2891}
2892
2672function setThumbnailPending (iconEl, pending)
2893function setThumbnailPending (iconEl, pending)
2673{
2894{
2674 if (!iconEl) return;
2895 if (!iconEl) return;
@@ -2833,6 +3054,12 @@ async function loadThumbnails ()
2833 {
3054 {
2834 observeThumbnailIcon(icon);
3055 observeThumbnailIcon(icon);
2835 }
3056 }
3057
3058 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
3059 for (const icon of folderIcons)
3060 {
3061 observeFolderIcon(icon);
3062 }
2836}
3063}
2837
3064
2838async function loadOneThumbnail (iconEl)
3065async function loadOneThumbnail (iconEl)
@@ -2957,6 +3184,122 @@ async function loadOneThumbnail (iconEl)
2957 iconEl.dataset.thumbReady = '1';
3184 iconEl.dataset.thumbReady = '1';
2958}
3185}
2959
3186
3187// ───────────────────────────────────────────────────────────────────────────
3188// FOLDER ICON THUMBNAILS
3189// ───────────────────────────────────────────────────────────────────────────
3190
3191function observeFolderIcon (iconEl)
3192{
3193 if (!iconEl || !iconEl.isConnected) return;
3194 if (iconEl.dataset.thumbReady === '1') return;
3195
3196 if (!('IntersectionObserver' in window))
3197 {
3198 void loadOneFolderIcon(iconEl);
3199 return;
3200 }
3201
3202 if (!STATE.folderIconObserver)
3203 {
3204 STATE.folderIconObserver = new IntersectionObserver((entries) =>
3205 {
3206 for (const entry of entries)
3207 {
3208 if (!entry.isIntersecting) continue;
3209 const icon = entry.target;
3210 STATE.folderIconObserver.unobserve(icon);
3211 void loadOneFolderIcon(icon);
3212 }
3213 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
3214 }
3215
3216 STATE.folderIconObserver.observe(iconEl);
3217}
3218
3219async function loadOneFolderIcon (iconEl)
3220{
3221 if (!iconEl.isConnected || !STATE.token) return;
3222 if (iconEl.dataset.thumbReady === '1') return;
3223
3224 const folderPath = iconEl.dataset.folderPath;
3225 if (!folderPath) return;
3226
3227 let res;
3228 try
3229 {
3230 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
3231 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3232 });
3233 } catch { return; }
3234
3235 if (!res.ok || !iconEl.isConnected) return;
3236
3237 const data = await res.json();
3238 if (!data.icon) return; // No icon available — keep plain folder SVG.
3239
3240 // Fetch the thumbnail through the auth-gated endpoint.
3241 let thumbRes;
3242 try
3243 {
3244 thumbRes = await fetch(
3245 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
3246 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
3247 );
3248 } catch { return; }
3249
3250 if (!thumbRes.ok || !iconEl.isConnected) return;
3251
3252 const blob = await thumbRes.blob();
3253 const srcUrl = URL.createObjectURL(blob);
3254 STATE.thumbnailUrls.push(srcUrl);
3255
3256 applyFolderThumbnail(iconEl, srcUrl);
3257}
3258
3259/**
3260 * Overlays a thumbnail image inside the folder SVG outline.
3261 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
3262 */
3263function applyFolderThumbnail (iconEl, srcUrl)
3264{
3265 if (!iconEl.isConnected) return;
3266 const svg = iconEl.querySelector('svg');
3267 if (!svg)
3268 {
3269 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
3270 return;
3271 }
3272
3273 const NS = 'http://www.w3.org/2000/svg';
3274 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
3275
3276 const defs = document.createElementNS(NS, 'defs');
3277 const clipPath = document.createElementNS(NS, 'clipPath');
3278 clipPath.setAttribute('id', id);
3279 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
3280 const clipShape = document.createElementNS(NS, 'path');
3281 // Folder outline path (same as iconFolder SVG path)
3282 clipShape.setAttribute('d', 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z');
3283 clipPath.appendChild(clipShape);
3284 defs.appendChild(clipPath);
3285
3286 // Image covers the folder body area; clip keeps it inside the outline.
3287 const img = document.createElementNS(NS, 'image');
3288 img.setAttribute('href', srcUrl);
3289 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
3290 img.setAttribute('x', '2');
3291 img.setAttribute('y', '3');
3292 img.setAttribute('width', '20');
3293 img.setAttribute('height', '18');
3294 img.setAttribute('clip-path', `url(#${id})`);
3295 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
3296
3297 // Prepend so the folder outline strokes render on top.
3298 svg.prepend(img);
3299 svg.prepend(defs);
3300 iconEl.dataset.thumbReady = '1';
3301}
3302
2960function wireEvents ()
3303function wireEvents ()
2961{
3304{
2962 // Auth form
3305 // Auth form
public/style.css +65 −0
@@ -498,6 +498,71 @@ button.danger:hover {
498 498 color: var(--text);
499 499 }
500 500
501 /* =========================================================
502 FOLDER ICON PICKER
503 ========================================================= */
504 .folder-icon-modal {
505 width: min(680px, 94vw);
506 max-height: 90vh;
507 display: flex;
508 flex-direction: column;
509 gap: 0.75rem;
510 overflow: hidden;
511 }
512
513 .folder-icon-grid {
514 display: grid;
515 grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
516 gap: 0.5rem;
517 max-height: 50vh;
518 overflow-y: auto;
519 padding: 0.25rem;
520 background: var(--bg);
521 border: 1px solid var(--border);
522 border-radius: var(--radius);
523 }
524
525 .folder-icon-cell {
526 display: flex;
527 flex-direction: column;
528 align-items: center;
529 gap: 0.3rem;
530 padding: 0.4rem;
531 border-radius: var(--radius);
532 border: 2px solid transparent;
533 cursor: pointer;
534 transition: border-color var(--transition), background var(--transition);
535 }
536
537 .folder-icon-cell:hover {
538 background: var(--surface2);
539 }
540
541 .folder-icon-cell.selected {
542 border-color: var(--accent);
543 background: rgba(91, 127, 255, 0.12);
544 }
545
546 .folder-icon-thumb {
547 width: 60px;
548 height: 60px;
549 object-fit: cover;
550 border-radius: 4px;
551 background: var(--surface2);
552 }
553
554 .folder-icon-label {
555 font-size: 0.68rem;
556 color: var(--text-muted);
557 word-break: break-all;
558 text-align: center;
559 max-width: 72px;
560 overflow: hidden;
561 display: -webkit-box;
562 -webkit-line-clamp: 2;
563 -webkit-box-orient: vertical;
564 }
565
501 566 /* Admin path list */
502 567 .path-row {
503 568 display: flex;
@@ -498,6 +498,71 @@ button.danger:hover {
498 color: var(--text);
498 color: var(--text);
499}
499}
500
500
501/* =========================================================
502 FOLDER ICON PICKER
503 ========================================================= */
504.folder-icon-modal {
505 width: min(680px, 94vw);
506 max-height: 90vh;
507 display: flex;
508 flex-direction: column;
509 gap: 0.75rem;
510 overflow: hidden;
511}
512
513.folder-icon-grid {
514 display: grid;
515 grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
516 gap: 0.5rem;
517 max-height: 50vh;
518 overflow-y: auto;
519 padding: 0.25rem;
520 background: var(--bg);
521 border: 1px solid var(--border);
522 border-radius: var(--radius);
523}
524
525.folder-icon-cell {
526 display: flex;
527 flex-direction: column;
528 align-items: center;
529 gap: 0.3rem;
530 padding: 0.4rem;
531 border-radius: var(--radius);
532 border: 2px solid transparent;
533 cursor: pointer;
534 transition: border-color var(--transition), background var(--transition);
535}
536
537.folder-icon-cell:hover {
538 background: var(--surface2);
539}
540
541.folder-icon-cell.selected {
542 border-color: var(--accent);
543 background: rgba(91, 127, 255, 0.12);
544}
545
546.folder-icon-thumb {
547 width: 60px;
548 height: 60px;
549 object-fit: cover;
550 border-radius: 4px;
551 background: var(--surface2);
552}
553
554.folder-icon-label {
555 font-size: 0.68rem;
556 color: var(--text-muted);
557 word-break: break-all;
558 text-align: center;
559 max-width: 72px;
560 overflow: hidden;
561 display: -webkit-box;
562 -webkit-line-clamp: 2;
563 -webkit-box-orient: vertical;
564}
565
501/* Admin path list */
566/* Admin path list */
502.path-row {
567.path-row {
503 display: flex;
568 display: flex;
server/routes/files.js +94 −1
@@ -9,7 +9,7 @@ const router = express.Router();
9 9 const { getDb } = require('../db');
10 10 const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11 11 const { requireAuth } = require('../auth');
12 const { getCachedThumbnailInfo } = require('../thumbnail-cache');
12 const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
13 13
14 14 // ---------------------------------------------------------------------------
15 15 // Multer storage — files are written directly to the target directory
@@ -749,4 +749,97 @@ router.post('/delete', requireAuth, (req, res) =>
749 749 res.json({ ok: true });
750 750 });
751 751
752 // ---------------------------------------------------------------------------
753 // GET /api/files/folder-images?dir=<absolute-path>
754 // Returns images inside dir (recursive) that already have a cached thumbnail.
755 // Only images with a ready thumbnail are included (user constraint).
756 // ---------------------------------------------------------------------------
757 router.get('/folder-images', requireAuth, async (req, res) =>
758 {
759 const dir = String(req.query.dir || '').trim();
760 if (!dir) return res.status(400).json({ error: 'dir is required.' });
761
762 const roots = effectivePaths();
763 const info = resolveRoot(dir, roots);
764 if (!info || !canRead(req.user, info.label))
765 {
766 return res.status(403).json({ error: 'Access denied.' });
767 }
768
769 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
770 {
771 return res.status(404).json({ error: 'Directory not found.' });
772 }
773
774 const images = await getImagesWithThumbnailsInDir(dir);
775 // Filter out any that escaped to a different root (safety check).
776 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
777
778 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
779 });
780
781 // ---------------------------------------------------------------------------
782 // GET /api/files/folder-icon?dir=<absolute-path>
783 // Returns the current icon source file for a folder (explicit or auto-first).
784 // ---------------------------------------------------------------------------
785 router.get('/folder-icon', requireAuth, async (req, res) =>
786 {
787 const dir = String(req.query.dir || '').trim();
788 if (!dir) return res.status(400).json({ error: 'dir is required.' });
789
790 const roots = effectivePaths();
791 const info = resolveRoot(dir, roots);
792 if (!info || !canRead(req.user, info.label))
793 {
794 return res.status(403).json({ error: 'Access denied.' });
795 }
796
797 const sourceFile = await getFolderIconSourceFile(dir);
798 if (!sourceFile) return res.json({ icon: null });
799
800 // Verify the source is still accessible within a configured root.
801 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
802
803 res.json({ icon: { filePath: sourceFile } });
804 });
805
806 // ---------------------------------------------------------------------------
807 // POST /api/files/folder-icon
808 // Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
809 // Requires write access; the image must already have a cached thumbnail.
810 // ---------------------------------------------------------------------------
811 router.post('/folder-icon', requireAuth, async (req, res) =>
812 {
813 const folderPath = String((req.body && req.body.folderPath) || '').trim();
814 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
815
816 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
817
818 const roots = effectivePaths();
819 const info = resolveRoot(folderPath, roots);
820 if (!info || !canWrite(req.user, info.label))
821 {
822 return res.status(403).json({ error: 'Access denied.' });
823 }
824
825 let stat;
826 try { stat = fs.statSync(folderPath); }
827 catch { return res.status(404).json({ error: 'Folder not found.' }); }
828 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
829
830 if (rawImage !== null)
831 {
832 // Verify the image is inside a readable root.
833 const imageRoot = getAllowedRoot(rawImage, roots);
834 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
835
836 // Must already have a cached thumbnail — only thumbnailed images can be selected.
837 const thumb = await getCachedThumbnailInfo(rawImage);
838 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
839 }
840
841 await setFolderIconAssignment(folderPath, rawImage);
842 res.json({ ok: true });
843 });
844
752 845 module.exports = router;
@@ -9,7 +9,7 @@ const router = express.Router();
9const { getDb } = require('../db');
9const { getDb } = require('../db');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
11const { requireAuth } = require('../auth');
12const { getCachedThumbnailInfo } = require('../thumbnail-cache');
12const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
13
13
14// ---------------------------------------------------------------------------
14// ---------------------------------------------------------------------------
15// Multer storage — files are written directly to the target directory
15// Multer storage — files are written directly to the target directory
@@ -749,4 +749,97 @@ router.post('/delete', requireAuth, (req, res) =>
749 res.json({ ok: true });
749 res.json({ ok: true });
750});
750});
751
751
752// ---------------------------------------------------------------------------
753// GET /api/files/folder-images?dir=<absolute-path>
754// Returns images inside dir (recursive) that already have a cached thumbnail.
755// Only images with a ready thumbnail are included (user constraint).
756// ---------------------------------------------------------------------------
757router.get('/folder-images', requireAuth, async (req, res) =>
758{
759 const dir = String(req.query.dir || '').trim();
760 if (!dir) return res.status(400).json({ error: 'dir is required.' });
761
762 const roots = effectivePaths();
763 const info = resolveRoot(dir, roots);
764 if (!info || !canRead(req.user, info.label))
765 {
766 return res.status(403).json({ error: 'Access denied.' });
767 }
768
769 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
770 {
771 return res.status(404).json({ error: 'Directory not found.' });
772 }
773
774 const images = await getImagesWithThumbnailsInDir(dir);
775 // Filter out any that escaped to a different root (safety check).
776 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
777
778 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
779});
780
781// ---------------------------------------------------------------------------
782// GET /api/files/folder-icon?dir=<absolute-path>
783// Returns the current icon source file for a folder (explicit or auto-first).
784// ---------------------------------------------------------------------------
785router.get('/folder-icon', requireAuth, async (req, res) =>
786{
787 const dir = String(req.query.dir || '').trim();
788 if (!dir) return res.status(400).json({ error: 'dir is required.' });
789
790 const roots = effectivePaths();
791 const info = resolveRoot(dir, roots);
792 if (!info || !canRead(req.user, info.label))
793 {
794 return res.status(403).json({ error: 'Access denied.' });
795 }
796
797 const sourceFile = await getFolderIconSourceFile(dir);
798 if (!sourceFile) return res.json({ icon: null });
799
800 // Verify the source is still accessible within a configured root.
801 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
802
803 res.json({ icon: { filePath: sourceFile } });
804});
805
806// ---------------------------------------------------------------------------
807// POST /api/files/folder-icon
808// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
809// Requires write access; the image must already have a cached thumbnail.
810// ---------------------------------------------------------------------------
811router.post('/folder-icon', requireAuth, async (req, res) =>
812{
813 const folderPath = String((req.body && req.body.folderPath) || '').trim();
814 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
815
816 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
817
818 const roots = effectivePaths();
819 const info = resolveRoot(folderPath, roots);
820 if (!info || !canWrite(req.user, info.label))
821 {
822 return res.status(403).json({ error: 'Access denied.' });
823 }
824
825 let stat;
826 try { stat = fs.statSync(folderPath); }
827 catch { return res.status(404).json({ error: 'Folder not found.' }); }
828 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
829
830 if (rawImage !== null)
831 {
832 // Verify the image is inside a readable root.
833 const imageRoot = getAllowedRoot(rawImage, roots);
834 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
835
836 // Must already have a cached thumbnail — only thumbnailed images can be selected.
837 const thumb = await getCachedThumbnailInfo(rawImage);
838 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
839 }
840
841 await setFolderIconAssignment(folderPath, rawImage);
842 res.json({ ok: true });
843});
844
752module.exports = router;
845module.exports = router;
server/thumbnail-cache.js +104 −0
@@ -10,6 +10,7 @@ const { loadConfig, getEffectivePaths } = require('./config');
10 10 const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
11 11 const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
12 12 const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
13 const FOLDER_ICONS_PATH = path.join(THUMBS_DIR, '.folder-icons.json');
13 14 const LOOP_DELAY_MS = 5000;
14 15
15 16 const IMAGE_EXTS = new Set([
@@ -356,10 +357,113 @@ async function getCachedThumbnailInfo (sourceFile)
356 357 };
357 358 }
358 359
360 // ---------------------------------------------------------------------------
361 // Folder icon assignments — stored in .folder-icons.json
362 // ---------------------------------------------------------------------------
363
364 async function readFolderIcons ()
365 {
366 try
367 {
368 const raw = await fs.promises.readFile(FOLDER_ICONS_PATH, 'utf8');
369 const parsed = JSON.parse(raw);
370 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
371 } catch
372 {
373 // Missing or malformed — treat as empty.
374 }
375 return {};
376 }
377
378 async function writeFolderIcons (obj)
379 {
380 await ensureDir(THUMBS_DIR);
381 const payload = JSON.stringify(obj, null, 2);
382 const tmp = FOLDER_ICONS_PATH + '.tmp';
383 await fs.promises.writeFile(tmp, payload, 'utf8');
384 await fs.promises.rename(tmp, FOLDER_ICONS_PATH);
385 }
386
387 /**
388 * Returns all images inside `dirPath` (recursive) that have a cached thumbnail,
389 * sorted lexicographically by absolute file path.
390 * Each element: { filePath: string, thumbRelPath: string }
391 */
392 async function getImagesWithThumbnailsInDir (dirPath)
393 {
394 const manifest = await readManifest();
395 const resolved = path.resolve(dirPath);
396 const results = [];
397
398 for (const [filePath, meta] of Object.entries(manifest.files || {}))
399 {
400 const resolvedFile = path.resolve(filePath);
401 const relative = path.relative(resolved, resolvedFile);
402 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) continue;
403 if (!meta || !meta.thumbRelPath) continue;
404
405 // Verify the thumbnail file actually exists on disk.
406 const thumbPath = path.resolve(path.join(PUBLIC_DIR, meta.thumbRelPath));
407 if (!(await exists(thumbPath))) continue;
408
409 results.push({ filePath, thumbRelPath: meta.thumbRelPath });
410 }
411
412 results.sort((a, b) => a.filePath.localeCompare(b.filePath));
413 return results;
414 }
415
416 /**
417 * Returns the source image file path used as the icon for `folderPath`.
418 * Looks up the explicit assignment first; falls back to the first cached image found.
419 * Returns null when no images with cached thumbnails exist inside the folder.
420 */
421 async function getFolderIconSourceFile (folderPath)
422 {
423 const resolved = path.resolve(folderPath);
424 const icons = await readFolderIcons();
425
426 if (icons[resolved])
427 {
428 const assigned = icons[resolved];
429 // Verify the assigned image still has a cached thumbnail.
430 const thumbPath = getThumbPathForSourceFile(assigned);
431 if (await exists(thumbPath)) return assigned;
432 // Stale — fall through to auto-detect.
433 }
434
435 // Auto: first cached image inside the folder.
436 const images = await getImagesWithThumbnailsInDir(folderPath);
437 return images.length ? images[0].filePath : null;
438 }
439
440 /**
441 * Saves an explicit folder icon assignment.
442 * Pass `imagePath = null` to clear the explicit assignment (auto-detect will be used instead).
443 */
444 async function setFolderIconAssignment (folderPath, imagePath)
445 {
446 const resolved = path.resolve(folderPath);
447 const icons = await readFolderIcons();
448
449 if (imagePath === null || imagePath === undefined)
450 {
451 delete icons[resolved];
452 } else
453 {
454 icons[resolved] = imagePath;
455 }
456
457 await writeFolderIcons(icons);
458 }
459
359 460 module.exports = {
360 461 getCachedThumbnailInfo,
361 462 getThumbPathForSourceFile,
362 463 getThumbRelPathForSourceFile,
464 getImagesWithThumbnailsInDir,
465 getFolderIconSourceFile,
466 setFolderIconAssignment,
363 467 startThumbnailCacheLoop,
364 468 stopThumbnailCacheLoop,
365 469 syncThumbnailCacheOnce,
@@ -10,6 +10,7 @@ const { loadConfig, getEffectivePaths } = require('./config');
10const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
10const PUBLIC_DIR = path.resolve(process.env.FILEMANAGER_PUBLIC_DIR || path.join(__dirname, '../public'));
11const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
11const THUMBS_DIR = path.resolve(process.env.FILEMANAGER_THUMBS_DIR || path.join(PUBLIC_DIR, 'thumbs'));
12const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
12const MANIFEST_PATH = path.join(THUMBS_DIR, '.manifest.json');
13const FOLDER_ICONS_PATH = path.join(THUMBS_DIR, '.folder-icons.json');
13const LOOP_DELAY_MS = 5000;
14const LOOP_DELAY_MS = 5000;
14
15
15const IMAGE_EXTS = new Set([
16const IMAGE_EXTS = new Set([
@@ -356,10 +357,113 @@ async function getCachedThumbnailInfo (sourceFile)
356 };
357 };
357}
358}
358
359
360// ---------------------------------------------------------------------------
361// Folder icon assignments — stored in .folder-icons.json
362// ---------------------------------------------------------------------------
363
364async function readFolderIcons ()
365{
366 try
367 {
368 const raw = await fs.promises.readFile(FOLDER_ICONS_PATH, 'utf8');
369 const parsed = JSON.parse(raw);
370 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
371 } catch
372 {
373 // Missing or malformed — treat as empty.
374 }
375 return {};
376}
377
378async function writeFolderIcons (obj)
379{
380 await ensureDir(THUMBS_DIR);
381 const payload = JSON.stringify(obj, null, 2);
382 const tmp = FOLDER_ICONS_PATH + '.tmp';
383 await fs.promises.writeFile(tmp, payload, 'utf8');
384 await fs.promises.rename(tmp, FOLDER_ICONS_PATH);
385}
386
387/**
388 * Returns all images inside `dirPath` (recursive) that have a cached thumbnail,
389 * sorted lexicographically by absolute file path.
390 * Each element: { filePath: string, thumbRelPath: string }
391 */
392async function getImagesWithThumbnailsInDir (dirPath)
393{
394 const manifest = await readManifest();
395 const resolved = path.resolve(dirPath);
396 const results = [];
397
398 for (const [filePath, meta] of Object.entries(manifest.files || {}))
399 {
400 const resolvedFile = path.resolve(filePath);
401 const relative = path.relative(resolved, resolvedFile);
402 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) continue;
403 if (!meta || !meta.thumbRelPath) continue;
404
405 // Verify the thumbnail file actually exists on disk.
406 const thumbPath = path.resolve(path.join(PUBLIC_DIR, meta.thumbRelPath));
407 if (!(await exists(thumbPath))) continue;
408
409 results.push({ filePath, thumbRelPath: meta.thumbRelPath });
410 }
411
412 results.sort((a, b) => a.filePath.localeCompare(b.filePath));
413 return results;
414}
415
416/**
417 * Returns the source image file path used as the icon for `folderPath`.
418 * Looks up the explicit assignment first; falls back to the first cached image found.
419 * Returns null when no images with cached thumbnails exist inside the folder.
420 */
421async function getFolderIconSourceFile (folderPath)
422{
423 const resolved = path.resolve(folderPath);
424 const icons = await readFolderIcons();
425
426 if (icons[resolved])
427 {
428 const assigned = icons[resolved];
429 // Verify the assigned image still has a cached thumbnail.
430 const thumbPath = getThumbPathForSourceFile(assigned);
431 if (await exists(thumbPath)) return assigned;
432 // Stale — fall through to auto-detect.
433 }
434
435 // Auto: first cached image inside the folder.
436 const images = await getImagesWithThumbnailsInDir(folderPath);
437 return images.length ? images[0].filePath : null;
438}
439
440/**
441 * Saves an explicit folder icon assignment.
442 * Pass `imagePath = null` to clear the explicit assignment (auto-detect will be used instead).
443 */
444async function setFolderIconAssignment (folderPath, imagePath)
445{
446 const resolved = path.resolve(folderPath);
447 const icons = await readFolderIcons();
448
449 if (imagePath === null || imagePath === undefined)
450 {
451 delete icons[resolved];
452 } else
453 {
454 icons[resolved] = imagePath;
455 }
456
457 await writeFolderIcons(icons);
458}
459
359module.exports = {
460module.exports = {
360 getCachedThumbnailInfo,
461 getCachedThumbnailInfo,
361 getThumbPathForSourceFile,
462 getThumbPathForSourceFile,
362 getThumbRelPathForSourceFile,
463 getThumbRelPathForSourceFile,
464 getImagesWithThumbnailsInDir,
465 getFolderIconSourceFile,
466 setFolderIconAssignment,
363 startThumbnailCacheLoop,
467 startThumbnailCacheLoop,
364 stopThumbnailCacheLoop,
468 stopThumbnailCacheLoop,
365 syncThumbnailCacheOnce,
469 syncThumbnailCacheOnce,
tests/files.routes.test.js +120 −0
@@ -11,6 +11,9 @@ let mockPaths = [];
11 11 let mockRootAliases = {};
12 12 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13 13 let mockThumbPath = null;
14 let mockFolderImages = [];
15 let mockFolderIconFile = null;
16 let lastFolderIconAssignment = undefined;
14 17
15 18 jest.mock('../server/db', () =>
16 19 {
@@ -71,6 +74,12 @@ jest.mock('../server/thumbnail-cache', () => ({
71 74 if (!mockThumbPath) return null;
72 75 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
73 76 },
77 getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(),
78 getFolderIconSourceFile: async () => mockFolderIconFile,
79 setFolderIconAssignment: async (folderPath, imagePath) =>
80 {
81 lastFolderIconAssignment = { folderPath, imagePath };
82 },
74 83 }));
75 84
76 85 const filesRoutes = require('../server/routes/files');
@@ -112,6 +121,9 @@ beforeEach(() =>
112 121 mockRootAliases = {};
113 122 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
114 123 mockThumbPath = null;
124 mockFolderImages = [];
125 mockFolderIconFile = null;
126 lastFolderIconAssignment = undefined;
115 127 const db = getDb();
116 128 db.prepare('DELETE FROM file_meta').run([]);
117 129 db.prepare('DELETE FROM users').run([]);
@@ -335,3 +347,111 @@ describe('GET /api/files/root-access', () =>
335 347 expect(status).toBe(400);
336 348 });
337 349 });
350
351 describe('folder icon endpoints', () =>
352 {
353 test('GET /api/files/folder-images returns images that have cached thumbnails', async () =>
354 {
355 const subDir = path.join(rootDir, 'photos');
356 fs.mkdirSync(subDir);
357 const imgPath = path.join(subDir, 'a.jpg');
358 fs.writeFileSync(imgPath, 'img');
359
360 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
361
362 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
363 expect(status).toBe(200);
364 expect(body.images).toHaveLength(1);
365 expect(body.images[0].filePath).toBe(imgPath);
366 });
367
368 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
369 {
370 mockFolderImages = [];
371
372 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
373 expect(status).toBe(200);
374 expect(body.images).toEqual([]);
375 });
376
377 test('GET /api/files/folder-icon returns null when no icon available', async () =>
378 {
379 mockFolderIconFile = null;
380
381 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
382 expect(status).toBe(200);
383 expect(body.icon).toBeNull();
384 });
385
386 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
387 {
388 const imgPath = path.join(rootDir, 'cover.jpg');
389 fs.writeFileSync(imgPath, 'img');
390 mockFolderIconFile = imgPath;
391
392 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
393 expect(status).toBe(200);
394 expect(body.icon).toMatchObject({ filePath: imgPath });
395 });
396
397 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
398 {
399 const imgPath = path.join(rootDir, 'cover.jpg');
400 const thumbFile = path.join(rootDir, 'cover.webp');
401 fs.writeFileSync(imgPath, 'img');
402 fs.writeFileSync(thumbFile, 'webp');
403 mockThumbPath = thumbFile;
404
405 const { status, body } = await req('POST', '/api/files/folder-icon', {
406 folderPath: rootDir,
407 imagePath: imgPath,
408 });
409 expect(status).toBe(200);
410 expect(body.ok).toBe(true);
411 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
412 });
413
414 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
415 {
416 const imgPath = path.join(rootDir, 'missing.jpg');
417 fs.writeFileSync(imgPath, 'img');
418 mockThumbPath = null;
419
420 const { status, body } = await req('POST', '/api/files/folder-icon', {
421 folderPath: rootDir,
422 imagePath: imgPath,
423 });
424 expect(status).toBe(404);
425 expect(body.error).toMatch(/thumbnail not ready/i);
426 });
427
428 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
429 {
430 const { status, body } = await req('POST', '/api/files/folder-icon', {
431 folderPath: rootDir,
432 imagePath: null,
433 });
434 expect(status).toBe(200);
435 expect(body.ok).toBe(true);
436 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
437 });
438
439 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
440 {
441 const label = path.basename(rootDir);
442 mockUser = {
443 username: 'reader',
444 isAdmin: false,
445 permissions: { [label]: { read: true, write: false } },
446 };
447
448 const imgPath = path.join(rootDir, 'photo.jpg');
449 fs.writeFileSync(imgPath, 'img');
450
451 const { status } = await req('POST', '/api/files/folder-icon', {
452 folderPath: rootDir,
453 imagePath: imgPath,
454 });
455 expect(status).toBe(403);
456 });
457 });
@@ -11,6 +11,9 @@ let mockPaths = [];
11let mockRootAliases = {};
11let mockRootAliases = {};
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockThumbPath = null;
13let mockThumbPath = null;
14let mockFolderImages = [];
15let mockFolderIconFile = null;
16let lastFolderIconAssignment = undefined;
14
17
15jest.mock('../server/db', () =>
18jest.mock('../server/db', () =>
16{
19{
@@ -71,6 +74,12 @@ jest.mock('../server/thumbnail-cache', () => ({
71 if (!mockThumbPath) return null;
74 if (!mockThumbPath) return null;
72 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
75 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
73 },
76 },
77 getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(),
78 getFolderIconSourceFile: async () => mockFolderIconFile,
79 setFolderIconAssignment: async (folderPath, imagePath) =>
80 {
81 lastFolderIconAssignment = { folderPath, imagePath };
82 },
74}));
83}));
75
84
76const filesRoutes = require('../server/routes/files');
85const filesRoutes = require('../server/routes/files');
@@ -112,6 +121,9 @@ beforeEach(() =>
112 mockRootAliases = {};
121 mockRootAliases = {};
113 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
122 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
114 mockThumbPath = null;
123 mockThumbPath = null;
124 mockFolderImages = [];
125 mockFolderIconFile = null;
126 lastFolderIconAssignment = undefined;
115 const db = getDb();
127 const db = getDb();
116 db.prepare('DELETE FROM file_meta').run([]);
128 db.prepare('DELETE FROM file_meta').run([]);
117 db.prepare('DELETE FROM users').run([]);
129 db.prepare('DELETE FROM users').run([]);
@@ -335,3 +347,111 @@ describe('GET /api/files/root-access', () =>
335 expect(status).toBe(400);
347 expect(status).toBe(400);
336 });
348 });
337});
349});
350
351describe('folder icon endpoints', () =>
352{
353 test('GET /api/files/folder-images returns images that have cached thumbnails', async () =>
354 {
355 const subDir = path.join(rootDir, 'photos');
356 fs.mkdirSync(subDir);
357 const imgPath = path.join(subDir, 'a.jpg');
358 fs.writeFileSync(imgPath, 'img');
359
360 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
361
362 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
363 expect(status).toBe(200);
364 expect(body.images).toHaveLength(1);
365 expect(body.images[0].filePath).toBe(imgPath);
366 });
367
368 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
369 {
370 mockFolderImages = [];
371
372 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
373 expect(status).toBe(200);
374 expect(body.images).toEqual([]);
375 });
376
377 test('GET /api/files/folder-icon returns null when no icon available', async () =>
378 {
379 mockFolderIconFile = null;
380
381 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
382 expect(status).toBe(200);
383 expect(body.icon).toBeNull();
384 });
385
386 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
387 {
388 const imgPath = path.join(rootDir, 'cover.jpg');
389 fs.writeFileSync(imgPath, 'img');
390 mockFolderIconFile = imgPath;
391
392 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
393 expect(status).toBe(200);
394 expect(body.icon).toMatchObject({ filePath: imgPath });
395 });
396
397 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
398 {
399 const imgPath = path.join(rootDir, 'cover.jpg');
400 const thumbFile = path.join(rootDir, 'cover.webp');
401 fs.writeFileSync(imgPath, 'img');
402 fs.writeFileSync(thumbFile, 'webp');
403 mockThumbPath = thumbFile;
404
405 const { status, body } = await req('POST', '/api/files/folder-icon', {
406 folderPath: rootDir,
407 imagePath: imgPath,
408 });
409 expect(status).toBe(200);
410 expect(body.ok).toBe(true);
411 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
412 });
413
414 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
415 {
416 const imgPath = path.join(rootDir, 'missing.jpg');
417 fs.writeFileSync(imgPath, 'img');
418 mockThumbPath = null;
419
420 const { status, body } = await req('POST', '/api/files/folder-icon', {
421 folderPath: rootDir,
422 imagePath: imgPath,
423 });
424 expect(status).toBe(404);
425 expect(body.error).toMatch(/thumbnail not ready/i);
426 });
427
428 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
429 {
430 const { status, body } = await req('POST', '/api/files/folder-icon', {
431 folderPath: rootDir,
432 imagePath: null,
433 });
434 expect(status).toBe(200);
435 expect(body.ok).toBe(true);
436 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
437 });
438
439 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
440 {
441 const label = path.basename(rootDir);
442 mockUser = {
443 username: 'reader',
444 isAdmin: false,
445 permissions: { [label]: { read: true, write: false } },
446 };
447
448 const imgPath = path.join(rootDir, 'photo.jpg');
449 fs.writeFileSync(imgPath, 'img');
450
451 const { status } = await req('POST', '/api/files/folder-icon', {
452 folderPath: rootDir,
453 imagePath: imgPath,
454 });
455 expect(status).toBe(403);
456 });
457});
tests/page.load.test.js +12 −0
@@ -18,6 +18,7 @@ describe('page load smoke test', () =>
18 18 let meFixture;
19 19 let thumbnailStatusFixture;
20 20 let rootAccessFixture;
21 let folderIconFixture;
21 22 let adminUsersFixture;
22 23 let adminConfigFixture;
23 24 let downloadFixture;
@@ -43,6 +44,7 @@ describe('page load smoke test', () =>
43 44 meFixture = { username: 'tester', isAdmin: false, permissions: {} };
44 45 thumbnailStatusFixture = {};
45 46 rootAccessFixture = {};
47 folderIconFixture = {};
46 48 adminUsersFixture = { users: [] };
47 49 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
48 50 downloadFixture = {};
@@ -98,6 +100,16 @@ describe('page load smoke test', () =>
98 100 const rootPath = String(req.query.rootPath || '');
99 101 res.json({ users: rootAccessFixture[rootPath] || [] });
100 102 });
103 app.get('/api/files/folder-icon', (req, res) =>
104 {
105 const dir = String(req.query.dir || '');
106 const icon = folderIconFixture[dir] || null;
107 res.json({ icon });
108 });
109 app.get('/api/files/folder-images', (req, res) =>
110 {
111 res.json({ images: [] });
112 });
101 113 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
102 114 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
103 115 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
@@ -18,6 +18,7 @@ describe('page load smoke test', () =>
18 let meFixture;
18 let meFixture;
19 let thumbnailStatusFixture;
19 let thumbnailStatusFixture;
20 let rootAccessFixture;
20 let rootAccessFixture;
21 let folderIconFixture;
21 let adminUsersFixture;
22 let adminUsersFixture;
22 let adminConfigFixture;
23 let adminConfigFixture;
23 let downloadFixture;
24 let downloadFixture;
@@ -43,6 +44,7 @@ describe('page load smoke test', () =>
43 meFixture = { username: 'tester', isAdmin: false, permissions: {} };
44 meFixture = { username: 'tester', isAdmin: false, permissions: {} };
44 thumbnailStatusFixture = {};
45 thumbnailStatusFixture = {};
45 rootAccessFixture = {};
46 rootAccessFixture = {};
47 folderIconFixture = {};
46 adminUsersFixture = { users: [] };
48 adminUsersFixture = { users: [] };
47 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
49 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
48 downloadFixture = {};
50 downloadFixture = {};
@@ -98,6 +100,16 @@ describe('page load smoke test', () =>
98 const rootPath = String(req.query.rootPath || '');
100 const rootPath = String(req.query.rootPath || '');
99 res.json({ users: rootAccessFixture[rootPath] || [] });
101 res.json({ users: rootAccessFixture[rootPath] || [] });
100 });
102 });
103 app.get('/api/files/folder-icon', (req, res) =>
104 {
105 const dir = String(req.query.dir || '');
106 const icon = folderIconFixture[dir] || null;
107 res.json({ icon });
108 });
109 app.get('/api/files/folder-images', (req, res) =>
110 {
111 res.json({ images: [] });
112 });
101 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
113 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
102 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
114 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
103 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
115 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));