Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(frontend): restore scroll position on browser navigation (#20920)

boojacka61cfc3d3864
diff --git a/frontend/src/react/app/RootLayout.tsx b/frontend/src/react/app/RootLayout.tsx
index 2a7d89d78c..816bef0afd 100644
--- a/frontend/src/react/app/RootLayout.tsx
+++ b/frontend/src/react/app/RootLayout.tsx
@@ -8,6 +8,7 @@ import { Watermark } from "@/react/components/Watermark";
import { AgentWindow } from "@/react/plugins/agent/components/AgentWindow";
import type { ReactRoute } from "@/react/router";
import { buildReactRoute, runBeforeEachGuards } from "@/react/router";
+import { NavigationScrollRestoration } from "@/react/router/NavigationScrollRestoration";
import { routes } from "@/react/router/routes";
// Translate a react-router Location into the legacy `ReactRoute` snapshot the
@@ -69,9 +70,11 @@ export function RootLayout() {
<AgentWindow />
<SessionExpiredSurfaceGate />
<LeaveGuardBlocker />
- <AuthGate>
- <Outlet />
- </AuthGate>
+ <NavigationScrollRestoration>
+ <AuthGate>
+ <Outlet />
+ </AuthGate>
+ </NavigationScrollRestoration>
</>
);
}
diff --git a/frontend/src/react/components/DashboardBodyShell.tsx b/frontend/src/react/components/DashboardBodyShell.tsx
index 5249bec97a..0c136e9f6d 100644
--- a/frontend/src/react/components/DashboardBodyShell.tsx
+++ b/frontend/src/react/components/DashboardBodyShell.tsx
@@ -8,6 +8,7 @@ import type {
DashboardShellTargets,
} from "@/react/dashboard-shell";
import { cn } from "@/react/lib/utils";
+import { MAIN_SCROLL_RESTORATION_ID } from "@/react/router/NavigationScrollRestoration";
function subscribeToViewport(onStoreChange: () => void) {
window.addEventListener("resize", onStoreChange);
@@ -144,6 +145,7 @@ export function DashboardBodyShell({
<div
id="bb-layout-main"
+ data-scroll-restoration-id={MAIN_SCROLL_RESTORATION_ID}
ref={mainContainerRef}
className={cn(
"flex-1 overflow-y-auto overscroll-y-contain",
diff --git a/frontend/src/react/components/RouterLink.test.tsx b/frontend/src/react/components/RouterLink.test.tsx
index 0d5ba55029..2faca870e8 100644
--- a/frontend/src/react/components/RouterLink.test.tsx
+++ b/frontend/src/react/components/RouterLink.test.tsx
@@ -207,4 +207,21 @@ describe("RouterLink", () => {
expect(mocks.push).not.toHaveBeenCalled();
unmount();
});
+
+ test("passes the scroll reset opt-out to the router", () => {
+ const to: RouteTarget = "/projects/default";
+ const { container, render, unmount } = renderIntoContainer(
+ <RouterLink to={to} preventScrollReset>
+ Project
+ </RouterLink>
+ );
+ render();
+
+ click(getLink(container));
+
+ expect(mocks.push).toHaveBeenCalledWith(to, {
+ preventScrollReset: true,
+ });
+ unmount();
+ });
});
diff --git a/frontend/src/react/components/RouterLink.tsx b/frontend/src/react/components/RouterLink.tsx
index af4d9451a3..4ec5b3b810 100644
--- a/frontend/src/react/components/RouterLink.tsx
+++ b/frontend/src/react/components/RouterLink.tsx
@@ -7,6 +7,7 @@ export type RouterLinkProps = Omit<
> & {
to: RouteTarget;
children?: ReactNode;
+ preventScrollReset?: boolean;
};
export function RouterLink({
@@ -15,6 +16,7 @@ export function RouterLink({
onClick,
target,
download,
+ preventScrollReset,
...props
}: RouterLinkProps) {
const href = router.resolve(to).href;
@@ -35,7 +37,13 @@ export function RouterLink({
}
event.preventDefault();
- router.push(to);
+ // Branch instead of always forwarding `{ preventScrollReset: undefined }`:
+ // many tests across the app assert the bare `router.push(to)` call shape.
+ if (preventScrollReset) {
+ router.push(to, { preventScrollReset });
+ } else {
+ router.push(to);
+ }
};
return (
diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsx
index 56c3aa80b7..286e47c9d5 100644
--- a/frontend/src/react/components/database/DatabaseTable.tsx
+++ b/frontend/src/react/components/database/DatabaseTable.tsx
@@ -6,6 +6,7 @@ import {
} from "@/react/hooks/useSessionPageSize";
import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import { router } from "@/react/router";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { autoDatabaseRoute } from "@/utils";
@@ -161,6 +162,12 @@ export function DatabaseTable({
fetchDatabases(false);
}
}, [isFetchingMore, fetchDatabases]);
+ useScrollRestorationLoadMore({
+ dataList: databases,
+ hasMore: !selectOnRowClick && hasMore,
+ isFetchingMore,
+ loadMore,
+ });
// Notify caller whenever the visible-page database list changes.
useEffect(() => {
diff --git a/frontend/src/react/hooks/useURLSearchParam.ts b/frontend/src/react/hooks/useURLSearchParam.ts
index cc2156a82d..7c9c6c4aaa 100644
--- a/frontend/src/react/hooks/useURLSearchParam.ts
+++ b/frontend/src/react/hooks/useURLSearchParam.ts
@@ -119,7 +119,10 @@ export function useURLSearchParam<T>({
if (apply(urlSearchParamsRef.current) === urlSearchParamsRef.current) {
return;
}
- setURLSearchParams(apply, { replace: true });
+ setURLSearchParams(apply, {
+ preventScrollReset: true,
+ replace: true,
+ });
},
[defaultValue, param, parse, serialize, setURLSearchParams]
);
diff --git a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
index 5face98cb3..b7a71847fa 100644
--- a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
@@ -18,6 +18,7 @@ import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { useURLSearchParam } from "@/react/hooks/useURLSearchParam";
import { refreshIssueList } from "@/react/lib/issue/issueListRefresh";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
@@ -122,6 +123,7 @@ export function ProjectIssueDashboardPage({
sessionKey: "bb.issue-table.project-issues",
fetchList: fetchIssueList,
});
+ useScrollRestorationLoadMore(paged);
useEffect(() => {
if (paged.dataList.length === 0) {
diff --git a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
index eea965f26b..a501eb23f1 100644
--- a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
@@ -60,6 +60,7 @@ import {
PROJECT_V1_ROUTE_PLAN_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
} from "@/react/router/handles";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import { buildPlanFindBySearchParams } from "@/react/stores/app/plan";
import { pushNotification } from "@/store";
@@ -212,6 +213,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
sessionKey: `bb.${projectName}.plan-table`,
fetchList: fetchPlanList,
});
+ useScrollRestorationLoadMore(paged);
useEffect(() => {
if (paged.dataList.length === 0) {
diff --git a/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx b/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
index 00681d9e0e..80063ad8ff 100644
--- a/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
@@ -24,6 +24,7 @@ import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { useURLSearchParam } from "@/react/hooks/useURLSearchParam";
import { cn } from "@/react/lib/utils";
import { router } from "@/react/router";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { getTimeForPbTimestampProtoEs } from "@/types";
@@ -86,6 +87,7 @@ export function ProjectReleaseDashboardPage({
sessionKey: `project-${projectName}-releases`,
fetchList: fetchReleaseList,
});
+ useScrollRestorationLoadMore(paged);
return (
<ProjectPageLayout>
diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsx
index 54008d9ee9..02c3c91399 100644
--- a/frontend/src/react/pages/settings/InstancesPage.tsx
+++ b/frontend/src/react/pages/settings/InstancesPage.tsx
@@ -79,6 +79,7 @@ import {
import { cn } from "@/react/lib/utils";
import { router, useCurrentRoute } from "@/react/router";
import { INSTANCE_ROUTE_CREATE } from "@/react/router/handles";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import type { InstanceFilter } from "@/react/stores/app/types";
import { pushNotification } from "@/store";
@@ -780,6 +781,12 @@ export function InstancesPage() {
fetchInstances(false);
}
}, [isFetchingMore, fetchInstances]);
+ useScrollRestorationLoadMore({
+ dataList: instances,
+ hasMore,
+ isFetchingMore,
+ loadMore,
+ });
// Selection state
const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
diff --git a/frontend/src/react/pages/settings/ProjectsPage.tsx b/frontend/src/react/pages/settings/ProjectsPage.tsx
index 93d471eb02..814a5ffca4 100644
--- a/frontend/src/react/pages/settings/ProjectsPage.tsx
+++ b/frontend/src/react/pages/settings/ProjectsPage.tsx
@@ -47,6 +47,7 @@ import {
import { cn } from "@/react/lib/utils";
import { router, useCurrentRoute } from "@/react/router";
import { PROJECT_V1_ROUTE_ISSUES } from "@/react/router/handles";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { getProjectName } from "@/store/modules/v1/common";
@@ -425,6 +426,12 @@ export function ProjectsPage() {
fetchProjects(false);
}
}, [isFetchingMore, fetchProjects]);
+ useScrollRestorationLoadMore({
+ dataList: projects,
+ hasMore,
+ isFetchingMore,
+ loadMore,
+ });
// Selection state
const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
diff --git a/frontend/src/react/pages/workspace/MyIssuesPage.tsx b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
index 19bcbe8e16..e13756eb9d 100644
--- a/frontend/src/react/pages/workspace/MyIssuesPage.tsx
+++ b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
@@ -16,6 +16,7 @@ import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { useURLSearchParam } from "@/react/hooks/useURLSearchParam";
import { refreshIssueList } from "@/react/lib/issue/issueListRefresh";
+import { useScrollRestorationLoadMore } from "@/react/router/NavigationScrollRestoration";
import { useAppStore } from "@/react/stores/app";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
@@ -88,6 +89,7 @@ export function MyIssuesPage() {
sessionKey: "bb.issue-table.my-issues",
fetchList: fetchIssueList,
});
+ useScrollRestorationLoadMore(paged);
useEffect(() => {
if (paged.dataList.length === 0) {
diff --git a/frontend/src/react/router/NavigationScrollRestoration.test.tsx b/frontend/src/react/router/NavigationScrollRestoration.test.tsx
new file mode 100644
index 0000000000..b0e339fecb
--- /dev/null
+++ b/frontend/src/react/router/NavigationScrollRestoration.test.tsx
@@ -0,0 +1,310 @@
+import { act, useState } from "react";
+import { createRoot } from "react-dom/client";
+import {
+ createMemoryRouter,
+ Outlet,
+ RouterProvider,
+} from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { setAppRouter } from "./navigation";
+import {
+ MAIN_SCROLL_RESTORATION_ID,
+ NavigationScrollRestoration,
+ useScrollRestorationLoadMore,
+} from "./NavigationScrollRestoration";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+function TestShell() {
+ return (
+ <NavigationScrollRestoration>
+ <div data-scroll-restoration-id={MAIN_SCROLL_RESTORATION_ID}>
+ <div data-scroll-restoration-id="panel">
+ <Outlet />
+ </div>
+ </div>
+ </NavigationScrollRestoration>
+ );
+}
+
+function makeScrollable(element: HTMLElement): void {
+ Object.defineProperties(element, {
+ clientHeight: { configurable: true, value: 200 },
+ clientWidth: { configurable: true, value: 200 },
+ scrollHeight: { configurable: true, value: 1000 },
+ scrollWidth: { configurable: true, value: 1000 },
+ });
+}
+
+function recordScroll(element: HTMLElement, top: number, left = 0): void {
+ element.scrollTop = top;
+ element.scrollLeft = left;
+ element.dispatchEvent(new Event("scroll"));
+}
+
+async function renderRouter(firstElement = <div>First</div>) {
+ const router = createMemoryRouter(
+ [
+ {
+ path: "/",
+ element: <TestShell />,
+ children: [
+ { path: "first", element: firstElement },
+ { path: "second", element: <div>Second</div> },
+ ],
+ },
+ ],
+ {
+ initialEntries: [{ pathname: "/first", key: "first-entry" }],
+ }
+ );
+ setAppRouter(router);
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(<RouterProvider router={router} />);
+ });
+
+ const main = container.querySelector<HTMLElement>(
+ `[data-scroll-restoration-id='${MAIN_SCROLL_RESTORATION_ID}']`
+ );
+ const panel = container.querySelector<HTMLElement>(
+ "[data-scroll-restoration-id='panel']"
+ );
+ if (!main || !panel) throw new Error("Missing test scroll targets");
+ makeScrollable(main);
+ makeScrollable(panel);
+
+ return {
+ main,
+ panel,
+ router,
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ container.remove();
+ });
+ router.dispose();
+ },
+ };
+}
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe("NavigationScrollRestoration", () => {
+ test("restores every scroll target on Back and Forward", async () => {
+ const { main, panel, router, unmount } = await renderRouter();
+
+ recordScroll(main, 240, 30);
+ recordScroll(panel, 120, 10);
+
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ expect(main.scrollTop).toBe(0);
+ expect(panel.scrollTop).toBe(0);
+
+ recordScroll(main, 360, 40);
+ recordScroll(panel, 180, 20);
+
+ await act(async () => {
+ await router.navigate(-1);
+ });
+ expect(main.scrollTop).toBe(240);
+ expect(main.scrollLeft).toBe(30);
+ expect(panel.scrollTop).toBe(120);
+ expect(panel.scrollLeft).toBe(10);
+
+ await act(async () => {
+ await router.navigate(1);
+ });
+ expect(main.scrollTop).toBe(360);
+ expect(main.scrollLeft).toBe(40);
+ expect(panel.scrollTop).toBe(180);
+ expect(panel.scrollLeft).toBe(20);
+
+ unmount();
+ });
+
+ test("snapshots the outgoing entry without waiting for a scroll event", async () => {
+ const { main, router, unmount } = await renderRouter();
+
+ main.scrollTop = 240;
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ await act(async () => {
+ await router.navigate(-1);
+ });
+
+ expect(main.scrollTop).toBe(240);
+ unmount();
+ });
+
+ test("restores after repeated Push and Back navigations", async () => {
+ const { main, router, unmount } = await renderRouter();
+
+ recordScroll(main, 240);
+ for (let i = 0; i < 3; i++) {
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ await act(async () => {
+ await router.navigate(-1);
+ });
+ expect(main.scrollTop).toBe(240);
+ }
+
+ unmount();
+ });
+
+ test("preserves the inherited position in a new history entry", async () => {
+ const { main, router, unmount } = await renderRouter();
+
+ recordScroll(main, 240);
+ await act(async () => {
+ await router.navigate("/first?tab=activity", {
+ preventScrollReset: true,
+ replace: true,
+ });
+ });
+ expect(main.scrollTop).toBe(240);
+
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ await act(async () => {
+ await router.navigate(-1);
+ });
+
+ expect(router.state.location.search).toBe("?tab=activity");
+ expect(main.scrollTop).toBe(240);
+ unmount();
+ });
+
+ test("asks paged content to grow until the saved position is reachable", async () => {
+ const onLoadMore = vi.fn();
+ const PagedPage = () => {
+ useScrollRestorationLoadMore({
+ hasMore: true,
+ isFetchingMore: false,
+ dataList: [],
+ loadMore: onLoadMore,
+ });
+ return <div>First</div>;
+ };
+ const { main, router, unmount } = await renderRouter(<PagedPage />);
+
+ recordScroll(main, 700);
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ Object.defineProperty(main, "scrollHeight", {
+ configurable: true,
+ value: 300,
+ });
+
+ await act(async () => {
+ await router.navigate(-1);
+ });
+
+ expect(onLoadMore).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ test("stops growing paged content after the user cancels restoration", async () => {
+ const onLoadMore = vi.fn();
+ let appendItem: (() => void) | undefined;
+ const PagedPage = () => {
+ const [dataList, setDataList] = useState<unknown[]>([]);
+ appendItem = () => setDataList((list) => [...list, {}]);
+ useScrollRestorationLoadMore({
+ hasMore: true,
+ isFetchingMore: false,
+ dataList,
+ loadMore: onLoadMore,
+ });
+ return <div>First</div>;
+ };
+ const { main, router, unmount } = await renderRouter(<PagedPage />);
+
+ recordScroll(main, 700);
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ Object.defineProperty(main, "scrollHeight", {
+ configurable: true,
+ value: 300,
+ });
+ await act(async () => {
+ await router.navigate(-1);
+ });
+ expect(onLoadMore).toHaveBeenCalledOnce();
+
+ await act(async () => {
+ document.dispatchEvent(new Event("pointerdown"));
+ });
+ act(() => appendItem?.());
+
+ expect(onLoadMore).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ test("keeps growing while a page request exceeds the idle timeout", async () => {
+ vi.useFakeTimers();
+ const onLoadMore = vi.fn();
+ let finishPage: (() => void) | undefined;
+ const PagedPage = () => {
+ const [dataList, setDataList] = useState<unknown[]>([]);
+ const [isFetchingMore, setIsFetchingMore] = useState(false);
+ finishPage = () => {
+ setDataList((list) => [...list, {}]);
+ setIsFetchingMore(false);
+ };
+ useScrollRestorationLoadMore({
+ hasMore: true,
+ isFetchingMore,
+ dataList,
+ loadMore: () => {
+ onLoadMore();
+ setIsFetchingMore(true);
+ },
+ });
+ return <div>First</div>;
+ };
+ const { main, router, unmount } = await renderRouter(<PagedPage />);
+
+ recordScroll(main, 700);
+ await act(async () => {
+ await router.navigate("/second");
+ });
+ Object.defineProperty(main, "scrollHeight", {
+ configurable: true,
+ value: 300,
+ });
+ await act(async () => {
+ await router.navigate(-1);
+ });
+ expect(onLoadMore).toHaveBeenCalledOnce();
+
+ await act(async () => {
+ vi.advanceTimersByTime(30001);
+ });
+ act(() => finishPage?.());
+
+ expect(onLoadMore).toHaveBeenCalledTimes(2);
+ unmount();
+ });
+});
diff --git a/frontend/src/react/router/NavigationScrollRestoration.tsx b/frontend/src/react/router/NavigationScrollRestoration.tsx
new file mode 100644
index 0000000000..45a30e89d1
--- /dev/null
+++ b/frontend/src/react/router/NavigationScrollRestoration.tsx
@@ -0,0 +1,581 @@
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import {
+ type Location,
+ useLocation,
+ useNavigationType,
+} from "react-router-dom";
+import type { PagedDataResult } from "@/react/hooks/usePagedData";
+import { getAppRouterState, subscribeRoute } from "@/react/router/navigation";
+import { minmax } from "@/utils/math";
+
+const STORAGE_KEY = "bb.navigation-scroll-restoration";
+const MAX_SAVED_ENTRIES = 50;
+const RESTORE_IDLE_TIMEOUT_MS = 30000;
+const RESTORE_MAX_TIMEOUT_MS = 5 * 60 * 1000;
+const WINDOW_TARGET_ID = "window";
+const CUSTOM_TARGET_PREFIX = "custom:";
+const TARGET_ATTRIBUTE = "data-scroll-restoration-id";
+/** The `data-scroll-restoration-id` value carried by the main layout pane. */
+export const MAIN_SCROLL_RESTORATION_ID = "main";
+const SCROLL_KEYS = new Set([
+ "ArrowDown",
+ "ArrowUp",
+ "End",
+ "Home",
+ "PageDown",
+ "PageUp",
+ " ",
+]);
+
+type ScrollPosition = {
+ x: number;
+ y: number;
+};
+
+type SavedPositions = Record<string, Record<string, ScrollPosition>>;
+type ScrollTarget = Window | HTMLElement;
+
+type ActiveRestoration = {
+ locationKey: string;
+ positions: Record<string, ScrollPosition>;
+};
+
+type PendingRestore = {
+ cancel: () => void;
+ keepAlive: () => void;
+ setBusy: (busy: boolean) => void;
+};
+
+type ScrollRestorationContextValue = {
+ positions: Record<string, ScrollPosition>;
+ keepAlive: (id: string) => void;
+ setBusy: (id: string, busy: boolean) => void;
+};
+
+const ScrollRestorationContext = createContext<
+ ScrollRestorationContextValue | undefined
+>(undefined);
+
+function isWindowTarget(target: ScrollTarget): target is Window {
+ return target === window;
+}
+
+function locationStorageKey(location: Location): string {
+ if (location.key !== "default") {
+ return location.key;
+ }
+ return `default:${location.pathname}${location.search}${location.hash}`;
+}
+
+function loadSavedPositions(): SavedPositions {
+ try {
+ const saved = sessionStorage.getItem(STORAGE_KEY);
+ return saved ? (JSON.parse(saved) as SavedPositions) : {};
+ } catch {
+ return {};
+ }
+}
+
+function persistSavedPositions(savedPositions: SavedPositions): void {
+ try {
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(savedPositions));
+ } catch {
+ // Scroll restoration is best-effort when storage is unavailable.
+ }
+}
+
+function savePosition(
+ savedPositions: SavedPositions,
+ locationKey: string,
+ targetId: string,
+ position: ScrollPosition
+): void {
+ if (!savedPositions[locationKey]) {
+ const savedKeys = Object.keys(savedPositions);
+ if (savedKeys.length >= MAX_SAVED_ENTRIES) {
+ delete savedPositions[savedKeys[0]];
+ }
+ savedPositions[locationKey] = {};
+ }
+ savedPositions[locationKey][targetId] = position;
+}
+
+function copyPositions(
+ savedPositions: SavedPositions,
+ fromLocationKey: string,
+ toLocationKey: string
+): void {
+ const positions = savedPositions[fromLocationKey];
+ if (!positions || fromLocationKey === toLocationKey) return;
+ for (const [id, position] of Object.entries(positions)) {
+ savePosition(savedPositions, toLocationKey, id, { ...position });
+ }
+}
+
+function customTargetId(value: string): string {
+ return `${CUSTOM_TARGET_PREFIX}${value}`;
+}
+
+function targetId(target: EventTarget | null): string | undefined {
+ if (target === document) {
+ return WINDOW_TARGET_ID;
+ }
+ if (!(target instanceof HTMLElement)) {
+ return undefined;
+ }
+ const id = target.getAttribute(TARGET_ATTRIBUTE);
+ return id ? customTargetId(id) : undefined;
+}
+
+function findTarget(id: string): ScrollTarget | null {
+ if (id === WINDOW_TARGET_ID) {
+ return window;
+ }
+ if (!id.startsWith(CUSTOM_TARGET_PREFIX)) {
+ return null;
+ }
+ const value = id.slice(CUSTOM_TARGET_PREFIX.length);
+ return document.querySelector<HTMLElement>(
+ `[${TARGET_ATTRIBUTE}="${CSS.escape(value)}"]`
+ );
+}
+
+function collectTargets(): Map<string, ScrollTarget> {
+ const targets = new Map<string, ScrollTarget>([[WINDOW_TARGET_ID, window]]);
+ for (const element of document.querySelectorAll<HTMLElement>(
+ `[${TARGET_ATTRIBUTE}]`
+ )) {
+ const id = element.getAttribute(TARGET_ATTRIBUTE);
+ if (id) {
+ targets.set(customTargetId(id), element);
+ }
+ }
+ return targets;
+}
+
+function readPosition(target: ScrollTarget): ScrollPosition {
+ if (isWindowTarget(target)) {
+ return { x: window.scrollX, y: window.scrollY };
+ }
+ return { x: target.scrollLeft, y: target.scrollTop };
+}
+
+function scrollRange(target: ScrollTarget): ScrollPosition {
+ if (isWindowTarget(target)) {
+ const root = document.documentElement;
+ const body = document.body;
+ return {
+ x: Math.max(
+ 0,
+ Math.max(root.scrollWidth, body?.scrollWidth ?? 0) - window.innerWidth
+ ),
+ y: Math.max(
+ 0,
+ Math.max(root.scrollHeight, body?.scrollHeight ?? 0) -
+ window.innerHeight
+ ),
+ };
+ }
+ return {
+ x: Math.max(0, target.scrollWidth - target.clientWidth),
+ y: Math.max(0, target.scrollHeight - target.clientHeight),
+ };
+}
+
+function applyPosition(
+ target: ScrollTarget,
+ position: ScrollPosition
+): { range: ScrollPosition; reached: boolean } {
+ const range = scrollRange(target);
+ const x = minmax(position.x, 0, range.x);
+ const y = minmax(position.y, 0, range.y);
+ if (isWindowTarget(target)) {
+ if (window.scrollX !== x || window.scrollY !== y) {
+ window.scrollTo(x, y);
+ }
+ } else {
+ if (target.scrollLeft !== x) target.scrollLeft = x;
+ if (target.scrollTop !== y) target.scrollTop = y;
+ }
+ return {
+ range,
+ reached: range.x >= position.x && range.y >= position.y,
+ };
+}
+
+function restoreWhenReady(
+ id: string,
+ position: ScrollPosition,
+ onDone: () => void
+): PendingRestore {
+ let stopped = false;
+ let busy = false;
+ let animationFrameId: number | undefined;
+ let intervalId: number | undefined;
+ let timeoutId: number | undefined;
+ let maxTimeoutId: number | undefined;
+ let resizeObserver: ResizeObserver | undefined;
+ let observedTarget: ScrollTarget | null = null;
+ let lastRange: ScrollPosition | undefined;
+
+ const stop = () => {
+ if (stopped) return;
+ stopped = true;
+ if (animationFrameId !== undefined) {
+ window.cancelAnimationFrame(animationFrameId);
+ }
+ if (intervalId !== undefined) window.clearInterval(intervalId);
+ if (timeoutId !== undefined) window.clearTimeout(timeoutId);
+ if (maxTimeoutId !== undefined) window.clearTimeout(maxTimeoutId);
+ resizeObserver?.disconnect();
+ onDone();
+ };
+
+ const keepAlive = () => {
+ if (stopped) return;
+ if (timeoutId !== undefined) window.clearTimeout(timeoutId);
+ timeoutId = window.setTimeout(() => {
+ if (busy) {
+ keepAlive();
+ return;
+ }
+ stop();
+ }, RESTORE_IDLE_TIMEOUT_MS);
+ };
+
+ const attempt = () => {
+ if (stopped) return;
+ if (
+ !observedTarget ||
+ (!isWindowTarget(observedTarget) && !observedTarget.isConnected)
+ ) {
+ const target = findTarget(id);
+ if (!target) return;
+ resizeObserver?.disconnect();
+ resizeObserver = new ResizeObserver(attempt);
+ const observedElement = isWindowTarget(target)
+ ? document.documentElement
+ : target;
+ resizeObserver.observe(observedElement);
+ if (
+ !isWindowTarget(target) &&
+ target.firstElementChild instanceof HTMLElement
+ ) {
+ resizeObserver.observe(target.firstElementChild);
+ }
+ observedTarget = target;
+ lastRange = undefined;
+ }
+ const { range, reached } = applyPosition(observedTarget, position);
+ if (reached) {
+ stop();
+ return;
+ }
+ if (!lastRange || range.x > lastRange.x || range.y > lastRange.y) {
+ keepAlive();
+ }
+ lastRange = range;
+ };
+
+ attempt();
+ if (!stopped) {
+ animationFrameId = window.requestAnimationFrame(attempt);
+ intervalId = window.setInterval(attempt, 100);
+ maxTimeoutId = window.setTimeout(stop, RESTORE_MAX_TIMEOUT_MS);
+ keepAlive();
+ }
+ return {
+ cancel: stop,
+ keepAlive,
+ setBusy: (value) => {
+ busy = value;
+ keepAlive();
+ },
+ };
+}
+
+// Resetting needs no clamping, so skip the forced-layout reads of
+// `applyPosition` — this runs on every forward navigation.
+function resetTargets(): void {
+ for (const target of collectTargets().values()) {
+ if (isWindowTarget(target)) {
+ window.scrollTo(0, 0);
+ } else {
+ target.scrollLeft = 0;
+ target.scrollTop = 0;
+ }
+ }
+}
+
+function scrollToHash(hash: string): boolean {
+ try {
+ const element = document.getElementById(decodeURIComponent(hash.slice(1)));
+ if (!element) return false;
+ element.scrollIntoView();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+type NavigationScrollRestorationProps = {
+ children: ReactNode;
+};
+
+export function useScrollRestorationLoadMore(
+ paged: Pick<
+ PagedDataResult<unknown>,
+ "hasMore" | "isFetchingMore" | "dataList" | "loadMore"
+ >,
+ /** The value of `data-scroll-restoration-id`; omit for the main layout pane. */
+ restorationId: string = MAIN_SCROLL_RESTORATION_ID
+): void {
+ const { hasMore, isFetchingMore, dataList, loadMore } = paged;
+ const restoration = useContext(ScrollRestorationContext);
+ const id = customTargetId(restorationId);
+ // Depend on the primitive: the saved-position record is replaced on every
+ // scroll event, so its identity churns without the requested `y` changing.
+ const requestedY = restoration?.positions[id]?.y;
+ const itemCount = dataList.length;
+
+ useEffect(() => {
+ if (requestedY === undefined) return;
+ restoration?.setBusy(id, isFetchingMore);
+ return () => restoration?.setBusy(id, false);
+ }, [id, isFetchingMore, requestedY, restoration]);
+
+ useEffect(() => {
+ if (requestedY === undefined || !hasMore || isFetchingMore) return;
+ const target = findTarget(id);
+ if (!target || scrollRange(target).y >= requestedY) return;
+ restoration?.keepAlive(id);
+ loadMore();
+ }, [
+ hasMore,
+ id,
+ isFetchingMore,
+ itemCount,
+ loadMore,
+ requestedY,
+ restoration,
+ ]);
+}
+
+/**
+ * Restores registered scroll containers by browser history entry.
+ * Nested containers opt in with `data-scroll-restoration-id="stable-id"`
+ * (the main layout pane registers as `MAIN_SCROLL_RESTORATION_ID`).
+ *
+ * Hand-rolled instead of react-router's `<ScrollRestoration>`, which only
+ * handles window scroll: this app scrolls in nested containers and needs the
+ * `useScrollRestorationLoadMore` growth protocol for paged lists. Never mount
+ * the built-in alongside — both manage `history.scrollRestoration` and would
+ * fight over the window position.
+ */
+export function NavigationScrollRestoration({
+ children,
+}: NavigationScrollRestorationProps) {
+ const location = useLocation();
+ const navigationType = useNavigationType();
+ // Lazy state, not `useRef(loadSavedPositions())`: a ref initializer argument
+ // is evaluated (storage read + JSON parse) on every render.
+ const [savedPositions] = useState(loadSavedPositions);
+ const locationKey = locationStorageKey(location);
+ const currentLocationKeyRef = useRef(locationKey);
+ const [pendingRestores] = useState(() => new Map<string, PendingRestore>());
+ const restorationGenerationRef = useRef(0);
+ const [activeRestoration, setActiveRestoration] =
+ useState<ActiveRestoration>();
+
+ const cancelPendingRestores = useCallback(() => {
+ restorationGenerationRef.current++;
+ for (const pending of pendingRestores.values()) {
+ pending.cancel();
+ }
+ pendingRestores.clear();
+ setActiveRestoration(undefined);
+ }, [pendingRestores]);
+
+ const keepRestorationAlive = useCallback(
+ (id: string) => pendingRestores.get(id)?.keepAlive(),
+ [pendingRestores]
+ );
+
+ const setRestorationBusy = useCallback(
+ (id: string, busy: boolean) => pendingRestores.get(id)?.setBusy(busy),
+ [pendingRestores]
+ );
+
+ const recordTarget = useCallback(
+ (target: EventTarget | null) => {
+ const id = targetId(target);
+ if (!id || pendingRestores.has(id)) return;
+ // Scroll events fire at frame rate: read the scrolled element directly
+ // instead of re-querying the DOM for it, and defer persistence to
+ // pagehide/unmount (SPA restores read the in-memory map).
+ savePosition(
+ savedPositions,
+ currentLocationKeyRef.current,
+ id,
+ readPosition(target === document ? window : (target as HTMLElement))
+ );
+ },
+ [pendingRestores, savedPositions]
+ );
+
+ const recordAllTargets = useCallback(
+ (locationKey?: string) => {
+ const key = locationKey ?? currentLocationKeyRef.current;
+ for (const [id, target] of collectTargets()) {
+ if (pendingRestores.has(id)) continue;
+ savePosition(savedPositions, key, id, readPosition(target));
+ }
+ },
+ [pendingRestores, savedPositions]
+ );
+
+ const flushToStorage = useCallback(() => {
+ recordAllTargets();
+ persistSavedPositions(savedPositions);
+ }, [recordAllTargets, savedPositions]);
+
+ useEffect(() => subscribeRoute(recordAllTargets), [recordAllTargets]);
+
+ useEffect(() => {
+ // Window scrolls arrive here too, targeting `document` — no separate
+ // window listener needed.
+ const handleElementScroll = (event: Event) => recordTarget(event.target);
+ const handleUserScrollIntent = () => cancelPendingRestores();
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (SCROLL_KEYS.has(event.key)) {
+ cancelPendingRestores();
+ }
+ };
+
+ document.addEventListener("scroll", handleElementScroll, {
+ capture: true,
+ passive: true,
+ });
+ document.addEventListener("pointerdown", handleUserScrollIntent, true);
+ document.addEventListener("touchstart", handleUserScrollIntent, {
+ capture: true,
+ passive: true,
+ });
+ document.addEventListener("wheel", handleUserScrollIntent, {
+ capture: true,
+ passive: true,
+ });
+ document.addEventListener("keydown", handleKeyDown, true);
+ window.addEventListener("pagehide", flushToStorage);
+
+ return () => {
+ document.removeEventListener("scroll", handleElementScroll, true);
+ document.removeEventListener("pointerdown", handleUserScrollIntent, true);
+ document.removeEventListener("touchstart", handleUserScrollIntent, true);
+ document.removeEventListener("wheel", handleUserScrollIntent, true);
+ document.removeEventListener("keydown", handleKeyDown, true);
+ window.removeEventListener("pagehide", flushToStorage);
+ };
+ }, [cancelPendingRestores, flushToStorage, recordTarget]);
+
+ useEffect(() => {
+ const previous = window.history.scrollRestoration;
+ window.history.scrollRestoration = "manual";
+ return () => {
+ window.history.scrollRestoration = previous;
+ flushToStorage();
+ };
+ }, [flushToStorage]);
+
+ useLayoutEffect(() => {
+ const previousLocationKey = currentLocationKeyRef.current;
+ if (previousLocationKey !== locationKey) {
+ recordAllTargets(previousLocationKey);
+ }
+ cancelPendingRestores();
+ currentLocationKeyRef.current = locationKey;
+ const savedForLocation = savedPositions[locationKey];
+ const preventScrollReset = getAppRouterState()?.preventScrollReset === true;
+
+ if (preventScrollReset) {
+ copyPositions(savedPositions, previousLocationKey, locationKey);
+ }
+
+ if (navigationType === "POP" && savedForLocation) {
+ const currentTargets = collectTargets();
+ const targetIds = new Set([
+ ...currentTargets.keys(),
+ ...Object.keys(savedForLocation),
+ ]);
+ const generation = restorationGenerationRef.current;
+ let remaining = targetIds.size;
+ setActiveRestoration({ locationKey, positions: savedForLocation });
+
+ for (const id of targetIds) {
+ const position = savedForLocation[id] ?? { x: 0, y: 0 };
+ // `restoreWhenReady` may finish synchronously; only register the
+ // canceler while the restore is still pending.
+ let settled = false;
+ const pending = restoreWhenReady(id, position, () => {
+ settled = true;
+ pendingRestores.delete(id);
+ if (restorationGenerationRef.current !== generation) return;
+ remaining--;
+ if (remaining === 0) {
+ setActiveRestoration(undefined);
+ }
+ });
+ if (!settled) {
+ pendingRestores.set(id, pending);
+ }
+ }
+ return cancelPendingRestores;
+ }
+
+ if (location.hash && scrollToHash(location.hash)) {
+ return;
+ }
+
+ if (preventScrollReset) {
+ return;
+ }
+
+ resetTargets();
+ }, [
+ cancelPendingRestores,
+ location,
+ locationKey,
+ navigationType,
+ pendingRestores,
+ recordAllTargets,
+ savedPositions,
+ ]);
+
+ const requestedRestoration = useMemo(
+ () =>
+ activeRestoration?.locationKey === locationKey
+ ? {
+ positions: activeRestoration.positions,
+ keepAlive: keepRestorationAlive,
+ setBusy: setRestorationBusy,
+ }
+ : undefined,
+ [activeRestoration, keepRestorationAlive, locationKey, setRestorationBusy]
+ );
+
+ return (
+ <ScrollRestorationContext value={requestedRestoration}>
+ {children}
+ </ScrollRestorationContext>
+ );
+}
diff --git a/frontend/src/react/router/index.ts b/frontend/src/react/router/index.ts
index e86885b97e..c039142da2 100644
--- a/frontend/src/react/router/index.ts
+++ b/frontend/src/react/router/index.ts
@@ -5,7 +5,11 @@ import {
useParams,
} from "react-router-dom";
import type { Permission } from "@/types";
-import type { RouterLocation, RouterMatch } from "./navigation";
+import type {
+ NavigationOptions,
+ RouterLocation,
+ RouterMatch,
+} from "./navigation";
import {
buildSearchString,
getAppRouterState,
@@ -227,14 +231,23 @@ export function resolveRoute(to: RouteTarget): ReactResolvedRoute {
return { href: fullPath, fullPath };
}
+type PushOptions = Omit<NavigationOptions, "replace">;
+
+function pushRoute(to: RouteTarget, options?: PushOptions): Promise<void> {
+ return navigateToPath(resolveTarget(to), options);
+}
+
+function replaceRoute(to: RouteTarget, options?: PushOptions): Promise<void> {
+ return navigateToPath(resolveTarget(to), { ...options, replace: true });
+}
+
export function useNavigate() {
// Hook call keeps React's router context wired; navigation itself goes
// through the resolver so by-name targets keep working.
useReactRouterNavigate();
return {
- push: (to: RouteTarget) => navigateToPath(resolveTarget(to)),
- replace: (to: RouteTarget) =>
- navigateToPath(resolveTarget(to), { replace: true }),
+ push: pushRoute,
+ replace: replaceRoute,
resolve: resolveRoute,
};
}
@@ -294,9 +307,8 @@ export function runBeforeEachGuards(
}
export const router = {
- push: (to: RouteTarget) => navigateToPath(resolveTarget(to)),
- replace: (to: RouteTarget) =>
- navigateToPath(resolveTarget(to), { replace: true }),
+ push: pushRoute,
+ replace: replaceRoute,
resolve: (to: RouteTarget): ReactResolvedRoute => resolveRoute(to),
back: () => routerGo(-1),
go: (delta: number) => routerGo(delta),
diff --git a/frontend/src/react/router/navigation.test.ts b/frontend/src/react/router/navigation.test.ts
index b17a0cee38..2082e8cfa8 100644
--- a/frontend/src/react/router/navigation.test.ts
+++ b/frontend/src/react/router/navigation.test.ts
@@ -112,10 +112,16 @@ describe("navigation dispatch", () => {
});
});
- test("navigateToPath passes the raw path through", () => {
+ test("navigateToPath passes the raw path and navigation options through", () => {
const navigate = vi.fn();
setAppRouter({ navigate });
- navigateToPath("/raw", { replace: false });
- expect(navigate).toHaveBeenCalledWith("/raw", { replace: false });
+ navigateToPath("/raw", {
+ preventScrollReset: true,
+ replace: false,
+ });
+ expect(navigate).toHaveBeenCalledWith("/raw", {
+ preventScrollReset: true,
+ replace: false,
+ });
});
});
diff --git a/frontend/src/react/router/navigation.ts b/frontend/src/react/router/navigation.ts
index ffb0b4a786..9c43adb4e8 100644
--- a/frontend/src/react/router/navigation.ts
+++ b/frontend/src/react/router/navigation.ts
@@ -9,13 +9,18 @@ export type RouterState = {
location: RouterLocation;
matches: RouterMatch[];
initialized: boolean;
+ preventScrollReset?: boolean;
+};
+export type NavigationOptions = {
+ replace?: boolean;
+ preventScrollReset?: boolean;
};
type AppRouterLike = {
// Overloaded to match the data router (`navigate(delta)` /
// `navigate(to, opts)`), so the concrete instance is assignable.
navigate: {
(delta: number): Promise<void>;
- (to: string, opts?: { replace?: boolean }): Promise<void>;
+ (to: string, opts?: NavigationOptions): Promise<void>;
};
subscribe?: (fn: (state: RouterState) => void) => () => void;
state?: RouterState;
@@ -110,26 +115,19 @@ export function setAppRouter(router: AppRouterLike): void {
// Navigate by route name (mirrors vue-router `router.push({ name, query })`).
export function navigateByName(
name: string,
- options: {
- params?: NavParams;
- query?: NavQuery;
- replace?: boolean;
- } = {}
+ options: { params?: NavParams; query?: NavQuery } & NavigationOptions = {}
): Promise<void> {
- const path = resolvePath(name, options);
- return Promise.resolve(
- appRouter?.navigate(path, { replace: options.replace })
- );
+ const { params, query, ...navigationOptions } = options;
+ const path = resolvePath(name, { params, query });
+ return Promise.resolve(appRouter?.navigate(path, navigationOptions));
}
// Navigate to a raw path (mirrors `router.push(path)` / `router.replace(path)`).
export function navigateToPath(
path: string,
- options: { replace?: boolean } = {}
+ options: NavigationOptions = {}
): Promise<void> {
- return Promise.resolve(
- appRouter?.navigate(path, { replace: options.replace })
- );
+ return Promise.resolve(appRouter?.navigate(path, options));
}
// Current data-router state (location + matches), for non-hook snapshots used
diff --git a/frontend/src/utils/web-storage.ts b/frontend/src/utils/web-storage.ts
index b79d823190..9bc1949773 100644
--- a/frontend/src/utils/web-storage.ts
+++ b/frontend/src/utils/web-storage.ts
@@ -11,7 +11,7 @@ export class WebStorageHelper {
const fullKey = `${this.keyPrefix}.${key}`;
try {
const json = JSON.stringify(value);
- localStorage.setItem(fullKey, json);
+ this.storage.setItem(fullKey, json);
} catch {
// nothing
}
@@ -20,7 +20,7 @@ export class WebStorageHelper {
load<T>(key: string, fallbackValue: T) {
const fullKey = `${this.keyPrefix}.${key}`;
try {
- const json = localStorage.getItem(fullKey) || "";
+ const json = this.storage.getItem(fullKey) || "";
return JSON.parse(json) as T;
} catch {
return fallbackValue;
@@ -30,17 +30,17 @@ export class WebStorageHelper {
remove(key: string) {
const fullKey = `${this.keyPrefix}.${key}`;
try {
- localStorage.removeItem(fullKey);
+ this.storage.removeItem(fullKey);
} catch {
// nothing
}
}
keys(): string[] {
- const { length } = localStorage;
+ const { length } = this.storage;
const keys: string[] = [];
for (let i = 0; i < length; i++) {
- const key = localStorage.key(i);
+ const key = this.storage.key(i);
if (key && key.startsWith(this.keyPrefix)) {
keys.push(key);
}
@@ -51,7 +51,7 @@ export class WebStorageHelper {
clear() {
const keys = this.keys();
keys.forEach((key) => {
- localStorage.removeItem(key);
+ this.storage.removeItem(key);
});
}
}