Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9402: preserve latest scroll offsets when switching issue views (#10736)
Bohan Jiangfe5fb2333f24
diff --git a/apps/desktop/src/renderer/src/platform/issue-view-scroll-restoration.test.tsx b/apps/desktop/src/renderer/src/platform/issue-view-scroll-restoration.test.tsxnew file mode 100644index 0000000000..e16b0c9cb5--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/issue-view-scroll-restoration.test.tsx@@ -0,0 +1,77 @@+import { useMemo } from "react";+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";+import { ScrollRestorationProvider, useRestoredScrollRef } from "@multica/views/platform";+import { getActiveTab, useTabStore } from "@/stores/tab-store";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@/stores/window-overlay-store", () => ({+ useWindowOverlayStore: Object.assign(() => null, { getState: () => ({ overlay: null, open: vi.fn(), close: vi.fn() }) }),+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(() => null, { getState: () => ({ logout: vi.fn() }) }),+}));++import { DesktopNavigationProvider } from "./navigation";+import { IssueViewUrlSync, __resetIssueViewTabsForTests, initIssueViewTabs } from "./issue-view-tabs";+import { __resetTabCoordinatorForTests, createScrollRestorationAdapter, initTabCoordinator, registerActiveHostElement } from "./tab-coordinator";++function ScrollRoot({ name }: { name: string }) {+ return <div ref={useRestoredScrollRef(name)} data-tab-scroll-root={name} />;+}++function Surface({ mode }: { mode: string }) {+ const view = useActiveIssueViewStore(s => s.active["ws-1:workspace"] ?? "default");+ // Match IssueSurface's remount on saved-view identity changes.+ return <div key={view}><ScrollRoot key={mode} name={mode} /></div>;+}++function Page({ mode }: { mode: string }) {+ const tabId = useTabStore(s => getActiveTab(s)!.id);+ const adapter = useMemo(() => createScrollRestorationAdapter(tabId), [tabId]);+ return <DesktopNavigationProvider>+ <div ref={registerActiveHostElement}>+ <ScrollRestorationProvider adapter={adapter}>+ <IssueViewUrlSync scope={{ scope_type: "workspace" }}>+ <Surface mode={mode} />+ </IssueViewUrlSync>+ </ScrollRestorationProvider>+ </div>+ </DesktopNavigationProvider>;+}++afterEach(() => {+ cleanup();+ __resetIssueViewTabsForTests();+ __resetTabCoordinatorForTests();+});++it("captures layout switches after returning from a saved view to All issues", () => {+ Object.defineProperty(window, "desktopAPI", {+ configurable: true,+ value: { runtimeConfig: { ok: true, config: { appUrl: "https://app.example" } } },+ });+ __resetTabCoordinatorForTests();+ __resetIssueViewTabsForTests();+ useActiveIssueViewStore.setState({ active: { "ws-1:workspace": "saved-a" } });+ useTabStore.getState().reset();+ useTabStore.getState().switchWorkspace("acme");+ useTabStore.getState().navigateActiveSession("/acme/issues?view=saved-a");+ initTabCoordinator();+ initIssueViewTabs();++ const rendered = render(<Page mode="board" />);+ const board = () => rendered.container.querySelector<HTMLElement>('[data-tab-scroll-root="board"]')!;+ board().scrollLeft = 640;+ // The saved-view title menu's Back to All issues action only clears the+ // active view. IssueViewUrlSync removes ?view= in a later passive effect.+ act(() => useActiveIssueViewStore.getState().setActive("ws-1:workspace", null));+ expect(getActiveTab(useTabStore.getState())!.url).toBe("/acme/issues");+ expect(board().scrollLeft).toBe(640);+ board().scrollLeft = 0;++ rendered.rerender(<Page mode="list" />);+ rendered.rerender(<Page mode="board" />);+ expect(board().scrollLeft).toBe(0);+});diff --git a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts b/apps/desktop/src/renderer/src/platform/tab-coordinator.tsindex 39a1fed0d5..c76e0cc1f3 100644--- a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts+++ b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts@@ -125,6 +125,29 @@ export function createScrollRestorationAdapter(const active = getActiveTab(useTabStore.getState());return active?.memento.scroll[scrollMementoKey(routeKey, containerKey)];},+ registerScrollRoot(containerKey, element) {+ const routeKey = activeRouteKey();+ // Peek/preview scrollers opt out of capture by omitting this marker.+ if (routeKey === null || !element.hasAttribute("data-tab-scroll-root")) {+ return () => {};+ }+ const state = useTabStore.getState();+ const generation = state.mountGeneration;+ return () => {+ const state = useTabStore.getState();+ // Tab, pathname and reload transitions already captured synchronously.+ // Their teardown must not overwrite that snapshot with a collapsed+ // scroller. Query/hash synchronization can leave this element mounted,+ // so it must keep capturing on a later detach.+ if (+ activeRouteKey() !== routeKey ||+ state.mountGeneration !== generation+ ) return;+ state.commitScrollMemento(tabId, routeKey, {+ [containerKey]: captureElementScrollEntry(element),+ });+ };+ },getViewState(entryKey) {const routeKey = activeRouteKey();if (routeKey === null) return undefined;@@ -175,13 +198,12 @@ function reconcile(): void {** Plain scroll containers self-mark with `data-tab-scroll-root` (the* attribute value is the container key, "main" when bare). Containers sitting- * at 0 on both axes are simply absent from the result — the store's per-route REPLACE- * semantics turn that absence into "clear the stale offset".+ * at 0 on both axes are included, so the store clears exactly those stale+ * offsets while preserving records for currently unmounted views.** External sources (sandboxed iframe documents) are merged in for the- * outgoing tab ONLY; unlike plain containers they are ALWAYS written,- * including at top 0, because their entry carries a `contentKey` and a- * top:0 write with the new key is how a content change replaces a stale+ * outgoing tab ONLY. Their zero entries are retained because they carry a+ * `contentKey`: a top:0 write with the new key replaces a stale* positive offset rather than resurrecting it.*/function captureScrollEntries(@@ -193,13 +215,8 @@ function captureScrollEntries("[data-tab-scroll-root]",);els.forEach((el) => {- const { scrollTop: top, scrollLeft: left } = el;- if (top <= 0 && left <= 0) return;const key = el.getAttribute("data-tab-scroll-root") || "main";- entries[key] =- left > 0- ? { top, height: el.scrollHeight, left }- : { top, height: el.scrollHeight };+ entries[key] = captureElementScrollEntry(el);});}if (outgoingTabId) {@@ -214,6 +231,11 @@ function captureScrollEntries(return entries;}+function captureElementScrollEntry(element: HTMLElement): ScrollRestorationEntry {+ const { scrollTop: top, scrollLeft: left, scrollHeight: height } = element;+ return left > 0 ? { top, height, left } : { top, height };+}+function handleStoreChange(): void {const state = useTabStore.getState();const active = getActiveTab(state);@@ -237,8 +259,8 @@ function handleStoreChange(): void {lastActiveUrl = activeUrl;if (outgoingTabId && outgoingUrl) {const routeKey = splitTabUrl(outgoingUrl).pathname;- // Always commit — REPLACE semantics clear entries for containers that- // scrolled back to 0; the store skips the write when nothing changed.+ // Include zero offsets to clear only the mounted containers' records;+ // unmounted views retain their last capture.useTabStore.getState().commitScrollMemento(diff --git a/apps/desktop/src/renderer/src/platform/tab-scroll-restoration.test.tsx b/apps/desktop/src/renderer/src/platform/tab-scroll-restoration.test.tsxnew file mode 100644index 0000000000..61846c9ddc--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/tab-scroll-restoration.test.tsx@@ -0,0 +1,162 @@+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ ScrollRestorationProvider,+ useRestoredScrollRef,+} from "@multica/views/platform";+import { getActiveTab, useTabStore } from "@/stores/tab-store";+import {+ __resetTabCoordinatorForTests,+ createScrollRestorationAdapter,+ initTabCoordinator,+ registerActiveHostElement,+} from "./tab-coordinator";++function ScrollRoot({ name, marked = true }: { name: string; marked?: boolean }) {+ const ref = useRestoredScrollRef(name);+ return <div ref={ref} data-tab-scroll-root={marked ? name : undefined} />;+}++describe("same-route scroll restoration", () => {+ beforeEach(() => {+ __resetTabCoordinatorForTests();+ useTabStore.getState().reset();+ useTabStore.getState().switchWorkspace("acme");+ initTabCoordinator();+ });++ afterEach(() => {+ cleanup();+ __resetTabCoordinatorForTests();+ });++ it("does not capture a peek scroller that omits the marker", () => {+ const tabId = getActiveTab(useTabStore.getState())!.id;+ const rendered = render(+ <ScrollRestorationProvider adapter={createScrollRestorationAdapter(tabId)}>+ <ScrollRoot name="main" marked={false} />+ </ScrollRestorationProvider>,+ );+ rendered.container.firstElementChild!.scrollTop = 500;+ rendered.unmount();++ expect(getActiveTab(useTabStore.getState())!.memento.scroll).toEqual({});+ });++ it.each([+ { left: 420, top: 120, columnTop: 240 },+ { left: 0, top: 120, columnTop: 240 },+ { left: 0, top: 0, columnTop: 0 },+ ])("captures the latest offsets on ref detach: %o", ({ left, top, columnTop }) => {+ const store = useTabStore.getState();+ const tabId = getActiveTab(store)!.id;+ const adapter = createScrollRestorationAdapter(tabId);+ store.commitScrollMemento(tabId, "/acme/issues", {+ board: { top: 80, left: 640, height: 1000 },+ "board:status:todo": { top: 600, height: 2000 },+ });+ const view = (mode: string) => (+ <ScrollRestorationProvider adapter={adapter}>+ {mode === "board" ? (+ <div key="board">+ <ScrollRoot name="board" />+ <ScrollRoot name="board:status:todo" />+ </div>+ ) : <ScrollRoot key="list" name="list" />}+ </ScrollRestorationProvider>+ );+ const rendered = render(view("board"));+ const board = rendered.container.querySelector<HTMLElement>('[data-tab-scroll-root="board"]')!;+ const column = rendered.container.querySelector<HTMLElement>('[data-tab-scroll-root="board:status:todo"]')!;+ board.scrollLeft = left;+ board.scrollTop = top;+ column.scrollTop = columnTop;++ rendered.rerender(view("list"));+ rendered.rerender(view("board"));++ const restoredBoard = rendered.container.querySelector<HTMLElement>('[data-tab-scroll-root="board"]')!;+ const restoredColumn = rendered.container.querySelector<HTMLElement>('[data-tab-scroll-root="board:status:todo"]')!;+ expect(restoredBoard.scrollLeft).toBe(left);+ expect(restoredBoard.scrollTop).toBe(top);+ expect(restoredColumn.scrollTop).toBe(columnTop);+ });++ it("keeps unmounted views when capturing a different view on tab switch", () => {+ const store = useTabStore.getState();+ const tabId = getActiveTab(store)!.id;+ store.commitScrollMemento(tabId, "/acme/issues", {+ board: { top: 0, left: 640, height: 1000 },+ swimlane: { top: 300, height: 2000 },+ });+ const adapter = createScrollRestorationAdapter(tabId);+ const rendered = render(+ <ScrollRestorationProvider adapter={adapter}>+ <ScrollRoot name="list" />+ </ScrollRestorationProvider>,+ );+ registerActiveHostElement(rendered.container);+ rendered.container.querySelector<HTMLElement>("[data-tab-scroll-root]")!.scrollTop = 150;++ act(() => { store.openTab("/acme/projects", "Projects", { activate: true }); });++ const saved = useTabStore.getState().byWorkspace.acme.tabs.find(t => t.id === tabId)!.memento.scroll;+ expect(saved["/acme/issues::board"]?.left).toBe(640);+ expect(saved["/acme/issues::swimlane"]?.top).toBe(300);+ expect(saved["/acme/issues::list"]?.top).toBe(150);+ });++ it.each(["?view=saved-a", "#comment-a"])(+ "keeps capturing after same-path URL synchronization from %s",+ (suffix) => {+ const store = useTabStore.getState();+ store.navigateActiveSession(`/acme/issues${suffix}`);+ const tabId = getActiveTab(useTabStore.getState())!.id;+ const adapter = createScrollRestorationAdapter(tabId);+ const rendered = render(+ <ScrollRestorationProvider adapter={adapter}>+ <ScrollRoot name="board" />+ </ScrollRestorationProvider>,+ );+ registerActiveHostElement(rendered.container);+ const board = rendered.container.firstElementChild as HTMLElement;+ board.scrollLeft = 640;++ act(() => store.navigateActiveSession("/acme/issues", { replace: true }));+ expect(adapter.get("board")?.left).toBe(640);+ board.scrollLeft = 0;+ rendered.unmount();++ expect(adapter.get("board")).toBeUndefined();+ },+ );++ it.each(["tab", "route", "reload"])("keeps the pre-unmount capture when %s changes before detach", (change) => {+ const store = useTabStore.getState();+ const tabId = getActiveTab(store)!.id;+ const adapter = createScrollRestorationAdapter(tabId);+ const rendered = render(+ <ScrollRestorationProvider adapter={adapter}>+ <ScrollRoot name="list" />+ </ScrollRestorationProvider>,+ );+ registerActiveHostElement(rendered.container);+ const list = rendered.container.querySelector<HTMLElement>("[data-tab-scroll-root]")!;+ list.scrollTop = 450;++ act(() => {+ if (change === "tab") store.openTab("/acme/projects", "Projects", { activate: true });+ else if (change === "route") store.navigateActiveSession("/acme/projects");+ else store.reloadActiveTab();+ });+ // A detached virtualized scroller can collapse during teardown. The+ // Coordinator already captured its outgoing DOM before the store changed.+ list.scrollTop = 0;+ rendered.unmount();++ const saved = useTabStore.getState().byWorkspace.acme.tabs.find(t => t.id === tabId)!.memento.scroll;+ expect(saved["/acme/issues::list"]?.top).toBe(450);+ expect(saved["/acme/projects::list"]).toBeUndefined();+ if (change === "tab") expect(getActiveTab(useTabStore.getState())!.memento.scroll).toEqual({});+ });+});diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.tsindex aa101f4b17..3cab3ee176 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts@@ -999,7 +999,7 @@ describe("commitScrollMemento", () => {});});- it("REPLACES the route's entries — scrolling back to 0 clears the stale offset", () => {+ it("clears a container captured at zero on both axes", () => {const store = useTabStore.getState();store.switchWorkspace("acme");const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;@@ -1007,9 +1007,9 @@ describe("commitScrollMemento", () => {store.commitScrollMemento(tabId, "/acme/issues", {list: { top: 500, height: 8000 },});- // User scrolled back to top before leaving: the capture has no entry- // for this container. The old 500 must not survive.- store.commitScrollMemento(tabId, "/acme/issues", {});+ store.commitScrollMemento(tabId, "/acme/issues", {+ list: { top: 0, height: 8000 },+ });expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({scroll: {},@@ -1017,6 +1017,48 @@ describe("commitScrollMemento", () => {});});+ it.each([+ { top: 180, left: 320 },+ { top: 180, left: 0 },+ { top: 0, left: 320 },+ { top: 0, left: 0 },+ ])("updates only the captured container at %o", ({ top, left }) => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const tabId = getActiveTab(useTabStore.getState())!.id;+ const otherTabId = store.openTab("/acme/inbox", "Inbox");+ store.commitScrollMemento(otherTabId, "/acme/issues", {+ board: { top: 50, height: 900 },+ });+ store.commitScrollMemento(tabId, "/acme/projects", {+ board: { top: 70, height: 900 },+ });+ store.commitScrollMemento(tabId, "/acme/issues", {+ board: { top: 200, left: 640, height: 1000 },+ list: { top: 400, height: 2000 },+ });++ store.commitScrollMemento(tabId, "/acme/issues", {+ board: { top, ...(left > 0 ? { left } : {}), height: 1000 },+ });++ const tabs = useTabStore.getState().byWorkspace.acme.tabs;+ const scroll = tabs.find(t => t.id === tabId)!.memento.scroll;+ expect(scroll["/acme/issues::board"]).toEqual(+ top > 0 || left > 0+ ? { top, ...(left > 0 ? { left } : {}), height: 1000 }+ : undefined,+ );+ expect(scroll["/acme/issues::list"]).toEqual({ top: 400, height: 2000 });+ expect(scroll["/acme/projects::board"]).toEqual({ top: 70, height: 900 });+ expect(tabs.find(t => t.id === otherTabId)!.memento.scroll).toEqual({+ "/acme/issues::board": { top: 50, height: 900 },+ });+ const before = useTabStore.getState().byWorkspace.acme;+ store.commitScrollMemento(tabId, "/acme/issues", {});+ expect(useTabStore.getState().byWorkspace.acme).toBe(before);+ });+it("keeps other routes' entries when one route commits", () => {const store = useTabStore.getState();store.switchWorkspace("acme");@@ -1070,7 +1112,7 @@ describe("commitScrollMemento", () => {).toEqual({ top: 0, height: 800, left: 900 });});- it("preserves view-state entries across a scroll REPLACE", () => {+ it("preserves view-state entries when clearing a scroll offset", () => {const store = useTabStore.getState();store.switchWorkspace("acme");const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;@@ -1079,9 +1121,9 @@ describe("commitScrollMemento", () => {list: { top: 500, height: 8000 },});- // Scrolled back to 0 before leaving: REPLACE clears the route's scroll- // entries — but never its view-state entries.- store.commitScrollMemento(tabId, "/acme/inbox", {});+ store.commitScrollMemento(tabId, "/acme/inbox", {+ list: { top: 0, height: 8000 },+ });expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({scroll: {},diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.tsindex 8379f864a4..0518d3ad18 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts@@ -64,9 +64,8 @@ export function scrollMementoKey(routeKey: string, containerKey: string): string}/**- * Upper bound on a tab's view-state entries. Scroll entries are bounded by- * REPLACE-per-route, but view entries are only cleared by the views that own- * them — a long-lived (persisted) tab would otherwise accumulate one entry+ * Upper bound on a tab's view-state entries. View entries are only cleared by+ * the views that own them — a long-lived (persisted) tab could accumulate one entry* per notification ever opened in it. Oldest-written entries evict first;* losing one merely re-runs a deep-link landing that old. Same bound as the* in-session scroll cache (use-issue-detail-scroll-restore).@@ -245,14 +244,10 @@ interface TabStore {/** Jump directly to one entry in the active session's virtual history. */goToHistoryIndex: (historyIndex: number) => void;/**- * Persist captured scroll offsets for one route of a tab (Coordinator, on- * deactivate / before in-tab navigation). REPLACE semantics per route: all- * of the route's previous entries are dropped and the given ones written —- * so a container scrolled back to 0 (captured as "no entry") clears its- * stale offset instead of resurrecting it on the next visit. External- * sources (iframe documents) always write an entry, including top:0, so a- * contentKey change can replace a stale positive offset rather than leave- * it behind.+ * Update captured containers for one route of a tab, preserving entries for+ * unmounted views. A plain container captured at zero on both axes clears+ * its stale offset. External sources retain zero entries with a contentKey+ * so a content change can invalidate a stale positive offset.*/commitScrollMemento: (tabId: string,@@ -1225,17 +1220,18 @@ export const useTabStore = create<TabStore>()(const { slug, group, index } = hit;const current = group.tabs[index];- const prefix = `${routeKey}::`;- const nextScroll: TabMemento["scroll"] = {};- for (const [key, value] of Object.entries(current.memento.scroll)) {- if (!key.startsWith(prefix)) nextScroll[key] = value;- }+ const nextScroll = { ...current.memento.scroll };for (const [containerKey, value] of Object.entries(entries)) {- nextScroll[scrollMementoKey(routeKey, containerKey)] = value;+ const key = scrollMementoKey(routeKey, containerKey);+ if (value.top <= 0 && (value.left ?? 0) <= 0 && value.contentKey === undefined) {+ delete nextScroll[key];+ } else {+ nextScroll[key] = value;+ }}- // Skip the write when nothing changed (common: an unscrolled route- // captured as empty over an already-empty route scope) — avoids a+ // Skip the write when nothing changed (common: a zero-offset capture+ // for a container with no saved entry) — avoids a// re-entrant store tick from inside the Coordinator's subscription.const prevKeys = Object.keys(current.memento.scroll);const nextKeys = Object.keys(nextScroll);diff --git a/apps/docs/content/docs/desktop-app.mdx b/apps/docs/content/docs/desktop-app.mdxindex 22b515f9e1..c19e83c56c 100644--- a/apps/docs/content/docs/desktop-app.mdx+++ b/apps/docs/content/docs/desktop-app.mdx@@ -52,6 +52,8 @@ Desktop saves tabs per workspace. For example, if you open three issues in worksA 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.+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.## Voice inputdiff --git a/apps/docs/content/docs/desktop-app.zh.mdx b/apps/docs/content/docs/desktop-app.zh.mdxindex 126253a586..7dc49e35db 100644--- a/apps/docs/content/docs/desktop-app.zh.mdx+++ b/apps/docs/content/docs/desktop-app.zh.mdx@@ -52,6 +52,8 @@ Desktop 会为每个工作区单独保存标签页。例如,你在工作区 A同一资源只会在当前工作区打开一次。标签页可以重新排序、固定、关闭,也会保留各自的前进、后退和滚动位置。固定的标签页排在最左边,没有关闭按钮,要先取消固定才能关;在它里面打开别的页面时会新开一个标签页,它自己停在原页面。点击或粘贴本部署的应用链接会直接在标签页中打开,不会跳转到浏览器。+在标签页内切换看板、列表和泳道时,也会保留各视图最新的滚动位置,包括看板的横向位置和列内滚动位置。+退出登录会清除本机保存的所有标签页,避免下一位登录者看到上一个账号留下的页面。## 语音输入diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsxindex 79637e3176..58d4426a35 100644--- a/packages/views/issues/components/swimlane-view.test.tsx+++ b/packages/views/issues/components/swimlane-view.test.tsx@@ -225,15 +225,19 @@ vi.mock("@dnd-kit/utilities", () => ({// nothing (and throws on its resize plumbing). Render every lane inline so the// virtualized swimlane exposes its lanes/cells/cards to the DOM, matching the// non-virtualized behavior these tests assert.+const mockVirtuosoLocation = vi.hoisted(() => vi.fn());vi.mock("react-virtuoso", () => ({- Virtuoso: ({ data, itemContent, components }: any) => (- <div data-testid="virtuoso-mock">- {(data ?? []).map((item: any, i: number) => (- <div key={i}>{itemContent(i, item)}</div>- ))}- {components?.Footer ? <components.Footer /> : null}- </div>- ),+ Virtuoso: ({ data, itemContent, components, initialTopMostItemIndex }: any) => {+ mockVirtuosoLocation(initialTopMostItemIndex);+ return (+ <div data-testid="virtuoso-mock">+ {(data ?? []).map((item: any, i: number) => (+ <div key={i}>{itemContent(i, item)}</div>+ ))}+ {components?.Footer ? <components.Footer /> : null}+ </div>+ );+ },}));const mockIssues: Issue[] = [@@ -1888,6 +1892,16 @@ describe("SwimLaneView", () => {describe("SwimLaneView tab-session scroll restoration (MUL-4741)", () => {it("registers the outer scroller for memento capture and restores the saved offset at attach", () => {+ const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect");+ rect.mockImplementation(function (this: HTMLElement) {+ const scroller = this.closest<HTMLElement>('[data-tab-scroll-root="swimlane"]');+ return {+ top: scroller && this !== scroller ? 176 - scroller.scrollTop : 100,+ left: 0, right: 800, bottom: 800, width: 800, height: 700,+ x: 0, y: 100, toJSON: () => ({}),+ };+ });+ mockVirtuosoLocation.mockClear();const adapter = {get: (key: string) =>key === "swimlane" ? { top: 240, height: 2000 } : undefined,@@ -1916,5 +1930,9 @@ describe("SwimLaneView tab-session scroll restoration (MUL-4741)", () => {// Restore side: the ref-attach assignment applies the saved offset// before first paint (jsdom has no layout, so no clamping applies).expect(scroller!.scrollTop).toBe(240);+ // The virtualizer's item offset excludes the 76px of padding/header+ // above its list, so the outer scroller also lands at 240 in Chromium.+ expect(mockVirtuosoLocation).toHaveBeenLastCalledWith({ index: 0, offset: 164 });+ rect.mockRestore();});});diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsxindex 6bbabed57f..731bf5b775 100644--- a/packages/views/issues/components/swimlane-view.tsx+++ b/packages/views/issues/components/swimlane-view.tsx@@ -992,10 +992,23 @@ function SwimLaneViewImpl({const [activeIssue, setActiveIssue] = useState<Issue | null>(null);// The outer scroll box is the customScrollParent for the lane Virtuoso.const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);+ const laneListRef = useRef<HTMLDivElement>(null);// Pull-based scroll restoration (MUL-4741): same wiring as board/list/// issue-detail — ref-attach assigns the saved offset pre-paint, and the- // lane Virtuoso is born at it via initialScrollTop.+ // lane Virtuoso starts at it via an initial item offset. Unlike+ // initialScrollTop, this also restores a single tall lane.const restoredScrollTop = useRestoredScrollOffset("swimlane");+ const initialLaneLocation = useMemo(() => {+ const list = laneListRef.current;+ if (restoredScrollTop === undefined || !scrollEl || !list) return 0;+ // Item offsets are relative to the lane list, while the memento includes+ // the outer padding and sticky status header above it.+ const listTop =+ list.getBoundingClientRect().top -+ scrollEl.getBoundingClientRect().top ++ scrollEl.scrollTop;+ return { index: 0, offset: restoredScrollTop - listTop };+ }, [restoredScrollTop, scrollEl]);const restoreScrollRef = useRestoredScrollRef("swimlane");const attachScroller = useCallback((el: HTMLDivElement | null) => {@@ -1539,25 +1552,27 @@ function SwimLaneViewImpl({settled after a remount, so the lane area never paints blank; onceit's set, mount the Virtuoso with a matching `initialItemCount` tosurvive the measurement frame (MUL-4750). */}- {scrollEl ? (- <Virtuoso- customScrollParent={scrollEl}- data={orderedLanes}- computeItemKey={computeLaneKey}- initialScrollTop={restoredScrollTop}- initialItemCount={Math.min(orderedLanes.length, SWIMLANE_LANE_SEED_COUNT)}- increaseViewportBy={{ top: 600, bottom: 600 }}- components={laneComponents}- itemContent={renderLane}- />- ) : (- <VirtuosoSeed- data={orderedLanes}- itemContent={renderLane}- computeItemKey={computeLaneKey}- count={SWIMLANE_LANE_SEED_COUNT}- />- )}+ <div ref={laneListRef}>+ {scrollEl ? (+ <Virtuoso+ customScrollParent={scrollEl}+ data={orderedLanes}+ computeItemKey={computeLaneKey}+ initialTopMostItemIndex={initialLaneLocation}+ initialItemCount={Math.min(orderedLanes.length, SWIMLANE_LANE_SEED_COUNT)}+ increaseViewportBy={{ top: 600, bottom: 600 }}+ components={laneComponents}+ itemContent={renderLane}+ />+ ) : (+ <VirtuosoSeed+ data={orderedLanes}+ itemContent={renderLane}+ computeItemKey={computeLaneKey}+ count={SWIMLANE_LANE_SEED_COUNT}+ />+ )}+ </div></SortableContext></div></div>diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsxindex 849d37c900..9ddc1bd1c0 100644--- a/packages/views/platform/scroll-restoration.tsx+++ b/packages/views/platform/scroll-restoration.tsx@@ -4,6 +4,7 @@ import {createContext,useCallback,useContext,+ useMemo,type ReactNode,} from "react";@@ -64,6 +65,12 @@ export interface ScrollRestorationAdapter {* when there is nothing to restore.*/get(containerKey: string): ScrollRestorationEntry | undefined;+ /**+ * Register a plain scroll container at attach time. The returned cleanup+ * captures it before detach, including same-route view changes. The platform+ * binds the capture to the tab/route that owned the element at registration.+ */+ registerScrollRoot?(containerKey: string, element: HTMLElement): () => void;/*** Register/unregister a scroll source that is not a `[data-tab-scroll-root]`* element (currently: a sandboxed iframe's internal document). Desktop@@ -146,24 +153,26 @@ export function useRestoredScrollOffset(containerKey: string): number | undefine* 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.+ * callback. Detach captures the latest offsets through the same adapter.*/export function useRestoredScrollRef(containerKey: string,): (el: HTMLElement | null) => void {const adapter = useContext(ScrollRestorationContext);- return useCallback(- (el: HTMLElement | null) => {+ return useMemo(() => {+ let capture: (() => void) | undefined;+ return (el: HTMLElement | null) => {+ capture?.();+ capture = undefined;if (!el) return;const saved = adapter?.get(containerKey);- if (!saved) return;- if (saved.top > 0) el.scrollTop = saved.top;- if (saved.left !== undefined && saved.left > 0) {+ if (saved && saved.top > 0) el.scrollTop = saved.top;+ if (saved?.left !== undefined && saved.left > 0) {el.scrollLeft = saved.left;}- },- [adapter, containerKey],- );+ capture = adapter?.registerScrollRoot?.(containerKey, el);+ };+ }, [adapter, containerKey]);}/**