Skip to content

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

Go

MUL-5973: fix(tabs): restore inbox scroll position and stop the highlight re-jump on tab return (#6690)

Naiyuan Qing0035345a57bc
diff --git a/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx b/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx
index 1cd8c2bbab..2267c90f54 100644
--- a/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx
+++ b/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx
@@ -26,7 +26,7 @@ function seedHistory() {
stack: ["/acme/issues", "/acme/issues/abc"],
index: 1,
},
- memento: { scroll: {} },
+ memento: { scroll: {}, view: {} },
},
],
activeTabId: "t1",
diff --git a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
index cdbcc4759b..53235f53c8 100644
--- a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
+++ b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
@@ -70,17 +70,37 @@ export function registerCoordinatorQueryClient(qc: QueryClient): void {
* see ScrollRestorationProvider in @multica/views/platform). Offsets are
* looked up live against the tab's memento, scoped to the route the view is
* mounting under, so in-tab back/forward pulls each route's own offsets.
+ *
+ * The generic view-state entries ride the same channel: reads resolve
+ * against the memento's `view` map, writes commit through the store — no
+ * capture pass, the view pushes at the moment its restorable state changes.
*/
export function createScrollRestorationAdapter(
tabId: string,
): ScrollRestorationAdapter {
+ const activeRouteKey = (): string | null => {
+ const state = useTabStore.getState();
+ const active = getActiveTab(state);
+ if (!active || active.id !== tabId) return null;
+ return splitTabUrl(active.url).pathname;
+ };
return {
get(containerKey) {
- const state = useTabStore.getState();
- const active = getActiveTab(state);
- if (!active || active.id !== tabId) return undefined;
- const routeKey = splitTabUrl(active.url).pathname;
- return active.memento.scroll[scrollMementoKey(routeKey, containerKey)];
+ const routeKey = activeRouteKey();
+ if (routeKey === null) return undefined;
+ const active = getActiveTab(useTabStore.getState());
+ return active?.memento.scroll[scrollMementoKey(routeKey, containerKey)];
+ },
+ getViewState(entryKey) {
+ const routeKey = activeRouteKey();
+ if (routeKey === null) return undefined;
+ const active = getActiveTab(useTabStore.getState());
+ return active?.memento.view[scrollMementoKey(routeKey, entryKey)];
+ },
+ setViewState(entryKey, value) {
+ const routeKey = activeRouteKey();
+ if (routeKey === null) return;
+ useTabStore.getState().commitViewState(tabId, routeKey, entryKey, value);
},
};
}
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
index 6b9cfe4840..2cb19d29d4 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -503,6 +503,7 @@ describe("commitScrollMemento", () => {
expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
scroll: { "/acme/issues::board:status:todo": { top: 420, height: 8000 } },
+ view: {},
});
});
@@ -520,6 +521,7 @@ describe("commitScrollMemento", () => {
expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
scroll: {},
+ view: {},
});
});
@@ -556,6 +558,97 @@ describe("commitScrollMemento", () => {
expect(useTabStore.getState().byWorkspace.acme).toBe(before);
});
+
+ it("preserves view-state entries across a scroll REPLACE", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+ store.commitScrollMemento(tabId, "/acme/inbox", {
+ 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", {});
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
+ scroll: {},
+ view: { "/acme/inbox::highlight:i1": "c1" },
+ });
+ });
+});
+
+describe("commitViewState", () => {
+ it("stores route-scoped entries on the addressed tab", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
+ scroll: {},
+ view: { "/acme/inbox::highlight:i1": "c1" },
+ });
+ });
+
+ it("clears an entry when the value is undefined, leaving others intact", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i2", "c2");
+
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", undefined);
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento.view).toEqual({
+ "/acme/inbox::highlight:i2": "c2",
+ });
+ });
+
+ it("skips the store write when the value is unchanged", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+ const before = useTabStore.getState().byWorkspace.acme;
+
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+ store.commitViewState(tabId, "/acme/inbox", "highlight:absent", undefined);
+
+ expect(useTabStore.getState().byWorkspace.acme).toBe(before);
+ });
+
+ it("evicts the oldest entries beyond the cap", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ for (let i = 0; i < 101; i++) {
+ store.commitViewState(tabId, "/acme/inbox", `highlight:i${i}`, "c");
+ }
+
+ const view = useTabStore.getState().byWorkspace.acme.tabs[0].memento.view;
+ expect(Object.keys(view)).toHaveLength(100);
+ expect(view["/acme/inbox::highlight:i0"]).toBeUndefined();
+ expect(view["/acme/inbox::highlight:i100"]).toBe("c");
+ });
+
+ it("preserves scroll entries when a view-state entry commits", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.commitScrollMemento(tabId, "/acme/inbox", {
+ list: { top: 500, height: 8000 },
+ });
+
+ store.commitViewState(tabId, "/acme/inbox", "highlight:i1", "c1");
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
+ scroll: { "/acme/inbox::list": { top: 500, height: 8000 } },
+ view: { "/acme/inbox::highlight:i1": "c1" },
+ });
+ });
});
describe("bulk tab closing", () => {
@@ -940,7 +1033,7 @@ describe("migrateV3ToV4 (legacy view-state import, MUL-4741)", () => {
title: "Issues",
pinned: true,
history: { stack: ["/acme/issues"], index: 0 },
- memento: { scroll: {} },
+ memento: { scroll: {}, view: {} },
},
]);
});
@@ -1004,6 +1097,20 @@ describe("mergePersistedTabs (rehydration, MUL-4370)", () => {
expect(tab.url).toBe("/acme/squads");
});
+ // Payloads written before the generic view-state entries existed carry a
+ // memento with only `scroll`; the session shape requires `view` too.
+ it("normalizes a memento persisted without view-state entries", () => {
+ const tab = rehydrate(
+ persistedTab("/acme/inbox", {
+ memento: { scroll: { "/acme/inbox::list": { top: 5, height: 100 } } },
+ }),
+ );
+ expect(tab.memento).toEqual({
+ scroll: { "/acme/inbox::list": { top: 5, height: 100 } },
+ view: {},
+ });
+ });
+
function rehydrateGroup(
activeTabId: string,
urls: Record<string, string>,
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index 352e7cacd8..0ab3eb8d0f 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -28,16 +28,36 @@ export interface TabMemento {
* for diagnostics and future pre-sizing heuristics.
*/
scroll: Record<string, { top: number; height: number }>;
+ /**
+ * Generic restorable view-state entries, keyed like `scroll`
+ * (`${routePathname}::${entryKey}`). The memento's second kind of cargo:
+ * state that must survive the active tab's unmount but is not a scroll
+ * offset — e.g. "this route's comment-highlight deep link already
+ * landed". Unlike scroll these are not captured by DOM scan; views write
+ * them through the restoration adapter when the state changes
+ * (commitViewState) and read them back at mount.
+ */
+ view: Record<string, string>;
}
export function emptyMemento(): TabMemento {
- return { scroll: {} };
+ return { scroll: {}, view: {} };
}
export function scrollMementoKey(routeKey: string, containerKey: string): string {
return `${routeKey}::${containerKey}`;
}
+/**
+ * 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
+ * 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).
+ */
+const VIEW_MEMENTO_MAX_ENTRIES = 100;
+
export interface TabSession {
id: string;
/**
@@ -183,6 +203,19 @@ interface TabStore {
routeKey: string,
entries: Record<string, { top: number; height: number }>,
) => void;
+ /**
+ * Write (string) or clear (undefined) one generic view-state entry for one
+ * route of a tab (views, through the restoration adapter, at the moment
+ * the state changes). Unlike scroll there is no capture pass and no
+ * per-route REPLACE: each entry's lifecycle is owned by the view that
+ * writes it.
+ */
+ commitViewState: (
+ tabId: string,
+ routeKey: string,
+ entryKey: string,
+ value: string | undefined,
+ ) => void;
/**
* Force-remount the active tab at the same URL: bump mountGeneration.
* Query invalidation for the current page's scope is handled by the
@@ -745,7 +778,49 @@ export const useTabStore = create<TabStore>()(
if (unchanged) return;
const nextTabs = [...group.tabs];
- nextTabs[index] = { ...current, memento: { scroll: nextScroll } };
+ nextTabs[index] = {
+ ...current,
+ memento: { ...current.memento, scroll: nextScroll },
+ };
+ set({
+ byWorkspace: {
+ ...byWorkspace,
+ [slug]: { ...group, tabs: nextTabs },
+ },
+ });
+ },
+
+ commitViewState(tabId, routeKey, entryKey, value) {
+ const { byWorkspace } = get();
+ const hit = findTabLocation(byWorkspace, tabId);
+ if (!hit) return;
+ const { slug, group, index } = hit;
+ const current = group.tabs[index];
+
+ const key = scrollMementoKey(routeKey, entryKey);
+ // Skip the write when nothing changed (covers clearing an absent
+ // entry) — avoids a re-entrant store tick from inside a view effect.
+ if (current.memento.view[key] === value) return;
+
+ const nextView = { ...current.memento.view };
+ if (value === undefined) {
+ delete nextView[key];
+ } else {
+ // Re-writing an existing key refreshes its age (delete-then-set
+ // moves it to the end of the insertion order the eviction reads).
+ delete nextView[key];
+ nextView[key] = value;
+ const keys = Object.keys(nextView);
+ for (let i = 0; i < keys.length - VIEW_MEMENTO_MAX_ENTRIES; i++) {
+ delete nextView[keys[i]];
+ }
+ }
+
+ const nextTabs = [...group.tabs];
+ nextTabs[index] = {
+ ...current,
+ memento: { ...current.memento, view: nextView },
+ };
set({
byWorkspace: {
...byWorkspace,
@@ -993,7 +1068,15 @@ export function mergePersistedTabs<T extends PersistedTabState>(
history: { stack, index },
memento:
pTab.memento && typeof pTab.memento.scroll === "object"
- ? pTab.memento
+ ? {
+ scroll: pTab.memento.scroll,
+ // Persisted by builds that predate the generic view-state
+ // entries — normalize to the current shape.
+ view:
+ typeof pTab.memento.view === "object" && pTab.memento.view
+ ? pTab.memento.view
+ : {},
+ }
: emptyMemento(),
});
}
@@ -1124,7 +1207,9 @@ interface V4PersistedTab {
icon?: string;
pinned: boolean;
history: { stack: string[]; index: number };
- memento: TabMemento;
+ /** `view` is absent in payloads written before the generic view-state
+ * entries existed; rehydration normalizes it to `{}`. */
+ memento: { scroll: TabMemento["scroll"]; view?: TabMemento["view"] };
}
interface V4PersistedGroup {
diff --git a/apps/web/platform/scroll-restoration.tsx b/apps/web/platform/scroll-restoration.tsx
index e5ee57d7b4..da1d19ec23 100644
--- a/apps/web/platform/scroll-restoration.tsx
+++ b/apps/web/platform/scroll-restoration.tsx
@@ -29,6 +29,15 @@ import {
*/
const savedOffsets = new Map<string, { top: number; height: number }>();
+/**
+ * Generic view-state entries (the desktop memento's second cargo — e.g.
+ * "this route's comment-highlight deep link already landed"). Views write
+ * through `setViewState` when the state changes and read back at mount.
+ * Same lifetime as the offsets: module state, per browser tab, reset on
+ * full reload.
+ */
+const savedViewState = new Map<string, string>();
+
/**
* Keys recently served through `adapter.get` are write-suppressed briefly:
* the restoring container assigns `scrollTop` at attach time, and if its
@@ -91,6 +100,16 @@ export function WebScrollRestorationProvider({
}
return saved;
},
+ getViewState(entryKey) {
+ return savedViewState.get(
+ mementoKey(window.location.pathname, entryKey),
+ );
+ },
+ setViewState(entryKey, value) {
+ const key = mementoKey(window.location.pathname, entryKey);
+ if (value === undefined) savedViewState.delete(key);
+ else savedViewState.set(key, value);
+ },
}),
[],
);
diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsx
index b33ac35271..1d90362c9d 100644
--- a/packages/views/inbox/components/inbox-list.tsx
+++ b/packages/views/inbox/components/inbox-list.tsx
@@ -9,8 +9,15 @@ import type { InboxItem } from "@multica/core/types";
import type { InboxView } from "./inbox-view";
import { InboxListItem } from "./inbox-list-item";
import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";
+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
import { useT } from "../../i18n";
+// Sizing only (like the board's card estimate): the seed's trailing spacer
+// and Virtuoso's defaultItemHeight share this value so the scroller's height
+// is truthful from the first frame and a restored offset sticks. A row is
+// two text lines (body + caption) plus py-2.5.
+const INBOX_ROW_ESTIMATED_HEIGHT = 58;
+
/**
* Scrollable, virtualized inbox notification list.
*
@@ -56,6 +63,19 @@ export function InboxList({
// A callback ref into state hands the element over once it mounts and
// triggers the re-render that lets Virtuoso attach to it.
const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741): assign the saved offset at
+ // ref-attach (the seed's estimate spacer gives the container a truthful
+ // height on the first commit, so the assignment sticks pre-paint) and feed
+ // the same offset into the Virtuoso as its initial position.
+ const restoredScrollTop = useRestoredScrollOffset("list");
+ const restoreScrollRef = useRestoredScrollRef("list");
+ const attachScrollEl = useCallback(
+ (el: HTMLDivElement | null) => {
+ setScrollEl(el);
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
const virtuosoRef = useRef<VirtuosoHandle>(null);
const isArchivedView = view === "archived";
@@ -185,7 +205,8 @@ export function InboxList({
// `initialItemCount` so the measurement frame keeps those rows (MUL-4750).
return (
<div
- ref={setScrollEl}
+ ref={attachScrollEl}
+ data-tab-scroll-root="list"
// Programmatically focusable only: the rows are buttons and already
// carry their own tab stops, so a tabbable container would just add a
// redundant one.
@@ -200,7 +221,9 @@ export function InboxList({
customScrollParent={scrollEl}
data={items}
computeItemKey={computeItemKey}
+ initialScrollTop={restoredScrollTop}
initialItemCount={Math.min(items.length, VIRTUOSO_SEED_COUNT)}
+ defaultItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}
increaseViewportBy={{ top: 400, bottom: 400 }}
itemContent={itemContent}
components={{ Footer }}
@@ -211,6 +234,7 @@ export function InboxList({
data={items}
itemContent={itemContent}
computeItemKey={computeItemKey}
+ estimatedItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}
/>
{/* The seed frame renders a bounded slice, so the entry would be
mid-list rather than after the last row — only show it once the
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 98830eacfc..67ef962768 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -69,9 +69,19 @@ vi.mock("@multica/core/inbox/mutations", () => {
};
});
+// Render-time capture of the props IssueDetail receives, so tests can assert
+// what the page threads into it (highlight replay token) without standing up
+// the real detail.
+const issueDetailProps = vi.hoisted(
+ () => [] as Array<Record<string, unknown>>,
+);
vi.mock("../../issues/components", () => ({
- IssueDetail: () => null,
+ IssueDetail: (props: Record<string, unknown>) => {
+ issueDetailProps.push(props);
+ return null;
+ },
StatusIcon: () => null,
+ issueHighlightMementoKey: (issueId: string) => `highlight:${issueId}`,
}));
const replace = vi.fn();
@@ -177,6 +187,7 @@ function reset() {
markReadMutate.mockClear();
markUnreadMutate.mockClear();
rowActions = null;
+ issueDetailProps.length = 0;
layout.width = PHONE;
}
@@ -242,6 +253,23 @@ describe("InboxPage", () => {
expect(replace).toHaveBeenCalledWith("/acme/inbox");
});
+ it("replays the comment highlight when the already-open row is clicked again", () => {
+ // Re-clicking the open notification is an explicit "take me back to that
+ // comment". It doesn't remount the detail (same issue key), so the page
+ // signals the replay through the bumped token; a selection change keeps
+ // the token still — its remount replays the landing by itself.
+ reset();
+ layout.width = DESKTOP;
+ listData.active = [item({ details: { comment_id: "comment-1" } })];
+
+ render(<InboxPage />);
+ fireEvent.click(screen.getByTestId("row"));
+ expect(issueDetailProps.at(-1)?.highlightRequestToken).toBe(0);
+
+ fireEvent.click(screen.getByTestId("row"));
+ expect(issueDetailProps.at(-1)?.highlightRequestToken).toBe(1);
+ });
+
it("keeps the archived view in the URL when selecting an item there", () => {
// A bare `?issue=` write would silently drop the user back to the main
// inbox on the next refresh — both pieces of state travel together.
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index c2408ac2a7..f4f6d3c910 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -25,7 +25,8 @@ import {
useArchiveCompletedInbox,
} from "@multica/core/inbox/mutations";
-import { IssueDetail } from "../../issues/components";
+import { IssueDetail, issueHighlightMementoKey } from "../../issues/components";
+import { useViewStateWriter } from "../../platform";
import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";
import { useNavigation } from "../../navigation";
import { toast } from "sonner";
@@ -252,8 +253,27 @@ export function InboxPage() {
}
}, [selectedId]);
+ const writeViewState = useViewStateWriter();
+ // Bumped when the already-open notification row is re-clicked; threaded to
+ // IssueDetail so it replays the comment-highlight landing without a
+ // remount. Selection changes don't need it — they remount the detail (key
+ // by issue) and a fresh mount with a cleared memento entry lands by itself.
+ const [highlightRequestToken, setHighlightRequestToken] = useState(0);
const handleSelect = (item: InboxItem) => {
- setSelectedKey(item.issue_id ?? item.id);
+ const nextKey = item.issue_id ?? item.id;
+ // Every click on a notification row is a fresh deep-link intent: clear
+ // the "highlight already landed" memento entry so the comment jump runs
+ // again even if this issue's detail was opened (and its landing
+ // consumed) before. Selection restored from the URL on a remount goes
+ // through the effects above, not through here, so a tab switch back
+ // keeps the entry and does NOT re-jump.
+ if (item.issue_id) {
+ writeViewState(issueHighlightMementoKey(item.issue_id), undefined);
+ if (nextKey === selectedKey) {
+ setHighlightRequestToken((t) => t + 1);
+ }
+ }
+ setSelectedKey(nextKey);
};
const handleMarkRead = (id: string) => {
@@ -532,6 +552,7 @@ export function InboxPage() {
defaultSidebarOpen={false}
layoutId="multica_inbox_issue_detail_layout"
highlightCommentId={selected.details?.comment_id ?? undefined}
+ highlightRequestToken={highlightRequestToken}
leadingAction={compactBackAction}
onDelete={() => {
// Issue deletion CASCADE-deletes the inbox item server-side, and the
diff --git a/packages/views/issues/components/index.ts b/packages/views/issues/components/index.ts
index b07438c40c..dea9abd814 100644
--- a/packages/views/issues/components/index.ts
+++ b/packages/views/issues/components/index.ts
@@ -2,7 +2,7 @@ export { StatusIcon } from "./status-icon";
export { StatusHeading } from "./status-heading";
export { PriorityIcon } from "./priority-icon";
export { StatusPicker, PriorityPicker, StagePicker, AssigneePicker, canAssignAgent, StartDatePicker, DueDatePicker, LabelPicker } from "./pickers";
-export { IssueDetail, IssueDetailSkeleton } from "./issue-detail";
+export { IssueDetail, IssueDetailSkeleton, issueHighlightMementoKey } from "./issue-detail";
export { IssueDetailRoute } from "./issue-detail-route";
export { IssuesPage } from "./issues-page";
export { CommentCard } from "./comment-card";
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 1221251b17..d1408ccd76 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -110,7 +110,12 @@ import { useIssueReactions } from "../hooks/use-issue-reactions";
import { useIssueSubscribers } from "../hooks/use-issue-subscribers";
import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
import { useTimeAgo } from "../../i18n";
-import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
+import {
+ useRestoredScrollOffset,
+ useRestoredScrollRef,
+ useRestoredViewState,
+ useViewStateWriter,
+} from "../../platform";
import { cn } from "@multica/ui/lib/utils";
import { ProgressRing } from "./progress-ring";
@@ -127,6 +132,17 @@ import {
useAnimatedRightSidebarState,
} from "../../layout/animated-right-sidebar";
+/**
+ * Memento entry recording that the comment-highlight deep link for this
+ * issue already landed on the current route (value: the consumed comment
+ * id). Lets a remount that merely restores the view (tab switch back) skip
+ * the jump-and-highlight, while a fresh selection — which clears the entry
+ * (see InboxPage.handleSelect) — runs it again.
+ */
+export function issueHighlightMementoKey(issueId: string): string {
+ return `highlight:${issueId}`;
+}
+
// Shared by the subscribe button and the unsubscribe menu trigger so the two
// stay one control visually — they occupy the same slot and only differ in
// what a click does.
@@ -919,6 +935,15 @@ interface IssueDetailProps {
layoutId?: string;
/** When set, the issue detail will auto-scroll to this comment and briefly highlight it. */
highlightCommentId?: string;
+ /**
+ * Bump to replay the `highlightCommentId` landing on an already-mounted
+ * detail. A remount replays it by itself (fresh mount, cleared memento
+ * entry); this token is for the one path with neither remount nor
+ * guaranteed re-render — re-clicking the notification row that is already
+ * open (see InboxPage.handleSelect). The bump both re-arms the landing
+ * guard and forces the render that re-reads the cleared memento entry.
+ */
+ highlightRequestToken?: number;
/**
* Far-left header slot, replacing the mobile sidebar trigger. A host that
* embeds this detail one level deep (the inbox, on a phone) passes its own
@@ -1048,7 +1073,7 @@ export function IssueDetailSkeleton({ leading }: { leading?: ReactNode } = {}) {
// IssueDetail
// ---------------------------------------------------------------------------
-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, leadingAction }: IssueDetailProps) {
+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction }: IssueDetailProps) {
const { t } = useT("issues");
const timeAgo = useTimeAgo();
const id = issueId;
@@ -1135,8 +1160,31 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// the flat render modes (real heights at commit); the virtualized browsing
// mode feeds the offset into Virtuoso's initialScrollTop below so the
// list's first render already materializes the rows around it.
- const restoredScrollTop = useRestoredScrollOffset("main");
- const restoreScrollRef = useRestoredScrollRef("main");
+ //
+ // The container key carries the issue id: on the issue route that is
+ // redundant with the route scoping, but in the inbox the selection lives
+ // in the query string while memento entries key by pathname — a bare
+ // "main" would restore notification A's offset into notification B's
+ // detail.
+ const scrollContainerKey = `main:${id}`;
+ const restoredScrollTop = useRestoredScrollOffset(scrollContainerKey);
+ const restoreScrollRef = useRestoredScrollRef(scrollContainerKey);
+ // Whether this issue's comment-highlight deep link already landed here
+ // (survives the tab's unmount, unlike didHighlightRef below): a remount
+ // that restores the view must not re-run the jump.
+ //
+ // The landing effect reads it through a ref, NOT through its dependency
+ // array: recording the landing writes this very value, and as an effect
+ // dependency that write would re-fire the effect one commit after the
+ // jump — whose cleanup cancels the centering rAF loop and the highlight
+ // fade before a single frame ran. Every path that must re-evaluate the
+ // landing already re-runs the effect through another dependency (mount,
+ // items arriving, token bump), and the render that precedes it refreshes
+ // this ref.
+ const consumedHighlightId = useRestoredViewState(issueHighlightMementoKey(id));
+ const consumedHighlightRef = useRef(consumedHighlightId);
+ consumedHighlightRef.current = consumedHighlightId;
+ const writeViewState = useViewStateWriter();
const attachScrollContainer = useCallback(
(el: HTMLDivElement | null) => {
setScrollContainerEl(el);
@@ -1221,6 +1269,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
});
}, []);
const didHighlightRef = useRef<string | null>(null);
+ // Last seen highlightRequestToken; a bump re-arms didHighlightRef so the
+ // landing effect below replays on an already-mounted detail.
+ const lastHighlightRequestTokenRef = useRef(highlightRequestToken);
// Issue data from TQ — uses detail query, seeded from list cache if available.
// Only seed when description is present; the list API omits it, so a partial
@@ -1699,7 +1750,22 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// the timeline (and the deep-link target id) has actually rendered.
useEffect(() => {
if (!highlightCommentId || items.length === 0) return;
+ // An explicit replay request (re-click on the already-open notification
+ // row): the host cleared the memento entry and bumped the token, so
+ // re-arm the landing guard and fall through to the jump.
+ if (lastHighlightRequestTokenRef.current !== highlightRequestToken) {
+ lastHighlightRequestTokenRef.current = highlightRequestToken;
+ didHighlightRef.current = null;
+ }
if (didHighlightRef.current === highlightCommentId) return;
+ // The deep link already landed before this mount (memento entry — a tab
+ // switch back or an in-tab return). The restored scroll offset is the
+ // state the user left, and the jump must not fight it. A fresh selection
+ // clears the entry, so this only ever suppresses a *repeat* landing.
+ if (consumedHighlightRef.current === highlightCommentId) {
+ didHighlightRef.current = highlightCommentId;
+ return;
+ }
const rootId = replyToRoot.get(highlightCommentId);
if (rootId && rootId !== highlightCommentId) {
@@ -1728,6 +1794,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
if (!el || !container) return;
didHighlightRef.current = highlightCommentId;
+ // Record the landing in the memento so a remount that merely restores
+ // this view (tab switch back) skips the jump instead of replaying it
+ // over the restored scroll position.
+ writeViewState(issueHighlightMementoKey(id), highlightCommentId);
// Center the target comment WITHIN its own scroll container by driving the
// container's scrollTop directly — never native scrollIntoView. Native
@@ -1766,7 +1836,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
cancelAnimationFrame(rafId);
clearTimeout(fade);
};
- }, [highlightCommentId, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);
+ }, [highlightCommentId, highlightRequestToken, id, writeViewState, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);
const descEditorRef = useRef<ContentEditorRef>(null);
// Keep the description editor mounted from the start. Unlike the empty
@@ -1976,7 +2046,15 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
restoreKey: `${wsId}:${id}`,
scrollContainerEl,
ready: !!issue && !loading && !timelineLoading,
- disabled: !!highlightCommentId,
+ // Disabled only while the comment deep link still has a landing to run —
+ // the jump owns the scroll then. Once the landing is consumed (a tab
+ // switch back), this hook's retry loop IS the restore: the one-shot
+ // ref-attach assignment clamps against a container whose async content
+ // (markdown, images) hasn't reached its captured height yet.
+ disabled: !!highlightCommentId && consumedHighlightId !== highlightCommentId,
+ // The tab memento's offset, when the platform serves one. It must win
+ // over this hook's module-level map — see the parameter doc.
+ overrideTop: restoredScrollTop,
});
if (loading) {
@@ -2544,7 +2622,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
nothing and render unchanged. */}
<div
ref={attachScrollContainer}
- data-tab-scroll-root
+ data-tab-scroll-root={scrollContainerKey}
className="relative flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]"
>
{/* Gutters: 32px is a comfortable reading margin on a desktop column
diff --git a/packages/views/issues/hooks/use-issue-detail-scroll-restore.test.tsx b/packages/views/issues/hooks/use-issue-detail-scroll-restore.test.tsx
index 7b7708316d..fd2be34461 100644
--- a/packages/views/issues/hooks/use-issue-detail-scroll-restore.test.tsx
+++ b/packages/views/issues/hooks/use-issue-detail-scroll-restore.test.tsx
@@ -17,10 +17,12 @@ function Harness({
restoreKey,
ready = true,
disabled = false,
+ overrideTop,
}: {
restoreKey: string;
ready?: boolean;
disabled?: boolean;
+ overrideTop?: number;
}) {
const [scrollContainerEl, setScrollContainerEl] =
useState<HTMLDivElement | null>(null);
@@ -30,6 +32,7 @@ function Harness({
scrollContainerEl,
ready,
disabled,
+ overrideTop,
});
return (
@@ -285,6 +288,28 @@ describe("useIssueDetailScrollRestore", () => {
expect(scroller.scrollTop).toBe(500);
});
+ it("restores the memento override over its own map when both exist", () => {
+ // The module map only hears scroll events, so it can hold an older
+ // visit's offset; the platform memento is captured from the live DOM at
+ // leave time and must win.
+ const issueA = nextKey("issue-a");
+ const issueB = nextKey("issue-b");
+
+ const { getByTestId, rerender } = render(<Harness restoreKey={issueA} />);
+ const scroller = getByTestId("scroller") as HTMLElement;
+ flushNextAnimationFrame();
+
+ setScroll(scroller, 500);
+
+ rerender(<Harness restoreKey={issueB} />);
+ flushNextAnimationFrame();
+ expect(scroller.scrollTop).toBe(0);
+
+ rerender(<Harness restoreKey={issueA} overrideTop={340} />);
+ flushNextAnimationFrame();
+ expect(scroller.scrollTop).toBe(340);
+ });
+
it("does not yank scroll to top when a same-issue comment highlight clears", () => {
const issueA = nextKey("issue-a");
diff --git a/packages/views/issues/hooks/use-issue-detail-scroll-restore.ts b/packages/views/issues/hooks/use-issue-detail-scroll-restore.ts
index e47a214912..fb21564f67 100644
--- a/packages/views/issues/hooks/use-issue-detail-scroll-restore.ts
+++ b/packages/views/issues/hooks/use-issue-detail-scroll-restore.ts
@@ -5,6 +5,17 @@ type UseIssueDetailScrollRestoreArgs = {
scrollContainerEl: HTMLElement | null;
ready: boolean;
disabled?: boolean;
+ /**
+ * Authoritative restore target from the platform's tab memento, when one
+ * is being served (MUL-4741). It wins over this hook's module-level map:
+ * the memento is captured from the live DOM at the moment the view is
+ * left, while the map only hears scroll *events* — content-driven
+ * position shifts (scroll anchoring, streaming blocks collapsing) move
+ * scrollTop without one, leaving the map holding an older visit. Without
+ * this, the two restores race and the retry loop below overwrites the
+ * memento's fresher offset with the stale one.
+ */
+ overrideTop?: number;
};
const scrollPositions = new Map<string, number>();
@@ -15,6 +26,7 @@ export function useIssueDetailScrollRestore({
scrollContainerEl,
ready,
disabled = false,
+ overrideTop,
}: UseIssueDetailScrollRestoreArgs) {
const restoredKeyRef = useRef<string | null>(null);
@@ -47,14 +59,14 @@ export function useIssueDetailScrollRestore({
restoredKeyRef.current = restoreKey;
- const target = scrollPositions.get(restoreKey) ?? 0;
+ const target = overrideTop ?? scrollPositions.get(restoreKey) ?? 0;
if (target <= 1) {
scrollContainerEl.scrollTop = target;
return;
}
return restoreScrollTopWithRetry(scrollContainerEl, target);
- }, [scrollContainerEl, restoreKey, ready, disabled]);
+ }, [scrollContainerEl, restoreKey, ready, disabled, overrideTop]);
}
function saveScrollPosition(restoreKey: string, scrollTop: number) {
diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.ts
index 1e22cc6001..d6c545b218 100644
--- a/packages/views/platform/index.ts
+++ b/packages/views/platform/index.ts
@@ -17,5 +17,7 @@ export {
ScrollRestorationProvider,
useRestoredScrollOffset,
useRestoredScrollRef,
+ useRestoredViewState,
+ useViewStateWriter,
type ScrollRestorationAdapter,
} from "./scroll-restoration";
diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsx
index d15eb45c01..ac113b7507 100644
--- a/packages/views/platform/scroll-restoration.tsx
+++ b/packages/views/platform/scroll-restoration.tsx
@@ -28,6 +28,20 @@ export interface ScrollRestorationAdapter {
* when there is nothing to restore.
*/
get(containerKey: string): { top: number; height: number } | undefined;
+ /**
+ * Generic restorable view-state entries — the memento's second kind of
+ * cargo, for state that must survive the view's unmount but is not a
+ * scroll offset (e.g. "this route's comment-highlight deep link already
+ * landed"). Unlike scroll, these are not captured by DOM scan: the view
+ * writes them through `setViewState` at the moment the state changes and
+ * reads them back at mount. Scoped per route + tab like scroll entries.
+ *
+ * Optional so scroll-only adapters stay valid; the hooks treat a missing
+ * implementation as "nothing stored / write ignored".
+ */
+ getViewState?(entryKey: string): string | undefined;
+ /** Write (string) or clear (undefined) an entry for the current route. */
+ setViewState?(entryKey: string, value: string | undefined): void;
}
const ScrollRestorationContext = createContext<ScrollRestorationAdapter | null>(
@@ -78,3 +92,31 @@ export function useRestoredScrollRef(
[adapter, containerKey],
);
}
+
+/**
+ * The saved view-state entry for a key on the current route, or undefined.
+ * Read at mount like the scroll offset — it reflects what this view recorded
+ * before it was last unmounted.
+ */
+export function useRestoredViewState(entryKey: string): string | undefined {
+ const adapter = useContext(ScrollRestorationContext);
+ return adapter?.getViewState?.(entryKey);
+}
+
+/**
+ * Imperative writer for view-state entries: call it when the restorable
+ * state changes (pass undefined to clear). No-op without a provider or on
+ * adapters that only track scroll.
+ */
+export function useViewStateWriter(): (
+ entryKey: string,
+ value: string | undefined,
+) => void {
+ const adapter = useContext(ScrollRestorationContext);
+ return useCallback(
+ (entryKey: string, value: string | undefined) => {
+ adapter?.setViewState?.(entryKey, value);
+ },
+ [adapter],
+ );
+}