Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update navigation history logic so it works for shared folders too (#2159)
Leendert de Borstfa0a635adf16
diff --git a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsxindex 1a504f0b9..03013375f 100644--- a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx+++ b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx@@ -1,15 +1,18 @@-import React, { createContext, useContext, useEffect, useMemo, useCallback } from 'react';-import { useLocation, useNavigate } from 'react-router-dom';+import React, { createContext, useContext, useEffect, useMemo, useCallback, useRef } from 'react';+import { useLocation, useNavigate, useNavigationType } from 'react-router-dom';import { useApp } from '@/entrypoints/popup/context/AppContext';import { useDb } from '@/entrypoints/popup/context/DbContext';import { AUTH_FLOW_PATHS } from '@/entrypoints/popup/utils/routes';+import type { NavigationStackState } from '@/utils/NavigationStack';+import { createNavigationStack, seedNavigationStack, trackNavigation } from '@/utils/NavigationStack';import type { NavigationHistoryEntry } from '@/utils/NavigationStateService';import { NavigationStateService } from '@/utils/NavigationStateService';type NavigationContextType = {storeCurrentPage: () => Promise<void>;+ seedNavigationStack: (entries: NavigationHistoryEntry[]) => void;isFullyInitialized: boolean;requiresAuth: boolean;};@@ -22,6 +25,10 @@ const NavigationContext = createContext<NavigationContextType | undefined>(undefexport const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const location = useLocation();const navigate = useNavigate();+ const navigationType = useNavigationType();++ // The pages visited in this popup, which is what a restore replays so back keeps working across popup opens.+ const navigationStack = useRef<NavigationStackState>(createNavigationStack());// Auth and DB stateconst { isInitialized: authInitialized, isLoggedIn } = useApp();@@ -32,7 +39,15 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ chconst requiresAuth = isFullyInitialized && (!isLoggedIn || !dbAvailable);/**- * Store the current page path, timestamp, and navigation history in storage.+ * Adopt a restored navigation stack so it keeps growing from where the previous popup left off.+ * @param entries - The restored entries, oldest first+ */+ const seedStack = useCallback((entries: NavigationHistoryEntry[]): void => {+ navigationStack.current = seedNavigationStack(entries);+ }, []);++ /**+ * Track the current page in the navigation stack and persist it together with the visit time.*/const storeCurrentPage = useCallback(async (): Promise<void> => {// Pages that are not allowed to be stored as these are auth conditional pages or dedicated popup pages.@@ -45,30 +60,15 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch];// Only store the page if we're fully initialized and don't need auth- if (isFullyInitialized && !requiresAuth && !notAllowedPaths.includes(location.pathname)) {- // Split the path into segments and build up the history- const segments = location.pathname.split('/').filter(Boolean);- const historyEntries: NavigationHistoryEntry[] = [];-- // Build history entries for each segment- let currentPath = '';- for (let i = 0; i < segments.length; i++) {- currentPath += '/' + segments[i];-- /*- * For settings subpages, include both /settings and the subpage- * For email details, include both /emails and the specific email- */- historyEntries.push({- pathname: currentPath,- search: location.search,- hash: location.hash,- });- }-- await NavigationStateService.storeNavigationState(location.pathname, historyEntries);+ if (!isFullyInitialized || requiresAuth || notAllowedPaths.includes(location.pathname)) {+ return;}- }, [location, isFullyInitialized, requiresAuth]);++ const entry: NavigationHistoryEntry = { pathname: location.pathname, search: location.search, hash: location.hash };+ navigationStack.current = trackNavigation(navigationStack.current, entry, navigationType);++ await NavigationStateService.storeNavigationState(location.pathname, navigationStack.current.stack);+ }, [location, navigationType, isFullyInitialized, requiresAuth]);// Store the current page whenever it changesuseEffect(() => {@@ -112,9 +112,10 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch// Return the context valueconst contextValue = useMemo(() => ({storeCurrentPage,+ seedNavigationStack: seedStack,isFullyInitialized,requiresAuth- }), [storeCurrentPage, isFullyInitialized, requiresAuth]);+ }), [storeCurrentPage, seedStack, isFullyInitialized, requiresAuth]);return (<NavigationContext.Provider value={contextValue}>diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsxindex 4eb9f9474..e7041d80d 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx@@ -4,6 +4,7 @@ import { useLocation, useNavigate } from 'react-router-dom';import { useApp } from '@/entrypoints/popup/context/AppContext';import { useDb } from '@/entrypoints/popup/context/DbContext';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';+import { useNavigation } from '@/entrypoints/popup/context/NavigationContext';import useCurrentTabMatching from '@/entrypoints/popup/hooks/useCurrentTabMatching';import { consumePendingRedirectUrl } from '@/entrypoints/popup/hooks/useVaultLockRedirect';import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';@@ -23,6 +24,7 @@ const Reinitialize: React.FC = () => {const { setIsInitialLoading } = useLoading();const { syncVault } = useVaultSync();const { matchCurrentTab } = useCurrentTabMatching();+ const { seedNavigationStack } = useNavigation();const hasInitialized = useRef(false);// Auth and DB state@@ -78,20 +80,19 @@ const Reinitialize: React.FC = () => {const shouldUseFreshMatch = hasTabChanged || isOnDefaultIndexPage;if (!shouldUseFreshMatch) {- // Restore user's navigation since they navigated away from auto-matched page- if (savedHistory && savedHistory.length > 1) {- // Navigate to the base route first- const firstEntry = savedHistory[0];- const firstPath = firstEntry.pathname + (firstEntry.search || '');- navigate(firstPath, { replace: true });- // Then navigate to the final destination with search params- const finalPath = lastPage + (lastHistoryEntry?.search || '');- navigate(finalPath, { replace: false });- } else {- // Simple navigation for non-nested routes- const fullPath = lastPage + (lastHistoryEntry?.search || '');- navigate(fullPath, { replace: true });- }+ /*+ * Restore the user's navigation since they navigated away from the auto-matched page. The full+ * stack is replayed, not just its first and last page, so the back button walks the same trail+ * the user took (e.g. items > folder > item) instead of dropping them back on the index.+ */+ const entries = savedHistory && savedHistory.length > 0 && lastHistoryEntry?.pathname === lastPage+ ? savedHistory+ : [{ pathname: lastPage, search: lastHistoryEntry?.search ?? '', hash: '' }];++ seedNavigationStack(entries);+ entries.forEach((entry, index) => {+ navigate(entry.pathname + (entry.search || ''), { replace: index === 0 });+ });return;}}@@ -110,7 +111,7 @@ const Reinitialize: React.FC = () => {// Navigate to the items index: any current-site match is shown as a suggestion there.navigateToIndex();- }, [navigate, matchCurrentTab, navigateToIndex]);+ }, [navigate, matchCurrentTab, navigateToIndex, seedNavigationStack]);/*** Run sync in background. If server has newer vault, useVaultSync will:diff --git a/apps/browser-extension/src/utils/NavigationStack.ts b/apps/browser-extension/src/utils/NavigationStack.tsnew file mode 100644index 000000000..c429f4bf4--- /dev/null+++ b/apps/browser-extension/src/utils/NavigationStack.ts@@ -0,0 +1,113 @@+import type { NavigationHistoryEntry } from '@/utils/NavigationStateService';++/**+ * How many entries of the navigation stack are kept, which bounds how deep a restore replays.+ */+export const MAX_HISTORY_ENTRIES = 10;++/**+ * How the router got to the current page, mirroring react-router's navigation type.+ */+export type NavigationAction = 'POP' | 'PUSH' | 'REPLACE';++/**+ * The pages visited in this popup, in order, plus the restore that is still replaying onto it.+ */+export type NavigationStackState = {+ stack: NavigationHistoryEntry[];+ replay: NavigationHistoryEntry[] | null;+ replayCursor: number;+};++/**+ * Whether two entries point at the same page.+ * @param a - First entry+ * @param b - Second entry+ */+const isSamePage = (a: NavigationHistoryEntry | null | undefined, b: NavigationHistoryEntry): boolean => {+ return a?.pathname === b.pathname && a?.search === b.search;+};++/**+ * An empty stack, for a popup that starts without a restored trail.+ */+export const createNavigationStack = (): NavigationStackState => ({ stack: [], replay: null, replayCursor: 0 });++/**+ * Adopt a restored trail so the stack keeps growing from where the previous popup left off.+ * @param entries - The restored entries, oldest first+ */+export const seedNavigationStack = (entries: NavigationHistoryEntry[]): NavigationStackState => {+ const stack = entries.slice(-MAX_HISTORY_ENTRIES);+ return { stack, replay: [...stack], replayCursor: 0 };+};++/**+ * Fit a page that a restore is replaying onto the seeded trail.+ * @param state - The current stack state+ * @param entry - The page that was navigated to+ * @returns The new state, or null when the page is not part of the replay+ */+const applyReplay = (state: NavigationStackState, entry: NavigationHistoryEntry): NavigationStackState | null => {+ const { replay, replayCursor } = state;+ if (!replay) {+ return null;+ }++ if (isSamePage(replay[replayCursor], entry)) {+ const cursor = replayCursor + 1;+ return { stack: replay.slice(0, cursor), replay: cursor >= replay.length ? null : replay, replayCursor: cursor };+ }++ if (isSamePage(replay[replay.length - 1], entry)) {+ return { stack: [...replay], replay: null, replayCursor: 0 };+ }++ // The user navigated somewhere the replay does not cover, so the restore is over.+ return null;+};++/**+ * Record a page visit in the navigation stack.+ * @param state - The current stack state+ * @param entry - The page that was navigated to+ * @param action - How the router got there+ */+export const trackNavigation = (state: NavigationStackState, entry: NavigationHistoryEntry, action: NavigationAction): NavigationStackState => {+ const replayed = applyReplay(state, entry);+ if (replayed) {+ return replayed;+ }++ const stack = [...state.stack];+ const top = stack.length > 0 ? stack[stack.length - 1] : null;++ if (action === 'POP') {+ // Back/forward: cut the stack back to the page that was returned to.+ let index = -1;+ for (let i = stack.length - 1; i >= 0; i--) {+ if (isSamePage(stack[i], entry)) {+ index = i;+ break;+ }+ }++ if (index === -1) {+ stack.push(entry);+ } else {+ stack.length = index + 1;+ stack[index] = entry;+ }+ } else if (top && (action === 'REPLACE' || isSamePage(top, entry))) {+ // A replace, or a re-navigation to the page already on top, updates that entry instead of stacking a second one.+ stack[stack.length - 1] = entry;+ } else {+ stack.push(entry);+ }++ if (stack.length > MAX_HISTORY_ENTRIES) {+ stack.splice(0, stack.length - MAX_HISTORY_ENTRIES);+ }++ return { stack, replay: null, replayCursor: 0 };+};