diff --git a/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx b/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx index d961a0981af..4b39b7538bd 100644 --- a/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx +++ b/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx @@ -41,7 +41,6 @@ vi.mock("@/components/ui/bottom-anchored-scroll-body.js", () => ({ isAtBottom: false, scrollToBottom: mocks.scrollToBottom, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: vi.fn(), }), diff --git a/apps/app/src/components/promptbox/composer-contract.test.tsx b/apps/app/src/components/promptbox/composer-contract.test.tsx index 8b896ceed20..5b4647e4cdc 100644 --- a/apps/app/src/components/promptbox/composer-contract.test.tsx +++ b/apps/app/src/components/promptbox/composer-contract.test.tsx @@ -73,7 +73,6 @@ vi.mock("@/components/ui/bottom-anchored-scroll-body.js", () => ({ isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }), diff --git a/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx b/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx index fe7e942d53f..4e0edecc248 100644 --- a/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx +++ b/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx @@ -472,7 +472,6 @@ describe("ThreadPendingInteractionBanner collapsed strip", () => { isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }} diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 6d7fface156..0c07780787b 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -111,6 +111,7 @@ import { TimelineScrollRestoreContext, useBottomAnchoredScroll, } from "@/components/ui/bottom-anchored-scroll-body.js"; +import type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper.js"; import { collectSearchedMessageAncestorRowIds, SearchMessageLocationProvider, @@ -242,10 +243,6 @@ interface TimelineRowsListProps { unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } -interface TimelineUnreadDividerProps { - autoScroll: boolean; -} - interface TimelineRowViewProps { activeLatestBundleId: string | null; compactActivityIntents: boolean; @@ -288,7 +285,15 @@ interface BuildTimelineRowsListItemsArgs { unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } -interface FindUnreadDividerIndexArgs { +interface UseLandOnUnreadDividerArgs { + items: readonly TimelineRowsListItem[]; + positionKeeper: ScrollPositionKeeper | null; + unreadDividerAutoScroll: boolean; + unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; +} + +interface UseLoadedUnreadDividerPlacementArgs { + hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } @@ -1045,34 +1050,9 @@ const ConversationRowContent = memo(function ConversationRowContent({ ); }); -function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { - const bottomAnchor = useBottomAnchoredScroll(); - const dividerRef = useRef(null); - const hasScrolledRef = useRef(false); - - useLayoutEffect(() => { - if (!autoScroll || !bottomAnchor || hasScrolledRef.current) { - return; - } - - const frameId = window.requestAnimationFrame(() => { - const divider = dividerRef.current; - if (!divider) { - return; - } - - hasScrolledRef.current = true; - bottomAnchor.scrollElementIntoViewClampedToMaxScroll({ - element: divider, - }); - }); - - return () => window.cancelAnimationFrame(frameId); - }, [autoScroll, bottomAnchor]); - +function TimelineUnreadDivider() { return (
(null); + const firstRow = rows[0]; + const isUnplaceable = + unreadDividerPlacement !== null && + (unreadDividerPlacement === unplaceablePlacement || + (hasOlderRows && + firstRow !== undefined && + firstRow.startedAt > unreadDividerPlacement.cutoffAt)); + if (isUnplaceable && unreadDividerPlacement !== unplaceablePlacement) { + setUnplaceablePlacement(unreadDividerPlacement); + } + return isUnplaceable ? null : unreadDividerPlacement; +} + +function useLandOnUnreadDivider({ + items, + positionKeeper, + unreadDividerAutoScroll, + unreadDividerPlacement, +}: UseLandOnUnreadDividerArgs): void { + const landedPlacementRef = + useRef(null); + const divider = items.find((item) => item.kind === "unread-divider"); + const dividerId = divider?.id ?? null; + + useLayoutEffect(() => { + if ( + !unreadDividerAutoScroll || + unreadDividerPlacement === null || + dividerId === null || + positionKeeper === null || + landedPlacementRef.current === unreadDividerPlacement + ) { + return; + } + landedPlacementRef.current = unreadDividerPlacement; + if (positionKeeper.hasUserScrolled()) return; + positionKeeper.restore({ + rowId: dividerId, + offsetWithinRow: 0, + atBottom: false, + }); + }, [ + dividerId, + positionKeeper, + unreadDividerAutoScroll, + unreadDividerPlacement, + ]); +} + function findUnreadDividerIndex({ rows, unreadDividerPlacement, -}: FindUnreadDividerIndexArgs): number { +}: BuildTimelineRowsListItemsArgs): number { if (unreadDividerPlacement === null) { return -1; } - switch (unreadDividerPlacement.kind) { - case "before-first": - return rows.length > 0 ? 0 : -1; - case "after-cutoff": - return rows.findIndex((row) => - isUnreadDividerCandidateAfterCutoff({ - cutoffAt: unreadDividerPlacement.cutoffAt, - row, - }), - ); - default: - assertNever(unreadDividerPlacement); - } + return rows.findIndex((row) => + isUnreadDividerCandidateAfterCutoff({ + cutoffAt: unreadDividerPlacement.cutoffAt, + row, + }), + ); } function isUserAuthoredConversationRow(row: ThreadTimelineViewRow): boolean { @@ -2054,10 +2083,25 @@ function TimelineRowsList({ () => findActiveLatestBundleId(rows), [rows], ); + const loadedUnreadDividerPlacement = useLoadedUnreadDividerPlacement({ + hasOlderRows: hasOlderTimelineRows ?? false, + rows, + unreadDividerPlacement, + }); const items = useMemo( - () => buildTimelineRowsListItems({ rows, unreadDividerPlacement }), - [rows, unreadDividerPlacement], + () => + buildTimelineRowsListItems({ + rows, + unreadDividerPlacement: loadedUnreadDividerPlacement, + }), + [rows, loadedUnreadDividerPlacement], ); + useLandOnUnreadDivider({ + items, + positionKeeper: bottomAnchor?.positionKeeper ?? null, + unreadDividerAutoScroll, + unreadDividerPlacement: loadedUnreadDividerPlacement, + }); const itemKeys = useMemo( () => items.map((item) => @@ -2141,11 +2185,10 @@ function TimelineRowsList({
- +
); } diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts index e85f5593b4b..1e23fb51e6d 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts @@ -1,3 +1,6 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; import { buildTimelineViewRows } from "@bb/thread-view"; import { describe, expect, it } from "vitest"; import type { TimelineRow } from "@bb/server-contract"; @@ -7,7 +10,10 @@ import { turnRow, } from "@/test/fixtures/thread-timeline-rows"; import type { ThreadTimelineUnreadDividerPlacement } from "./types"; -import { buildTimelineRowsListItems } from "./ThreadTimelineRows"; +import { + buildTimelineRowsListItems, + useLoadedUnreadDividerPlacement, +} from "./ThreadTimelineRows"; const DIVIDER = "__divider__"; @@ -69,7 +75,7 @@ describe("unread divider placement", () => { command(400), assistantMessage(500), ], - { kind: "after-cutoff", cutoffAt: 350 }, + { cutoffAt: 350 }, ); expect(sequence).toEqual(["user", "step-summary", DIVIDER, "assistant"]); @@ -84,7 +90,7 @@ describe("unread divider placement", () => { command(500), assistantMessage(600), ], - { kind: "after-cutoff", cutoffAt: 300 }, + { cutoffAt: 300 }, ); expect(sequence).toEqual([ @@ -111,7 +117,7 @@ describe("unread divider placement", () => { }), assistantMessage(500), ], - { kind: "after-cutoff", cutoffAt: 350 }, + { cutoffAt: 350 }, ); expect(collapsed).toEqual(["user", "turn", DIVIDER, "assistant"]); @@ -120,7 +126,7 @@ describe("unread divider placement", () => { it("never anchors the divider on the reader's own message", () => { const sequence = renderTopLevelSequence( [assistantMessage(100), userMessage(400), command(500)], - { kind: "after-cutoff", cutoffAt: 300 }, + { cutoffAt: 300 }, ); expect(sequence).toEqual(["assistant", "user", DIVIDER, "work"]); @@ -129,18 +135,59 @@ describe("unread divider placement", () => { it("omits the divider when no row started after the cutoff", () => { const sequence = renderTopLevelSequence( [userMessage(100), command(200), assistantMessage(300)], - { kind: "after-cutoff", cutoffAt: 400 }, + { cutoffAt: 400 }, ); expect(sequence).not.toContain(DIVIDER); }); +}); - it("places the divider above the first row for an explicitly unread thread", () => { - const sequence = renderTopLevelSequence( - [userMessage(100), command(200), assistantMessage(300)], - { kind: "before-first" }, +describe("loaded unread divider placement", () => { + it("drops a divider whose cutoff is older than the loaded rows, and keeps it dropped after older rows load", () => { + const placement = { cutoffAt: 350 }; + const latestPage = buildTimelineViewRows([ + command(400), + assistantMessage(500), + ]); + const { result, rerender } = renderHook( + (props: Parameters[0]) => + useLoadedUnreadDividerPlacement(props), + { + initialProps: { + hasOlderRows: true, + rows: latestPage, + unreadDividerPlacement: placement, + }, + }, ); + expect(result.current).toBeNull(); - expect(sequence[0]).toBe(DIVIDER); + rerender({ + hasOlderRows: false, + rows: buildTimelineViewRows([ + userMessage(100), + command(200), + command(400), + assistantMessage(500), + ]), + unreadDividerPlacement: placement, + }); + expect(result.current).toBeNull(); + }); + + it("keeps a divider whose cutoff falls inside the loaded rows", () => { + const placement = { cutoffAt: 350 }; + const { result } = renderHook(() => + useLoadedUnreadDividerPlacement({ + hasOlderRows: true, + rows: buildTimelineViewRows([ + userMessage(300), + command(400), + assistantMessage(500), + ]), + unreadDividerPlacement: placement, + }), + ); + expect(result.current).toBe(placement); }); }); diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx index 18f6a24d71f..79c2a8aa58e 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx @@ -185,7 +185,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: count }, (_, index) => @@ -245,7 +244,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: 80 }, (_, index) => { @@ -300,7 +298,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: 80 }, (_, index) => diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx index d31d132356e..fb4ec106e4d 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx @@ -51,7 +51,6 @@ describe("ThreadTimelineSurface load-older control", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const onLoadOlderRows = vi diff --git a/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx b/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx index cdead28f9c6..bbd9772c19a 100644 --- a/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx +++ b/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx @@ -124,7 +124,6 @@ describe("ConversationMessageOverflowToggle", () => { isAtBottom: true, scrollToBottom: vi.fn(), scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition, }; diff --git a/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx b/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx index c3b83ac64f1..d0d1eedd538 100644 --- a/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx +++ b/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx @@ -107,7 +107,6 @@ const conversationRows: TimelineRow[] = [ ]; const afterCutoffPlacement: ThreadTimelineUnreadDividerPlacement = { - kind: "after-cutoff", cutoffAt: T0 + 3 * MINUTE + 30_000, }; diff --git a/apps/app/src/components/thread/timeline/types.ts b/apps/app/src/components/thread/timeline/types.ts index a6cff2ee899..2cc27257b7b 100644 --- a/apps/app/src/components/thread/timeline/types.ts +++ b/apps/app/src/components/thread/timeline/types.ts @@ -63,14 +63,9 @@ export interface ThreadTimelineConsumerMessageAction { run(message: ThreadChatMessageReference): void | Promise; } -export type ThreadTimelineUnreadDividerPlacement = - | { - kind: "after-cutoff"; - cutoffAt: number; - } - | { - kind: "before-first"; - }; +export interface ThreadTimelineUnreadDividerPlacement { + cutoffAt: number; +} export type UserAttachmentImageSrcResolver = ( pathOrUrl: string, diff --git a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx index 5b71065af23..9a38fac47d8 100644 --- a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx +++ b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx @@ -25,7 +25,6 @@ function createBottomAnchor( isAtBottom: false, scrollToBottom: vi.fn(), scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper, holdContentPosition: vi.fn(), }; diff --git a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx index 58cc4d57923..607903105f2 100644 --- a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx +++ b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx @@ -253,7 +253,6 @@ function installAutoLoadEnvironment() { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const emitIntersection = () => { diff --git a/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx b/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx index b6d19719ae3..d2e4880a798 100644 --- a/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx +++ b/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx @@ -329,7 +329,6 @@ beforeEach(() => { isAtBottom: false, scrollToBottom: vi.fn(), scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: vi.fn(), } as unknown as ReturnType); diff --git a/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx b/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx index d0be93e5ef7..1e87488d9eb 100644 --- a/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx +++ b/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx @@ -60,7 +60,6 @@ function scrollBodyContext(scrollElement: HTMLElement) { isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }; diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx index b43dde0df98..72637cc1c06 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx @@ -28,9 +28,6 @@ export interface BottomAnchorContextValue { isAtBottom: boolean; scrollToBottom: () => void; scrollElementIntoView: (args: ScrollElementIntoViewArgs) => void; - scrollElementIntoViewClampedToMaxScroll: ( - args: ScrollElementIntoViewClampedToMaxScrollArgs, - ) => void; holdContentPosition: (args: HoldContentPositionArgs) => void; positionKeeper: ScrollPositionKeeper; } @@ -55,10 +52,6 @@ interface ScrollElementIntoViewArgs { options?: ScrollIntoViewOptions; } -interface ScrollElementIntoViewClampedToMaxScrollArgs { - element: HTMLElement; -} - interface HoldContentPositionArgs { edge: "top" | "bottom"; element: HTMLElement; @@ -164,23 +157,6 @@ export function BottomAnchoredScrollBody({ [positionKeeper], ); - const scrollElementIntoViewClampedToMaxScroll = useCallback( - ({ element }: ScrollElementIntoViewClampedToMaxScrollArgs) => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) { - element.scrollIntoView({ block: "start", inline: "nearest" }); - return; - } - positionKeeper.scrollTo( - element.getBoundingClientRect().top - - scrollArea.getBoundingClientRect().top + - scrollArea.scrollTop, - "instant", - ); - }, - [positionKeeper], - ); - const holdContentPosition = useCallback( ({ edge, element, update }: HoldContentPositionArgs) => { positionKeeper.hold(element, edge); @@ -332,7 +308,6 @@ export function BottomAnchoredScrollBody({ isAtBottom, scrollToBottom, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, holdContentPosition, positionKeeper, }), @@ -341,7 +316,6 @@ export function BottomAnchoredScrollBody({ isAtBottom, scrollToBottom, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, holdContentPosition, positionKeeper, ], diff --git a/apps/app/src/components/ui/scroll-position-keeper.model.test.ts b/apps/app/src/components/ui/scroll-position-keeper.model.test.ts new file mode 100644 index 00000000000..747bc6b618a --- /dev/null +++ b/apps/app/src/components/ui/scroll-position-keeper.model.test.ts @@ -0,0 +1,472 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { installFakeFlowLayout, setFakeHeight } from "@/test/fake-flow-layout"; +import { ScrollPositionKeeper } from "./scroll-position-keeper"; + +const THRESHOLD_PX = 4; +const SEED_COUNT = Number(process.env.KEEPER_MODEL_SEEDS ?? 200); +const STEPS_PER_SEED = 40; +const SETTLE_MS = 3_600; + +interface Row { + id: string; + height: number; +} + +type StepKind = "reader" | "layout" | "navigation"; + +interface Step { + kind: StepKind; + label: string; + heldRowId?: string; + run: () => void; +} + +function createRandom(seed: number) { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296; + }; + return { + next, + int: (min: number, max: number) => + min + Math.floor(next() * (max - min + 1)), + pick: (items: readonly T[]): T => { + const item = items[Math.floor(next() * items.length)]; + if (item === undefined) throw new Error("pick from empty list"); + return item; + }, + }; +} + +let restoreLayout: (() => void) | null = null; + +afterEach(() => { + restoreLayout?.(); + restoreLayout = null; + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +function runSeed(seed: number): string[] { + const random = createRandom(seed); + const deferWrites = random.next() < 0.5; + let nextId = 0; + const newRow = (): Row => ({ + id: `r${nextId++}`, + height: random.int(20, 420), + }); + let rows: Row[] = Array.from({ length: random.int(1, 30) }, newRow); + const initiallyAttached = random.next() < 0.7; + + const scrollElement = document.createElement("div"); + const content = document.createElement("div"); + const items = document.createElement("div"); + items.setAttribute("data-timeline-items", ""); + content.append(items); + scrollElement.append(content); + document.body.append(scrollElement); + let viewportHeight = random.int(300, 900); + const layout = installFakeFlowLayout({ scrollElement, viewportHeight }); + const elements = new Map(); + const render = () => { + items.replaceChildren( + ...rows.map((row) => { + const element = elements.get(row.id) ?? document.createElement("div"); + elements.set(row.id, element); + element.setAttribute("data-timeline-row-id", row.id); + setFakeHeight(element, row.height); + return element; + }), + ); + }; + render(); + const keeper = new ScrollPositionKeeper({ + bottomThresholdPx: THRESHOLD_PX, + deferWritesWhileScrolling: deferWrites, + getContentElement: () => content, + getFooterElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => + items.querySelectorAll(":scope > [data-timeline-row-id]"), + initiallyAttached, + }); + const disconnect = keeper.connect(scrollElement); + restoreLayout = () => { + disconnect(); + layout.restore(); + }; + + const history: string[] = [ + `seed ${seed} ${initiallyAttached ? "timeline" : "detail box"} deferWrites=${deferWrites}`, + ]; + const fromEnd = () => layout.maxScrollTop() - layout.scrollTop; + const topOf = (id: string) => + elements.get(id)?.isConnected === true + ? elements.get(id)!.getBoundingClientRect().top + : null; + + const browserLayout = () => { + const clamped = layout.scrollTop > layout.maxScrollTop(); + if (clamped) layout.bounceTo(layout.maxScrollTop()); + const fireScroll = () => { + if (clamped) scrollElement.dispatchEvent(new Event("scroll")); + }; + if (random.next() < 0.5) { + fireScroll(); + layout.flushResizeObservers(); + } else { + layout.flushResizeObservers(); + fireScroll(); + } + }; + const changeRows = (next: Row[]) => { + rows = next; + render(); + browserLayout(); + }; + const randomIndex = () => random.int(0, Math.max(0, rows.length - 1)); + + const steps: Array<{ weight: number; make: () => Step }> = [ + { + weight: 6, + make: () => { + const toEnd = random.next() < 0.2; + const delta = random.int(-900, 900); + return { + kind: "reader", + label: toEnd ? "wheel to end" : `wheel ${delta}`, + run: () => + layout.userScrollTo( + toEnd ? layout.maxScrollTop() : layout.scrollTop + delta, + ), + }; + }, + }, + { + weight: 4, + make: () => { + const delta = random.int(-700, 700); + return { + kind: "reader", + label: `touch drag ${delta}`, + run: () => { + scrollElement.dispatchEvent(new TouchEvent("touchstart")); + layout.layoutScrollTo(layout.scrollTop + delta); + scrollElement.dispatchEvent(new TouchEvent("touchend")); + }, + }; + }, + }, + { + weight: 4, + make: () => { + const visible = rows.filter((row) => { + const top = topOf(row.id); + return top !== null && top >= 0 && top < viewportHeight; + }); + const row = visible.length === 0 ? null : random.pick(visible); + const height = random.int(20, 600); + return { + kind: "layout", + label: `tap toggle row ${row?.id ?? "none"} to ${height}`, + ...(row === null ? {} : { heldRowId: row.id }), + run: () => { + if (row === null) return; + scrollElement.dispatchEvent(new TouchEvent("touchstart")); + scrollElement.dispatchEvent(new TouchEvent("touchend")); + const element = elements.get(row.id); + if (element !== undefined) keeper.hold(element, "top"); + changeRows( + rows.map((candidate) => + candidate.id === row.id ? { ...candidate, height } : candidate, + ), + ); + keeper.reconcile(); + }, + }; + }, + }, + { + weight: 4, + make: () => { + const index = randomIndex(); + const height = random.int(20, 600); + return { + kind: "layout", + label: `resize row ${index} to ${height}`, + run: () => + changeRows( + rows.map((row, current) => + current === index ? { ...row, height } : row, + ), + ), + }; + }, + }, + { + weight: 4, + make: () => { + const count = random.int(1, 3); + return { + kind: "layout", + label: `append ${count}`, + run: () => + changeRows([...rows, ...Array.from({ length: count }, newRow)]), + }; + }, + }, + { + weight: 3, + make: () => { + const grow = random.int(5, 200); + return { + kind: "layout", + label: `stream into last row +${grow}`, + run: () => + changeRows( + rows.map((row, index) => + index === rows.length - 1 + ? { ...row, height: row.height + grow } + : row, + ), + ), + }; + }, + }, + { + weight: 2, + make: () => { + const count = random.int(1, 3); + return { + kind: "layout", + label: `remove last ${count}`, + run: () => + changeRows(rows.slice(0, Math.max(1, rows.length - count))), + }; + }, + }, + { + weight: 3, + make: () => { + const count = random.int(1, 8); + return { + kind: "layout", + label: `prepend ${count}`, + run: () => + changeRows([...Array.from({ length: count }, newRow), ...rows]), + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + return { + kind: "layout", + label: `regroup rows ${index}..${index + 1}`, + run: () => { + const first = rows[index]; + const second = rows[index + 1]; + if (first === undefined || second === undefined) return; + const merged = { + id: `r${nextId++}`, + height: first.height + second.height - random.int(0, 40), + }; + changeRows([ + ...rows.slice(0, index), + merged, + ...rows.slice(index + 2), + ]); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + const shrunk = random.int(10, 60); + return { + kind: "layout", + label: `shrink row ${index} to ${shrunk} for one frame`, + run: () => { + const original = rows; + changeRows( + rows.map((row, current) => + current === index ? { ...row, height: shrunk } : row, + ), + ); + changeRows(original); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const height = random.int(250, 1000); + return { + kind: "layout", + label: `viewport ${height}`, + run: () => { + viewportHeight = height; + layout.setViewportHeight(height); + browserLayout(); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const fraction = random.next(); + return { + kind: "navigation", + label: `navigate to ${fraction.toFixed(2)}`, + run: () => + keeper.scrollTo( + Math.round(fraction * (layout.maxScrollTop() + 200)), + "instant", + ), + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + const missing = random.next() < 0.15; + const offset = random.int(0, 300); + const atBottom = random.next() < 0.2; + return { + kind: "navigation", + label: `restore ${missing ? "missing row" : `row ${index}`} offset ${offset}${atBottom ? " at bottom" : ""}`, + run: () => + keeper.restore({ + rowId: missing ? "not-loaded" : (rows[index]?.id ?? "none"), + offsetWithinRow: offset, + atBottom, + }), + }; + }, + }, + { + weight: 1, + make: () => ({ + kind: "navigation", + label: "jump to bottom", + run: () => keeper.scrollToBottom(), + }), + }, + ]; + const totalWeight = steps.reduce((sum, step) => sum + step.weight, 0); + const nextStep = (): Step => { + let roll = random.next() * totalWeight; + for (const step of steps) { + roll -= step.weight; + if (roll < 0) return step.make(); + } + return steps[0]!.make(); + }; + + const settle = () => { + vi.advanceTimersByTime(SETTLE_MS); + keeper.reconcile(); + vi.advanceTimersByTime(50); + }; + const fail = (message: string): never => + expect.fail( + `${message}\n scrollTop=${layout.scrollTop} max=${layout.maxScrollTop()} attached=${keeper.isAttached()}\n ${history.join("\n ")}`, + ); + + settle(); + for (let index = 0; index < STEPS_PER_SEED; index += 1) { + const step = nextStep(); + history.push(step.label); + const wasAttached = keeper.isAttached(); + const position = keeper.getPosition(); + const anchorKey = + step.heldRowId ?? + (position.kind === "anchor" && keeper.pendingRestoreRowId() === null + ? position.key + : null); + const anchorTop = anchorKey === null ? null : topOf(anchorKey); + + step.run(); + const afterGesture = layout.scrollTop; + const transform = content.style.transform; + const runState = `${Math.round(layout.scrollTop)}/${Math.round(layout.maxScrollTop())} ${keeper.isAttached() ? "attached" : "detached"}${transform === "" ? "" : ` ${transform}`}`; + settle(); + history[history.length - 1] += + ` [after: ${runState}; settled: ${Math.round(layout.scrollTop)}/${Math.round(layout.maxScrollTop())} ${keeper.isAttached() ? "attached" : "detached"}]`; + + const attached = keeper.isAttached(); + const atEnd = fromEnd() <= THRESHOLD_PX; + const placed = keeper.getPosition().kind !== "free"; + if (attached !== atEnd && (attached || placed)) { + fail( + attached + ? "attached but not at the end" + : "detached while at the end (scroll-to-bottom button shows at the bottom)", + ); + } + if (step.kind === "layout" && wasAttached && !attached) { + fail("a content change detached the reader"); + } + if ( + step.kind === "layout" && + !attached && + anchorKey !== null && + anchorTop !== null + ) { + const top = topOf(anchorKey); + const clamped = + layout.scrollTop <= 0.5 || + layout.scrollTop >= layout.maxScrollTop() - 0.5; + if (top !== null && !clamped && Math.abs(top - anchorTop) > 1) { + fail( + `the reading row ${anchorKey} moved from ${anchorTop} to ${top} without the reader`, + ); + } + } + if (step.kind === "reader" && !attached) { + if (Math.abs(layout.scrollTop - afterGesture) > 1) { + fail( + `the reader's scroll to ${afterGesture} was moved to ${layout.scrollTop}`, + ); + } + } + } + return history; +} + +describe("ScrollPositionKeeper model", () => { + it( + `keeps the button, the bottom, and the reading row consistent across ${SEED_COUNT} random sequences`, + { timeout: SEED_COUNT * 200 }, + () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + for (let seed = 1; seed <= SEED_COUNT; seed += 1) { + runSeed(seed); + restoreLayout?.(); + restoreLayout = null; + document.body.replaceChildren(); + } + }, + ); +}); diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index 61d60aae4d5..cd8a033cd19 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -147,7 +147,10 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before); }); - it("never attaches when content shrinks under a detached reader and the browser clamps to the end", () => { + it("attaches when content shrinks under a detached reader and the clamp to the end persists", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); const rows = rowsOf(10); const timeline = createTimeline(rows); timeline.userScrollTo(1200); @@ -155,13 +158,85 @@ describe("ScrollPositionKeeper", () => { timeline.setRows(rows.slice(0, 7)); timeline.keeper.reconcile(); timeline.scrollElement.dispatchEvent(new Event("scroll")); + expect(timeline.keeper.isAttached()).toBe(false); + vi.advanceTimersToNextFrame(); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + + it("attaches when a row collapses onto the end right after a touch drag, while fling momentum still counts as the reader's", () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + const rows = rowsOf(10); + const timeline = createTimeline(rows, { attached: true }); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 55); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + vi.advanceTimersByTime(500); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + timeline.resize("row-9", 40); + timeline.layout.layoutScrollTo(timeline.layout.maxScrollTop()); + timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + + it("leaves a view the reader never placed at the top while its content loads in, instead of following it", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); + const timeline = createTimeline(rowsOf(1, 100)); + vi.advanceTimersToNextFrame(); + + timeline.setRows(rowsOf(10)); + timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); + + expect(timeline.layout.scrollTop).toBe(0); + expect(timeline.keeper.isAttached()).toBe(false); + }); + + it("keeps a detached reader on their row when content shrinks onto the end for a single frame", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(1200); + const before = timeline.topOf("row-7"); + + timeline.setRows(rows.slice(0, 7)); + timeline.keeper.reconcile(); + timeline.setRows(rows); + vi.advanceTimersToNextFrame(); + + expect(timeline.topOf("row-7")).toBe(before); expect(timeline.keeper.isAttached()).toBe(false); }); it("attaches when the viewport grows and the reader's position no longer fits above the end", () => { - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); const timeline = createTimeline(rowsOf(10)); timeline.userScrollTo(1350); vi.advanceTimersByTime(500); @@ -170,6 +245,7 @@ describe("ScrollPositionKeeper", () => { timeline.layout.setViewportHeight(800); timeline.layout.layoutScrollTo(timeline.layout.maxScrollTop()); timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); expect(timeline.keeper.isAttached()).toBe(true); timeline.setRows(rowsOf(11)); @@ -191,22 +267,6 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before); }); - it("attaches a reader left detached at the end when they drag toward the end, though the drag cannot scroll", () => { - const rows = rowsOf(10); - const timeline = createTimeline(rows); - timeline.userScrollTo(1200); - timeline.setRows(rows.slice(0, 7)); - timeline.keeper.reconcile(); - expect(timeline.keeper.isAttached()).toBe(false); - const touch = (type: string, clientY: number) => - Object.assign(new Event(type), { touches: [{ clientY }] }); - - timeline.scrollElement.dispatchEvent(touch("touchstart", 300)); - timeline.scrollElement.dispatchEvent(touch("touchmove", 280)); - - expect(timeline.keeper.isAttached()).toBe(true); - }); - it("saves a detached reader who sits at the end as at the bottom", () => { const rows = rowsOf(10); const timeline = createTimeline(rows); @@ -235,6 +295,30 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(true); }); + it("lands on a landmark between rows and holds it at the top while rows above it change height", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows, { attached: true }); + const landmark = document.createElement("div"); + landmark.setAttribute("data-scroll-landmark-id", "divider"); + setFakeHeight(landmark, 24); + const items = timeline.scrollElement.querySelector("[data-timeline-items]"); + const rowFour = items?.children[4] ?? null; + items?.insertBefore(landmark, rowFour); + + timeline.keeper.restore({ + rowId: "divider", + offsetWithinRow: 0, + atBottom: false, + }); + const viewportTop = timeline.scrollElement.getBoundingClientRect().top; + expect(landmark.getBoundingClientRect().top).toBe(viewportTop); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.resize("row-1", 520); + timeline.keeper.reconcile(); + expect(landmark.getBoundingClientRect().top).toBe(viewportTop); + }); + it("keeps the end in view on every layout change while attached and stays attached", () => { const timeline = createTimeline(rowsOf(10), { attached: true }); expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index d2444fde65f..6d687dceba2 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -50,7 +50,9 @@ interface PendingRestore { } const ROW_ID_ATTRIBUTE = "data-timeline-row-id"; +const LANDMARK_ID_ATTRIBUTE = "data-scroll-landmark-id"; const ROW_SELECTOR = `[${ROW_ID_ATTRIBUTE}]`; +const ANCHORABLE_SELECTOR = `${ROW_SELECTOR}, [${LANDMARK_ID_ATTRIBUTE}]`; const DIRECT_ROW_SELECTOR = [ `:scope > ${ROW_SELECTOR}`, `:scope > [data-timeline-items] > ${ROW_SELECTOR}`, @@ -61,26 +63,41 @@ const MAX_ANCHOR_NEIGHBORS = 8; const SCROLL_SETTLE_MS = 150; const RESTORE_WAIT_MS = 1_000; const PASSIVE_CAPTURE = { capture: true, passive: true } as const; -const ATTACH_KEYS = new Set(["End", "PageDown", " ", "ArrowDown"]); -const SCROLL_KEYS = new Set([...ATTACH_KEYS, "Home", "PageUp", "ArrowUp"]); +const SCROLL_KEYS = new Set([ + "End", + "PageDown", + " ", + "ArrowDown", + "Home", + "PageUp", + "ArrowUp", +]); const WHEEL_SESSION_MS = 150; const KEY_SESSION_MS = 500; const PROGRAMMATIC_SMOOTH_SESSION_MS = 1_000; const SESSION_EXTENSION_MS = 150; const MOMENTUM_SESSION_MS = 3_000; -const TOUCH_ATTACH_DRAG_PX = 8; const FREE: ReadingPosition = { kind: "free" }; export function getDirectTimelineRows(list: Element): NodeListOf { return list.querySelectorAll(DIRECT_ROW_SELECTOR); } +function anchorKey(element: HTMLElement): string | null { + return ( + element.getAttribute(ROW_ID_ATTRIBUTE) ?? + element.getAttribute(LANDMARK_ID_ATTRIBUTE) + ); +} + function findMountedRow( scrollElement: HTMLElement, - rowId: string, + key: string, ): HTMLElement | null { - for (const row of scrollElement.querySelectorAll(ROW_SELECTOR)) { - if (row.getAttribute(ROW_ID_ATTRIBUTE) === rowId) return row; + for (const element of scrollElement.querySelectorAll( + ANCHORABLE_SELECTOR, + )) { + if (anchorKey(element) === key) return element; } return null; } @@ -116,7 +133,6 @@ export class ScrollPositionKeeper { private maxScrollTop = 0; private viewportHeight = 0; private reconciledWidth = 0; - private reconciledViewportHeight = 0; private reconciledScrollHeight = 0; private topRow: TopRow | null = null; private deferred = 0; @@ -126,11 +142,11 @@ export class ScrollPositionKeeper { private gestureScrolled = false; private inputUntil = Number.NEGATIVE_INFINITY; private touchStartScrollTop = 0; - private touchStartY: number | null = null; private userScrolled = false; private scrollMovedAt = Number.NEGATIVE_INFINITY; private settleTimeout: number | null = null; private clampFrame: number | null = null; + private attachFrame: number | null = null; private readonly lists = new Set(); private readonly listeners = new Set<() => void>(); private readonly positionListeners = new Set<() => void>(); @@ -185,26 +201,18 @@ export class ScrollPositionKeeper { scrollElement.style.overflowAnchor = "none"; this.ownScrollTop = scrollElement.scrollTop; const onScroll = () => this.handleScroll(); - const onTouchStart = (event: TouchEvent) => { + const onTouchStart = () => { if (!this.touching) { this.gestureScrolled = false; this.touchStartScrollTop = scrollElement.scrollTop; - this.touchStartY = event.touches[0]?.clientY ?? null; } this.touching = true; }; - const onTouchMove = (event: TouchEvent) => { - const startY = this.touchStartY; - const y = event.touches[0]?.clientY; - if (startY === null || y === undefined) return; - if (startY - y >= TOUCH_ATTACH_DRAG_PX) this.attachIfAtEnd(); - }; const activeTouchPointers = new Set(); const endTouch = () => { if (!this.touching) return; activeTouchPointers.clear(); this.touching = false; - this.touchStartY = null; if (Math.abs(scrollElement.scrollTop - this.touchStartScrollTop) >= 1) { this.gestureScrolled = true; this.scrollMovedAt = window.performance.now(); @@ -238,9 +246,8 @@ export class ScrollPositionKeeper { this.pointerDown = false; if (this.gestureScrolled) this.extendInput(SESSION_EXTENSION_MS); }; - const onWheel = (event: WheelEvent) => { + const onWheel = () => { this.extendInput(WHEEL_SESSION_MS); - if (event.deltaY > 0) this.attachIfAtEnd(); }; const onKeyDown = (event: KeyboardEvent) => { if (!SCROLL_KEYS.has(event.key) || isEditableTarget(event.target)) { @@ -255,12 +262,10 @@ export class ScrollPositionKeeper { return; } this.extendInput(KEY_SESSION_MS); - if (ATTACH_KEYS.has(event.key)) this.attachIfAtEnd(); }; scrollElement.addEventListener("scroll", onScroll, { passive: true }); scrollElement.addEventListener("wheel", onWheel, { passive: true }); scrollElement.addEventListener("touchstart", onTouchStart, PASSIVE_CAPTURE); - scrollElement.addEventListener("touchmove", onTouchMove, PASSIVE_CAPTURE); scrollElement.addEventListener("touchend", onTouchEnd, PASSIVE_CAPTURE); scrollElement.addEventListener("touchcancel", onTouchEnd, PASSIVE_CAPTURE); scrollElement.addEventListener("pointerdown", onPointerDown, { @@ -292,11 +297,6 @@ export class ScrollPositionKeeper { onTouchStart, PASSIVE_CAPTURE, ); - scrollElement.removeEventListener( - "touchmove", - onTouchMove, - PASSIVE_CAPTURE, - ); scrollElement.removeEventListener( "touchend", onTouchEnd, @@ -316,8 +316,11 @@ export class ScrollPositionKeeper { if (this.settleTimeout !== null) window.clearTimeout(this.settleTimeout); if (this.clampFrame !== null) window.cancelAnimationFrame(this.clampFrame); + if (this.attachFrame !== null) + window.cancelAnimationFrame(this.attachFrame); this.settleTimeout = null; this.clampFrame = null; + this.attachFrame = null; this.setDeferred(0); }; } @@ -342,11 +345,8 @@ export class ScrollPositionKeeper { if (scrollElement === null) return; this.ownScrollTop = scrollElement.scrollTop; this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollElement.scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -365,11 +365,8 @@ export class ScrollPositionKeeper { } this.write(scrollElement, top); this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollElement.scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -479,8 +476,6 @@ export class ScrollPositionKeeper { this.setPosition(this.capture(scrollElement) ?? FREE); } } - } else if (movedDown && this.isAtEnd(scrollTop)) { - this.setPosition({ kind: "bottom" }); } else { if (position.kind === "anchor") this.apply(scrollElement, false); const current = this.position; @@ -492,6 +487,7 @@ export class ScrollPositionKeeper { this.setPosition(this.capture(scrollElement) ?? FREE); } if (this.deferred !== 0) this.scheduleDeferredWrite(); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -512,12 +508,7 @@ export class ScrollPositionKeeper { const widthChanged = this.reconciledWidth > 0 && Math.abs(this.reconciledWidth - width) >= 1; if (widthChanged) this.keepAnchorVisible(scrollElement); - const resized = - widthChanged || - (this.reconciledViewportHeight > 0 && - Math.abs(this.reconciledViewportHeight - this.viewportHeight) >= 1); this.reconciledWidth = width; - this.reconciledViewportHeight = this.viewportHeight; const previous = this.ownScrollTop; if ( previous !== null && @@ -540,19 +531,10 @@ export class ScrollPositionKeeper { this.position.kind === "bottom" && !extentChanged && Math.abs(max - scrollTop) <= this.options.bottomThresholdPx; - let target = + const target = bouncing || settledAtEnd ? null : this.targetScrollTop(scrollElement, scrollTop, max); - if ( - target !== null && - (resized || restored) && - this.position.kind === "anchor" && - target >= max - this.options.bottomThresholdPx - ) { - this.setPosition({ kind: "bottom" }); - target = max; - } if (target !== null) { const clamped = defer ? Math.min( @@ -571,6 +553,8 @@ export class ScrollPositionKeeper { this.scheduleClampSettle(); } } + if (restored) this.attachIfAtEnd(scrollElement); + else this.scheduleAttachAtEnd(scrollElement); if (notify) this.notifyLists(urgent); } @@ -643,7 +627,7 @@ export class ScrollPositionKeeper { if ( element === null || !element.isConnected || - element.getAttribute(ROW_ID_ATTRIBUTE) !== position.key + anchorKey(element) !== position.key ) { element = findMountedRow(scrollElement, position.key); if (element !== null) position.element = element; @@ -787,15 +771,6 @@ export class ScrollPositionKeeper { ); } - private attachIfAtEnd(): void { - const scrollElement = this.options.getScrollElement(); - if (scrollElement === null || this.position.kind === "bottom") return; - if (!this.isAtEnd(scrollElement.scrollTop)) return; - this.pendingRestore = null; - this.setPosition({ kind: "bottom" }); - this.reconcile(); - } - private foldPendingInputScroll(): void { const scrollElement = this.options.getScrollElement(); const previous = this.ownScrollTop; @@ -806,11 +781,8 @@ export class ScrollPositionKeeper { if (Math.abs(scrollTop - previous) < MIN_WRITE_PX) return; this.ownScrollTop = scrollTop; this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); } private isAtEnd(scrollTop: number): boolean { @@ -902,6 +874,37 @@ export class ScrollPositionKeeper { }); } + private isDetachedAtEnd(scrollElement: HTMLElement): boolean { + return ( + this.position.kind !== "bottom" && + this.pendingRestore === null && + this.isAtEnd(scrollElement.scrollTop) + ); + } + + private attachIfAtEnd(scrollElement: HTMLElement): void { + if (!this.isDetachedAtEnd(scrollElement)) return; + this.setPosition({ kind: "bottom" }); + this.reconcile(); + } + + private scheduleAttachAtEnd(scrollElement: HTMLElement): void { + if ( + this.attachFrame !== null || + this.position.kind === "free" || + !this.isDetachedAtEnd(scrollElement) + ) { + return; + } + this.attachFrame = window.requestAnimationFrame(() => { + this.attachFrame = null; + const current = this.options.getScrollElement(); + if (current === null) return; + this.refreshExtent(current); + this.attachIfAtEnd(current); + }); + } + private write(scrollElement: HTMLElement, target: number): void { if (Math.abs(scrollElement.scrollTop - target) >= MIN_WRITE_PX) { scrollElement.scrollTop = target; diff --git a/apps/app/src/test/fake-flow-layout.ts b/apps/app/src/test/fake-flow-layout.ts index 23848106764..74b09eac71a 100644 --- a/apps/app/src/test/fake-flow-layout.ts +++ b/apps/app/src/test/fake-flow-layout.ts @@ -1,6 +1,7 @@ import { vi } from "vitest"; interface FakeFlowLayoutOptions { + heightOf?: (element: Element) => number | null; scrollElement: HTMLElement | (() => HTMLElement | null); viewportHeight: number; } @@ -31,6 +32,7 @@ export function setFakeHeight(element: Element, height: number): void { } export function installFakeFlowLayout({ + heightOf, scrollElement: scrollElementOption, viewportHeight: initialViewportHeight, }: FakeFlowLayoutOptions) { @@ -45,12 +47,14 @@ export function installFakeFlowLayout({ const layout = () => { boxes.clear(); const place = (element: Element, top: number): number => { - const own = element.getAttribute(HEIGHT_ATTRIBUTE); + const attribute = element.getAttribute(HEIGHT_ATTRIBUTE); + const own = + attribute !== null ? Number(attribute) : (heightOf?.(element) ?? null); const style = element instanceof HTMLElement ? element.style : null; const shift = element instanceof HTMLElement ? translateY(element) : 0; let height: number; if (own !== null) { - height = Number(own); + height = own; let childTop = top + shift; for (const child of element.children) { childTop += place(child, childTop); diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index a39630e96b2..c80c891079a 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -56,10 +56,7 @@ import { import { useForkThreadFromMessage } from "@/hooks/useForkThreadFromMessage"; import { isThreadForkable } from "@bb/client-core"; import { useRequestEnvironmentAction } from "../../hooks/mutations/environment-mutations"; -import { - useMarkThreadRead, - useUpdateThread, -} from "../../hooks/mutations/thread-state-mutations"; +import { useUpdateThread } from "../../hooks/mutations/thread-state-mutations"; import { useCreateThreadQueuedMessage, useEditThreadMessage, @@ -75,11 +72,9 @@ import { type ChildThreadPendingAttentionSource, } from "../../hooks/queries/child-thread-pending-interactions"; import { - didThreadDetailBootstrapRefreshAfterMount, useChildThreads, useProjectThreadSubset, useThread, - useThreadDetailBootstrap, useThreadPendingInteractions, type ProjectThreadSubsetFilters, } from "../../hooks/queries/thread-queries"; @@ -234,8 +229,7 @@ import type { } from "@/components/secondary-panel/ThreadSecondaryPanel"; import { useEnvironmentMergeBase } from "@/components/secondary-panel/git-diff/useEnvironmentMergeBase"; import { useThreadGitActions } from "./useThreadGitActions"; -import { useThreadReadTracking } from "@/hooks/useThreadReadTracking"; -import { useThreadUnreadDividerState } from "./useThreadUnreadDividerState"; +import { useThreadDetailThread } from "./useThreadDetailThread"; import { buildTerminalSyncedSecondaryFileTabs, syncTerminalTabsInFixedPanelState, @@ -465,22 +459,12 @@ function ThreadDetailViewInternal( const navigate = useImmediateRouteNavigate(); useFixedPanelTabsStorageMaintenance(); const systemConfigQuery = useSystemConfig(); - const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId); - const hasThreadDetailBootstrapSettled = - threadDetailBootstrapQuery.isSuccess || threadDetailBootstrapQuery.isError; const { - data: thread, - isFetching, - isLoadingError, - error, - } = useThread(threadId, { - enabled: hasThreadDetailBootstrapSettled, - refetchOnMount: didThreadDetailBootstrapRefreshAfterMount( - threadDetailBootstrapQuery, - ) - ? false - : "always", - }); + hasThreadDetailBootstrapSettled, + threadDetailBootstrapQuery, + threadQuery: { data: thread, isFetching, isLoadingError, error }, + unreadDividerState, + } = useThreadDetailThread(threadId, timelineEnabled); const environmentQuery = useEnvironment(thread?.environmentId, { enabled: hasThreadDetailBootstrapSettled, staleTime: 5_000, @@ -575,10 +559,6 @@ function ThreadDetailViewInternal( ); const pendingInteractions = pendingInteractionsQuery.data ?? []; const hasPendingInteraction = pendingInteractions.length > 0; - const unreadDividerState = useThreadUnreadDividerState({ - routeThreadId: threadId, - thread, - }); const [hasRequestedMergeBaseOptions, setHasRequestedMergeBaseOptions] = useState(false); const [shouldAutoFocusNewTab, setShouldAutoFocusNewTab] = useState(false); @@ -773,7 +753,6 @@ function ThreadDetailViewInternal( const editMessage = useEditThreadMessage(); const createQueuedMessage = useCreateThreadQueuedMessage(); const requestEnvironmentAction = useRequestEnvironmentAction(); - const markThreadRead = useMarkThreadRead(); const updateEnvironment = useUpdateEnvironment(); const updateThread = useUpdateThread({ errorMessage: "Failed to assign parent thread.", @@ -1770,10 +1749,6 @@ function ThreadDetailViewInternal( return { ...childThreadsSection, pendingInteractions }; }, [childThreadsSection, childPendingInteractions]); const isThreadTimelinePending = timelineLoading && timelineRows.length === 0; - useThreadReadTracking({ - markThreadRead, - thread: timelineEnabled ? thread : undefined, - }); const { effectiveMergeBaseBranch, handleMergeBaseBranchChange, diff --git a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx new file mode 100644 index 00000000000..b28e65ab2d1 --- /dev/null +++ b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx @@ -0,0 +1,552 @@ +// @vitest-environment jsdom + +import { act, cleanup, render } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import type { + ThreadResponse, + ThreadTimelineResponse, + TimelineRow, +} from "@bb/server-contract"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll-body"; +import { ThreadTimelineSurface } from "@/components/thread/timeline/ThreadTimelineSurface"; +import { useThreadTimelineController } from "@/components/thread/timeline/useThreadTimelineController"; +import { sdk } from "@/lib/sdk"; +import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures"; +import { threadListQueryKey } from "@/hooks/queries/query-keys"; +import { installFakeFlowLayout } from "@/test/fake-flow-layout"; +import { + makeThreadResponse, + makeThreadTimelineResponse, +} from "@/test/fixtures/thread-responses"; +import { conversationRow } from "@/test/fixtures/thread-timeline-rows"; +import { createQueryClientTestHarness } from "@/test/queryClientTestHarness"; +import { useThreadDetailThread } from "./useThreadDetailThread"; + +const SEED_COUNT = Number(process.env.OPENING_MODEL_SEEDS ?? 40); +const THREAD_ID = "thr_opening"; +const DESKTOP_SEGMENT_LIMIT = 20; +const COMPACT_SEGMENT_LIMIT = 8; +const THRESHOLD_PX = 4; + +const viewport = vi.hoisted(() => ({ compact: false })); + +vi.mock("@/lib/sdk", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + sdk: { threads: { get: vi.fn(), timeline: vi.fn(), markRead: vi.fn() } }, + }; +}); + +vi.mock("@/hooks/useRealtimeSubscription", () => ({ + useThreadDetailRealtimeSubscription: vi.fn(), + useThreadTimelineRealtimeSubscription: vi.fn(), +})); + +vi.mock("@/hooks/useServerConnectionState", () => ({ + useServerConnectionState: () => "connected", +})); + +vi.mock("@bb/shared-ui/hooks/use-compact-viewport", async (importOriginal) => { + const actual = + await importOriginal< + typeof import("@bb/shared-ui/hooks/use-compact-viewport") + >(); + return { ...actual, useIsCompactViewport: () => viewport.compact }; +}); + +vi.mock("@/lib/user-activity", () => ({ useUserActive: () => true })); + +function createRandom(seed: number) { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296; + }; + return { + next, + int: (min: number, max: number) => + min + Math.floor(next() * (max - min + 1)), + }; +} + +interface HistoryRow { + row: TimelineRow; + height: number; + segmentStart: boolean; + authoredByReader: boolean; +} + +interface Pending { + label: string; + release: () => void; +} + +function OpenedThread() { + const { unreadDividerState } = useThreadDetailThread(THREAD_ID, true); + const timeline = useThreadTimelineController({ threadId: THREAD_ID }); + return ( + + + + ); +} + +function Host({ shown }: { shown: boolean }) { + return shown ? :
; +} + +let restoreLayout: (() => void) | null = null; + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + "Date", + ], + }); + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { + configurable: true, + value: vi.fn(), + }); +}); + +afterEach(() => { + cleanup(); + restoreLayout?.(); + restoreLayout = null; + vi.mocked(sdk.threads.get).mockReset(); + vi.mocked(sdk.threads.timeline).mockReset(); + vi.mocked(sdk.threads.markRead).mockReset(); + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +async function runSeed(seed: number): Promise { + const random = createRandom(seed); + const compact = random.next() < 0.5; + viewport.compact = compact; + const segmentLimit = compact ? COMPACT_SEGMENT_LIMIT : DESKTOP_SEGMENT_LIMIT; + const viewportHeight = compact ? 760 : random.int(500, 950); + + let seq = 0; + let clock = 1_000_000; + const history: HistoryRow[] = []; + const appendSegment = (kind: "reader" | "agent") => { + seq += 1; + clock += random.int(500, 60_000); + history.push({ + row: conversationRow({ + id: `msg-${seq}`, + role: "user", + initiator: kind === "reader" ? "user" : "agent", + seq, + createdAt: clock, + startedAt: clock, + text: `${kind} message ${seq}`, + threadId: THREAD_ID, + turnId: `turn-${seq}`, + }), + height: random.int(50, 160), + segmentStart: true, + authoredByReader: kind === "reader", + }); + const replies = random.int(1, 3); + for (let index = 0; index < replies; index += 1) { + seq += 1; + clock += random.int(500, 30_000); + history.push({ + row: conversationRow({ + id: `msg-${seq}`, + role: "assistant", + seq, + createdAt: clock, + startedAt: clock, + text: `reply ${seq}`, + threadId: THREAD_ID, + turnId: `turn-${seq}`, + }), + height: random.int(40, 520), + segmentStart: false, + authoredByReader: false, + }); + } + }; + const segmentCount = random.int(3, 34); + for (let index = 0; index < segmentCount; index += 1) { + appendSegment(random.next() < 0.6 ? "reader" : "agent"); + } + + const heights = new Map(); + const heightOfRow = (id: string) => heights.get(id) ?? 80; + const syncHeights = () => { + for (const entry of history) heights.set(entry.row.id, entry.height); + }; + syncHeights(); + + let lastReadAt: number | null = clock + 1; + let latestAttentionAt = clock; + let snapshot = 1; + + const pending: Pending[] = []; + const deferred = (label: string, value: () => T): Promise => + new Promise((resolve) => { + pending.push({ label, release: () => resolve(value()) }); + }); + const threadResponse = (): ThreadResponse => + makeThreadResponse({ + id: THREAD_ID, + lastReadAt, + latestAttentionAt, + status: "idle", + }); + const pageBefore = (anchorSeq: number | null): ThreadTimelineResponse => { + const eligible = history.filter( + (entry) => anchorSeq === null || entry.row.sourceSeqStart < anchorSeq, + ); + let segments = 0; + let start = eligible.length; + while (start > 0 && segments < segmentLimit) { + start -= 1; + if (eligible[start]!.segmentStart) segments += 1; + } + const pageRows = eligible.slice(start); + const first = pageRows[0]; + const hasOlder = start > 0 && first !== undefined; + return makeThreadTimelineResponse({ + rows: pageRows.map((entry) => entry.row), + maxSeq: seq, + timelinePage: { + returnedSegmentCount: segments, + historySnapshot: `snapshot-${snapshot}`, + olderCursor: hasOlder + ? { + anchorId: `anchor-${first.row.sourceSeqStart}`, + anchorSeq: first.row.sourceSeqStart, + } + : null, + olderRowsSourceSeqEnd: hasOlder + ? eligible[start - 1]!.row.sourceSeqEnd + : null, + }, + }); + }; + vi.mocked(sdk.threads.get).mockImplementation(((args: { include?: string }) => + deferred(args.include === undefined ? "thread" : "bootstrap", () => + threadResponse(), + )) as unknown as typeof sdk.threads.get); + vi.mocked(sdk.threads.timeline).mockImplementation(((args: { + beforeAnchorSeq?: string; + }) => + deferred( + args.beforeAnchorSeq === undefined ? "latest page" : "older page", + () => + pageBefore( + args.beforeAnchorSeq === undefined + ? null + : Number(args.beforeAnchorSeq), + ), + )) as unknown as typeof sdk.threads.timeline); + + vi.mocked(sdk.threads.markRead).mockImplementation(() => + deferred("mark read", () => { + lastReadAt = latestAttentionAt; + return threadResponse(); + }), + ); + + const getScrollElement = () => + document.querySelector("[data-page-scroll-viewport]"); + const layout = installFakeFlowLayout({ + heightOf: (element) => { + if (element.hasAttribute("data-scroll-landmark-id")) return 24; + const rowId = element.getAttribute("data-timeline-row-id"); + if (rowId === null) return null; + return element.parentElement?.closest("[data-timeline-row-id]") + ? null + : heightOfRow(rowId); + }, + scrollElement: getScrollElement, + viewportHeight, + }); + restoreLayout = layout.restore; + + const log: string[] = [ + `seed ${seed} ${compact ? "phone" : "desktop"} viewport=${viewportHeight} segments=${segmentCount}`, + ]; + const flush = async (ms: number) => { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms); + }); + await act(async () => { + layout.flushResizeObservers(); + await vi.advanceTimersByTimeAsync(0); + }); + }; + const releaseAll = async (onRelease?: () => Promise) => { + for (let guard = 0; guard < 200; guard += 1) { + await flush(random.int(0, 40)); + if (pending.length === 0) { + await flush(20); + if (pending.length === 0) return; + } + const index = random.int(0, pending.length - 1); + const [next] = pending.splice(index, 1); + log.push(`release ${next!.label}`); + next!.release(); + await onRelease?.(); + } + throw new Error(`requests never settled\n ${log.join("\n ")}`); + }; + const rowTop = (id: string): number | null => { + const scrollElement = getScrollElement(); + const element = [ + ...document.querySelectorAll("[data-timeline-row-id]"), + ].find( + (candidate) => candidate.getAttribute("data-timeline-row-id") === id, + ); + if (scrollElement === null || element === undefined) return null; + return ( + element.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top + ); + }; + const topRowOnScreen = (): { id: string; top: number } | null => { + for (const entry of history) { + const top = rowTop(entry.row.id); + if (top !== null && top + entry.height > 1) { + return { id: entry.row.id, top }; + } + } + return null; + }; + const fail = (message: string): never => + expect.fail( + `${message}\n scrollTop=${layout.scrollTop} max=${layout.maxScrollTop()}\n ${log.join("\n ")}`, + ); + + const { wrapper: Wrapper, queryClient } = createQueryClientTestHarness(); + const tree = (shown: boolean) => ( + + + + + + ); + const view = render(tree(false)); + const showThread = (shown: boolean) => view.rerender(tree(shown)); + + const returning = random.next() < 0.5; + let saved: { id: string; top: number } | null = null; + if (returning) { + log.push("first visit, read"); + await act(async () => showThread(true)); + await releaseAll(); + await flush(500); + if (random.next() < 0.5 && layout.maxScrollTop() > 0) { + const up = random.int(50, 1_500); + layout.userScrollTo(layout.scrollTop - up); + log.push(`reader scrolls up ${up}`); + await flush(3_600); + if (layout.maxScrollTop() - layout.scrollTop > THRESHOLD_PX) { + saved = topRowOnScreen(); + } + } + await act(async () => showThread(false)); + const away = random.int(10_000, 600_000); + await flush(away); + const added = random.int(1, 4); + for (let index = 0; index < added; index += 1) { + appendSegment(random.next() < 0.7 ? "agent" : "reader"); + } + syncHeights(); + snapshot += 1; + log.push( + `switched away for ${Math.round(away / 1000)}s; ${added} segments arrived`, + ); + } + + const readState = random.next(); + const lastReaderRow = [...history] + .reverse() + .find((entry) => entry.authoredByReader); + const realistic = history.filter( + (entry) => + lastReaderRow === undefined || + entry.row.startedAt >= lastReaderRow.row.startedAt, + ); + if (readState < 0.15) { + lastReadAt = clock + 1; + log.push("thread read"); + } else if (readState < 0.25) { + lastReadAt = null; + log.push("thread marked unread"); + } else { + const pool = readState < 0.85 ? realistic : history; + const at = pool[random.int(0, pool.length - 1)]!; + lastReadAt = at.row.startedAt + random.int(0, 400); + log.push( + `read up to ${at.row.id}${pool === history ? " (any point)" : ""}`, + ); + } + latestAttentionAt = clock + 2; + const openingLastReadAt = lastReadAt; + + queryClient.setQueryData(threadListQueryKey({ archived: false }), [ + makeThreadListEntry({ id: THREAD_ID, lastReadAt, latestAttentionAt }), + ]); + await act(async () => showThread(true)); + log.push(returning ? "returns to the thread" : "opens the thread"); + + let readerScroll: { id: string; top: number } | null = null; + const scrollWhileLoading = random.next() < 0.2; + await releaseAll(async () => { + if (!scrollWhileLoading || readerScroll !== null) return; + if (random.next() > 0.3 || layout.maxScrollTop() <= 0) return; + const up = random.int(50, 900); + layout.userScrollTo(layout.scrollTop - up); + await flush(16); + readerScroll = topRowOnScreen(); + log.push(`reader scrolls up ${up} while loading`); + }); + await flush(4_000); + + const divider = document.querySelector( + "[data-testid=thread-unread-divider]", + ); + const scrollElement = getScrollElement(); + if (scrollElement === null) return fail("no scroll element"); + const dividerTop = + divider === null + ? null + : divider.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top; + const fromEnd = layout.maxScrollTop() - layout.scrollTop; + const attached = + scrollElement.closest("[data-scroll-attached]") !== null || + document.querySelector("[data-scroll-attached]") !== null; + log.push( + `settled: divider=${dividerTop === null ? "none" : Math.round(dividerTop)} fromEnd=${Math.round(fromEnd)} attached=${attached}`, + ); + + const unread = + openingLastReadAt !== null && openingLastReadAt < latestAttentionAt; + const cutoff = openingLastReadAt ?? 0; + const expected = unread + ? history.find( + (entry) => entry.row.startedAt > cutoff && !entry.authoredByReader, + ) + : undefined; + const firstPage = pageBefore(null).rows; + const firstPageStart = firstPage[0]?.startedAt ?? 0; + const firstPageHasOlder = firstPage.length < history.length; + + if (attached !== fromEnd <= THRESHOLD_PX) { + fail( + attached + ? "attached but not at the end" + : "detached at the end (the jump-to-bottom button shows at the bottom)", + ); + } + if (divider !== null) { + if (expected === undefined) fail("a divider shows on a read thread"); + const landmark = divider.closest("[data-scroll-landmark-id]"); + const nextId = landmark?.nextElementSibling?.getAttribute( + "data-timeline-row-id", + ); + const previousId = landmark?.previousElementSibling?.getAttribute( + "data-timeline-row-id", + ); + const expectedIndex = history.findIndex( + (entry) => entry.row.id === expected!.row.id, + ); + if (nextId != null && nextId !== expected!.row.id) { + fail(`NEW sits above ${nextId}, not above ${expected!.row.id}`); + } + if ( + previousId != null && + previousId !== history[expectedIndex - 1]?.row.id + ) { + fail(`NEW sits below ${previousId}, not above ${expected!.row.id}`); + } + if (readerScroll === null && dividerTop !== null) { + const atTop = Math.abs(dividerTop) <= 1; + if (!atTop && !(attached && fromEnd <= THRESHOLD_PX)) { + fail(`NEW landed at ${Math.round(dividerTop)} instead of the top`); + } + } + } else if ( + expected !== undefined && + (cutoff >= firstPageStart || !firstPageHasOlder) + ) { + fail(`no NEW although the read point is in the first page`); + } + if (readerScroll !== null) { + const scrolled: { id: string; top: number } = readerScroll; + const top = rowTop(scrolled.id); + const clamped = layout.scrollTop <= 0.5 || fromEnd <= THRESHOLD_PX; + if (top !== null && !clamped && Math.abs(top - scrolled.top) > 1) { + fail( + `the reader's row ${scrolled.id} moved from ${Math.round(scrolled.top)} to ${Math.round(top)}`, + ); + } + } else if (divider === null && returning && saved !== null) { + const top = rowTop(saved.id); + const clamped = fromEnd <= THRESHOLD_PX; + if (top !== null && !clamped && Math.abs(top - saved.top) > 1) { + fail( + `returned to ${saved.id} at ${Math.round(top)} instead of its saved ${Math.round(saved.top)}`, + ); + } + } else if (divider === null && readerScroll === null && saved === null) { + if (!attached) fail("opened without NEW but not at the bottom"); + } +} + +describe("thread opening model", () => { + it( + `lands every opening where the read state says, across ${SEED_COUNT} random loading orders`, + { timeout: SEED_COUNT * 2_000 }, + async () => { + for (let seed = 1; seed <= SEED_COUNT; seed += 1) { + await runSeed(seed); + cleanup(); + restoreLayout?.(); + restoreLayout = null; + document.body.replaceChildren(); + } + }, + ); +}); diff --git a/apps/app/src/views/thread-detail/useThreadDetailThread.ts b/apps/app/src/views/thread-detail/useThreadDetailThread.ts new file mode 100644 index 00000000000..c6fdb9c9d5d --- /dev/null +++ b/apps/app/src/views/thread-detail/useThreadDetailThread.ts @@ -0,0 +1,42 @@ +import { + didThreadDetailBootstrapRefreshAfterMount, + useThread, + useThreadDetailBootstrap, +} from "@/hooks/queries/thread-queries"; +import { useMarkThreadRead } from "@/hooks/mutations/thread-state-mutations"; +import { useThreadReadTracking } from "@/hooks/useThreadReadTracking"; +import { useThreadUnreadDividerState } from "./useThreadUnreadDividerState"; + +export function useThreadDetailThread(threadId: string, trackRead: boolean) { + const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId); + const hasThreadDetailBootstrapSettled = + threadDetailBootstrapQuery.isSuccess || threadDetailBootstrapQuery.isError; + const threadQuery = useThread(threadId, { + enabled: hasThreadDetailBootstrapSettled, + refetchOnMount: didThreadDetailBootstrapRefreshAfterMount( + threadDetailBootstrapQuery, + ) + ? false + : "always", + }); + const thread = threadQuery.data; + const unreadDividerState = useThreadUnreadDividerState({ + hasFreshThread: + thread !== undefined && + !threadQuery.isPlaceholderData && + !threadQuery.isFetching && + !threadDetailBootstrapQuery.isFetching, + routeThreadId: threadId, + thread, + }); + useThreadReadTracking({ + markThreadRead: useMarkThreadRead(), + thread: trackRead && unreadDividerState.ready ? thread : undefined, + }); + return { + hasThreadDetailBootstrapSettled, + threadDetailBootstrapQuery, + threadQuery, + unreadDividerState, + }; +} diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts index 7491bd854aa..b3fd45c6ae5 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts @@ -10,25 +10,39 @@ interface DividerThread { latestAttentionAt: number; } -function renderDividerState(initialThread: DividerThread) { +interface DividerProps { + hasFreshThread: boolean; + thread: DividerThread; +} + +function renderDividerState( + initialThread: DividerThread, + initialHasFreshThread = true, +) { const renders: ReturnType[] = []; const view = renderHook( - ({ thread }: { thread: DividerThread }) => { + ({ hasFreshThread, thread }: DividerProps) => { const state = useThreadUnreadDividerState({ + hasFreshThread, routeThreadId: thread.id, thread, }); renders.push(state); return state; }, - { initialProps: { thread: initialThread } }, + { + initialProps: { + hasFreshThread: initialHasFreshThread, + thread: initialThread, + }, + }, ); return { renders, result: view.result, - show: (thread: DividerThread) => { + show: (thread: DividerThread, hasFreshThread = true) => { renders.length = 0; - view.rerender({ thread }); + view.rerender({ hasFreshThread, thread }); }, }; } @@ -46,8 +60,9 @@ describe("useThreadUnreadDividerState", () => { }); expect(renders[0]).toEqual({ + ready: true, autoScroll: true, - placement: { kind: "after-cutoff", cutoffAt: 100 }, + placement: { cutoffAt: 100 }, }); }); @@ -58,11 +73,33 @@ describe("useThreadUnreadDividerState", () => { latestAttentionAt: 200, }); - show({ id: "thr_b", lastReadAt: null, latestAttentionAt: 300 }); + show({ id: "thr_b", lastReadAt: 250, latestAttentionAt: 300 }); expect(renders[0]).toEqual({ + ready: true, autoScroll: true, - placement: { kind: "before-first" }, + placement: { cutoffAt: 250 }, + }); + }); + + it("opens a thread marked unread without a divider, and adds none when marked unread while open", () => { + const { result, show } = renderDividerState({ + id: "thr_a", + lastReadAt: null, + latestAttentionAt: 200, + }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); + + show({ id: "thr_b", lastReadAt: 300, latestAttentionAt: 200 }); + show({ id: "thr_b", lastReadAt: null, latestAttentionAt: 200 }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, }); }); @@ -75,12 +112,17 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 250, latestAttentionAt: 200 }); expect(result.current).toEqual({ + ready: true, autoScroll: true, - placement: { kind: "after-cutoff", cutoffAt: 100 }, + placement: { cutoffAt: 100 }, }); show({ id: "thr_a", lastReadAt: 400, latestAttentionAt: 300 }); - expect(result.current).toEqual({ autoScroll: false, placement: null }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); }); it("opens a read thread without a divider", () => { @@ -90,6 +132,44 @@ describe("useThreadUnreadDividerState", () => { latestAttentionAt: 200, }); - expect(renders[0]).toEqual({ autoScroll: false, placement: null }); + expect(renders[0]).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); + }); + + it("auto-scrolls to a divider that arrives with the fresh fetch after reopening on cached read state", () => { + const { result, show } = renderDividerState( + { id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }, + false, + ); + expect(result.current).toEqual({ + ready: false, + autoScroll: false, + placement: null, + }); + + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); + expect(result.current).toEqual({ + ready: true, + autoScroll: true, + placement: { cutoffAt: 300 }, + }); + }); + + it("does not auto-scroll to a divider from a reply that lands after the thread settled", () => { + const { result, show } = renderDividerState( + { id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }, + false, + ); + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }); + + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: { cutoffAt: 300 }, + }); }); }); diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts index 884e9470291..feae801c015 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts @@ -15,6 +15,7 @@ interface ThreadUnreadDividerSnapshot { } interface ThreadUnreadDividerState { + ready: boolean; autoScroll: boolean; placement: ThreadTimelineUnreadDividerPlacement | null; } @@ -25,11 +26,13 @@ interface ShouldTrackThreadUnreadDividerArgs { } interface UseThreadUnreadDividerStateArgs { + hasFreshThread: boolean; routeThreadId: string | undefined; thread: ThreadUnreadDividerThreadState | undefined; } const NO_UNREAD_DIVIDER_STATE: ThreadUnreadDividerState = { + ready: false, autoScroll: false, placement: null, }; @@ -48,48 +51,42 @@ function shouldTrackThreadUnreadDivider({ function buildUnreadDividerPlacement( thread: ThreadUnreadDividerThreadState, ): ThreadTimelineUnreadDividerPlacement | null { - if (thread.lastReadAt === null) { - return { kind: "before-first" }; - } - if (thread.lastReadAt < thread.latestAttentionAt) { - return { kind: "after-cutoff", cutoffAt: thread.lastReadAt }; + if ( + thread.lastReadAt === null || + thread.lastReadAt >= thread.latestAttentionAt + ) { + return null; } - return null; + return { cutoffAt: thread.lastReadAt }; } function nextThreadUnreadDividerSnapshot( currentSnapshot: ThreadUnreadDividerSnapshot | null, thread: ThreadUnreadDividerThreadState, -): ThreadUnreadDividerSnapshot { + hasFreshThread: boolean, +): ThreadUnreadDividerSnapshot | null { + const isOpening = currentSnapshot?.threadId !== thread.id; + if (isOpening && !hasFreshThread) { + return null; + } if ( currentSnapshot?.threadId === thread.id && currentSnapshot.attentionAt === thread.latestAttentionAt ) { - if (thread.lastReadAt === null) { - if (currentSnapshot.placement?.kind === "before-first") { - return currentSnapshot; - } - return { - attentionAt: thread.latestAttentionAt, - autoScroll: - currentSnapshot.placement !== null && currentSnapshot.autoScroll, - placement: { kind: "before-first" }, - threadId: thread.id, - }; - } return currentSnapshot; } const placement = buildUnreadDividerPlacement(thread); return { attentionAt: thread.latestAttentionAt, - autoScroll: currentSnapshot?.threadId !== thread.id && placement !== null, + autoScroll: isOpening && placement !== null, placement, threadId: thread.id, }; } export function useThreadUnreadDividerState({ + hasFreshThread, routeThreadId, thread, }: UseThreadUnreadDividerStateArgs): ThreadUnreadDividerState { @@ -113,7 +110,11 @@ export function useThreadUnreadDividerState({ const currentSnapshot = trackedThread === null ? null - : nextThreadUnreadDividerSnapshot(snapshot, trackedThread); + : nextThreadUnreadDividerSnapshot( + snapshot, + trackedThread, + hasFreshThread, + ); if (currentSnapshot !== snapshot) { setSnapshot(currentSnapshot); } @@ -123,6 +124,7 @@ export function useThreadUnreadDividerState({ } return { + ready: true, autoScroll: currentSnapshot.autoScroll, placement: currentSnapshot.placement, }; diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index ed3c1c98f72..6e2cff21b19 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -226,7 +226,8 @@ anchor. The position changes only when: - the viewport gets narrower or wider and the anchor would leave the visible viewport, in which case the anchor moves just enough to stay on screen; - the content really shrinks, so the browser clamps a correction, and the clamp - is still there on the next frame. + is still there on the next frame; +- the view sits at the end while detached (see below). A scroll counts as the reader's during an input session: a wheel, a scroll key, a touch or pointer drag that scrolled, and the momentum that follows (up to @@ -240,12 +241,26 @@ so the app's own jump is never counted as the reader's gesture. Any other scroll that comes with a change in the scroll extent is layout, such as a clamp after content briefly shrank, and the owner reconciles it back to the position. A scroll without input or size change, such as find in page or focus moving to -an offscreen control, is navigation, and the position follows it. Moving down -into the last 4 px, or a wheel, End/PageDown or a touch drag toward the end -while at the end, attaches. A navigation, a restore, or a viewport resize that -leaves the reading position at or past the end also attaches. Moving up out of -the end detaches. Content changes never attach or detach: a detached reader -whose content shrinks onto the end stays detached until they scroll toward it. +an offscreen control, is navigation, and the position follows it. + +Attachment follows one rule: a detached view within 4 px of the end attaches, +whatever put it there, unless a restore or landing is still waiting for its row. +When the reader's scroll, a navigation, or a completed restore put it there, it +attaches at once. When only layout did, such as a row collapsing near the end +or the viewport growing, it attaches if the view is still at the end on the +next frame, so content that shrinks and regrows within a frame does not attach. +Moving up out of the end detaches. Content changes never detach. A view the +reader never placed, such as a tool output box that was not streaming when it +opened, attaches only when the reader or a navigation brings it to the end, so +output that loads in after it opens does not pull it down. + +`scroll-position-keeper.model.test.ts` checks these rules over random sequences +of reader scrolls, touch gestures, toggles, streaming, prepends, regroups, +transient shrinks, resizes, navigations, and restores, with and without iOS +write deferral: attached exactly when at the end, content changes never detach, +the reading row never moves without the reader unless the content cannot hold +it, and a reader's scroll is never moved. It runs 200 sequences by default; set +`KEEPER_MODEL_SEEDS` for a deeper local run. Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout @@ -314,5 +329,30 @@ at the bottom for up to a second. The timeline keeps the loaded pages of the eight most recent threads for each query client, so a position in older history survives a thread switch. +Opening an unread thread decides its landing once, from the first copy of the +thread fetched after it opens, not a cached one, and the rows loaded at that +moment. Automatic read tracking waits for that opening snapshot, so sidebar +placeholder data cannot mark the thread read before its unread cutoff is saved. +If the read cutoff falls inside the loaded rows, the NEW divider is +placed and the owner lands on it through the restore path, with the divider as +the anchor at the top of the viewport, so rows that render or resize around it +afterwards do not move it. Otherwise, and for a thread marked unread, there is +no divider and the saved position or the bottom stands. No older pages are +loaded to find the cutoff, and a divider dropped this way stays dropped when +the reader pages back. A reader who scrolls before the landing keeps their +position. + +`thread-opening.model.test.tsx` checks the landing end to end. It renders the +timeline with the thread view's own loading and automatic read-tracking hooks, +including cached sidebar placeholders, against a fake server that +pages a random history, opens or returns to the thread with random read +states, page sizes, and time away, and resolves the bootstrap, thread, and +timeline requests in random orders, sometimes with the reader scrolling while +they load. Once settled, NEW must sit above the first unread row of the whole +history, must be at the top unless the reader scrolled or the view is at the +end, and must show whenever the read cutoff is inside the first page; +otherwise the saved position or the bottom stands. It runs 40 sequences by +default; set `OPENING_MODEL_SEEDS` for more. + Content shorter than the viewport is top-aligned. In that case a row that expands moves the rows below it, including the latest row.