Skip to content

Commit bce474e

Browse files
fix(web): constrain minimap highlights to visible rows (pingdotgg#16191)
Co-authored-by: Julius Marminge <[email protected]>
1 parent f57cfe1 commit bce474e

3 files changed

Lines changed: 189 additions & 79 deletions

File tree

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ import {
3535
normalizeCompactToolLabel,
3636
resolveAssistantMessageCopyState,
3737
resolveTimelineIsAtEnd,
38+
isTimelineMinimapRowVisible,
39+
resolveTimelineMinimapCurrentIndex,
40+
resolveTimelineMinimapVisibleRange,
3841
resolveTimelineMinimapHasPersistentGutter,
3942
resolveTimelineMinimapHeightStyle,
4043
resolveTimelineMinimapHitStripWidth,
@@ -5636,6 +5639,64 @@ describe("shouldCollapseUserMessage", () => {
56365639
});
56375640

56385641
describe("timeline end and minimap geometry", () => {
5642+
it("highlights only visible rows inside the rendered buffer despite stale offscreen geometry", () => {
5643+
const range = resolveTimelineMinimapVisibleRange({
5644+
startBuffered: 9,
5645+
endBuffered: 12,
5646+
scroll: 1000,
5647+
scrollLength: 200,
5648+
// Both earlier and later unmounted rows retain coordinates inside the viewport.
5649+
positionAtIndex: (index) => (index < 9 || index > 12 ? 1050 : index * 100),
5650+
sizeAtIndex: () => 100,
5651+
});
5652+
expect(range).toEqual({ start: 10, end: 11 });
5653+
const rowIndices = [0, 9, 10, 11, 12, 20];
5654+
expect(
5655+
rowIndices.filter((index) => isTimelineMinimapRowVisible(index, range.start, range.end)),
5656+
).toEqual([10, 11]);
5657+
expect(
5658+
resolveTimelineMinimapCurrentIndex({
5659+
visibleStart: range.start,
5660+
visibleEnd: range.end,
5661+
rowIndices,
5662+
}),
5663+
).toBe(2);
5664+
});
5665+
5666+
it("refreshes the visible rows after scrolling and measurement within the same buffer", () => {
5667+
const state = {
5668+
startBuffered: 0,
5669+
endBuffered: 2,
5670+
scroll: 0,
5671+
scrollLength: 200,
5672+
positionAtIndex: (index: number) => [50, 150, 300][index],
5673+
sizeAtIndex: (): number | undefined => undefined,
5674+
};
5675+
expect(resolveTimelineMinimapVisibleRange(state)).toEqual({ start: 0, end: 1 });
5676+
const scrolled = { ...state, scroll: 100 };
5677+
expect(resolveTimelineMinimapVisibleRange(scrolled)).toEqual({ start: 1, end: 1 });
5678+
expect(resolveTimelineMinimapVisibleRange({ ...scrolled, sizeAtIndex: () => 100 })).toEqual({
5679+
start: 0,
5680+
end: 1,
5681+
});
5682+
expect(
5683+
resolveTimelineMinimapVisibleRange({ ...scrolled, scroll: 400, sizeAtIndex: () => 100 }),
5684+
).toEqual({ start: null, end: null });
5685+
});
5686+
5687+
it("navigates from the first visible user message or the preceding turn when only its response is visible", () => {
5688+
const rowIndices = [0, 10, 20, 30, 40];
5689+
const currentIndex = (visibleStart: number | null, visibleEnd: number | null) =>
5690+
resolveTimelineMinimapCurrentIndex({ visibleStart, visibleEnd, rowIndices });
5691+
5692+
expect(currentIndex(19, 31)).toBe(2);
5693+
expect(currentIndex(21, 29)).toBe(2);
5694+
expect(currentIndex(41, 45)).toBe(4);
5695+
expect(currentIndex(0, 0)).toBe(0);
5696+
expect(currentIndex(null, null)).toBeNull();
5697+
expect(isTimelineMinimapRowVisible(20, null, null)).toBe(false);
5698+
});
5699+
56395700
it("treats the follow re-arm band above the content bottom as the live edge", () => {
56405701
expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
56415702
expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 52 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -369,30 +369,63 @@ export function resolveTimelineMinimapIndexFromPointer(input: {
369369
return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
370370
}
371371

372+
/** Recheck the rendered buffer: LegendList's unbuffered range can lag during scrolling. */
373+
export function resolveTimelineMinimapVisibleRange(state: {
374+
readonly startBuffered: number | null | undefined;
375+
readonly endBuffered: number | null | undefined;
376+
readonly scroll: number;
377+
readonly scrollLength: number;
378+
readonly positionAtIndex: (index: number) => number | undefined;
379+
readonly sizeAtIndex: (index: number) => number | undefined;
380+
}) {
381+
let start: number | null = null;
382+
let end: number | null = null;
383+
if (state.startBuffered == null || state.endBuffered == null || state.startBuffered < 0) {
384+
return { start, end };
385+
}
386+
const bottom = state.scroll + state.scrollLength;
387+
for (let index = state.startBuffered; index <= state.endBuffered; index += 1) {
388+
const top = state.positionAtIndex(index);
389+
const height = state.sizeAtIndex(index);
390+
if (
391+
top != null &&
392+
Number.isFinite(top) &&
393+
top < bottom &&
394+
top + Math.max(1, height != null && Number.isFinite(height) ? height : 1) > state.scroll
395+
) {
396+
start ??= index;
397+
end = index;
398+
}
399+
}
400+
return { start, end };
401+
}
402+
403+
export function isTimelineMinimapRowVisible(
404+
rowIndex: number,
405+
visibleStart: number | null | undefined,
406+
visibleEnd: number | null | undefined,
407+
): boolean {
408+
return (
409+
visibleStart != null && visibleEnd != null && rowIndex >= visibleStart && rowIndex <= visibleEnd
410+
);
411+
}
412+
372413
export function resolveTimelineMinimapCurrentIndex(input: {
373-
readonly scrollTop: number;
374-
readonly scrollBottom: number;
375-
readonly itemBounds: ReadonlyArray<{
376-
readonly top: number | null;
377-
readonly height: number | null;
378-
}>;
414+
readonly visibleStart: number | null | undefined;
415+
readonly visibleEnd: number | null | undefined;
416+
readonly rowIndices: ReadonlyArray<number>;
379417
}): number | null {
418+
if (input.visibleStart == null || input.visibleEnd == null) {
419+
return null;
420+
}
380421
let precedingIndex: number | null = null;
381-
382-
for (const [index, item] of input.itemBounds.entries()) {
383-
if (item.top === null) {
384-
continue;
385-
}
386-
const inView =
387-
item.top < input.scrollBottom && item.top + Math.max(1, item.height ?? 1) > input.scrollTop;
388-
if (inView) {
389-
return index;
390-
}
391-
if (item.top <= input.scrollTop) {
392-
precedingIndex = index;
422+
for (const [index, rowIndex] of input.rowIndices.entries()) {
423+
if (rowIndex >= input.visibleStart) {
424+
// Prefer the first visible user message, otherwise the turn being read.
425+
return rowIndex <= input.visibleEnd ? index : precedingIndex;
393426
}
427+
precedingIndex = index;
394428
}
395-
396429
return precedingIndex;
397430
}
398431

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 76 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
} from "@t3tools/client-runtime/state/subagent-display";
6262
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
6363
import { observeResize } from "~/lib/observeResize";
64+
import { useStableCallback } from "~/hooks/useStableCallback";
6465

6566
const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
6667
const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
@@ -208,6 +209,8 @@ import {
208209
resolveTimelineIsAtEnd,
209210
resolveTimelineMinimapHasPersistentGutter,
210211
resolveTimelineMinimapCurrentIndex,
212+
isTimelineMinimapRowVisible,
213+
resolveTimelineMinimapVisibleRange,
211214
resolveTimelineMinimapHeightStyle,
212215
resolveTimelineMinimapHitStripWidth,
213216
resolveTimelineMinimapIndexFromPointer,
@@ -870,6 +873,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
870873
// must not change with them or every timeline row re-renders per event.
871874
const runs = useStableHandoffRuns(runsProp);
872875
const minimapItems = deriveTimelineMinimapItems(rows);
876+
const minimapRowIndices = minimapItems.map((item) => item.rowIndex);
873877
// Preserve initialScrollAtEnd's measured target until the list is reused
874878
// for another thread; scrollToEnd would replace it with an estimated offset.
875879
const listOpenedOnRef = useRef<{
@@ -1126,20 +1130,67 @@ const ConversationTimeline = memo(function ConversationTimeline({
11261130
onContentOverflowChange(measureContentOverflow());
11271131
});
11281132
};
1129-
const handleItemSizeChanged = () => {
1130-
if (disclosurePinsEndRef.current) {
1131-
queueMicrotask(pinDisclosureToEnd);
1132-
scheduleDisclosureSettle();
1133-
}
1134-
reportContentOverflow();
1135-
};
11361133
useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);
11371134
useLayoutEffect(() => {
11381135
cancelContentOverflowFrame();
11391136
onContentOverflowChange?.(measureContentOverflow());
11401137
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.
11411138
}, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);
11421139

1140+
const refreshMinimap = useStableCallback(() => {
1141+
const state = listRef.current?.getState?.();
1142+
if (restoringThreadPosition || state?.data !== rows) return;
1143+
if (!state || minimapItems.length === 0) {
1144+
return;
1145+
}
1146+
1147+
const firstBufferedIndex = state.startBuffered;
1148+
const firstBufferedRow: HTMLElement | undefined =
1149+
firstBufferedIndex == null ? undefined : state.elementAtIndex(firstBufferedIndex);
1150+
const firstBufferedTop =
1151+
firstBufferedIndex == null ? undefined : state.positionAtIndex(firstBufferedIndex);
1152+
const viewport: HTMLElement | undefined = listRef.current?.getScrollableNode();
1153+
// Cached row positions exclude the header and pending scroll adjustments.
1154+
const scroll =
1155+
firstBufferedRow && viewport && firstBufferedTop !== undefined
1156+
? firstBufferedTop +
1157+
viewport.getBoundingClientRect().top -
1158+
firstBufferedRow.getBoundingClientRect().top
1159+
: state.scroll;
1160+
const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll });
1161+
for (const item of minimapItems) {
1162+
const strip = minimapStripMap.get(item.id);
1163+
const inView = isTimelineMinimapRowVisible(
1164+
item.rowIndex,
1165+
visibleRange.start,
1166+
visibleRange.end,
1167+
);
1168+
const next = inView ? "true" : "false";
1169+
// Avoid dirtying style state on every scroll tick for unchanged strips.
1170+
if (strip && strip.dataset.inView !== next) {
1171+
strip.dataset.inView = next;
1172+
}
1173+
}
1174+
const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({
1175+
visibleStart: visibleRange.start,
1176+
visibleEnd: visibleRange.end,
1177+
rowIndices: minimapRowIndices,
1178+
});
1179+
setMinimapCurrentIndex((current) =>
1180+
current === nextCurrentIndex ? current : nextCurrentIndex,
1181+
);
1182+
});
1183+
1184+
const minimapRefreshFrameRef = useRef<number | null>(null);
1185+
const scheduleMinimapRefresh = () => {
1186+
if (minimapRefreshFrameRef.current !== null) return;
1187+
// LegendList recycles row containers before React commits their positions.
1188+
minimapRefreshFrameRef.current = requestAnimationFrame(() => {
1189+
minimapRefreshFrameRef.current = null;
1190+
refreshMinimap();
1191+
});
1192+
};
1193+
11431194
const handleScroll = () => {
11441195
const state = listRef.current?.getState?.();
11451196
if (restoringThreadPosition || state?.data !== rows) return;
@@ -1172,45 +1223,28 @@ const ConversationTimeline = memo(function ConversationTimeline({
11721223
onIsAtEndChange(isAtEnd);
11731224
}
11741225
reportContentOverflow();
1175-
if (!state || minimapItems.length === 0) {
1176-
return;
1177-
}
1178-
1179-
const scrollTop = state.scroll ?? 0;
1180-
const scrollBottom = scrollTop + (state.scrollLength ?? 0);
1181-
1182-
const itemBounds = minimapItems.map((item) => ({
1183-
top: resolveTimelineRowTop(state, item.rowIndex),
1184-
height: resolveTimelineRowHeight(state, item.rowIndex),
1185-
}));
1226+
scheduleMinimapRefresh();
1227+
};
11861228

1187-
for (const [index, item] of minimapItems.entries()) {
1188-
const strip = minimapStripMap.get(item.id);
1189-
const bounds = itemBounds[index];
1190-
const rowTop = bounds?.top ?? null;
1191-
const rowHeight = bounds?.height ?? null;
1192-
const inView =
1193-
rowTop !== null &&
1194-
rowTop < scrollBottom &&
1195-
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
1196-
1197-
// Skip no-op attribute writes: this runs for every strip on every scroll
1198-
// tick, and rewriting an unchanged attribute still dirties style state.
1199-
const next = inView ? "true" : "false";
1200-
if (strip && strip.dataset.inView !== next) {
1201-
strip.dataset.inView = next;
1202-
}
1229+
const handleItemSizeChanged = () => {
1230+
if (disclosurePinsEndRef.current) {
1231+
queueMicrotask(pinDisclosureToEnd);
1232+
scheduleDisclosureSettle();
12031233
}
1204-
const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({
1205-
scrollTop,
1206-
scrollBottom,
1207-
itemBounds,
1208-
});
1209-
setMinimapCurrentIndex((current) =>
1210-
current === nextCurrentIndex ? current : nextCurrentIndex,
1211-
);
1234+
reportContentOverflow();
1235+
scheduleMinimapRefresh();
12121236
};
12131237

1238+
useEffect(
1239+
() => () => {
1240+
if (minimapRefreshFrameRef.current !== null) {
1241+
cancelAnimationFrame(minimapRefreshFrameRef.current);
1242+
minimapRefreshFrameRef.current = null;
1243+
}
1244+
},
1245+
[],
1246+
);
1247+
12141248
useEffect(() => {
12151249
const frame = requestAnimationFrame(handleScroll);
12161250
return () => cancelAnimationFrame(frame);
@@ -1613,24 +1647,6 @@ function getItemType(item: MessagesTimelineRow) {
16131647
return `message:${item.message.role}:${lengthBucket}`;
16141648
}
16151649

1616-
interface TimelinePositionState {
1617-
readonly contentLength?: number;
1618-
readonly scroll?: number;
1619-
readonly scrollLength?: number;
1620-
readonly positionAtIndex?: (index: number) => number | undefined;
1621-
readonly sizeAtIndex?: (index: number) => number | undefined;
1622-
}
1623-
1624-
function resolveTimelineRowTop(state: TimelinePositionState, rowIndex: number) {
1625-
const top = state.positionAtIndex?.(rowIndex);
1626-
return typeof top === "number" && Number.isFinite(top) ? top : null;
1627-
}
1628-
1629-
function resolveTimelineRowHeight(state: TimelinePositionState, rowIndex: number) {
1630-
const height = state.sizeAtIndex?.(rowIndex);
1631-
return typeof height === "number" && Number.isFinite(height) ? height : null;
1632-
}
1633-
16341650
function timelineMinimapEventTargetsPreview(target: EventTarget): boolean {
16351651
return target instanceof Element && target.closest("[data-minimap-preview]") !== null;
16361652
}

0 commit comments

Comments
 (0)