BlueGit

timfa filemanager

Merge feature: last folder and browser history

timfa Tim Falken · pushed by timfa

Authored 2026-05-26 · 5 months ago

Hash
3e597d6f76c36c1e1b11d2b63b0f29e1c56259c9
7 files changed +489 −9
.github/technical-reference.md +6 −0
@@ -44,6 +44,7 @@
44 44
45 45 ## server/db.js
46 46 - initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
47 - initDb() - Also creates `user_last_navigation` to persist each user's last visited folder path and timestamp across sessions.
47 48 - getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
48 49 - closeDb() - Closes singleton DB handle to release file locks.
49 50
@@ -85,6 +86,7 @@
85 86 ## server/routes/files.js
86 87 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
87 88 - GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
89 - GET /api/files/roots - Returns `lastDir` when the authenticated user's previously visited folder is still accessible and exists; clears stale/inaccessible saved folders.
88 90 - loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
89 91 - parseOctalMode(rawValue, fallback) - Parses optional octal chmod mode overrides from environment variables and falls back to secure defaults when invalid.
90 92 - envFlagEnabled(name) - Boolean environment flag parser for file-route runtime feature toggles.
@@ -105,6 +107,7 @@
105 107 - POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
106 108 - GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
107 109 - GET /api/files/list - Returns directory items including name/path/isDir plus size, mtime, and uploadedAt; uploadedAt comes from persisted `file_meta.uploaded_at` when present, otherwise it is backfilled from filesystem creation/change metadata and saved.
110 - GET /api/files/list - Persists the authenticated user's most recently opened folder in `user_last_navigation` after a successful directory listing.
108 111 - GET /api/files/list - When FILEMANAGER_LIST_ACCESS_CHMOD=1, runs a best-effort shallow chmod on the opened folder before listing (opened folder + direct children only; defaults: dirs 0777, files 0666; overrides via FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE and FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE).
109 112 - GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
110 113 - GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
@@ -214,7 +217,10 @@
214 217 - getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
215 218 - saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
216 219 - loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
220 - loadRoots(opts) - Prefers local restoreDir/rootPath, then server-provided `lastDir`, and opens that folder automatically when still accessible.
217 221 - api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
222 - Browser popstate navigation - Maintains an in-app folder navigation array mirrored to History API state; browser back/forward steps through folder history.
223 - onBrowserPopState(event) - When history reaches browse index 0, shows: "Do you want to close the application and return to the previous webpage?" and on Yes runs normal browser back navigation.
218 224 - renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
219 225 - performLogout() - Explicit logout path that revokes server session and clears local session state.
220 226 - initAuth() - Restores prior session when valid and auto-logins without credential prompt.
@@ -44,6 +44,7 @@
44
44
45## server/db.js
45## server/db.js
46- initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
46- initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
47- initDb() - Also creates `user_last_navigation` to persist each user's last visited folder path and timestamp across sessions.
47- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
48- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
48- closeDb() - Closes singleton DB handle to release file locks.
49- closeDb() - Closes singleton DB handle to release file locks.
49
50
@@ -85,6 +86,7 @@
85## server/routes/files.js
86## server/routes/files.js
86- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
87- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
87- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
88- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
89- GET /api/files/roots - Returns `lastDir` when the authenticated user's previously visited folder is still accessible and exists; clears stale/inaccessible saved folders.
88- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
90- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
89- parseOctalMode(rawValue, fallback) - Parses optional octal chmod mode overrides from environment variables and falls back to secure defaults when invalid.
91- parseOctalMode(rawValue, fallback) - Parses optional octal chmod mode overrides from environment variables and falls back to secure defaults when invalid.
90- envFlagEnabled(name) - Boolean environment flag parser for file-route runtime feature toggles.
92- envFlagEnabled(name) - Boolean environment flag parser for file-route runtime feature toggles.
@@ -105,6 +107,7 @@
105- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
107- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
106- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
108- GET /api/files/search - Fuzzy-searches all readable roots (and personal folder when configured) for files, returning ranked matches with path metadata.
107- GET /api/files/list - Returns directory items including name/path/isDir plus size, mtime, and uploadedAt; uploadedAt comes from persisted `file_meta.uploaded_at` when present, otherwise it is backfilled from filesystem creation/change metadata and saved.
109- GET /api/files/list - Returns directory items including name/path/isDir plus size, mtime, and uploadedAt; uploadedAt comes from persisted `file_meta.uploaded_at` when present, otherwise it is backfilled from filesystem creation/change metadata and saved.
110- GET /api/files/list - Persists the authenticated user's most recently opened folder in `user_last_navigation` after a successful directory listing.
108- GET /api/files/list - When FILEMANAGER_LIST_ACCESS_CHMOD=1, runs a best-effort shallow chmod on the opened folder before listing (opened folder + direct children only; defaults: dirs 0777, files 0666; overrides via FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE and FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE).
111- GET /api/files/list - When FILEMANAGER_LIST_ACCESS_CHMOD=1, runs a best-effort shallow chmod on the opened folder before listing (opened folder + direct children only; defaults: dirs 0777, files 0666; overrides via FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE and FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE).
109- GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
112- GET /api/files/search-images - Fuzzy-searches readable roots for image files with ready thumbnails, returning capped results plus scan-truncation metadata for scalable global favicon selection.
110- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
113- GET /api/files/global-favicon-image - Publicly serves the configured global favicon thumbnail file so browsers can load `<link rel="icon">` without auth headers.
@@ -214,7 +217,10 @@
214- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
217- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
215- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
218- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
216- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
219- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
220- loadRoots(opts) - Prefers local restoreDir/rootPath, then server-provided `lastDir`, and opens that folder automatically when still accessible.
217- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
221- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
222- Browser popstate navigation - Maintains an in-app folder navigation array mirrored to History API state; browser back/forward steps through folder history.
223- onBrowserPopState(event) - When history reaches browse index 0, shows: "Do you want to close the application and return to the previous webpage?" and on Yes runs normal browser back navigation.
218- renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
224- renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
219- performLogout() - Explicit logout path that revokes server session and clears local session state.
225- performLogout() - Explicit logout path that revokes server session and clears local session state.
220- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
226- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
.github/tests.md +1 −0
@@ -44,6 +44,7 @@
44 44 - `POST /api/files/upload`
45 45 - `POST /api/files/move`
46 46 - `root alias endpoints`
47 - `last visited folder persistence`
47 48 - `GET /api/files/thumbnail`
48 49 - `GET /api/files/root-access`
49 50 - `orphaned user folder access`
@@ -44,6 +44,7 @@
44- `POST /api/files/upload`
44- `POST /api/files/upload`
45- `POST /api/files/move`
45- `POST /api/files/move`
46- `root alias endpoints`
46- `root alias endpoints`
47- `last visited folder persistence`
47- `GET /api/files/thumbnail`
48- `GET /api/files/thumbnail`
48- `GET /api/files/root-access`
49- `GET /api/files/root-access`
49- `orphaned user folder access`
50- `orphaned user folder access`
public/app.js +195 −7
@@ -38,6 +38,10 @@ const STATE = {
38 38 restoreRootPath: null,
39 39 lastOperationAt: null,
40 40
41 // In-app navigation history mirrored to browser history state.
42 navigationHistory: [],
43 navigationIndex: -1,
44
41 45 // Background refresh state
42 46 autoRefreshTimer: null,
43 47 uploadInProgress: false,
@@ -736,6 +740,170 @@ function clearSessionState ()
736 740 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
737 741 }
738 742
743 function makeNavEntryForRoots ()
744 {
745 return { kind: 'roots' };
746 }
747
748 function makeNavEntryForDir (dirPath, rootPath)
749 {
750 return {
751 kind: 'dir',
752 dir: String(dirPath || ''),
753 rootPath: String(rootPath || ''),
754 };
755 }
756
757 function sameNavEntry (a, b)
758 {
759 if (!a || !b) return false;
760 if (a.kind !== b.kind) return false;
761 if (a.kind === 'roots') return true;
762 return samePath(a.dir, b.dir) && samePath(a.rootPath, b.rootPath);
763 }
764
765 function trimNavState (state)
766 {
767 if (!state || typeof state !== 'object') return null;
768
769 const kind = String(state.kind || '').trim().toLowerCase();
770 if (kind === 'roots') return makeNavEntryForRoots();
771 if (kind !== 'dir') return null;
772
773 const dir = String(state.dir || '').trim();
774 const rootPath = String(state.rootPath || '').trim();
775 if (!dir || !rootPath) return null;
776 return makeNavEntryForDir(dir, rootPath);
777 }
778
779 function navStatePayload (entry, index)
780 {
781 return {
782 filemanagerNav: entry,
783 filemanagerNavIndex: Number(index),
784 };
785 }
786
787 function canUseBrowserHistory ()
788 {
789 return !!(
790 typeof window !== 'undefined'
791 && window.history
792 && typeof window.history.pushState === 'function'
793 && typeof window.history.replaceState === 'function'
794 );
795 }
796
797 function writeBrowserNavState (entry, index, mode = 'push')
798 {
799 if (!canUseBrowserHistory()) return;
800 const payload = navStatePayload(entry, index);
801 if (mode === 'replace')
802 {
803 window.history.replaceState(payload, '', window.location.href);
804 } else
805 {
806 window.history.pushState(payload, '', window.location.href);
807 }
808 }
809
810 function recordNavigationEntry (entry, mode = 'push')
811 {
812 if (!entry) return;
813
814 if (!STATE.navigationHistory.length)
815 {
816 STATE.navigationHistory = [entry];
817 STATE.navigationIndex = 0;
818 writeBrowserNavState(entry, 0, 'replace');
819 return;
820 }
821
822 const current = STATE.navigationHistory[STATE.navigationIndex] || null;
823 if (sameNavEntry(current, entry))
824 {
825 writeBrowserNavState(entry, STATE.navigationIndex, 'replace');
826 return;
827 }
828
829 if (mode === 'replace')
830 {
831 STATE.navigationHistory[STATE.navigationIndex] = entry;
832 writeBrowserNavState(entry, STATE.navigationIndex, 'replace');
833 return;
834 }
835
836 STATE.navigationHistory = STATE.navigationHistory.slice(0, STATE.navigationIndex + 1);
837 STATE.navigationHistory.push(entry);
838 STATE.navigationIndex = STATE.navigationHistory.length - 1;
839 writeBrowserNavState(entry, STATE.navigationIndex, 'push');
840 }
841
842 async function applyPopNavigationState (navEntry)
843 {
844 if (!navEntry) return;
845
846 if (navEntry.kind === 'roots')
847 {
848 renderRootsView({ historyMode: 'skip' });
849 return;
850 }
851
852 if (navEntry.kind !== 'dir') return;
853
854 const currentRoot = STATE.roots.find(r => samePath(r.path, navEntry.rootPath));
855 if (currentRoot)
856 {
857 await navigateTo(navEntry.dir, currentRoot, { historyMode: 'skip', keepSidebar: true });
858 return;
859 }
860
861 await loadRoots({
862 preferredDir: navEntry.dir,
863 preferredRootPath: navEntry.rootPath,
864 historyMode: 'skip',
865 });
866 }
867
868 async function onBrowserPopState (event)
869 {
870 if (!canUseBrowserHistory()) return;
871 if (!STATE.token) return;
872
873 const state = event && event.state && typeof event.state === 'object' ? event.state : null;
874 const navEntry = trimNavState(state && state.filemanagerNav);
875 if (!navEntry) return;
876
877 const rawIndex = Number(state.filemanagerNavIndex);
878 const hasIndex = Number.isInteger(rawIndex);
879 const maxIndex = Math.max(STATE.navigationHistory.length - 1, 0);
880 const targetIndex = hasIndex ? Math.max(0, Math.min(rawIndex, maxIndex)) : 0;
881 STATE.navigationIndex = targetIndex;
882
883 try
884 {
885 await applyPopNavigationState(navEntry);
886 }
887 catch
888 {
889 await loadRoots({ historyMode: 'replace' });
890 return;
891 }
892
893 if (targetIndex === 0 && STATE.navigationHistory.length > 1)
894 {
895 const leave = await showConfirm(
896 'Leave application',
897 'Do you want to close the application and return to the previous webpage?',
898 { okLabel: 'Yes' }
899 );
900 if (leave)
901 {
902 window.history.back();
903 }
904 }
905 }
906
739 907 // ───────────────────────────────────────────────────────────────────────────
740 908 // API
741 909 // ───────────────────────────────────────────────────────────────────────────
@@ -1343,6 +1511,8 @@ async function performLogout ()
1343 1511 STATE.restoreDir = null;
1344 1512 STATE.restoreRootPath = null;
1345 1513 STATE.lastOperationAt = null;
1514 STATE.navigationHistory = [];
1515 STATE.navigationIndex = -1;
1346 1516 _adminUpdateStatus = null;
1347 1517 setAdminUpdateBadge(0);
1348 1518 clearSessionState();
@@ -1361,17 +1531,21 @@ async function loadRoots (opts = {})
1361 1531 if (!data) return;
1362 1532 STATE.roots = data.roots;
1363 1533
1364 const preferredDir = opts.preferredDir || null;
1534 const preferredDir = opts.preferredDir || data.lastDir || null;
1365 1535 const preferredRootPath = opts.preferredRootPath || null;
1536 const historyMode = opts.historyMode || 'replace';
1366 1537
1367 if (preferredDir && preferredRootPath)
1538 if (preferredDir)
1368 1539 {
1369 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
1540 const preferredRoot = preferredRootPath
1541 ? STATE.roots.find(r => samePath(r.path, preferredRootPath))
1542 : STATE.roots.find(r => pathInside(preferredDir, r.path));
1543
1370 1544 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1371 1545 {
1372 1546 try
1373 1547 {
1374 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
1548 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true, historyMode });
1375 1549 return;
1376 1550 } catch
1377 1551 {
@@ -1383,14 +1557,14 @@ async function loadRoots (opts = {})
1383 1557 if (STATE.roots.length === 1)
1384 1558 {
1385 1559 // Single root → open it directly
1386 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
1560 await navigateTo(STATE.roots[0].path, STATE.roots[0], { historyMode });
1387 1561 } else
1388 1562 {
1389 renderRootsView();
1563 renderRootsView({ historyMode });
1390 1564 }
1391 1565 }
1392 1566
1393 function renderRootsView ()
1567 function renderRootsView (opts = {})
1394 1568 {
1395 1569 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1396 1570 disconnectThumbnailObserver();
@@ -1414,6 +1588,11 @@ function renderRootsView ()
1414 1588 grid.appendChild(el);
1415 1589 }
1416 1590
1591 if (opts.historyMode !== 'skip')
1592 {
1593 recordNavigationEntry(makeNavEntryForRoots(), opts.historyMode || 'push');
1594 }
1595
1417 1596 loadThumbnails();
1418 1597 }
1419 1598
@@ -1432,6 +1611,11 @@ async function navigateTo (absPath, root, opts = {})
1432 1611 renderFileGrid();
1433 1612 await refreshFolderStats();
1434 1613 closeSidebar();
1614
1615 if (opts.historyMode !== 'skip')
1616 {
1617 recordNavigationEntry(makeNavEntryForDir(absPath, STATE.currentRoot && STATE.currentRoot.path), opts.historyMode || 'push');
1618 }
1435 1619 }
1436 1620
1437 1621 async function runGlobalFileSearch ()
@@ -6754,6 +6938,10 @@ function wireEvents ()
6754 6938
6755 6939 window.addEventListener('resize', closeCustomContextMenu);
6756 6940 window.addEventListener('scroll', closeCustomContextMenu, true);
6941 window.addEventListener('popstate', (event) =>
6942 {
6943 void onBrowserPopState(event);
6944 });
6757 6945 document.addEventListener('click', closeCustomContextMenu);
6758 6946 document.addEventListener('keydown', (e) =>
6759 6947 {
@@ -38,6 +38,10 @@ const STATE = {
38 restoreRootPath: null,
38 restoreRootPath: null,
39 lastOperationAt: null,
39 lastOperationAt: null,
40
40
41 // In-app navigation history mirrored to browser history state.
42 navigationHistory: [],
43 navigationIndex: -1,
44
41 // Background refresh state
45 // Background refresh state
42 autoRefreshTimer: null,
46 autoRefreshTimer: null,
43 uploadInProgress: false,
47 uploadInProgress: false,
@@ -736,6 +740,170 @@ function clearSessionState ()
736 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
740 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
737}
741}
738
742
743function makeNavEntryForRoots ()
744{
745 return { kind: 'roots' };
746}
747
748function makeNavEntryForDir (dirPath, rootPath)
749{
750 return {
751 kind: 'dir',
752 dir: String(dirPath || ''),
753 rootPath: String(rootPath || ''),
754 };
755}
756
757function sameNavEntry (a, b)
758{
759 if (!a || !b) return false;
760 if (a.kind !== b.kind) return false;
761 if (a.kind === 'roots') return true;
762 return samePath(a.dir, b.dir) && samePath(a.rootPath, b.rootPath);
763}
764
765function trimNavState (state)
766{
767 if (!state || typeof state !== 'object') return null;
768
769 const kind = String(state.kind || '').trim().toLowerCase();
770 if (kind === 'roots') return makeNavEntryForRoots();
771 if (kind !== 'dir') return null;
772
773 const dir = String(state.dir || '').trim();
774 const rootPath = String(state.rootPath || '').trim();
775 if (!dir || !rootPath) return null;
776 return makeNavEntryForDir(dir, rootPath);
777}
778
779function navStatePayload (entry, index)
780{
781 return {
782 filemanagerNav: entry,
783 filemanagerNavIndex: Number(index),
784 };
785}
786
787function canUseBrowserHistory ()
788{
789 return !!(
790 typeof window !== 'undefined'
791 && window.history
792 && typeof window.history.pushState === 'function'
793 && typeof window.history.replaceState === 'function'
794 );
795}
796
797function writeBrowserNavState (entry, index, mode = 'push')
798{
799 if (!canUseBrowserHistory()) return;
800 const payload = navStatePayload(entry, index);
801 if (mode === 'replace')
802 {
803 window.history.replaceState(payload, '', window.location.href);
804 } else
805 {
806 window.history.pushState(payload, '', window.location.href);
807 }
808}
809
810function recordNavigationEntry (entry, mode = 'push')
811{
812 if (!entry) return;
813
814 if (!STATE.navigationHistory.length)
815 {
816 STATE.navigationHistory = [entry];
817 STATE.navigationIndex = 0;
818 writeBrowserNavState(entry, 0, 'replace');
819 return;
820 }
821
822 const current = STATE.navigationHistory[STATE.navigationIndex] || null;
823 if (sameNavEntry(current, entry))
824 {
825 writeBrowserNavState(entry, STATE.navigationIndex, 'replace');
826 return;
827 }
828
829 if (mode === 'replace')
830 {
831 STATE.navigationHistory[STATE.navigationIndex] = entry;
832 writeBrowserNavState(entry, STATE.navigationIndex, 'replace');
833 return;
834 }
835
836 STATE.navigationHistory = STATE.navigationHistory.slice(0, STATE.navigationIndex + 1);
837 STATE.navigationHistory.push(entry);
838 STATE.navigationIndex = STATE.navigationHistory.length - 1;
839 writeBrowserNavState(entry, STATE.navigationIndex, 'push');
840}
841
842async function applyPopNavigationState (navEntry)
843{
844 if (!navEntry) return;
845
846 if (navEntry.kind === 'roots')
847 {
848 renderRootsView({ historyMode: 'skip' });
849 return;
850 }
851
852 if (navEntry.kind !== 'dir') return;
853
854 const currentRoot = STATE.roots.find(r => samePath(r.path, navEntry.rootPath));
855 if (currentRoot)
856 {
857 await navigateTo(navEntry.dir, currentRoot, { historyMode: 'skip', keepSidebar: true });
858 return;
859 }
860
861 await loadRoots({
862 preferredDir: navEntry.dir,
863 preferredRootPath: navEntry.rootPath,
864 historyMode: 'skip',
865 });
866}
867
868async function onBrowserPopState (event)
869{
870 if (!canUseBrowserHistory()) return;
871 if (!STATE.token) return;
872
873 const state = event && event.state && typeof event.state === 'object' ? event.state : null;
874 const navEntry = trimNavState(state && state.filemanagerNav);
875 if (!navEntry) return;
876
877 const rawIndex = Number(state.filemanagerNavIndex);
878 const hasIndex = Number.isInteger(rawIndex);
879 const maxIndex = Math.max(STATE.navigationHistory.length - 1, 0);
880 const targetIndex = hasIndex ? Math.max(0, Math.min(rawIndex, maxIndex)) : 0;
881 STATE.navigationIndex = targetIndex;
882
883 try
884 {
885 await applyPopNavigationState(navEntry);
886 }
887 catch
888 {
889 await loadRoots({ historyMode: 'replace' });
890 return;
891 }
892
893 if (targetIndex === 0 && STATE.navigationHistory.length > 1)
894 {
895 const leave = await showConfirm(
896 'Leave application',
897 'Do you want to close the application and return to the previous webpage?',
898 { okLabel: 'Yes' }
899 );
900 if (leave)
901 {
902 window.history.back();
903 }
904 }
905}
906
739// ───────────────────────────────────────────────────────────────────────────
907// ───────────────────────────────────────────────────────────────────────────
740// API
908// API
741// ───────────────────────────────────────────────────────────────────────────
909// ───────────────────────────────────────────────────────────────────────────
@@ -1343,6 +1511,8 @@ async function performLogout ()
1343 STATE.restoreDir = null;
1511 STATE.restoreDir = null;
1344 STATE.restoreRootPath = null;
1512 STATE.restoreRootPath = null;
1345 STATE.lastOperationAt = null;
1513 STATE.lastOperationAt = null;
1514 STATE.navigationHistory = [];
1515 STATE.navigationIndex = -1;
1346 _adminUpdateStatus = null;
1516 _adminUpdateStatus = null;
1347 setAdminUpdateBadge(0);
1517 setAdminUpdateBadge(0);
1348 clearSessionState();
1518 clearSessionState();
@@ -1361,17 +1531,21 @@ async function loadRoots (opts = {})
1361 if (!data) return;
1531 if (!data) return;
1362 STATE.roots = data.roots;
1532 STATE.roots = data.roots;
1363
1533
1364 const preferredDir = opts.preferredDir || null;
1534 const preferredDir = opts.preferredDir || data.lastDir || null;
1365 const preferredRootPath = opts.preferredRootPath || null;
1535 const preferredRootPath = opts.preferredRootPath || null;
1536 const historyMode = opts.historyMode || 'replace';
1366
1537
1367 if (preferredDir && preferredRootPath)
1538 if (preferredDir)
1368 {
1539 {
1369 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
1540 const preferredRoot = preferredRootPath
1541 ? STATE.roots.find(r => samePath(r.path, preferredRootPath))
1542 : STATE.roots.find(r => pathInside(preferredDir, r.path));
1543
1370 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1544 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1371 {
1545 {
1372 try
1546 try
1373 {
1547 {
1374 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
1548 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true, historyMode });
1375 return;
1549 return;
1376 } catch
1550 } catch
1377 {
1551 {
@@ -1383,14 +1557,14 @@ async function loadRoots (opts = {})
1383 if (STATE.roots.length === 1)
1557 if (STATE.roots.length === 1)
1384 {
1558 {
1385 // Single root → open it directly
1559 // Single root → open it directly
1386 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
1560 await navigateTo(STATE.roots[0].path, STATE.roots[0], { historyMode });
1387 } else
1561 } else
1388 {
1562 {
1389 renderRootsView();
1563 renderRootsView({ historyMode });
1390 }
1564 }
1391}
1565}
1392
1566
1393function renderRootsView ()
1567function renderRootsView (opts = {})
1394{
1568{
1395 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1569 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1396 disconnectThumbnailObserver();
1570 disconnectThumbnailObserver();
@@ -1414,6 +1588,11 @@ function renderRootsView ()
1414 grid.appendChild(el);
1588 grid.appendChild(el);
1415 }
1589 }
1416
1590
1591 if (opts.historyMode !== 'skip')
1592 {
1593 recordNavigationEntry(makeNavEntryForRoots(), opts.historyMode || 'push');
1594 }
1595
1417 loadThumbnails();
1596 loadThumbnails();
1418}
1597}
1419
1598
@@ -1432,6 +1611,11 @@ async function navigateTo (absPath, root, opts = {})
1432 renderFileGrid();
1611 renderFileGrid();
1433 await refreshFolderStats();
1612 await refreshFolderStats();
1434 closeSidebar();
1613 closeSidebar();
1614
1615 if (opts.historyMode !== 'skip')
1616 {
1617 recordNavigationEntry(makeNavEntryForDir(absPath, STATE.currentRoot && STATE.currentRoot.path), opts.historyMode || 'push');
1618 }
1435}
1619}
1436
1620
1437async function runGlobalFileSearch ()
1621async function runGlobalFileSearch ()
@@ -6754,6 +6938,10 @@ function wireEvents ()
6754
6938
6755 window.addEventListener('resize', closeCustomContextMenu);
6939 window.addEventListener('resize', closeCustomContextMenu);
6756 window.addEventListener('scroll', closeCustomContextMenu, true);
6940 window.addEventListener('scroll', closeCustomContextMenu, true);
6941 window.addEventListener('popstate', (event) =>
6942 {
6943 void onBrowserPopState(event);
6944 });
6757 document.addEventListener('click', closeCustomContextMenu);
6945 document.addEventListener('click', closeCustomContextMenu);
6758 document.addEventListener('keydown', (e) =>
6946 document.addEventListener('keydown', (e) =>
6759 {
6947 {
server/db.js +8 −0
@@ -52,6 +52,14 @@ function initDb ()
52 52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
53 53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
54 54
55 CREATE TABLE IF NOT EXISTS user_last_navigation (
56 username TEXT PRIMARY KEY,
57 last_dir TEXT,
58 updated_at INTEGER NOT NULL
59 );
60
61 CREATE INDEX IF NOT EXISTS idx_user_last_navigation_updated_at ON user_last_navigation(updated_at);
62
55 63 CREATE TABLE IF NOT EXISTS share_tokens (
56 64 token TEXT PRIMARY KEY,
57 65 file_path TEXT NOT NULL,
@@ -52,6 +52,14 @@ function initDb ()
52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
52 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
53 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
54
54
55 CREATE TABLE IF NOT EXISTS user_last_navigation (
56 username TEXT PRIMARY KEY,
57 last_dir TEXT,
58 updated_at INTEGER NOT NULL
59 );
60
61 CREATE INDEX IF NOT EXISTS idx_user_last_navigation_updated_at ON user_last_navigation(updated_at);
62
55 CREATE TABLE IF NOT EXISTS share_tokens (
63 CREATE TABLE IF NOT EXISTS share_tokens (
56 token TEXT PRIMARY KEY,
64 token TEXT PRIMARY KEY,
57 file_path TEXT NOT NULL,
65 file_path TEXT NOT NULL,
server/routes/files.js +76 −1
@@ -270,6 +270,49 @@ function effectivePaths ()
270 270 return getEffectivePaths(loadConfig().paths || []);
271 271 }
272 272
273 function ensureUserNavigationTable (db)
274 {
275 db.exec(`
276 CREATE TABLE IF NOT EXISTS user_last_navigation (
277 username TEXT PRIMARY KEY,
278 last_dir TEXT,
279 updated_at INTEGER NOT NULL
280 );
281 `);
282 }
283
284 function setUserLastDir (username, dirPath)
285 {
286 if (!username) return;
287 const db = getDb();
288 ensureUserNavigationTable(db);
289 db.prepare(`
290 INSERT INTO user_last_navigation (username, last_dir, updated_at)
291 VALUES (?, ?, ?)
292 ON CONFLICT(username) DO UPDATE SET
293 last_dir = excluded.last_dir,
294 updated_at = excluded.updated_at
295 `).run([String(username), String(dirPath || ''), Date.now()]);
296 }
297
298 function getUserLastDir (username)
299 {
300 if (!username) return null;
301 const db = getDb();
302 ensureUserNavigationTable(db);
303 const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]);
304 const value = String(row && row.last_dir || '').trim();
305 return value || null;
306 }
307
308 function clearUserLastDir (username)
309 {
310 if (!username) return;
311 const db = getDb();
312 ensureUserNavigationTable(db);
313 db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]);
314 }
315
273 316 /**
274 317 * Loads config and returns { config, roots } together so both are consistent
275 318 * and user-folder checks can be performed in route handlers.
@@ -981,7 +1024,31 @@ router.get('/roots', requireAuth, (req, res) =>
981 1024 }
982 1025 }
983 1026
984 res.json({ roots: readable });
1027 let lastDir = getUserLastDir(req.user && req.user.username);
1028 if (lastDir)
1029 {
1030 const info = resolveRootForUser(lastDir, roots, req.user, config);
1031 const hasAccess = !!(info && canReadInfo(req.user, info));
1032 let isDir = false;
1033 if (hasAccess)
1034 {
1035 try
1036 {
1037 isDir = fs.statSync(lastDir).isDirectory();
1038 } catch
1039 {
1040 isDir = false;
1041 }
1042 }
1043
1044 if (!hasAccess || !isDir)
1045 {
1046 clearUserLastDir(req.user && req.user.username);
1047 lastDir = null;
1048 }
1049 }
1050
1051 res.json({ roots: readable, lastDir });
985 1052 });
986 1053
987 1054 // ---------------------------------------------------------------------------
@@ -1179,6 +1246,14 @@ router.get('/list', requireAuth, (req, res) =>
1179 1246 };
1180 1247 });
1181 1248
1249 try
1250 {
1251 setUserLastDir(req.user && req.user.username, dir);
1252 } catch
1253 {
1254 // Non-fatal preference persistence.
1255 }
1256
1182 1257 res.json({ items });
1183 1258 });
1184 1259
@@ -270,6 +270,49 @@ function effectivePaths ()
270 return getEffectivePaths(loadConfig().paths || []);
270 return getEffectivePaths(loadConfig().paths || []);
271}
271}
272
272
273function ensureUserNavigationTable (db)
274{
275 db.exec(`
276 CREATE TABLE IF NOT EXISTS user_last_navigation (
277 username TEXT PRIMARY KEY,
278 last_dir TEXT,
279 updated_at INTEGER NOT NULL
280 );
281 `);
282}
283
284function setUserLastDir (username, dirPath)
285{
286 if (!username) return;
287 const db = getDb();
288 ensureUserNavigationTable(db);
289 db.prepare(`
290 INSERT INTO user_last_navigation (username, last_dir, updated_at)
291 VALUES (?, ?, ?)
292 ON CONFLICT(username) DO UPDATE SET
293 last_dir = excluded.last_dir,
294 updated_at = excluded.updated_at
295 `).run([String(username), String(dirPath || ''), Date.now()]);
296}
297
298function getUserLastDir (username)
299{
300 if (!username) return null;
301 const db = getDb();
302 ensureUserNavigationTable(db);
303 const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]);
304 const value = String(row && row.last_dir || '').trim();
305 return value || null;
306}
307
308function clearUserLastDir (username)
309{
310 if (!username) return;
311 const db = getDb();
312 ensureUserNavigationTable(db);
313 db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]);
314}
315
273/**
316/**
274 * Loads config and returns { config, roots } together so both are consistent
317 * Loads config and returns { config, roots } together so both are consistent
275 * and user-folder checks can be performed in route handlers.
318 * and user-folder checks can be performed in route handlers.
@@ -981,7 +1024,31 @@ router.get('/roots', requireAuth, (req, res) =>
981 }
1024 }
982 }
1025 }
983
1026
984 res.json({ roots: readable });
1027 let lastDir = getUserLastDir(req.user && req.user.username);
1028 if (lastDir)
1029 {
1030 const info = resolveRootForUser(lastDir, roots, req.user, config);
1031 const hasAccess = !!(info && canReadInfo(req.user, info));
1032 let isDir = false;
1033 if (hasAccess)
1034 {
1035 try
1036 {
1037 isDir = fs.statSync(lastDir).isDirectory();
1038 } catch
1039 {
1040 isDir = false;
1041 }
1042 }
1043
1044 if (!hasAccess || !isDir)
1045 {
1046 clearUserLastDir(req.user && req.user.username);
1047 lastDir = null;
1048 }
1049 }
1050
1051 res.json({ roots: readable, lastDir });
985});
1052});
986
1053
987// ---------------------------------------------------------------------------
1054// ---------------------------------------------------------------------------
@@ -1179,6 +1246,14 @@ router.get('/list', requireAuth, (req, res) =>
1179 };
1246 };
1180 });
1247 });
1181
1248
1249 try
1250 {
1251 setUserLastDir(req.user && req.user.username, dir);
1252 } catch
1253 {
1254 // Non-fatal preference persistence.
1255 }
1256
1182 res.json({ items });
1257 res.json({ items });
1183});
1258});
1184
1259
tests/files.routes.test.js +68 −0
@@ -566,6 +566,74 @@ describe('root alias endpoints', () =>
566 566
567 567 expect(status).toBe(400);
568 568 });
569
570 test('GET /api/files/roots returns lastDir when user still has access', async () =>
571 {
572 const nestedDir = path.join(rootDir, 'series');
573 fs.mkdirSync(nestedDir, { recursive: true });
574
575 const db = getDb();
576 db.exec(`
577 CREATE TABLE IF NOT EXISTS user_last_navigation (
578 username TEXT PRIMARY KEY,
579 last_dir TEXT,
580 updated_at INTEGER NOT NULL
581 );
582 `);
583 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
584 .run(['admin', nestedDir, Date.now()]);
585
586 const { status, body } = await req('GET', '/api/files/roots');
587 expect(status).toBe(200);
588 expect(body.lastDir).toBe(nestedDir);
589 });
590
591 test('GET /api/files/roots returns null lastDir when saved folder is no longer accessible', async () =>
592 {
593 const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-outside-'));
594 mockUser = {
595 username: 'reader',
596 isAdmin: false,
597 permissions: {},
598 };
599
600 const db = getDb();
601 db.exec(`
602 CREATE TABLE IF NOT EXISTS user_last_navigation (
603 username TEXT PRIMARY KEY,
604 last_dir TEXT,
605 updated_at INTEGER NOT NULL
606 );
607 `);
608 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
609 .run(['reader', outsideDir, Date.now()]);
610
611 try
612 {
613 const { status, body } = await req('GET', '/api/files/roots');
614 expect(status).toBe(200);
615 expect(body.lastDir).toBeNull();
616 } finally
617 {
618 fs.rmSync(outsideDir, { recursive: true, force: true });
619 }
620 });
621 });
622
623 describe('last visited folder persistence', () =>
624 {
625 test('GET /api/files/list stores the visited folder for the authenticated user', async () =>
626 {
627 const visited = path.join(rootDir, 'visited-folder');
628 fs.mkdirSync(visited, { recursive: true });
629
630 const { status } = await req('GET', `/api/files/list?dir=${encodeURIComponent(visited)}`);
631 expect(status).toBe(200);
632
633 const row = getDb().prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get(['admin']);
634 expect(row).toBeTruthy();
635 expect(row.last_dir).toBe(visited);
636 });
569 637 });
570 638
571 639 describe('GET /api/files/thumbnail', () =>
@@ -566,6 +566,74 @@ describe('root alias endpoints', () =>
566
566
567 expect(status).toBe(400);
567 expect(status).toBe(400);
568 });
568 });
569
570 test('GET /api/files/roots returns lastDir when user still has access', async () =>
571 {
572 const nestedDir = path.join(rootDir, 'series');
573 fs.mkdirSync(nestedDir, { recursive: true });
574
575 const db = getDb();
576 db.exec(`
577 CREATE TABLE IF NOT EXISTS user_last_navigation (
578 username TEXT PRIMARY KEY,
579 last_dir TEXT,
580 updated_at INTEGER NOT NULL
581 );
582 `);
583 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
584 .run(['admin', nestedDir, Date.now()]);
585
586 const { status, body } = await req('GET', '/api/files/roots');
587 expect(status).toBe(200);
588 expect(body.lastDir).toBe(nestedDir);
589 });
590
591 test('GET /api/files/roots returns null lastDir when saved folder is no longer accessible', async () =>
592 {
593 const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-outside-'));
594 mockUser = {
595 username: 'reader',
596 isAdmin: false,
597 permissions: {},
598 };
599
600 const db = getDb();
601 db.exec(`
602 CREATE TABLE IF NOT EXISTS user_last_navigation (
603 username TEXT PRIMARY KEY,
604 last_dir TEXT,
605 updated_at INTEGER NOT NULL
606 );
607 `);
608 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
609 .run(['reader', outsideDir, Date.now()]);
610
611 try
612 {
613 const { status, body } = await req('GET', '/api/files/roots');
614 expect(status).toBe(200);
615 expect(body.lastDir).toBeNull();
616 } finally
617 {
618 fs.rmSync(outsideDir, { recursive: true, force: true });
619 }
620 });
621});
622
623describe('last visited folder persistence', () =>
624{
625 test('GET /api/files/list stores the visited folder for the authenticated user', async () =>
626 {
627 const visited = path.join(rootDir, 'visited-folder');
628 fs.mkdirSync(visited, { recursive: true });
629
630 const { status } = await req('GET', `/api/files/list?dir=${encodeURIComponent(visited)}`);
631 expect(status).toBe(200);
632
633 const row = getDb().prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get(['admin']);
634 expect(row).toBeTruthy();
635 expect(row.last_dir).toBe(visited);
636 });
569});
637});
570
638
571describe('GET /api/files/thumbnail', () =>
639describe('GET /api/files/thumbnail', () =>
tests/page.load.test.js +135 −1
@@ -34,6 +34,7 @@ describe('page load smoke test', () =>
34 34 let metaWatchedByFixture;
35 35 let releasedVideoStreamSessions;
36 36 let setupNeededFixture;
37 let lastDirFixture;
37 38 const openDoms = [];
38 39
39 40 beforeEach(() =>
@@ -67,6 +68,7 @@ describe('page load smoke test', () =>
67 68 metaWatchedByFixture = {};
68 69 releasedVideoStreamSessions = [];
69 70 setupNeededFixture = false;
71 lastDirFixture = null;
70 72 });
71 73
72 74 beforeAll(async () =>
@@ -82,7 +84,7 @@ describe('page load smoke test', () =>
82 84 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
83 85 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: setupNeededFixture }));
84 86 app.get('/api/auth/me', (req, res) => res.json(meFixture));
85 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
87 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture, lastDir: lastDirFixture }));
86 88 app.get('/api/files/list', (req, res) =>
87 89 {
88 90 const dir = req.query.dir;
@@ -628,6 +630,138 @@ describe('page load smoke test', () =>
628 630 dom.window.close();
629 631 });
630 632
633 test('restores server lastDir on app load when saved session has no folder', async () =>
634 {
635 lastDirFixture = '/data/sub';
636 listFixture = {
637 '/data': [
638 {
639 name: 'sub',
640 path: '/data/sub',
641 isDir: true,
642 size: 0,
643 mtime: Date.now(),
644 },
645 ],
646 '/data/sub': [
647 {
648 name: 'episode-01.mkv',
649 path: '/data/sub/episode-01.mkv',
650 isDir: false,
651 size: 1024,
652 mtime: Date.now(),
653 },
654 ],
655 };
656
657 const { dom, runtimeErrors } = await bootClient({
658 savedSession: {
659 token: 'saved-token',
660 dir: null,
661 rootPath: null,
662 lastOperationAt: Date.now(),
663 },
664 });
665 expect(runtimeErrors).toEqual([]);
666
667 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub/episode-01.mkv"]'));
668 expect(dom.window.document.querySelector('.file-item[data-path="/data/sub/episode-01.mkv"]')).toBeTruthy();
669
670 const breadcrumbText = String(dom.window.document.getElementById('breadcrumb').textContent || '');
671 expect(breadcrumbText).toContain('sub');
672
673 dom.window.close();
674 });
675
676 test('browser back and forward navigate folder history and prompt on index 0', async () =>
677 {
678 listFixture = {
679 '/data': [
680 {
681 name: 'a',
682 path: '/data/a',
683 isDir: true,
684 size: 0,
685 mtime: Date.now(),
686 },
687 {
688 name: 'b',
689 path: '/data/b',
690 isDir: true,
691 size: 0,
692 mtime: Date.now(),
693 },
694 ],
695 '/data/a': [
696 {
697 name: 'inside-a.txt',
698 path: '/data/a/inside-a.txt',
699 isDir: false,
700 size: 1,
701 mtime: Date.now(),
702 },
703 ],
704 '/data/b': [
705 {
706 name: 'inside-b.txt',
707 path: '/data/b/inside-b.txt',
708 isDir: false,
709 size: 1,
710 mtime: Date.now(),
711 },
712 ],
713 };
714
715 const { dom, runtimeErrors } = await bootClient({
716 savedSession: {
717 token: 'saved-token',
718 dir: null,
719 rootPath: null,
720 lastOperationAt: Date.now(),
721 },
722 });
723 expect(runtimeErrors).toEqual([]);
724
725 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a"]'));
726
727 const folderA = dom.window.document.querySelector('.file-item[data-path="/data/a"]');
728 folderA.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
729 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
730
731 const homeCrumb = dom.window.document.querySelector('#breadcrumb .crumb');
732 homeCrumb.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
733 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b"]'));
734
735 const folderB = dom.window.document.querySelector('.file-item[data-path="/data/b"]');
736 folderB.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
737 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b/inside-b.txt"]'));
738
739 dom.window.history.back();
740 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b"]'));
741
742 dom.window.history.back();
743 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
744
745 dom.window.history.back();
746 await waitFor(dom, () =>
747 {
748 const confirm = dom.window.document.getElementById('confirm-modal');
749 return !!(confirm && !confirm.classList.contains('hidden'));
750 });
751
752 const confirmMessage = dom.window.document.getElementById('confirm-modal-message');
753 expect(confirmMessage.textContent).toContain('Do you want to close the application and return to the previous webpage?');
754
755 const cancelBtn = dom.window.document.getElementById('confirm-modal-cancel');
756 cancelBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
757 await waitFor(dom, () => dom.window.document.getElementById('confirm-modal').classList.contains('hidden'));
758
759 dom.window.history.forward();
760 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
761
762 dom.window.close();
763 });
764
631 765 test('root sidebar shows alias and original name, and excludes Move to action', async () =>
632 766 {
633 767 rootsFixture = [
@@ -34,6 +34,7 @@ describe('page load smoke test', () =>
34 let metaWatchedByFixture;
34 let metaWatchedByFixture;
35 let releasedVideoStreamSessions;
35 let releasedVideoStreamSessions;
36 let setupNeededFixture;
36 let setupNeededFixture;
37 let lastDirFixture;
37 const openDoms = [];
38 const openDoms = [];
38
39
39 beforeEach(() =>
40 beforeEach(() =>
@@ -67,6 +68,7 @@ describe('page load smoke test', () =>
67 metaWatchedByFixture = {};
68 metaWatchedByFixture = {};
68 releasedVideoStreamSessions = [];
69 releasedVideoStreamSessions = [];
69 setupNeededFixture = false;
70 setupNeededFixture = false;
71 lastDirFixture = null;
70 });
72 });
71
73
72 beforeAll(async () =>
74 beforeAll(async () =>
@@ -82,7 +84,7 @@ describe('page load smoke test', () =>
82 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
84 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
83 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: setupNeededFixture }));
85 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: setupNeededFixture }));
84 app.get('/api/auth/me', (req, res) => res.json(meFixture));
86 app.get('/api/auth/me', (req, res) => res.json(meFixture));
85 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
87 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture, lastDir: lastDirFixture }));
86 app.get('/api/files/list', (req, res) =>
88 app.get('/api/files/list', (req, res) =>
87 {
89 {
88 const dir = req.query.dir;
90 const dir = req.query.dir;
@@ -628,6 +630,138 @@ describe('page load smoke test', () =>
628 dom.window.close();
630 dom.window.close();
629 });
631 });
630
632
633 test('restores server lastDir on app load when saved session has no folder', async () =>
634 {
635 lastDirFixture = '/data/sub';
636 listFixture = {
637 '/data': [
638 {
639 name: 'sub',
640 path: '/data/sub',
641 isDir: true,
642 size: 0,
643 mtime: Date.now(),
644 },
645 ],
646 '/data/sub': [
647 {
648 name: 'episode-01.mkv',
649 path: '/data/sub/episode-01.mkv',
650 isDir: false,
651 size: 1024,
652 mtime: Date.now(),
653 },
654 ],
655 };
656
657 const { dom, runtimeErrors } = await bootClient({
658 savedSession: {
659 token: 'saved-token',
660 dir: null,
661 rootPath: null,
662 lastOperationAt: Date.now(),
663 },
664 });
665 expect(runtimeErrors).toEqual([]);
666
667 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/sub/episode-01.mkv"]'));
668 expect(dom.window.document.querySelector('.file-item[data-path="/data/sub/episode-01.mkv"]')).toBeTruthy();
669
670 const breadcrumbText = String(dom.window.document.getElementById('breadcrumb').textContent || '');
671 expect(breadcrumbText).toContain('sub');
672
673 dom.window.close();
674 });
675
676 test('browser back and forward navigate folder history and prompt on index 0', async () =>
677 {
678 listFixture = {
679 '/data': [
680 {
681 name: 'a',
682 path: '/data/a',
683 isDir: true,
684 size: 0,
685 mtime: Date.now(),
686 },
687 {
688 name: 'b',
689 path: '/data/b',
690 isDir: true,
691 size: 0,
692 mtime: Date.now(),
693 },
694 ],
695 '/data/a': [
696 {
697 name: 'inside-a.txt',
698 path: '/data/a/inside-a.txt',
699 isDir: false,
700 size: 1,
701 mtime: Date.now(),
702 },
703 ],
704 '/data/b': [
705 {
706 name: 'inside-b.txt',
707 path: '/data/b/inside-b.txt',
708 isDir: false,
709 size: 1,
710 mtime: Date.now(),
711 },
712 ],
713 };
714
715 const { dom, runtimeErrors } = await bootClient({
716 savedSession: {
717 token: 'saved-token',
718 dir: null,
719 rootPath: null,
720 lastOperationAt: Date.now(),
721 },
722 });
723 expect(runtimeErrors).toEqual([]);
724
725 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a"]'));
726
727 const folderA = dom.window.document.querySelector('.file-item[data-path="/data/a"]');
728 folderA.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
729 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
730
731 const homeCrumb = dom.window.document.querySelector('#breadcrumb .crumb');
732 homeCrumb.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
733 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b"]'));
734
735 const folderB = dom.window.document.querySelector('.file-item[data-path="/data/b"]');
736 folderB.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
737 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b/inside-b.txt"]'));
738
739 dom.window.history.back();
740 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/b"]'));
741
742 dom.window.history.back();
743 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
744
745 dom.window.history.back();
746 await waitFor(dom, () =>
747 {
748 const confirm = dom.window.document.getElementById('confirm-modal');
749 return !!(confirm && !confirm.classList.contains('hidden'));
750 });
751
752 const confirmMessage = dom.window.document.getElementById('confirm-modal-message');
753 expect(confirmMessage.textContent).toContain('Do you want to close the application and return to the previous webpage?');
754
755 const cancelBtn = dom.window.document.getElementById('confirm-modal-cancel');
756 cancelBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
757 await waitFor(dom, () => dom.window.document.getElementById('confirm-modal').classList.contains('hidden'));
758
759 dom.window.history.forward();
760 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/a/inside-a.txt"]'));
761
762 dom.window.close();
763 });
764
631 test('root sidebar shows alias and original name, and excludes Move to action', async () =>
765 test('root sidebar shows alias and original name, and excludes Move to action', async () =>
632 {
766 {
633 rootsFixture = [
767 rootsFixture = [