TypeScript
fix(web): constrain minimap highlights to visible rows (#16191)
Utkarsh Patilbce474e35dc0
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex b11a2c4b936..d9506825491 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -35,6 +35,9 @@ import {normalizeCompactToolLabel,resolveAssistantMessageCopyState,resolveTimelineIsAtEnd,+ isTimelineMinimapRowVisible,+ resolveTimelineMinimapCurrentIndex,+ resolveTimelineMinimapVisibleRange,resolveTimelineMinimapHasPersistentGutter,resolveTimelineMinimapHeightStyle,resolveTimelineMinimapHitStripWidth,@@ -5636,6 +5639,64 @@ describe("shouldCollapseUserMessage", () => {});describe("timeline end and minimap geometry", () => {+ it("highlights only visible rows inside the rendered buffer despite stale offscreen geometry", () => {+ const range = resolveTimelineMinimapVisibleRange({+ startBuffered: 9,+ endBuffered: 12,+ scroll: 1000,+ scrollLength: 200,+ // Both earlier and later unmounted rows retain coordinates inside the viewport.+ positionAtIndex: (index) => (index < 9 || index > 12 ? 1050 : index * 100),+ sizeAtIndex: () => 100,+ });+ expect(range).toEqual({ start: 10, end: 11 });+ const rowIndices = [0, 9, 10, 11, 12, 20];+ expect(+ rowIndices.filter((index) => isTimelineMinimapRowVisible(index, range.start, range.end)),+ ).toEqual([10, 11]);+ expect(+ resolveTimelineMinimapCurrentIndex({+ visibleStart: range.start,+ visibleEnd: range.end,+ rowIndices,+ }),+ ).toBe(2);+ });++ it("refreshes the visible rows after scrolling and measurement within the same buffer", () => {+ const state = {+ startBuffered: 0,+ endBuffered: 2,+ scroll: 0,+ scrollLength: 200,+ positionAtIndex: (index: number) => [50, 150, 300][index],+ sizeAtIndex: (): number | undefined => undefined,+ };+ expect(resolveTimelineMinimapVisibleRange(state)).toEqual({ start: 0, end: 1 });+ const scrolled = { ...state, scroll: 100 };+ expect(resolveTimelineMinimapVisibleRange(scrolled)).toEqual({ start: 1, end: 1 });+ expect(resolveTimelineMinimapVisibleRange({ ...scrolled, sizeAtIndex: () => 100 })).toEqual({+ start: 0,+ end: 1,+ });+ expect(+ resolveTimelineMinimapVisibleRange({ ...scrolled, scroll: 400, sizeAtIndex: () => 100 }),+ ).toEqual({ start: null, end: null });+ });++ it("navigates from the first visible user message or the preceding turn when only its response is visible", () => {+ const rowIndices = [0, 10, 20, 30, 40];+ const currentIndex = (visibleStart: number | null, visibleEnd: number | null) =>+ resolveTimelineMinimapCurrentIndex({ visibleStart, visibleEnd, rowIndices });++ expect(currentIndex(19, 31)).toBe(2);+ expect(currentIndex(21, 29)).toBe(2);+ expect(currentIndex(41, 45)).toBe(4);+ expect(currentIndex(0, 0)).toBe(0);+ expect(currentIndex(null, null)).toBeNull();+ expect(isTimelineMinimapRowVisible(20, null, null)).toBe(false);+ });+it("treats the follow re-arm band above the content bottom as the live edge", () => {expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex 89a7971f548..9ebb6eda426 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -369,30 +369,63 @@ export function resolveTimelineMinimapIndexFromPointer(input: {return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));}+/** Recheck the rendered buffer: LegendList's unbuffered range can lag during scrolling. */+export function resolveTimelineMinimapVisibleRange(state: {+ readonly startBuffered: number | null | undefined;+ readonly endBuffered: number | null | undefined;+ readonly scroll: number;+ readonly scrollLength: number;+ readonly positionAtIndex: (index: number) => number | undefined;+ readonly sizeAtIndex: (index: number) => number | undefined;+}) {+ let start: number | null = null;+ let end: number | null = null;+ if (state.startBuffered == null || state.endBuffered == null || state.startBuffered < 0) {+ return { start, end };+ }+ const bottom = state.scroll + state.scrollLength;+ for (let index = state.startBuffered; index <= state.endBuffered; index += 1) {+ const top = state.positionAtIndex(index);+ const height = state.sizeAtIndex(index);+ if (+ top != null &&+ Number.isFinite(top) &&+ top < bottom &&+ top + Math.max(1, height != null && Number.isFinite(height) ? height : 1) > state.scroll+ ) {+ start ??= index;+ end = index;+ }+ }+ return { start, end };+}++export function isTimelineMinimapRowVisible(+ rowIndex: number,+ visibleStart: number | null | undefined,+ visibleEnd: number | null | undefined,+): boolean {+ return (+ visibleStart != null && visibleEnd != null && rowIndex >= visibleStart && rowIndex <= visibleEnd+ );+}+export function resolveTimelineMinimapCurrentIndex(input: {- readonly scrollTop: number;- readonly scrollBottom: number;- readonly itemBounds: ReadonlyArray<{- readonly top: number | null;- readonly height: number | null;- }>;+ readonly visibleStart: number | null | undefined;+ readonly visibleEnd: number | null | undefined;+ readonly rowIndices: ReadonlyArray<number>;}): number | null {+ if (input.visibleStart == null || input.visibleEnd == null) {+ return null;+ }let precedingIndex: number | null = null;-- for (const [index, item] of input.itemBounds.entries()) {- if (item.top === null) {- continue;- }- const inView =- item.top < input.scrollBottom && item.top + Math.max(1, item.height ?? 1) > input.scrollTop;- if (inView) {- return index;- }- if (item.top <= input.scrollTop) {- precedingIndex = index;+ for (const [index, rowIndex] of input.rowIndices.entries()) {+ if (rowIndex >= input.visibleStart) {+ // Prefer the first visible user message, otherwise the turn being read.+ return rowIndex <= input.visibleEnd ? index : precedingIndex;}+ precedingIndex = index;}-return precedingIndex;}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex ac02feb76b1..bb209924a1c 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -61,6 +61,7 @@ import {} from "@t3tools/client-runtime/state/subagent-display";import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";import { observeResize } from "~/lib/observeResize";+import { useStableCallback } from "~/hooks/useStableCallback";const NOOP_USE_ARTIFACT_TEMPLATE = () => {};const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};@@ -208,6 +209,8 @@ import {resolveTimelineIsAtEnd,resolveTimelineMinimapHasPersistentGutter,resolveTimelineMinimapCurrentIndex,+ isTimelineMinimapRowVisible,+ resolveTimelineMinimapVisibleRange,resolveTimelineMinimapHeightStyle,resolveTimelineMinimapHitStripWidth,resolveTimelineMinimapIndexFromPointer,@@ -870,6 +873,7 @@ const ConversationTimeline = memo(function ConversationTimeline({// must not change with them or every timeline row re-renders per event.const runs = useStableHandoffRuns(runsProp);const minimapItems = deriveTimelineMinimapItems(rows);+ const minimapRowIndices = minimapItems.map((item) => item.rowIndex);// Preserve initialScrollAtEnd's measured target until the list is reused// for another thread; scrollToEnd would replace it with an estimated offset.const listOpenedOnRef = useRef<{@@ -1126,13 +1130,6 @@ const ConversationTimeline = memo(function ConversationTimeline({onContentOverflowChange(measureContentOverflow());});};- const handleItemSizeChanged = () => {- if (disclosurePinsEndRef.current) {- queueMicrotask(pinDisclosureToEnd);- scheduleDisclosureSettle();- }- reportContentOverflow();- };useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);useLayoutEffect(() => {cancelContentOverflowFrame();@@ -1140,6 +1137,60 @@ const ConversationTimeline = memo(function ConversationTimeline({// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.}, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);+ const refreshMinimap = useStableCallback(() => {+ const state = listRef.current?.getState?.();+ if (restoringThreadPosition || state?.data !== rows) return;+ if (!state || minimapItems.length === 0) {+ return;+ }++ const firstBufferedIndex = state.startBuffered;+ const firstBufferedRow: HTMLElement | undefined =+ firstBufferedIndex == null ? undefined : state.elementAtIndex(firstBufferedIndex);+ const firstBufferedTop =+ firstBufferedIndex == null ? undefined : state.positionAtIndex(firstBufferedIndex);+ const viewport: HTMLElement | undefined = listRef.current?.getScrollableNode();+ // Cached row positions exclude the header and pending scroll adjustments.+ const scroll =+ firstBufferedRow && viewport && firstBufferedTop !== undefined+ ? firstBufferedTop ++ viewport.getBoundingClientRect().top -+ firstBufferedRow.getBoundingClientRect().top+ : state.scroll;+ const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll });+ for (const item of minimapItems) {+ const strip = minimapStripMap.get(item.id);+ const inView = isTimelineMinimapRowVisible(+ item.rowIndex,+ visibleRange.start,+ visibleRange.end,+ );+ const next = inView ? "true" : "false";+ // Avoid dirtying style state on every scroll tick for unchanged strips.+ if (strip && strip.dataset.inView !== next) {+ strip.dataset.inView = next;+ }+ }+ const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({+ visibleStart: visibleRange.start,+ visibleEnd: visibleRange.end,+ rowIndices: minimapRowIndices,+ });+ setMinimapCurrentIndex((current) =>+ current === nextCurrentIndex ? current : nextCurrentIndex,+ );+ });++ const minimapRefreshFrameRef = useRef<number | null>(null);+ const scheduleMinimapRefresh = () => {+ if (minimapRefreshFrameRef.current !== null) return;+ // LegendList recycles row containers before React commits their positions.+ minimapRefreshFrameRef.current = requestAnimationFrame(() => {+ minimapRefreshFrameRef.current = null;+ refreshMinimap();+ });+ };+const handleScroll = () => {const state = listRef.current?.getState?.();if (restoringThreadPosition || state?.data !== rows) return;@@ -1172,45 +1223,28 @@ const ConversationTimeline = memo(function ConversationTimeline({onIsAtEndChange(isAtEnd);}reportContentOverflow();- if (!state || minimapItems.length === 0) {- return;- }-- const scrollTop = state.scroll ?? 0;- const scrollBottom = scrollTop + (state.scrollLength ?? 0);-- const itemBounds = minimapItems.map((item) => ({- top: resolveTimelineRowTop(state, item.rowIndex),- height: resolveTimelineRowHeight(state, item.rowIndex),- }));+ scheduleMinimapRefresh();+ };- for (const [index, item] of minimapItems.entries()) {- const strip = minimapStripMap.get(item.id);- const bounds = itemBounds[index];- const rowTop = bounds?.top ?? null;- const rowHeight = bounds?.height ?? null;- const inView =- rowTop !== null &&- rowTop < scrollBottom &&- rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;-- // Skip no-op attribute writes: this runs for every strip on every scroll- // tick, and rewriting an unchanged attribute still dirties style state.- const next = inView ? "true" : "false";- if (strip && strip.dataset.inView !== next) {- strip.dataset.inView = next;- }+ const handleItemSizeChanged = () => {+ if (disclosurePinsEndRef.current) {+ queueMicrotask(pinDisclosureToEnd);+ scheduleDisclosureSettle();}- const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({- scrollTop,- scrollBottom,- itemBounds,- });- setMinimapCurrentIndex((current) =>- current === nextCurrentIndex ? current : nextCurrentIndex,- );+ reportContentOverflow();+ scheduleMinimapRefresh();};+ useEffect(+ () => () => {+ if (minimapRefreshFrameRef.current !== null) {+ cancelAnimationFrame(minimapRefreshFrameRef.current);+ minimapRefreshFrameRef.current = null;+ }+ },+ [],+ );+useEffect(() => {const frame = requestAnimationFrame(handleScroll);return () => cancelAnimationFrame(frame);@@ -1613,24 +1647,6 @@ function getItemType(item: MessagesTimelineRow) {return `message:${item.message.role}:${lengthBucket}`;}-interface TimelinePositionState {- readonly contentLength?: number;- readonly scroll?: number;- readonly scrollLength?: number;- readonly positionAtIndex?: (index: number) => number | undefined;- readonly sizeAtIndex?: (index: number) => number | undefined;-}--function resolveTimelineRowTop(state: TimelinePositionState, rowIndex: number) {- const top = state.positionAtIndex?.(rowIndex);- return typeof top === "number" && Number.isFinite(top) ? top : null;-}--function resolveTimelineRowHeight(state: TimelinePositionState, rowIndex: number) {- const height = state.sizeAtIndex?.(rowIndex);- return typeof height === "number" && Number.isFinite(height) ? height : null;-}-function timelineMinimapEventTargetsPreview(target: EventTarget): boolean {return target instanceof Element && target.closest("[data-minimap-preview]") !== null;}