Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(views): keep every page's scroll position across Desktop tab switches (MUL-9567) (#10896)

Multica Eve4b3697363002
diff --git a/apps/docs/content/docs/desktop-app.mdx b/apps/docs/content/docs/desktop-app.mdx
index a93db0de8f..f85fa612ab 100644
--- a/apps/docs/content/docs/desktop-app.mdx
+++ b/apps/docs/content/docs/desktop-app.mdx
@@ -52,7 +52,7 @@ Desktop saves tabs per workspace. For example, if you open three issues in works
A given resource opens only once in the current workspace. Tabs can be reordered, pinned, and closed, and each keeps its own forward/back history and scroll position. Pinned tabs sit at the left end and have no close button; unpin a tab to close it. Opening another page from a pinned tab opens a new tab, and the pinned tab stays where it is. Clicking or pasting an app link for this deployment opens it directly in a tab instead of jumping to the browser.
-Switching between Board, List, and Swimlane in a tab also keeps each view's latest scroll position, including the board's horizontal position and scrolling within its columns.
+Switching between Board, List, Table, Swimlane, and Gantt in a tab also keeps each view's latest scroll position, including the board's horizontal position and scrolling within its columns.
Logging out clears every tab saved on the machine, so the next person to sign in never sees pages left behind by the previous account.
diff --git a/apps/docs/content/docs/desktop-app.zh.mdx b/apps/docs/content/docs/desktop-app.zh.mdx
index 754c1be8cf..a13044a794 100644
--- a/apps/docs/content/docs/desktop-app.zh.mdx
+++ b/apps/docs/content/docs/desktop-app.zh.mdx
@@ -52,7 +52,7 @@ Desktop 会为每个工作区单独保存标签页。例如,你在工作区 A
同一资源只会在当前工作区打开一次。标签页可以重新排序、固定、关闭,也会保留各自的前进、后退和滚动位置。固定的标签页排在最左边,没有关闭按钮,要先取消固定才能关;在它里面打开别的页面时会新开一个标签页,它自己停在原页面。点击或粘贴本部署的应用链接会直接在标签页中打开,不会跳转到浏览器。
-在标签页内切换看板、列表和泳道时,也会保留各视图最新的滚动位置,包括看板的横向位置和列内滚动位置。
+在标签页内切换看板、列表、表格、泳道和甘特图时,也会保留各视图最新的滚动位置,包括看板的横向位置和列内滚动位置。
退出登录会清除本机保存的所有标签页,避免下一位登录者看到上一个账号留下的页面。
diff --git a/packages/ui/components/ui/data-table.test.tsx b/packages/ui/components/ui/data-table.test.tsx
new file mode 100644
index 0000000000..9922fc29ac
--- /dev/null
+++ b/packages/ui/components/ui/data-table.test.tsx
@@ -0,0 +1,93 @@
+import { render } from "@testing-library/react";
+import {
+ getCoreRowModel,
+ useReactTable,
+ type ColumnDef,
+} from "@tanstack/react-table";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { DataTable } from "./data-table";
+
+type Row = { title: string };
+
+const columns: ColumnDef<Row>[] = [{ accessorKey: "title", header: "Issue" }];
+
+function Table({
+ rowCount,
+ scrollContainerRef,
+ initialScrollTop,
+}: {
+ rowCount: number;
+ scrollContainerRef?: (element: HTMLDivElement | null) => void;
+ initialScrollTop?: number;
+}) {
+ const table = useReactTable({
+ data: Array.from({ length: rowCount }, (_, i) => ({ title: `Row ${i}` })),
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ });
+ return (
+ <DataTable
+ table={table}
+ virtualizeRows
+ virtualRowHeight={40}
+ scrollContainerRef={scrollContainerRef}
+ initialScrollTop={initialScrollTop}
+ scrollContainerAttributes={{ "data-tab-scroll-root": "table" }}
+ />
+ );
+}
+
+describe("DataTable scroll container", () => {
+ // jsdom has no Element.scrollTo, which the row virtualizer calls on the
+ // scroller when it attaches; without it that call would silently vanish.
+ beforeEach(() => {
+ HTMLElement.prototype.scrollTo = function (this: HTMLElement, options?: ScrollToOptions | number) {
+ if (typeof options === "object" && options.top !== undefined) this.scrollTop = options.top;
+ } as HTMLElement["scrollTo"];
+ });
+ afterEach(() => {
+ delete (HTMLElement.prototype as Partial<HTMLElement>).scrollTo;
+ });
+
+ // The virtualizer scrolls its element to its initial offset when it
+ // attaches, after the caller's ref has assigned the restored one.
+ it("opens at initialScrollTop instead of being scrolled back to the top", () => {
+ const { container } = render(
+ <Table
+ rowCount={500}
+ initialScrollTop={2400}
+ scrollContainerRef={(el) => {
+ if (el) el.scrollTop = 2400;
+ }}
+ />,
+ );
+
+ const scroller = container.querySelector<HTMLElement>('[data-tab-scroll-root="table"]');
+ expect(scroller?.scrollTop).toBe(2400);
+ });
+
+ it("hands the scroller to the caller and carries its data attributes", () => {
+ const scrollContainerRef = vi.fn();
+ const { container } = render(
+ <Table rowCount={3} scrollContainerRef={scrollContainerRef} />,
+ );
+
+ const scroller = container.querySelector('[data-tab-scroll-root="table"]');
+ expect(scroller).not.toBeNull();
+ expect(scroller).toContainElement(container.querySelector("table"));
+ expect(scrollContainerRef).toHaveBeenCalledWith(scroller);
+ });
+
+ // A restored offset is assigned when the scroller attaches, before the
+ // virtualizer has measured the viewport (jsdom never gives it one). The
+ // rows it has not windowed yet still have to take up their height then, or
+ // the browser clamps the offset back to the top.
+ it("spans every row before the virtualizer has measured the viewport", () => {
+ const { container } = render(<Table rowCount={500} />);
+
+ const spacer = container.querySelector<HTMLElement>(
+ "tbody tr[aria-hidden] td",
+ );
+ expect(spacer?.style.height).toBe(`${500 * 40}px`);
+ });
+});
diff --git a/packages/ui/components/ui/data-table.tsx b/packages/ui/components/ui/data-table.tsx
index b3389d2a47..efa8dee942 100644
--- a/packages/ui/components/ui/data-table.tsx
+++ b/packages/ui/components/ui/data-table.tsx
@@ -67,6 +67,14 @@ interface DataTableProps<TData> extends React.ComponentProps<"div"> {
virtualizeRows?: boolean;
virtualRowHeight?: number;
virtualOverscan?: number;
+ // The element that scrolls both axes, for callers that save and restore its
+ // offsets; data attributes land on the same element.
+ scrollContainerRef?: (element: HTMLDivElement | null) => void;
+ scrollContainerAttributes?: { [attribute: `data-${string}`]: string | undefined };
+ // Vertical offset to open at. With virtualizeRows the virtualizer scrolls
+ // its element here when it attaches, so a restored offset must come in
+ // through this rather than only through scrollContainerRef.
+ initialScrollTop?: number;
}
// Headless data-table shell — adapted from Dice UI's data-table
@@ -97,6 +105,9 @@ export function DataTable<TData>({
virtualizeRows = false,
virtualRowHeight = 41,
virtualOverscan = 10,
+ scrollContainerRef,
+ scrollContainerAttributes,
+ initialScrollTop,
className,
...props
}: DataTableProps<TData>) {
@@ -317,6 +328,13 @@ export function DataTable<TData>({
}, [columnSizing, leafColumns]);
const scrollRef = React.useRef<HTMLDivElement | null>(null);
+ const attachScrollContainer = React.useCallback(
+ (element: HTMLDivElement | null) => {
+ scrollRef.current = element;
+ scrollContainerRef?.(element);
+ },
+ [scrollContainerRef],
+ );
// Drives the pinned columns' trailing shadow. It only means something once
// content is passing beneath them, so it stays off at rest. The state is a
@@ -360,6 +378,7 @@ export function DataTable<TData>({
estimateSize: () => virtualRowHeight,
getItemKey: getVirtualRowKey,
overscan: virtualOverscan,
+ initialOffset: initialScrollTop,
// Rows are not all one height. Callers use renderRow for group headers and
// end-of-column footers, which are shorter than a data row, so a single
// estimate drifts from the real layout as those accumulate — the window
@@ -372,9 +391,12 @@ export function DataTable<TData>({
const firstVirtualItem = virtualItems[0];
const lastVirtualItem = virtualItems[virtualItems.length - 1];
const virtualPaddingTop = firstVirtualItem?.start ?? 0;
+ // Before the virtualizer has measured the viewport it yields no items; the
+ // spacer still spans every row so the first commit has its real height
+ // (a restored scroll offset assigned then is not clamped to the top).
const virtualPaddingBottom = lastVirtualItem
? rowVirtualizer.getTotalSize() - lastVirtualItem.end
- : 0;
+ : rowVirtualizer.getTotalSize();
const bodyProps: DataTableBodyProps<TData> = {
table,
@@ -398,7 +420,8 @@ export function DataTable<TData>({
>
<div className="relative flex min-h-0 flex-1 flex-col">
<div
- ref={scrollRef}
+ ref={attachScrollContainer}
+ {...scrollContainerAttributes}
className="flex min-h-0 flex-1 flex-col overflow-auto bg-background"
>
<table
diff --git a/packages/views/autopilots/components/workspace-wakeups.tsx b/packages/views/autopilots/components/workspace-wakeups.tsx
index 3f55ff6ce4..2196451726 100644
--- a/packages/views/autopilots/components/workspace-wakeups.tsx
+++ b/packages/views/autopilots/components/workspace-wakeups.tsx
@@ -517,6 +517,8 @@ export function WorkspaceWakeups() {
} else {
body = (
<CollectionList
+ // Shares the autopilots route with that page's own list.
+ scrollKey="wakeups"
label={t(($) => $.wakeups.scopes[filters.scope])}
columns={columns}
rows={rows}
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 5c9fbd12ab..a4f9842ee4 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -30,6 +30,7 @@ import { CollectionPageState } from "../../layout/collection-page";
import { PageHeader } from "../../layout/page-header";
import { KpiCard } from "../../runtimes/components/shared";
import { useNavigation } from "../../navigation";
+import { useRestoredScrollRef } from "../../platform/scroll-restoration";
import {
addDaysIso,
aggregateByWeek,
@@ -154,6 +155,8 @@ export function DashboardPage() {
const locales = i18n.resolvedLanguage ?? i18n.language;
const [days, setDays] = useState<TimeRange>(30);
const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);
+ // One scroller for both tabs: the offset restored is the shown tab's.
+ const restoreScrollRef = useRestoredScrollRef("dashboard");
// The tab lives in the URL because the Errors view is the half of this page
// people paste at each other ("this agent failed 54 times, see for
@@ -514,7 +517,11 @@ export function DashboardPage() {
</div>
</PageHeader>
- <div className="flex-1 overflow-y-auto">
+ <div
+ ref={restoreScrollRef}
+ data-tab-scroll-root="dashboard"
+ className="flex-1 overflow-y-auto"
+ >
<div className="mx-auto max-w-6xl p-6">
<TabsContent value="usage" className="space-y-5">
{usageLoading ? (
diff --git a/packages/views/issues/components/gantt-view.test.tsx b/packages/views/issues/components/gantt-view.test.tsx
index 49ba45bf0e..ea99449a22 100644
--- a/packages/views/issues/components/gantt-view.test.tsx
+++ b/packages/views/issues/components/gantt-view.test.tsx
@@ -13,6 +13,10 @@ import {
import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
import type { Issue } from "@multica/core/types";
import { renderWithI18n } from "../../test/i18n";
+import {
+ ScrollRestorationProvider,
+ type ScrollRestorationAdapter,
+} from "../../platform";
import { IssueContextMenuProvider } from "../actions";
vi.mock("@tanstack/react-query", async (importOriginal) => ({
@@ -82,18 +86,49 @@ const ISSUE = {
updated_at: "2026-03-01T00:00:00Z",
} as unknown as Issue;
-function renderGantt(locale: "en" | "zh-Hans") {
+function renderGantt(
+ locale: "en" | "zh-Hans",
+ scroll: ScrollRestorationAdapter = { get: () => undefined },
+) {
const store = createStore<IssueViewState>()(viewStoreSlice);
return renderWithI18n(
<ViewStoreProvider store={store}>
- <IssueContextMenuProvider>
- <GanttView issues={[ISSUE]} />
- </IssueContextMenuProvider>
+ <ScrollRestorationProvider adapter={scroll}>
+ <IssueContextMenuProvider>
+ <GanttView issues={[ISSUE]} />
+ </IssueContextMenuProvider>
+ </ScrollRestorationProvider>
</ViewStoreProvider>,
{ locale },
);
}
+describe("GanttView scroll restoration", () => {
+ function scroller() {
+ return document.querySelector<HTMLElement>('[data-tab-scroll-root="gantt"]')!;
+ }
+
+ it("brings both axes back instead of jumping to today", () => {
+ const { unmount } = renderGantt("en", {
+ get: (key) => (key === "gantt" ? { top: 240, left: 90, height: 900 } : undefined),
+ });
+
+ expect(scroller().scrollTop).toBe(240);
+ expect(scroller().scrollLeft).toBe(90);
+ unmount();
+ });
+
+ it("still opens on today when nothing was saved sideways", () => {
+ const { unmount } = renderGantt("en", {
+ get: (key) => (key === "gantt" ? { top: 240, height: 900 } : undefined),
+ });
+
+ expect(scroller().scrollTop).toBe(240);
+ expect(scroller().scrollLeft).toBeGreaterThan(0);
+ unmount();
+ });
+});
+
describe("GanttView date localization", () => {
beforeAll(() => {
// The browser speaks English while the UI does not. Dates must follow the
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index d56620871e..d2057abb52 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
@@ -32,6 +32,7 @@ import { PriorityIcon } from "./priority-icon";
import { IssueActionsContextMenu } from "../actions";
import { sortIssues } from "../utils/sort";
import { useLocale, useT } from "../../i18n";
+import { useRestoredScrollEntry, useRestoredScrollRef } from "../../platform";
// Date utilities — everything is UTC-day-aligned so a `due_date` ISO string
// produced anywhere maps to exactly one column on the axis.
@@ -454,6 +455,8 @@ function ScheduledRow({
// GanttView — public component
+const GANTT_SCROLL_KEY = "gantt";
+
export function GanttView({ issues }: { issues: Issue[] }) {
const { t } = useT("issues");
const zoom = useViewStore((s) => s.ganttZoom);
@@ -498,9 +501,25 @@ export function GanttView({ issues }: { issues: Issue[] }) {
const todayOffsetDays = daysBetween(range.start, today);
const scrollRef = useRef<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741) for the two-axis scroller. A
+ // restored horizontal offset replaces the jump to today on mount.
+ const restoreScrollRef = useRestoredScrollRef(GANTT_SCROLL_KEY);
+ const restoredLeft = useRestoredScrollEntry(GANTT_SCROLL_KEY)?.left ?? 0;
+ const keepRestoredLeftRef = useRef(restoredLeft > 0);
+ const attachScroller = useCallback(
+ (el: HTMLDivElement | null) => {
+ scrollRef.current = el;
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
+ if (keepRestoredLeftRef.current) {
+ keepRestoredLeftRef.current = false;
+ return;
+ }
const target = Math.max(0, LEFT_COL_WIDTH + todayOffsetDays * dayPx - 240);
el.scrollLeft = target;
}, [todayOffsetDays, dayPx]);
@@ -552,7 +571,11 @@ export function GanttView({ issues }: { issues: Issue[] }) {
</div>
{/* Body — single scroll container drives both vertical + horizontal */}
- <div ref={scrollRef} className="flex-1 min-h-0 overflow-auto">
+ <div
+ ref={attachScroller}
+ data-tab-scroll-root={GANTT_SCROLL_KEY}
+ className="flex-1 min-h-0 overflow-auto"
+ >
<div style={{ minWidth: LEFT_COL_WIDTH + timelineWidth }}>
{/* Sticky header row */}
<div className="sticky top-0 z-20 flex">
diff --git a/packages/views/issues/components/table-view-editing.test.tsx b/packages/views/issues/components/table-view-editing.test.tsx
index 7ee95e8023..922689df6a 100644
--- a/packages/views/issues/components/table-view-editing.test.tsx
+++ b/packages/views/issues/components/table-view-editing.test.tsx
@@ -34,6 +34,7 @@ import type {
IssueTableRowsResponse,
} from "@multica/core/types";
import { renderWithI18n } from "../../test/i18n";
+import { ScrollRestorationProvider } from "../../platform";
import { IssueSurfaceSelectionProvider } from "../surface/selection-context";
import type { IssueSurfaceSelection } from "../surface/selection-context";
import type { IssueCreateDefaults } from "../surface/types";
@@ -571,6 +572,33 @@ describe("TableView cell editors under data refresh", () => {
"noopener,noreferrer",
);
});
+ it("brings the table back to where it was scrolled when it mounts again", async () => {
+ serverIssues = [makeIssue("a", "Alpha task", "todo")];
+ const get = vi.fn((key: string) =>
+ key === "table" ? { top: 820, left: 160, height: 4000 } : undefined,
+ );
+
+ renderWithI18n(
+ <QueryClientProvider client={queryClient}>
+ <ScrollRestorationProvider adapter={{ get }}>
+ <Harness
+ childProgressMap={new Map()}
+ surfaceKey={`test-scroll-restore-${Math.floor(Math.random() * 1e9)}`}
+ />
+ </ScrollRestorationProvider>
+ </QueryClientProvider>,
+ );
+
+ await screen.findByText("MUL-a");
+ const scroller = document.querySelector<HTMLElement>(
+ '[data-tab-scroll-root="table"]',
+ )!;
+ // Marked so the tab coordinator captures it on the way out, and given
+ // both saved offsets back when it attaches.
+ expect(scroller).toContainElement(screen.getByText("MUL-a"));
+ expect(scroller.scrollTop).toBe(820);
+ expect(scroller.scrollLeft).toBe(160);
+ });
});
// Row virtualization unmounts a cell when its row scrolls out of the window
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index cf65e5164c..c1aab9d7db 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -129,6 +129,7 @@ import { ActorAvatar } from "../../common/actor-avatar";
import { DeferredTooltip } from "../../common/deferred-tooltip";
import { LabelChip } from "../../labels/label-chip";
import { resolveClickIntent, useIntentNavigate } from "../../navigation";
+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
import { ProjectPicker } from "../../projects/components/project-picker";
import { useT } from "../../i18n";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
@@ -1338,6 +1339,9 @@ function PullRequestsCell({ issueId }: { issueId: string }) {
);
}
+const TABLE_SCROLL_KEY = "table";
+const TABLE_SCROLL_ROOT = { "data-tab-scroll-root": TABLE_SCROLL_KEY };
+
export function TableView({
serverQuery,
childProgressMap,
@@ -1404,6 +1408,10 @@ export function TableView({
// The one cell whose editor (picker popup / rename input) is open — see
// TableViewMeta.editingCellKey.
const [editingCellKey, setEditingCellKey] = useState<string | null>(null);
+ // Pull-based scroll restoration (MUL-4741): the table's two-axis scroller
+ // gets its saved offsets back when it attaches.
+ const restoredScrollTop = useRestoredScrollOffset(TABLE_SCROLL_KEY);
+ const restoreScrollRef = useRestoredScrollRef(TABLE_SCROLL_KEY);
const groupingPropertyId = propertyIdFromViewKey(tableGrouping);
const effectiveTableGrouping =
@@ -2552,6 +2560,9 @@ export function TableView({
<DataTable
table={table}
virtualizeRows
+ scrollContainerRef={restoreScrollRef}
+ initialScrollTop={restoredScrollTop}
+ scrollContainerAttributes={TABLE_SCROLL_ROOT}
emptyMessage={t(($) => $.table.empty)}
onRowClick={(row, event) => {
if (row.original.kind === "issue") {
diff --git a/packages/views/layout/collection-list/collection-list.test.tsx b/packages/views/layout/collection-list/collection-list.test.tsx
new file mode 100644
index 0000000000..17b6506c02
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-list.test.tsx
@@ -0,0 +1,107 @@
+import { screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import {
+ ScrollRestorationProvider,
+ type ScrollRestorationAdapter,
+} from "../../platform";
+import { renderWithI18n } from "../../test/i18n";
+import { CollectionList, type CollectionColumn } from "./collection-list";
+
+type Row = { id: string; name: string };
+
+const columns: CollectionColumn<Row>[] = [
+ { key: "name", header: "Name", cell: (row) => row.name },
+];
+
+const navigation: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/agents",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+};
+
+function renderList({
+ rowCount,
+ adapter,
+ scrollKey,
+}: {
+ rowCount: number;
+ adapter: ScrollRestorationAdapter;
+ scrollKey?: string;
+}) {
+ const rows = Array.from({ length: rowCount }, (_, i) => ({
+ id: `row-${i}`,
+ name: `Agent ${i}`,
+ }));
+ return renderWithI18n(
+ <NavigationProvider value={navigation}>
+ <ScrollRestorationProvider adapter={adapter}>
+ <CollectionList
+ label="Agents"
+ columns={columns}
+ rows={rows}
+ getRowId={(row) => row.id}
+ scrollKey={scrollKey}
+ />
+ </ScrollRestorationProvider>
+ </NavigationProvider>,
+ );
+}
+
+describe("CollectionList scroll restoration", () => {
+ // jsdom has no Element.scrollTo, which the list's virtualizer calls on the
+ // scroller when it attaches; without it that call would silently vanish.
+ beforeEach(() => {
+ HTMLElement.prototype.scrollTo = function (this: HTMLElement, options?: ScrollToOptions | number) {
+ if (typeof options === "object" && options.top !== undefined) this.scrollTop = options.top;
+ } as HTMLElement["scrollTo"];
+ });
+ afterEach(() => {
+ delete (HTMLElement.prototype as Partial<HTMLElement>).scrollTo;
+ });
+
+ it("brings the list back to where it was scrolled when it mounts again", () => {
+ const get = vi.fn((key: string) =>
+ key === "collection" ? { top: 640, height: 2000 } : undefined,
+ );
+ renderList({ rowCount: 3, adapter: { get } });
+
+ const grid = screen.getByRole("grid", { name: "Agents" });
+ const scroller = grid.parentElement!;
+ // Marked so the tab coordinator captures it on the way out …
+ expect(scroller.getAttribute("data-tab-scroll-root")).toBe("collection");
+ // … and given the saved offset back when it attaches.
+ expect(scroller.scrollTop).toBe(640);
+ });
+
+ it("keys the offset by scrollKey when a route swaps between lists", () => {
+ const get = vi.fn((key: string) =>
+ key === "wakeups" ? { top: 320, height: 2000 } : undefined,
+ );
+ renderList({ rowCount: 3, adapter: { get }, scrollKey: "wakeups" });
+
+ const scroller = screen.getByRole("grid", { name: "Agents" }).parentElement!;
+ expect(scroller.getAttribute("data-tab-scroll-root")).toBe("wakeups");
+ expect(scroller.scrollTop).toBe(320);
+ });
+
+ // Long lists virtualize, and the saved offset is assigned before the
+ // virtualizer has measured the viewport (jsdom never gives it one). The rows
+ // it has not windowed yet must already take up their height, or the browser
+ // clamps the restored offset back to the top.
+ it("spans every row of a long list before the viewport is measured", () => {
+ renderList({ rowCount: 200, adapter: { get: () => undefined } });
+
+ const grid = screen.getByRole("grid", { name: "Agents" });
+ const spacers = grid.querySelectorAll<HTMLElement>(":scope > [aria-hidden]");
+ const height = [...spacers].reduce(
+ (sum, el) => sum + Number.parseFloat(el.style.height || "0"),
+ 0,
+ );
+ expect(height).toBe(200 * 36);
+ });
+});
diff --git a/packages/views/layout/collection-list/collection-list.tsx b/packages/views/layout/collection-list/collection-list.tsx
index bfe87d4b46..8e2b28a71b 100644
--- a/packages/views/layout/collection-list/collection-list.tsx
+++ b/packages/views/layout/collection-list/collection-list.tsx
@@ -25,6 +25,10 @@ import {
import { useModalStore } from "@multica/core/modals";
import { useIntentNavigate, useRowLink } from "../../navigation";
import { useT } from "../../i18n";
+import {
+ useRestoredScrollOffset,
+ useRestoredScrollRef,
+} from "../../platform/scroll-restoration";
import { CollectionRowContext, type RowMenuState } from "./row-context";
export type CollectionSortDirection = "asc" | "desc";
@@ -105,6 +109,11 @@ export interface CollectionListProps<T> {
onLoadMore?: () => void;
/** Renders inside the page's own scroller instead of owning one. */
embedded?: boolean;
+ /**
+ * Names the list's scroller for scroll restoration, which keys offsets by
+ * route. Override when one route swaps between different lists.
+ */
+ scrollKey?: string;
/** J/K and arrows reach the list while nothing else has focus. */
pageShortcuts?: boolean;
className?: string;
@@ -178,6 +187,7 @@ export function CollectionList<T>({
loadingMore = false,
onLoadMore,
embedded = false,
+ scrollKey = "collection",
pageShortcuts = !embedded,
className,
}: CollectionListProps<T>) {
@@ -187,6 +197,15 @@ export function CollectionList<T>({
const intentNavigate = useIntentNavigate();
const scrollRef = useRef<HTMLDivElement | null>(null);
const gridRef = useRef<HTMLDivElement | null>(null);
+ const restoredScrollTop = useRestoredScrollOffset(scrollKey);
+ const restoreScrollRef = useRestoredScrollRef(scrollKey);
+ const attachScroller = useCallback(
+ (el: HTMLDivElement | null) => {
+ scrollRef.current = el;
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
const columns = useMemo(
() =>
@@ -242,6 +261,10 @@ export function CollectionList<T>({
paddingStart: HEADER_HEIGHT,
scrollPaddingStart: HEADER_HEIGHT,
overscan: 12,
+ // The virtualizer scrolls its element to this offset when it attaches,
+ // even while it has nothing to window; the default 0 would undo the
+ // restored offset.
+ initialOffset: restoredScrollTop,
});
// Selection
@@ -532,7 +555,11 @@ export function CollectionList<T>({
const first = virtualItems[0];
const last = virtualItems[virtualItems.length - 1];
const top = first ? first.start - HEADER_HEIGHT : 0;
- const bottom = last ? virtualizer.getTotalSize() - last.end : 0;
+ // Before the virtualizer has measured the viewport it yields no items;
+ // the spacer still spans every row, so a restored offset is not clamped.
+ const bottom = last
+ ? virtualizer.getTotalSize() - last.end
+ : virtualizer.getTotalSize() - HEADER_HEIGHT;
body = (
<>
{top > 0 ? <div aria-hidden className="col-span-full" style={{ height: top }} /> : null}
@@ -613,7 +640,11 @@ export function CollectionList<T>({
if (embedded) return <div className="@container min-w-0 overflow-x-auto">{grid}</div>;
return (
- <div ref={scrollRef} className="min-h-0 flex-1 overflow-auto @container">
+ <div
+ ref={attachScroller}
+ data-tab-scroll-root={scrollKey}
+ className="min-h-0 flex-1 overflow-auto @container"
+ >
{grid}
</div>
);
diff --git a/packages/views/layout/object-page.test.tsx b/packages/views/layout/object-page.test.tsx
index f8da37a94f..4f6a0b242f 100644
--- a/packages/views/layout/object-page.test.tsx
+++ b/packages/views/layout/object-page.test.tsx
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { Pencil } from "@multica/ui/icons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { ScrollRestorationProvider, type ScrollRestorationAdapter } from "../platform";
import { renderWithI18n } from "../test/i18n";
import {
ObjectIdentity,
@@ -24,25 +25,37 @@ function makeAdapter(): NavigationAdapter {
};
}
-function renderPage(panel?: React.ReactNode) {
+function renderPage(
+ panel?: React.ReactNode,
+ {
+ scroll = { get: () => undefined },
+ scrollRef,
+ }: {
+ scroll?: ScrollRestorationAdapter;
+ scrollRef?: (el: HTMLDivElement | null) => void;
+ } = {},
+) {
return renderWithI18n(
<NavigationProvider value={makeAdapter()}>
- <ObjectPage
- type="agent"
- layoutId="test_object_page"
- segments={[{ href: "/acme/agents", label: "Agents" }]}
- leaf={<span>Lambda</span>}
- actions={<button type="button">Assign work</button>}
- panel={panel}
- >
- <ObjectIdentity media={<span />} title="Lambda" description="Design and frontend" />
- <ObjectSection
- title="Instructions"
- action={<ObjectSectionAction icon={Pencil}>Edit</ObjectSectionAction>}
+ <ScrollRestorationProvider adapter={scroll}>
+ <ObjectPage
+ type="agent"
+ layoutId="test_object_page"
+ segments={[{ href: "/acme/agents", label: "Agents" }]}
+ leaf={<span>Lambda</span>}
+ actions={<button type="button">Assign work</button>}
+ panel={panel}
+ scrollRef={scrollRef}
>
- <p>Mock before you build.</p>
- </ObjectSection>
- </ObjectPage>
+ <ObjectIdentity media={<span />} title="Lambda" description="Design and frontend" />
+ <ObjectSection
+ title="Instructions"
+ action={<ObjectSectionAction icon={Pencil}>Edit</ObjectSectionAction>}
+ >
+ <p>Mock before you build.</p>
+ </ObjectSection>
+ </ObjectPage>
+ </ScrollRestorationProvider>
</NavigationProvider>,
);
}
@@ -68,6 +81,21 @@ describe("ObjectPage", () => {
expect(screen.queryByRole("button", { name: "Toggle right sidebar" })).toBeNull();
});
+ it("brings the body back to where it was scrolled and still hands it to scrollRef", () => {
+ const scrollRef = vi.fn();
+ renderPage(undefined, {
+ scroll: { get: (key) => (key === "object" ? { top: 480, height: 1600 } : undefined) },
+ scrollRef,
+ });
+
+ const body = screen.getByText("Mock before you build.").closest<HTMLElement>("[data-tab-scroll-root]")!;
+ // Marked so the tab coordinator captures it on the way out …
+ expect(body.getAttribute("data-tab-scroll-root")).toBe("object");
+ // … and given the saved offset back when it attaches.
+ expect(body.scrollTop).toBe(480);
+ expect(scrollRef).toHaveBeenCalledWith(body);
+ });
+
it("renders the properties panel beside the body", () => {
renderPage(<ObjectProperty label="Runtime">MacBook Pro</ObjectProperty>);
expect(screen.getByRole("button", { name: "Toggle right sidebar" })).toBeInTheDocument();
diff --git a/packages/views/layout/object-page.tsx b/packages/views/layout/object-page.tsx
index aee3056a35..23d44c0522 100644
--- a/packages/views/layout/object-page.tsx
+++ b/packages/views/layout/object-page.tsx
@@ -7,7 +7,6 @@ import {
useState,
type ComponentProps,
type ReactNode,
- type Ref,
} from "react";
import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
import { ChevronRight, PanelRight, type IconComponent } from "@multica/ui/icons";
@@ -24,6 +23,7 @@ import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { cn } from "@multica/ui/lib/utils";
import { ActionShortcutKeycaps } from "../common/shortcut-keycaps";
import { useT } from "../i18n";
+import { useRestoredScrollRef } from "../platform/scroll-restoration";
import {
AnimatedRightSidebar,
getAnimatedRightSidebarInitialOpen,
@@ -37,6 +37,8 @@ import { BreadcrumbHeader, type BreadcrumbSegment } from "./breadcrumb-header";
export const OBJECT_PAGE_BODY =
"mx-auto w-full max-w-[var(--object-page-max-width,760px)] px-[var(--space-lg,1.5rem)] py-[var(--space-xl,2rem)]";
+const OBJECT_PAGE_SCROLL_KEY = "object";
+
/** What an object page shows, as themes see it on `data-type`. */
export type ObjectPageType = "project" | "agent" | "squad" | "runtime" | "member" | "autopilot" | "skill";
@@ -61,7 +63,7 @@ interface ObjectPageProps {
*/
children: ReactNode;
/** The body scroll owner, for sections that virtualize their rows. */
- scrollRef?: Ref<HTMLDivElement>;
+ scrollRef?: (el: HTMLDivElement | null) => void;
}
/**
@@ -109,6 +111,17 @@ export function ObjectPage({ type, segments, leaf, actions, panel, layoutId, chi
useRightSidebarShortcut(shortcutTargetRef, toggle);
+ // The body is the page's one vertical scroller: the platform restores its
+ // offset when the page mounts again (e.g. switching back to its tab).
+ const restoreScrollRef = useRestoredScrollRef(OBJECT_PAGE_SCROLL_KEY);
+ const attachBody = useCallback(
+ (el: HTMLDivElement | null) => {
+ scrollRef?.(el);
+ restoreScrollRef(el);
+ },
+ [scrollRef, restoreScrollRef],
+ );
+
const header = (
<BreadcrumbHeader
segments={segments}
@@ -135,7 +148,15 @@ export function ObjectPage({ type, segments, leaf, actions, panel, layoutId, chi
/>
);
- const body = <div ref={scrollRef} className="flex min-h-0 flex-1 flex-col overflow-y-auto">{children}</div>;
+ const body = (
+ <div
+ ref={attachBody}
+ data-tab-scroll-root={OBJECT_PAGE_SCROLL_KEY}
+ className="flex min-h-0 flex-1 flex-col overflow-y-auto"
+ >
+ {children}
+ </div>
+ );
if (!panel) {
return (
diff --git a/packages/views/platform/scroll-restoration.test.tsx b/packages/views/platform/scroll-restoration.test.tsx
index 915db0a0ae..aa0daee46c 100644
--- a/packages/views/platform/scroll-restoration.test.tsx
+++ b/packages/views/platform/scroll-restoration.test.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import {
ScrollRestorationProvider,
@@ -63,3 +63,122 @@ describe("scroll-restoration public surface", () => {
expect(offset.result.current).toBeUndefined();
});
});
+
+describe("useRestoredScrollRef while the content settles", () => {
+ let frames = new Map<number, FrameRequestCallback>();
+ let nextId = 0;
+ let now = 0;
+
+ beforeEach(() => {
+ frames = new Map();
+ now = 0;
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ frames.set(++nextId, cb);
+ return nextId;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+ });
+
+ function nextFrame(ms = 16) {
+ now += ms;
+ const pending = [...frames.values()];
+ frames.clear();
+ pending.forEach((cb) => cb(now));
+ }
+
+ // jsdom has no layout: model a scroller whose content height can change
+ // and whose offset the "browser" clamps to it.
+ function scroller(contentHeight: number) {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const viewport = 600;
+ let height = contentHeight;
+ let top = 0;
+ const clamp = (v: number) => Math.max(0, Math.min(v, height - viewport));
+ Object.defineProperties(el, {
+ scrollHeight: { get: () => height },
+ scrollTop: { get: () => top, set: (v: number) => { top = clamp(v); } },
+ });
+ return {
+ el,
+ resize(next: number) {
+ height = next;
+ top = clamp(top);
+ },
+ // Content above the viewport changing size moves what is on screen.
+ shiftAbove(delta: number) {
+ height += delta;
+ top = clamp(top + delta);
+ },
+ };
+ }
+
+ function attach(el: HTMLElement, top: number) {
+ const adapter = makeAdapter(() => ({ top, height: 3000 }));
+ const { result } = renderHook(() => useRestoredScrollRef("main"), {
+ wrapper: ({ children }) => (
+ <ScrollRestorationProvider adapter={adapter}>{children}</ScrollRestorationProvider>
+ ),
+ });
+ result.current(el);
+ return result.current;
+ }
+
+ it("reaches the saved offset once content that lands after mount makes room", () => {
+ const view = scroller(600);
+ attach(view.el, 1500);
+ expect(view.el.scrollTop).toBe(0);
+
+ view.resize(3000);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(1500);
+ });
+
+ it("holds the offset through a layout shift above it", () => {
+ const view = scroller(3000);
+ attach(view.el, 1500);
+ expect(view.el.scrollTop).toBe(1500);
+
+ view.shiftAbove(-60);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(1500);
+ });
+
+ it("yields to the user scrolling before the content lands", () => {
+ const view = scroller(600);
+ attach(view.el, 1500);
+
+ view.el.dispatchEvent(new Event("wheel"));
+ view.resize(3000);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(0);
+ });
+
+ it("yields to other code moving the offset without the content changing", () => {
+ const view = scroller(3000);
+ attach(view.el, 1500);
+
+ view.el.scrollTop = 400;
+ nextFrame();
+ view.resize(3200);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(400);
+ });
+
+ it("lets go after the settle window", () => {
+ const view = scroller(600);
+ attach(view.el, 1500);
+
+ nextFrame(2000);
+ view.resize(3000);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(0);
+ });
+});
diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsx
index 9ddc1bd1c0..44634f98b8 100644
--- a/packages/views/platform/scroll-restoration.tsx
+++ b/packages/views/platform/scroll-restoration.tsx
@@ -148,12 +148,77 @@ export function useRestoredScrollOffset(containerKey: string): number | undefine
return top !== undefined && top > 0 ? top : undefined;
}
+/**
+ * How long a restore holds the saved offset while the content settles. Long
+ * enough for cached data and lazy sections to land after mount, short enough
+ * that a slow network load does not yank the page later.
+ */
+const RESTORE_SETTLE_MS = 1500;
+
+/** Inputs that mean the user is scrolling the container themselves. */
+const USER_SCROLL_EVENTS = ["wheel", "touchstart", "pointerdown", "keydown"] as const;
+
+/**
+ * Assign the saved offsets to a container that just attached, then hold them
+ * while the content settles. Sections that render a frame or two after mount
+ * move the offset: the browser clamps it while the content is still short,
+ * and content that grows or collapses above it shifts it. So until the
+ * deadline, an offset moved by a change in the content's size is put back.
+ * The restore yields for good once the user scrolls the container, or other
+ * code moves it without the content changing size (a deep-link jump).
+ * Returns a cancel for the pending hold.
+ */
+function restoreOffsets(
+ el: HTMLElement,
+ saved: ScrollRestorationEntry,
+): () => void {
+ const top = saved.top > 0 ? saved.top : undefined;
+ const left = saved.left !== undefined && saved.left > 0 ? saved.left : undefined;
+ if (top === undefined && left === undefined) return () => {};
+ const apply = () => {
+ if (top !== undefined && el.scrollTop !== top) el.scrollTop = top;
+ if (left !== undefined && el.scrollLeft !== left) el.scrollLeft = left;
+ };
+ // Only the restored axes count: the other may be the view's own business.
+ const position = () =>
+ `${top === undefined ? "" : el.scrollTop}:${left === undefined ? "" : el.scrollLeft}`;
+ const size = () => `${el.scrollHeight}:${el.scrollWidth}`;
+
+ apply();
+ if (typeof requestAnimationFrame !== "function") return () => {};
+
+ const deadline = performance.now() + RESTORE_SETTLE_MS;
+ let landed = position();
+ let lastSize = size();
+ let frame = 0;
+ const stop = () => {
+ cancelAnimationFrame(frame);
+ for (const type of USER_SCROLL_EVENTS) el.removeEventListener(type, stop);
+ };
+ const tick = () => {
+ if (!el.isConnected || performance.now() > deadline) return stop();
+ const nextSize = size();
+ if (position() !== landed && nextSize === lastSize) return stop();
+ apply();
+ landed = position();
+ lastSize = nextSize;
+ frame = requestAnimationFrame(tick);
+ };
+ for (const type of USER_SCROLL_EVENTS) {
+ el.addEventListener(type, stop, { passive: true });
+ }
+ frame = requestAnimationFrame(tick);
+ return stop;
+}
+
/**
* Ref callback for PLAIN (non-virtualized) scroll containers: assigns the
* saved offsets (vertical and horizontal) when the element attaches, which
* happens during commit — before paint — so the first visible frame is
- * already at the restored position. Compose it with other refs via a merged
- * callback. Detach captures the latest offsets through the same adapter.
+ * already at the restored position when the content is there; content that
+ * lands a few frames later is caught up by `restoreOffsets`. Compose it with
+ * other refs via a merged callback. Detach captures the latest offsets
+ * through the same adapter.
*/
export function useRestoredScrollRef(
containerKey: string,
@@ -161,15 +226,15 @@ export function useRestoredScrollRef(
const adapter = useContext(ScrollRestorationContext);
return useMemo(() => {
let capture: (() => void) | undefined;
+ let cancelRestore: (() => void) | undefined;
return (el: HTMLElement | null) => {
+ cancelRestore?.();
+ cancelRestore = undefined;
capture?.();
capture = undefined;
if (!el) return;
const saved = adapter?.get(containerKey);
- if (saved && saved.top > 0) el.scrollTop = saved.top;
- if (saved?.left !== undefined && saved.left > 0) {
- el.scrollLeft = saved.left;
- }
+ if (saved) cancelRestore = restoreOffsets(el, saved);
capture = adapter?.registerScrollRoot?.(containerKey, el);
};
}, [adapter, containerKey]);
diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsx
index cfd14e7190..e3ddb76773 100644
--- a/packages/views/runtimes/components/runtimes-page.tsx
+++ b/packages/views/runtimes/components/runtimes-page.tsx
@@ -83,6 +83,7 @@ import {
} from "../../layout/collection-list";
import { cn } from "@multica/ui/lib/utils";
import { useNavigation } from "../../navigation";
+import { useRestoredScrollRef } from "../../platform/scroll-restoration";
import { getMikaOnboarding, pickContentLang } from "../../onboarding/templates";
import { qoderOptions } from "@multica/core/runtimes/qoder";
import { QODER_RUNTIME_LOCATOR } from "./qoder-detail-page";
@@ -190,6 +191,7 @@ export function RuntimesPage({
const [showConnectDialog, setShowConnectDialog] = useState(false);
const [showCloudRuntimeDialog, setShowCloudRuntimeDialog] = useState(false);
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
+ const restoreScrollRef = useRestoredScrollRef("runtimes");
const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
runtimeListOptions(wsId),
@@ -512,7 +514,11 @@ export function RuntimesPage({
}
/>
) : (
- <div className="min-h-0 flex-1 overflow-y-auto">
+ <div
+ ref={restoreScrollRef}
+ data-tab-scroll-root="runtimes"
+ className="min-h-0 flex-1 overflow-y-auto"
+ >
<CollectionList
embedded
pageShortcuts
diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsx
index 26ebd5ec59..e8f3294b3e 100644
--- a/packages/views/settings/components/settings-page.test.tsx
+++ b/packages/views/settings/components/settings-page.test.tsx
@@ -8,6 +8,7 @@ import {
PLUGINS_V1_FLAG,
} from "@multica/core/feature-flags";
import { renderWithI18n } from "../../test/i18n";
+import { ScrollRestorationProvider } from "../../platform";
// This file tests the settings SHELL — the chrome around the tabs — so every
// tab panel is stubbed out. Their contents have their own test files. Profile
@@ -227,6 +228,36 @@ describe("SettingsPage header", () => {
});
});
+describe("SettingsPage scroll restoration", () => {
+ // Every settings page shares the route, so one page's offset must not land
+ // on another when the content remounts.
+ it("gives each page its own saved offset", () => {
+ const get = vi.fn((key: string) =>
+ key === "settings:members:" ? { top: 360, height: 1400 } : undefined,
+ );
+ navigationState.search = "tab=members";
+ const { rerender } = renderWithI18n(
+ <ScrollRestorationProvider adapter={{ get }}>
+ <SettingsPage />
+ </ScrollRestorationProvider>,
+ );
+
+ const members = screen.getByText("MembersTab").closest<HTMLElement>("[data-tab-scroll-root]")!;
+ expect(members.getAttribute("data-tab-scroll-root")).toBe("settings:members:");
+ expect(members.scrollTop).toBe(360);
+
+ navigationState.search = "tab=labels";
+ rerender(
+ <ScrollRestorationProvider adapter={{ get }}>
+ <SettingsPage />
+ </ScrollRestorationProvider>,
+ );
+ const labels = screen.getByText("LabelsTab").closest<HTMLElement>("[data-tab-scroll-root]")!;
+ expect(labels.getAttribute("data-tab-scroll-root")).toBe("settings:labels:");
+ expect(labels.scrollTop).toBe(0);
+ });
+});
+
describe("SettingsPage Plugin feature flag", () => {
it("hides Plugins and falls back from a direct tab URL when disabled", () => {
navigationState.search = "tab=plugins";
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index aa35dd16dc..608fe68432 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import React, { useEffect, useMemo, useRef, useState } from "react";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Bell,
Blocks,
@@ -36,6 +36,7 @@ import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { cn } from "@multica/ui/lib/utils";
import { resolveSettingsLocation, settingsHref } from "./settings-navigation";
import { AppLink, useNavigation } from "../../navigation";
+import { useRestoredScrollRef } from "../../platform/scroll-restoration";
import { AccountTab } from "./account-tab";
import { PreferencesTab } from "./preferences-tab";
import { AppearanceTab } from "./appearance-tab";
@@ -350,6 +351,16 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
// page. Tab content can still be loading on the first frame, so wait briefly
// for the anchor before scrolling it into view and flashing it.
const contentRef = useRef<HTMLDivElement>(null);
+ // Every settings page shares the route, so each restores its own offset.
+ const contentKey = `${active.value}:${location.integration ?? ""}`;
+ const restoreScrollRef = useRestoredScrollRef(`settings:${contentKey}`);
+ const attachContent = useCallback(
+ (el: HTMLDivElement | null) => {
+ contentRef.current = el;
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
useEffect(() => {
const anchor = location.section;
if (!anchor) return;
@@ -602,8 +613,9 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
</PageHeader>
<SettingsHeaderContext.Provider value={headerSlots}>
<div
- ref={contentRef}
- key={`${active.value}:${location.integration ?? ""}`}
+ ref={attachContent}
+ key={contentKey}
+ data-tab-scroll-root={`settings:${contentKey}`}
className="min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain"
>
<div className="mx-auto w-full max-w-(--settings-column) px-4 py-6 sm:px-6 md:px-10 md:py-8">