Restore chat scroll anchoring and minimap navigation

- Keep the timeline following the live edge until manual navigation
- Re-anchor new turns and reveal their streamed content reliably
- Update minimap behavior and add anchoring coverage
This commit is contained in:
Julius Marminge committed 2026-06-29 12:16:19 -07:00
1 parent d8c3bc0506
commit 7f42657387
5 files changed
+551 -97

No files matched your search

+206 -26
View File
@@ -85,6 +85,7 @@ import {
isLatestTurnSettled,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
import {
buildPendingUserInputAnswers,
derivePendingUserInputProgress,
@@ -2013,7 +2014,6 @@ function ChatViewContent(props: ChatViewProps) {
: // Spread only fires for the few messages that actually changed;
// unchanged ones early-return their original reference.
// In-place mutation would break React's immutable state contract.
// oxlint-disable-next-line no-map-spread
messages.map((message) => {
if (
message.role !== "user" ||
@@ -3155,24 +3155,100 @@ function ChatViewContent(props: ChatViewProps) {
const showScrollDebouncer = useRef(
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
);
// Scrolling is explicit so streamed timeline updates never take control away
// from the user after the newly sent row has been positioned once.
const scrollToEnd = useCallback((animated = false) => {
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
const activeTimelineAnchorIndexRef = useRef<number | null>(null);
const anchorUserScrollGenerationRef = useRef(0);
const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
const pendingAnchorScrollRestoreRef = useRef<{
readonly messageId: MessageId;
readonly offset: number;
readonly userScrollGeneration: number;
} | null>(null);
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {
anchorUserScrollGenerationRef.current += 1;
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
pendingAnchorScrollRestoreRef.current = null;
if (anchorScrollRestoreFrameRef.current !== null) {
cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
anchorScrollRestoreFrameRef.current = null;
}
}, []);
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
cancelTimelineLiveFollowForUserNavigation,
);
useEffect(() => {
cancelTimelineLiveFollowForUserNavigationRef.current =
cancelTimelineLiveFollowForUserNavigation;
}, [cancelTimelineLiveFollowForUserNavigation]);
const getActiveTimelineTurnMetrics = useCallback(
(list?: LegendListRef | null) => {
const resolvedList = list ?? legendListRef.current;
const anchorIndex = activeTimelineAnchorIndexRef.current;
const state = resolvedList?.getState();
if (!resolvedList || !state || anchorIndex === null) {
return null;
}
return getAnchoredTurnMetrics({
state,
anchorIndex,
composerOverlayHeight,
anchorOffset: CHAT_LIST_ANCHOR_OFFSET,
});
},
[composerOverlayHeight],
);
const timelineRealContentOverflowsViewport = useCallback(
(list?: LegendListRef | null) => {
const resolvedList = list ?? legendListRef.current;
const state = resolvedList?.getState();
if (!resolvedList || !state || state.data.length === 0) {
return false;
}
const lastRowIndex = state.data.length - 1;
const lastRowTop = state.positionAtIndex(lastRowIndex);
const lastRowHeight = state.sizeAtIndex(lastRowIndex);
if (
typeof lastRowTop !== "number" ||
typeof lastRowHeight !== "number" ||
!Number.isFinite(lastRowTop) ||
!Number.isFinite(lastRowHeight)
) {
return false;
}
const realContentBottom = lastRowTop + Math.max(1, lastRowHeight);
const visibleScrollLength = Math.max(
0,
(state.scrollLength ?? 0) - composerOverlayHeight - CHAT_LIST_ANCHOR_OFFSET,
);
return realContentBottom > visibleScrollLength;
},
[composerOverlayHeight],
);
// Live-follow stays active after send/thread-open until an actual list scroll
// gesture opts out.
const scrollToEnd = useCallback((animated = false) => {
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
useEffect(() => {
let removeListeners: (() => void) | null = null;
const frame = requestAnimationFrame(() => {
@@ -3180,21 +3256,22 @@ function ChatViewContent(props: ChatViewProps) {
if (!scrollNode) {
return;
}
const markUserScrollIntent = () => {
anchorUserScrollGenerationRef.current += 1;
pendingAnchorScrollRestoreRef.current = null;
if (anchorScrollRestoreFrameRef.current !== null) {
cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
anchorScrollRestoreFrameRef.current = null;
}
const handleManualNavigation = () => {
cancelTimelineLiveFollowForUserNavigationRef.current();
};
scrollNode.addEventListener("wheel", markUserScrollIntent, { passive: true });
scrollNode.addEventListener("touchmove", markUserScrollIntent, { passive: true });
scrollNode.addEventListener("pointerdown", markUserScrollIntent, { passive: true });
scrollNode.addEventListener("wheel", handleManualNavigation, {
passive: true,
});
scrollNode.addEventListener("touchmove", handleManualNavigation, {
passive: true,
});
scrollNode.addEventListener("pointerdown", handleManualNavigation, {
passive: true,
});
removeListeners = () => {
scrollNode.removeEventListener("wheel", markUserScrollIntent);
scrollNode.removeEventListener("touchmove", markUserScrollIntent);
scrollNode.removeEventListener("pointerdown", markUserScrollIntent);
scrollNode.removeEventListener("wheel", handleManualNavigation);
scrollNode.removeEventListener("touchmove", handleManualNavigation);
scrollNode.removeEventListener("pointerdown", handleManualNavigation);
};
});
@@ -3205,18 +3282,25 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThread?.id]);
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
if (pendingTimelineAnchorRef.current === messageId) {
pendingTimelineAnchorRef.current = null;
}
activeTimelineAnchorIndexRef.current = anchorIndex;
if (positionedTimelineAnchorRef.current === messageId) {
return;
}
positionedTimelineAnchorRef.current = messageId;
settledTimelineAnchorRef.current = null;
requestAnimationFrame(() => {
const positionAnchor = (remainingAttempts: number) => {
requestAnimationFrame(() => {
if (positionedTimelineAnchorRef.current !== messageId) {
return;
}
const list = legendListRef.current;
if (!list) {
if (remainingAttempts > 0) {
positionAnchor(remainingAttempts - 1);
}
return;
}
const scrollNode = list.getScrollableNode();
@@ -3244,12 +3328,16 @@ function ChatViewContent(props: ChatViewProps) {
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
});
});
});
};
requestAnimationFrame(() => positionAnchor(12));
}, []);
const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
if (settledTimelineAnchorRef.current !== messageId) {
return;
}
if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
return;
}
const scrollOffset = legendListRef.current?.getState().scroll;
if (scrollOffset === undefined) {
return;
@@ -3286,19 +3374,103 @@ function ChatViewContent(props: ChatViewProps) {
}, []);
const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
if (
!isAtEnd &&
liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
) {
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
return;
}
if (isAtEndRef.current === isAtEnd) return;
isAtEndRef.current = isAtEnd;
if (isAtEnd) {
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
} else {
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
showScrollDebouncer.current.maybeExecute();
}
}, []);
useEffect(() => {
if (!activeThread?.id) {
return;
}
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
return;
}
let secondFrame: number | null = null;
const frame = requestAnimationFrame(() => {
secondFrame = requestAnimationFrame(() => {
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
return;
}
if (pendingTimelineAnchorRef.current !== null) {
return;
}
if (
positionedTimelineAnchorRef.current !== null &&
settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current
) {
return;
}
const list = legendListRef.current;
if (!list) {
return;
}
if (timelineScrollModeRef.current === "anchoring-new-turn") {
const metrics = getActiveTimelineTurnMetrics(list);
if (!metrics) {
return;
}
if (metrics.scrollDeltaToRevealEnd <= 1) {
return;
}
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
void list.scrollToOffset({ offset: nextOffset, animated: false });
return;
}
if (timelineScrollModeRef.current !== "following-end") {
return;
}
if (!timelineRealContentOverflowsViewport(list)) {
return;
}
void list.scrollToEnd?.({ animated: false });
});
});
return () => {
cancelAnimationFrame(frame);
if (secondFrame !== null) {
cancelAnimationFrame(secondFrame);
}
};
}, [
activeThread?.id,
timelineEntries,
getActiveTimelineTurnMetrics,
timelineRealContentOverflowsViewport,
]);
useEffect(() => {
setPullRequestDialogState(null);
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
if (planSidebarOpenOnNextThreadRef.current) {
@@ -3309,7 +3481,6 @@ function ChatViewContent(props: ChatViewProps) {
}
planSidebarDismissedForTurnRef.current = null;
// activeThreadRef resets transitively with the active thread.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeThread?.id]);
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
@@ -3859,6 +4030,10 @@ function ChatViewContent(props: ChatViewProps) {
// anchored end-space target so it lands near the top while the response
// streams into the reserved space below it.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
@@ -4292,6 +4467,10 @@ function ChatViewContent(props: ChatViewProps) {
// Position this sent row once LegendList has measured the anchored tail.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
@@ -4921,6 +5100,7 @@ function ChatViewContent(props: ChatViewProps) {
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
/>
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
@@ -22,7 +22,16 @@ vi.mock("@legendapp/list/react", async () => {
};
contentInsetEndAdjustment?: number;
className?: string;
maintainScrollAtEnd?: boolean;
maintainScrollAtEnd?:
| boolean
| {
animated?: boolean;
on?: {
dataChange?: boolean;
itemLayout?: boolean;
layout?: boolean;
};
};
maintainVisibleContentPosition?:
| boolean
| {
@@ -45,7 +54,27 @@ vi.mock("@legendapp/list/react", async () => {
data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
data-content-inset-end={props.contentInsetEndAdjustment}
data-class-name={props.className}
data-maintain-scroll-at-end={props.maintainScrollAtEnd}
data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
data-maintain-scroll-at-end-animated={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.animated
: undefined
}
data-maintain-scroll-at-end-data-change={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.dataChange
: undefined
}
data-maintain-scroll-at-end-item-layout={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.itemLayout
: undefined
}
data-maintain-scroll-at-end-layout={
typeof props.maintainScrollAtEnd === "object"
? props.maintainScrollAtEnd.on?.layout
: undefined
}
data-maintain-visible-content-position={
typeof props.maintainVisibleContentPosition === "object"
? "object"
@@ -162,6 +191,7 @@ function buildProps() {
onAnchorSizeChanged: () => {},
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
onManualNavigation: () => {},
};
}
@@ -266,7 +296,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("data-anchor-max-size=");
expect(markup).toContain('data-content-inset-end="144"');
expect(markup).toContain("[overflow-anchor:none]");
expect(markup).not.toContain("data-maintain-scroll-at-end=");
expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-visible-content-position="object"');
expect(markup).toContain('data-maintain-visible-content-position-data="true"');
expect(markup).toContain('data-maintain-visible-content-position-size="false"');
@@ -285,6 +315,11 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Show full message");
expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
@@ -178,6 +178,7 @@ interface MessagesTimelineProps {
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
}
// ---------------------------------------------------------------------------
@@ -210,6 +211,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onAnchorSizeChanged,
contentInsetEndAdjustment,
onIsAtEndChange,
onManualNavigation,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -479,6 +481,18 @@ export const MessagesTimeline = memo(function MessagesTimeline({
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainScrollAtEnd={
anchoredEndSpace
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition={{
data: true,
size: false,
@@ -494,6 +508,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
hasPersistentGutter={minimapHasPersistentGutter}
stripMap={minimapStripMap}
onSelect={(item) => {
onManualNavigation();
void listRef.current?.scrollToIndex({
index: item.rowIndex,
animated: true,
@@ -616,20 +631,27 @@ function TimelineMinimap({
? "-100%"
: "-50%";
const updateActiveIndexFromPointer = useCallback(
const resolveActiveIndexFromPointer = useCallback(
(event: MouseEvent<HTMLElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
const nextIndex = resolveTimelineMinimapIndexFromPointer({
return resolveTimelineMinimapIndexFromPointer({
itemCount: items.length,
railTop: rect.top,
railHeight: rect.height,
pointerY: event.clientY,
});
setActiveIndex(nextIndex);
},
[items.length],
);
const updateActiveIndexFromPointer = useCallback(
(event: MouseEvent<HTMLElement>) => {
const nextIndex = resolveActiveIndexFromPointer(event);
setActiveIndex(nextIndex);
},
[resolveActiveIndexFromPointer],
);
const moveActiveIndex = useCallback(
(delta: number) => {
setActiveIndex((current) => {
@@ -649,58 +671,25 @@ function TimelineMinimap({
return (
<div
className={cn(
"group/minimap pointer-events-auto absolute left-0 z-40 hidden w-18 -translate-y-1/2 py-3 md:block",
"group/minimap pointer-events-auto absolute top-0 left-0 z-40 hidden w-18 md:block",
hasPersistentGutter
? "opacity-100"
: "opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
)}
data-testid="timeline-minimap"
data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
style={{ top: `calc((100% - ${safeBottomInset}px) / 2)` }}
style={{ bottom: safeBottomInset }}
>
<div
className="relative ml-3 w-10 select-none"
style={{ height: resolveTimelineMinimapHeightStyle(items.length) }}
>
<div className="absolute top-0 left-3 h-full w-px bg-border/15" />
{items.map((item, index) => {
const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`;
const activeDistance =
resolvedActiveIndex === null ? null : Math.abs(index - resolvedActiveIndex);
return (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-0 h-0.5 -translate-y-1/2 rounded-full bg-muted-foreground/35 transition-[background-color,width] duration-150 data-[in-view=true]:bg-foreground/90",
activeDistance === 0
? "w-6 bg-muted-foreground/75"
: activeDistance === 1
? "w-4"
: activeDistance === 2
? "w-2.5"
: "w-2",
)}
data-in-view="false"
data-minimap-strip
key={item.id}
ref={(node) => {
if (node) {
stripMap.set(item.id, node);
} else {
stripMap.delete(item.id);
}
}}
style={{ top }}
/>
);
})}
<div className="relative h-full w-full select-none">
<button
aria-label={`Jump to message: ${activeItem?.userText ?? "User message"}`}
className="pointer-events-auto absolute top-0 left-0 h-full w-10 cursor-pointer bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
className="pointer-events-auto absolute top-1/2 left-3 w-10 -translate-y-1/2 cursor-pointer bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
onBlur={() => setActiveIndex(null)}
onClick={() => {
if (activeItem) {
onSelect(activeItem);
onClick={(event) => {
const nextIndex = resolveActiveIndexFromPointer(event);
const nextItem = nextIndex === null ? null : (items[nextIndex] ?? null);
if (nextItem) {
onSelect(nextItem);
}
}}
onFocus={() => setActiveIndex((current) => current ?? 0)}
@@ -726,33 +715,67 @@ function TimelineMinimap({
}}
onMouseLeave={() => setActiveIndex(null)}
onMouseMove={updateActiveIndexFromPointer}
style={{ height: resolveTimelineMinimapHeightStyle(items.length) }}
type="button"
/>
{activeItem ? (
<span
className="pointer-events-none absolute left-8 w-80 rounded-xl border border-border/70 bg-popover/95 p-3 text-left text-popover-foreground shadow-xl shadow-black/25 backdrop-blur"
style={{
top: `${activeTopPercent}%`,
transform: `translateY(${activeTooltipTranslate})`,
}}
>
<span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
{activeItem.userText ?? "User message"}
</span>
{activeItem.assistantText ? (
>
<div className="absolute top-0 left-3 h-full w-px bg-border/15" />
{items.map((item, index) => {
const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`;
const activeDistance =
resolvedActiveIndex === null ? null : Math.abs(index - resolvedActiveIndex);
return (
<span
className="mt-1 max-h-[3.75rem] overflow-hidden text-muted-foreground text-sm leading-5"
style={{
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 3,
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-0 h-0.5 -translate-y-1/2 rounded-full bg-muted-foreground/35 transition-[background-color,width] duration-150 data-[in-view=true]:bg-foreground/90",
activeDistance === 0
? "w-6 bg-muted-foreground/75"
: activeDistance === 1
? "w-4"
: activeDistance === 2
? "w-2.5"
: "w-2",
)}
data-in-view="false"
data-minimap-strip
key={item.id}
ref={(node) => {
if (node) {
stripMap.set(item.id, node);
} else {
stripMap.delete(item.id);
}
}}
>
{activeItem.assistantText}
style={{ top }}
/>
);
})}
{activeItem ? (
<span
className="pointer-events-none absolute left-8 w-80 rounded-xl border border-border/70 bg-popover/95 p-3 text-left text-popover-foreground shadow-xl shadow-black/25 backdrop-blur"
style={{
top: `${activeTopPercent}%`,
transform: `translateY(${activeTooltipTranslate})`,
}}
>
<span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
{activeItem.userText ?? "User message"}
</span>
) : null}
</span>
) : null}
{activeItem.assistantText ? (
<span
className="mt-1 max-h-[3.75rem] overflow-hidden text-muted-foreground text-sm leading-5"
style={{
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 3,
}}
>
{activeItem.assistantText}
</span>
) : null}
</span>
) : null}
</button>
</div>
</div>
);
@@ -0,0 +1,138 @@
import { describe, expect, it } from "vite-plus/test";
import { getAnchoredTurnMetrics, getRowBottom } from "./timelineScrollAnchoring";
function buildState({
positions,
sizes,
scroll = 0,
scrollLength = 700,
}: {
readonly positions: readonly number[];
readonly sizes: readonly number[];
readonly scroll?: number;
readonly scrollLength?: number;
}) {
return {
data: positions.map((_, index) => index),
scroll,
scrollLength,
positionAtIndex: (index: number) => positions[index],
sizeAtIndex: (index: number) => sizes[index],
};
}
describe("timeline scroll anchoring", () => {
it("measures row bottoms from LegendList row position and size", () => {
const state = buildState({
positions: [0, 120],
sizes: [80, 40],
});
expect(getRowBottom(state, 1)).toBe(160);
});
it("treats the active turn as fitting when it fits above the composer", () => {
const state = buildState({
positions: [0, 300, 460],
sizes: [240, 80, 140],
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.turnHeight).toBe(300);
expect(metrics?.usableViewportHeight).toBe(564);
expect(metrics?.overflowsUsableViewport).toBe(false);
expect(metrics?.targetScrollToRevealEnd).toBe(36);
expect(metrics?.scrollDeltaToRevealEnd).toBe(36);
});
it("targets the real row end instead of any temporary reserved tail", () => {
const state = buildState({
positions: [0, 1720, 1880],
sizes: [1600, 80, 120],
scroll: 1900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.lastBottom).toBe(2000);
expect(metrics?.targetScrollToRevealEnd).toBe(1436);
expect(metrics?.scrollDeltaToRevealEnd).toBe(0);
});
it("reports overflow only for the current anchored turn", () => {
const state = buildState({
positions: [0, 900, 1180],
sizes: [800, 220, 300],
scroll: 900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.turnHeight).toBe(580);
expect(metrics?.usableViewportHeight).toBe(564);
expect(metrics?.overflowsUsableViewport).toBe(true);
});
it("returns the minimal positive scroll delta needed to reveal the turn end", () => {
const state = buildState({
positions: [0, 900, 1180],
sizes: [800, 220, 360],
scroll: 900,
scrollLength: 760,
});
const metrics = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 180,
anchorOffset: 16,
});
expect(metrics?.lastBottom).toBe(1540);
expect(metrics?.visibleUsableBottom).toBe(1464);
expect(metrics?.scrollDeltaToRevealEnd).toBe(76);
});
it("subtracts composer height from usable viewport height", () => {
const state = buildState({
positions: [0, 300],
sizes: [120, 470],
scrollLength: 700,
});
const withoutComposer = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 0,
anchorOffset: 16,
});
const withComposer = getAnchoredTurnMetrics({
state,
anchorIndex: 1,
composerOverlayHeight: 220,
anchorOffset: 16,
});
expect(withoutComposer?.overflowsUsableViewport).toBe(false);
expect(withComposer?.overflowsUsableViewport).toBe(true);
});
});
@@ -0,0 +1,78 @@
export type TimelineScrollMode = "following-end" | "anchoring-new-turn" | "free-scrolling";
export interface TimelineListMeasurementState {
readonly data: readonly unknown[];
readonly scroll: number;
readonly scrollLength: number;
readonly positionAtIndex: (index: number) => number | undefined;
readonly sizeAtIndex: (index: number) => number | undefined;
}
export interface AnchoredTurnMetrics {
readonly anchorTop: number;
readonly lastBottom: number;
readonly turnHeight: number;
readonly usableViewportHeight: number;
readonly visibleUsableBottom: number;
readonly overflowsUsableViewport: boolean;
readonly targetScrollToRevealEnd: number;
readonly scrollDeltaToRevealEnd: number;
}
export function getRowBottom(state: TimelineListMeasurementState, index: number): number | null {
const top = state.positionAtIndex(index);
const height = state.sizeAtIndex(index);
if (
typeof top !== "number" ||
typeof height !== "number" ||
!Number.isFinite(top) ||
!Number.isFinite(height)
) {
return null;
}
return top + Math.max(1, height);
}
export function getAnchoredTurnMetrics({
state,
anchorIndex,
composerOverlayHeight,
anchorOffset,
}: {
readonly state: TimelineListMeasurementState;
readonly anchorIndex: number;
readonly composerOverlayHeight: number;
readonly anchorOffset: number;
}): AnchoredTurnMetrics | null {
if (state.data.length === 0) {
return null;
}
const boundedAnchorIndex = Math.max(0, Math.min(anchorIndex, state.data.length - 1));
const anchorTop = state.positionAtIndex(boundedAnchorIndex);
const lastBottom = getRowBottom(state, state.data.length - 1);
if (typeof anchorTop !== "number" || !Number.isFinite(anchorTop) || lastBottom === null) {
return null;
}
const usableViewportHeight = Math.max(
0,
state.scrollLength - composerOverlayHeight - anchorOffset,
);
const turnHeight = Math.max(0, lastBottom - anchorTop);
const visibleUsableBottom = state.scroll + usableViewportHeight;
const targetScrollToRevealEnd = Math.max(0, lastBottom - usableViewportHeight);
const scrollDeltaToRevealEnd = Math.max(0, targetScrollToRevealEnd - state.scroll);
return {
anchorTop,
lastBottom,
turnHeight,
usableViewportHeight,
visibleUsableBottom,
overflowsUsableViewport: turnHeight > usableViewportHeight,
targetScrollToRevealEnd,
scrollDeltaToRevealEnd,
};
}