From 48ad8f9d794f4f60faf74fb5f0878a463ab63b4e Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Tue, 20 Oct 2026 18:31:05 -0700 Subject: [PATCH 1/7] Rebuild iOS timeline windowing on the ScrollPositionKeeper Window timeline lists on iOS WebKit too. ScrollPositionKeeper (#5879) stays the only scroll writer, and it gains a hold mode for iOS. While a finger is down, momentum is running, or the edge is bouncing, it keeps the correction as a transform on the scroll content. It writes the correction to scrollTop once scrolling has been still for 150 ms. TanStack reads scrollTop plus the held offset, so the window matches what is on screen. Also: - Upgrade @tanstack/react-virtual to 3.14.20 (virtual-core 3.19.5) and drop the virtual-core 3.17.1 patch, which is fixed upstream. - Restore the saved reading row when a detached reader's scrollport changes width (iPad rotation), clamped to the row's new height. - Re-read the live scroll extent before treating a position past the cached extent as a return to the bottom. - While a saved-row restore waits for its row, park at the bottom instead of the scroll root's initial position. That position could keep loading older pages, all the way to the start of the thread. - Document browser scroll ownership in docs/timeline-pagination.md. Co-Authored-By: Claude Opus 5.5 --- apps/app/package.json | 2 +- .../ThreadTimelineRows.windowing.test.tsx | 2 +- .../timeline/TimelineWindowedItems.test.tsx | 29 ++- .../thread/timeline/TimelineWindowedItems.tsx | 30 ++- .../thread/timeline/useStickyBottomScroll.ts | 11 +- ...d-scroll-body.scroll-preservation.test.tsx | 210 +++++++++++++++--- .../ui/bottom-anchored-scroll-body.tsx | 129 ++++++++++- .../ui/scroll-position-keeper.test.ts | 112 +++++++++- .../components/ui/scroll-position-keeper.ts | 124 ++++++++++- apps/app/src/test/scroll-position-keeper.ts | 2 + docs/timeline-pagination.md | 37 +++ package.json | 1 - patches/@tanstack__virtual-core@3.17.1.patch | 114 ---------- pnpm-lock.yaml | 21 +- 14 files changed, 632 insertions(+), 192 deletions(-) delete mode 100644 patches/@tanstack__virtual-core@3.17.1.patch diff --git a/apps/app/package.json b/apps/app/package.json index 27aeff1a011..b23a8aec9d0 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -53,7 +53,7 @@ "@radix-ui/react-slot": "^1.3.0", "@radix-ui/react-tooltip": "^1.2.12", "@tanstack/react-query": "^5.62.0", - "@tanstack/react-virtual": "^3.14.2", + "@tanstack/react-virtual": "3.14.20", "@tiptap/core": "^3.26.0", "@tiptap/extension-blockquote": "^3.26.0", "@tiptap/extension-document": "^3.26.0", 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..96123593540 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx @@ -220,7 +220,7 @@ describe("ThreadTimelineRows windowing", () => { expect(view.container.textContent).toContain( `Window message ${count - 1}`, ); - if (count < 20 || iPhone) { + if (count < 20) { expect(mountedRows.length).toBe(count); expect( view.container.querySelector("[data-timeline-virtual-spacer]"), diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx index eb5e530493b..3d658376ebb 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx @@ -10,6 +10,7 @@ import { } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AutoHeightSnapContext } from "@/components/ui/height-transition"; +import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; import { TimelineWindowedItems, type TimelineWindowedItemRenderState, @@ -19,6 +20,7 @@ const ITEM_KEYS = Array.from({ length: 100 }, (_, index) => `row-${index}`); let scrollElement: HTMLDivElement; let itemHeights = new Map(); +let renderedShift = 0; function rect(top: number, height: number): DOMRect { return { @@ -89,6 +91,7 @@ function renderWindowedItems(options?: { measurements?: Map; snapAutoHeight?: () => void; pinnedToEnd?: boolean; + positionKeeper?: ScrollPositionKeeper; }) { const measurements = options?.measurements ?? new Map(); Object.defineProperty(scrollElement, "clientHeight", { @@ -109,7 +112,7 @@ function renderWindowedItems(options?: { getScrollElement={() => scrollElement} itemKeys={ITEM_KEYS} measurements={measurements} - positionKeeper={null} + positionKeeper={options?.positionKeeper ?? null} pinnedToEnd={options?.pinnedToEnd ?? false} renderItem={( index: number, @@ -138,6 +141,7 @@ function renderWindowedItems(options?: { beforeEach(() => { itemHeights = new Map(); + renderedShift = 0; scrollElement = document.createElement("div"); document.body.append(scrollElement); Object.defineProperty(scrollElement, "clientWidth", { @@ -157,14 +161,14 @@ beforeEach(() => { if (this === scrollElement) return rect(0, scrollElement.clientHeight); if (this.hasAttribute("data-timeline-virtual-spacer")) { return rect( - -scrollElement.scrollTop, + -scrollElement.scrollTop - renderedShift, Number.parseFloat(this.style.height) || 0, ); } const index = Number(this.dataset.index); if (Number.isInteger(index)) { return rect( - index * 32 - scrollElement.scrollTop, + index * 32 - scrollElement.scrollTop - renderedShift, itemHeights.get(index) ?? 32, ); } @@ -316,6 +320,25 @@ describe("TimelineWindowedItems", () => { ).toBeNull(); }); + it("windows around the reader's rendered position while the keeper holds a correction", async () => { + const positionKeeper = new ScrollPositionKeeper({ + deferWritesWhileScrolling: true, + getDeferredOffsetElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => [], + isActive: () => true, + }); + vi.spyOn(positionKeeper, "getDeferredOffset").mockReturnValue(1_600); + renderedShift = 1_600; + renderWindowedItems({ positionKeeper }); + + fireEvent.scroll(scrollElement); + + await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); + expect(screen.queryByTestId("content-0")).toBeNull(); + expect(scrollElement.scrollTop).toBe(0); + }); + it("mounts only the visible TanStack range and removes offscreen wrappers", async () => { renderWindowedItems(); diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index 147caf7b95b..34657cfab95 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -20,7 +20,6 @@ import { } from "@tanstack/react-virtual"; import { AutoHeightSnapContext } from "@/components/ui/height-transition"; import type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; -import { isIOSWebKit } from "@/lib/ios-webkit"; export const DEFAULT_WINDOWING_MIN_ITEM_COUNT = 20; const MAX_MEASUREMENTS = 2_000; @@ -113,11 +112,7 @@ export function TimelineWindowedItems({ renderItem, pinnedToEnd, }: TimelineWindowedItemsProps) { - const [scrollAdjustmentsKeepMomentum] = useState( - () => typeof navigator === "undefined" || !isIOSWebKit(navigator), - ); const configured = - scrollAdjustmentsKeepMomentum && itemKeys.length >= DEFAULT_WINDOWING_MIN_ITEM_COUNT && getScrollElement !== null; const [scrollRootStatus, setScrollRootStatus] = useState< @@ -188,7 +183,12 @@ export function TimelineWindowedItems({ ); const initialOffset = useCallback(() => { const scrollElement = resolvedGetScrollElement(); - if (!pinnedToEnd) return scrollElement?.scrollTop ?? 0; + if (!pinnedToEnd) { + return ( + (scrollElement?.scrollTop ?? 0) + + (positionKeeper?.getDeferredOffset() ?? 0) + ); + } let estimatedEnd = scrollMargin; for (let index = 0; index < itemKeys.length; index += 1) { estimatedEnd += estimateSize(index) + (index > 0 ? gap : 0); @@ -200,6 +200,7 @@ export function TimelineWindowedItems({ gap, initialRect, itemKeys, + positionKeeper, resolvedGetScrollElement, scrollMargin, pinnedToEnd, @@ -219,11 +220,19 @@ export function TimelineWindowedItems({ ); const observeOffset = useCallback>( (instance, callback) => { - const unobserve = observeElementOffset(instance, callback); + const unobserve = observeElementOffset(instance, (offset, isScrolling) => + callback( + offset + (positionKeeper?.getDeferredOffset() ?? 0), + isScrolling, + ), + ); const unsubscribe = positionKeeper?.subscribeScrollWrites(() => { const scrollElement = instance.scrollElement; if (scrollElement !== null) { - callback(scrollElement.scrollTop, instance.isScrolling); + callback( + scrollElement.scrollTop + positionKeeper.getDeferredOffset(), + instance.isScrolling, + ); } }); return () => { @@ -310,11 +319,12 @@ export function TimelineWindowedItems({ container.getBoundingClientRect().top - scrollElement.getBoundingClientRect().top + scrollElement.scrollTop - - scrollElement.clientTop; + scrollElement.clientTop + + (positionKeeper?.getDeferredOffset() ?? 0); setScrollMargin((previous) => Math.abs(previous - nextMargin) < 0.5 ? previous : nextMargin, ); - }, [configured, resolvedGetScrollElement]); + }, [configured, positionKeeper, resolvedGetScrollElement]); useLayoutEffect(() => { if (!configured) return; diff --git a/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts b/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts index 7dc03d83f8f..cc3a45d6828 100644 --- a/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts +++ b/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts @@ -13,6 +13,7 @@ import { ScrollPositionKeeper, getDirectTimelineRows, } from "@/components/ui/scroll-position-keeper"; +import { isIOSWebKit } from "@/lib/ios-webkit"; interface StickyBottomScrollBinding { contentRef: RefObject; @@ -72,6 +73,8 @@ export function useStickyBottomScroll({ const [positionKeeper] = useState( () => new ScrollPositionKeeper({ + deferWritesWhileScrolling: isIOSWebKit(navigator), + getDeferredOffsetElement: () => contentRef.current, getScrollElement: () => scrollRef.current, getTopLevelRows, isActive: () => !shouldStickToBottomRef.current, @@ -88,7 +91,8 @@ export function useStickyBottomScroll({ const element = scrollRef.current; if (!element) return; refreshMaxScrollOffset(element); - if (typeof ResizeObserver === "undefined") return; + const unobserveTouches = positionKeeper.observeTouches(element); + if (typeof ResizeObserver === "undefined") return unobserveTouches; const observer = new ResizeObserver(() => { positionKeeper.reconcile(); @@ -100,7 +104,10 @@ export function useStickyBottomScroll({ if (content) { observer.observe(content); } - return () => observer.disconnect(); + return () => { + unobserveTouches(); + observer.disconnect(); + }; }, [positionKeeper, refreshMaxScrollOffset]); useEffect(() => { diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.scroll-preservation.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.scroll-preservation.test.tsx index c84f27b439c..a6d3c63d269 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.scroll-preservation.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.scroll-preservation.test.tsx @@ -39,8 +39,8 @@ class ResizeObserverMock implements ResizeObserver { } unobserve() {} disconnect() {} - trigger() { - this.callback(this.targets.map(makeResizeEntry), this); + trigger(entries = this.targets.map(makeResizeEntry)) { + this.callback(entries, this); } } @@ -368,6 +368,91 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { expect(scrollArea.hasAttribute("data-scrollbar-scrolling")).toBe(false); }); + it("does not resume bottom following when a correction exceeds the cached scroll extent", () => { + const { scrollArea } = renderTimeline({ + threadId: "thread-a", + rowIds: ["row-a", "row-b"], + }); + setScrollMetrics(scrollArea, { + scrollHeight: 1_000, + clientHeight: 100, + scrollTop: 900, + }); + getLatestResizeObserver().trigger(); + scrollArea.scrollTop = 400; + fireEvent.wheel(scrollArea, { deltaY: -500 }); + fireEvent.scroll(scrollArea); + + setScrollMetrics(scrollArea, { + scrollHeight: 3_000, + clientHeight: 100, + scrollTop: 2_400, + }); + fireEvent.scroll(scrollArea); + getLatestResizeObserver().trigger(); + + expect(scrollArea.scrollTop).toBe(2_400); + }); + + it("restores the reading row after a width change clamps the viewport to the end", () => { + const { scrollArea, getRow } = renderTimeline({ + threadId: "thread-a", + rowIds: ["row-a", "row-b"], + }); + let width = 100; + Object.defineProperty(scrollArea, "clientWidth", { + configurable: true, + get: () => width, + }); + mockScrollAreaRect(scrollArea); + vi.spyOn(getRow("row-a"), "getBoundingClientRect").mockImplementation( + () => + new DOMRect(0, -scrollArea.scrollTop, width, width === 100 ? 380 : 100), + ); + vi.spyOn(getRow("row-b"), "getBoundingClientRect").mockImplementation( + () => + new DOMRect( + 0, + (width === 100 ? 380 : 100) - scrollArea.scrollTop, + width, + 200, + ), + ); + setScrollMetrics(scrollArea, { + scrollHeight: 1_000, + clientHeight: 100, + scrollTop: 900, + }); + const observer = getLatestResizeObserver(); + observer.trigger(); + scrollArea.scrollTop = 400; + fireEvent.wheel(scrollArea, { deltaY: -500 }); + fireEvent.scroll(scrollArea); + expect(readAnchor("thread-a")).toMatchObject({ + rowId: "row-b", + offsetWithinRow: 20, + atBottom: false, + }); + + width = 200; + setScrollMetrics(scrollArea, { + scrollHeight: 400, + clientHeight: 100, + scrollTop: 300, + }); + fireEvent.scroll(scrollArea); + const entries = observer.targets.map((target) => { + const entry = makeResizeEntry(target); + return target === scrollArea + ? { ...entry, contentBoxSize: [{ blockSize: 100, inlineSize: 200 }] } + : entry; + }); + act(() => observer.trigger(entries)); + + expect(scrollArea.scrollTop).toBe(120); + expect(getRow("row-b").getBoundingClientRect().top).toBe(-20); + }); + it("captures the top-most visible row when scrolled mid-timeline", () => { const { scrollArea, rowElements } = renderTimeline({ threadId: "thread-a", @@ -679,6 +764,39 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { expect(scrollArea.scrollTop).toBe(300); }); + it("waits at the bottom until the saved row renders, then restores it", () => { + getDefaultStore().set(threadTimelineScrollAnchorAtomFamily("thread-a"), { + rowId: "row-late", + offsetWithinRow: 20, + atBottom: false, + }); + + const { scrollArea, rerenderRows, getRow } = renderTimeline({ + threadId: "thread-a", + rowIds: ["row-a", "row-b"], + }); + mockScrollAreaRect(scrollArea); + setScrollMetrics(scrollArea, { + scrollHeight: 400, + clientHeight: 100, + scrollTop: 0, + }); + + getLatestResizeObserver().trigger(); + expect(scrollArea.scrollTop).toBe(300); + + rerenderRows(["row-late", "row-a", "row-b"]); + mockRowRect(getRow("row-late"), { top: -250, bottom: -150 }); + setScrollMetrics(scrollArea, { + scrollHeight: 500, + clientHeight: 100, + scrollTop: 300, + }); + getLatestResizeObserver().trigger(); + + expect(scrollArea.scrollTop).toBe(70); + }); + it.each(["bottom", "message", "clamped message"])( "does not let a pending saved-row restore undo an explicit %s scroll", (destination) => { @@ -930,18 +1048,30 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { rowIds: ["row-a", "row-b", "row-c"], }); mockScrollAreaRect(scrollArea); - mockRowRect(requireHTMLElement(rowElements.get("row-a")!), { - top: -120, - bottom: -20, - }); - mockRowRect(requireHTMLElement(rowElements.get("row-b")!), { - top: -20, - bottom: 80, - }); - mockRowRect(requireHTMLElement(rowElements.get("row-c")!), { - top: 80, - bottom: 180, - }); + mockRowRect( + requireHTMLElement(rowElements.get("row-a")!), + { + top: -120, + bottom: -20, + }, + 300, + ); + mockRowRect( + requireHTMLElement(rowElements.get("row-b")!), + { + top: -20, + bottom: 80, + }, + 300, + ); + mockRowRect( + requireHTMLElement(rowElements.get("row-c")!), + { + top: 80, + bottom: 180, + }, + 300, + ); setScrollMetrics(scrollArea, { scrollHeight: 400, clientHeight: 100, @@ -979,8 +1109,8 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { expect(readScrollHeight).not.toHaveBeenCalled(); expect(readClientHeight).not.toHaveBeenCalled(); expect(readAnchor("thread-a")).toEqual({ - rowId: "row-b", - offsetWithinRow: 20, + rowId: "row-a", + offsetWithinRow: 0, atBottom: false, }); setScrollMetrics(scrollArea, { @@ -1043,14 +1173,22 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { rowIds: ["row-a", "row-b", "row-c"], }); mockScrollAreaRect(scrollArea); - mockRowRect(requireHTMLElement(rowElements.get("row-a")!), { - top: -120, - bottom: -20, - }, 100); - mockRowRect(requireHTMLElement(rowElements.get("row-b")!), { - top: -20, - bottom: 80, - }, 100); + mockRowRect( + requireHTMLElement(rowElements.get("row-a")!), + { + top: -120, + bottom: -20, + }, + 100, + ); + mockRowRect( + requireHTMLElement(rowElements.get("row-b")!), + { + top: -20, + bottom: 80, + }, + 100, + ); mockRowRect( requireHTMLElement(rowElements.get("row-c")!), { top: 80, bottom: 180 }, @@ -1111,14 +1249,22 @@ describe("BottomAnchoredScrollBody scroll preservation", () => { rowIds: ["row-a", "row-b", "row-c"], }); mockScrollAreaRect(scrollArea); - mockRowRect(requireHTMLElement(rowElements.get("row-a")!), { - top: -120, - bottom: -20, - }, 150); - mockRowRect(requireHTMLElement(rowElements.get("row-b")!), { - top: -20, - bottom: 80, - }, 150); + mockRowRect( + requireHTMLElement(rowElements.get("row-a")!), + { + top: -120, + bottom: -20, + }, + 150, + ); + mockRowRect( + requireHTMLElement(rowElements.get("row-b")!), + { + top: -20, + bottom: 80, + }, + 150, + ); mockRowRect( requireHTMLElement(rowElements.get("row-c")!), { top: 80, bottom: 180 }, 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 91a40fd9ff0..00b39231a7b 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx @@ -16,6 +16,7 @@ import { usePointerCoarse } from "@bb/shared-ui/hooks/use-pointer-coarse"; import { PAGE_SHELL_CONTENT_STYLE } from "./page-shell-content-style.js"; import { supportsScrollAnchoring } from "@/lib/scroll-anchoring-support"; import { PAGE_SCROLL_TO_TOP_EVENT } from "@/lib/page-scroll-to-top"; +import { isIOSWebKit } from "@/lib/ios-webkit"; import { threadTimelineScrollAnchorAtomFamily, type ScrollAnchor, @@ -235,6 +236,7 @@ export function BottomAnchoredScrollBody({ const isPointerCoarse = usePointerCoarse(); const scrollAreaRef = useRef(null); const scrollContentRef = useRef(null); + const pageContentRef = useRef(null); const scrollFooterRef = useRef(null); const hasFooter = Boolean(footer); const shouldStickToBottomRef = useRef(true); @@ -248,6 +250,7 @@ export function BottomAnchoredScrollBody({ anchor: ScrollAnchor; attemptsRemaining: number; lastAppliedScrollTop: number | null; + clampToRow: boolean; } | null>(null); const contentPositionHoldUntilRef = useRef(0); const scrollAnchorCaptureThrottleRef = useRef<{ @@ -259,10 +262,24 @@ export function BottomAnchoredScrollBody({ const resizeObserverHasDeliveredRef = useRef(false); const observedScrollGeometryRef = useRef<{ scrollAreaClientHeight: number | null; + scrollAreaClientWidth: number | null; scrollContentHeight: number | null; - }>({ scrollAreaClientHeight: null, scrollContentHeight: null }); + }>({ + scrollAreaClientHeight: null, + scrollAreaClientWidth: null, + scrollContentHeight: null, + }); const scrollAnchorRowsRef = useRef | null>(null); const [isAtBottom, setIsAtBottom] = useState(true); + const [viewportRestore, setViewportRestore] = useState<{ + threadId: string; + rowId: string; + } | null>(null); + const viewportRestoreRowId = + viewportRestore !== null && + viewportRestore.threadId === scrollAnchorThreadId + ? viewportRestore.rowId + : null; const initialScrollRestoreRowId = useMemo(() => { if (scrollAnchorThreadId === undefined) return null; const anchor = store.get( @@ -293,6 +310,8 @@ export function BottomAnchoredScrollBody({ const [positionKeeper] = useState( () => new ScrollPositionKeeper({ + deferWritesWhileScrolling: isIOSWebKit(navigator), + getDeferredOffsetElement: () => pageContentRef.current, getScrollElement: () => scrollAreaRef.current, getTopLevelRows: getScrollAnchorRowsCached, isActive: () => @@ -301,6 +320,17 @@ export function BottomAnchoredScrollBody({ }), ); + const viewportWidthChanged = useCallback((scrollArea: HTMLElement) => { + const previousWidth = + observedScrollGeometryRef.current.scrollAreaClientWidth; + return ( + previousWidth !== null && + previousWidth > 0 && + scrollArea.clientWidth > 0 && + Math.abs(previousWidth - scrollArea.clientWidth) > 1 + ); + }, []); + const refreshMaxScrollOffset = useCallback((scrollArea: HTMLElement) => { const maxScrollOffset = getMaxScrollOffset(scrollArea); maxScrollOffsetRef.current = maxScrollOffset; @@ -492,12 +522,23 @@ export function BottomAnchoredScrollBody({ (scrollAreaOverride?: HTMLElement) => { if (scrollAnchorThreadId === undefined) return; const scrollArea = scrollAreaOverride ?? scrollAreaRef.current; - if (!scrollArea) return; + if ( + !scrollArea || + viewportWidthChanged(scrollArea) || + pendingScrollRestoreRef.current !== null + ) { + return; + } let atBottomByGeometry = isScrolledNearBottom( readMaxScrollOffset(scrollArea), scrollArea.scrollTop, ); - if (!atBottomByGeometry && shouldStickToBottomRef.current) { + if ( + (atBottomByGeometry && + scrollArea.scrollTop > + maxScrollOffsetRef.current + BOTTOM_ANCHOR_THRESHOLD_PX) || + (!atBottomByGeometry && shouldStickToBottomRef.current) + ) { atBottomByGeometry = isScrolledNearBottom( refreshMaxScrollOffset(scrollArea), scrollArea.scrollTop, @@ -547,6 +588,7 @@ export function BottomAnchoredScrollBody({ refreshMaxScrollOffset, scrollAnchorThreadId, store, + viewportWidthChanged, ], ); @@ -573,7 +615,7 @@ export function BottomAnchoredScrollBody({ }, [scrollAnchorCaptureThrottleMs, scrollAnchorThreadId, writeScrollAnchor]); const applyScrollRestore = useCallback( - (anchor: ScrollAnchor): number | null => { + (anchor: ScrollAnchor, clampToRow: boolean): number | null => { const scrollArea = scrollAreaRef.current; if (!scrollArea) return null; const rowElement = findTimelineRowElement(scrollArea, anchor.rowId); @@ -587,7 +629,13 @@ export function BottomAnchoredScrollBody({ }); const targetScrollTop = Math.min( refreshMaxScrollOffset(scrollArea), - revealOffset + anchor.offsetWithinRow, + revealOffset + + (clampToRow + ? Math.min( + anchor.offsetWithinRow, + Math.max(0, rowElement.getBoundingClientRect().height - 1), + ) + : anchor.offsetWithinRow), ); scrollArea.scrollTop = targetScrollTop; return targetScrollTop; @@ -718,6 +766,14 @@ export function BottomAnchoredScrollBody({ const scrollArea = scrollAreaRef.current; if (!scrollArea) return; + if ( + !hasRecentUserScrollIntent() && + (viewportWidthChanged(scrollArea) || + pendingScrollRestoreRef.current !== null) + ) { + return; + } + if (scrollToTopInProgressRef.current) { if (scrollArea.scrollTop <= 0) scrollToTopInProgressRef.current = false; return; @@ -728,9 +784,12 @@ export function BottomAnchoredScrollBody({ scrollArea.scrollTop, ); if ( - !nearBottom && - shouldStickToBottomRef.current && - hasRecentUserScrollIntent() + (nearBottom && + scrollArea.scrollTop > + maxScrollOffsetRef.current + BOTTOM_ANCHOR_THRESHOLD_PX) || + (!nearBottom && + shouldStickToBottomRef.current && + hasRecentUserScrollIntent()) ) { nearBottom = isScrolledNearBottom( refreshMaxScrollOffset(scrollArea), @@ -756,6 +815,7 @@ export function BottomAnchoredScrollBody({ hasRecentUserScrollIntent, readMaxScrollOffset, refreshMaxScrollOffset, + viewportWidthChanged, ]); const handleScroll = useCallback(() => { @@ -769,13 +829,19 @@ export function BottomAnchoredScrollBody({ const pending = pendingScrollRestoreRef.current; if (!pending) return false; pending.attemptsRemaining -= 1; - const appliedScrollTop = applyScrollRestore(pending.anchor); + const appliedScrollTop = applyScrollRestore( + pending.anchor, + pending.clampToRow, + ); if (appliedScrollTop !== null) { if (pending.lastAppliedScrollTop === appliedScrollTop) { pendingScrollRestoreRef.current = null; return true; } pending.lastAppliedScrollTop = appliedScrollTop; + } else if (pending.lastAppliedScrollTop === null) { + const scrollArea = scrollAreaRef.current; + if (scrollArea) scrollArea.scrollTop = refreshMaxScrollOffset(scrollArea); } if (pending.attemptsRemaining <= 0) { pendingScrollRestoreRef.current = null; @@ -786,7 +852,7 @@ export function BottomAnchoredScrollBody({ } } return true; - }, [applyScrollRestore, queueBottomRestore]); + }, [applyScrollRestore, queueBottomRestore, refreshMaxScrollOffset]); const handleScrollAreaResize = useCallback( (entries: ResizeObserverEntry[]) => { @@ -798,8 +864,11 @@ export function BottomAnchoredScrollBody({ const previousMaxScrollOffset = maxScrollOffsetRef.current; const cacheWasAuthoritative = resizeObserverHasDeliveredRef.current; const observedGeometry = observedScrollGeometryRef.current; + const previousWidth = observedGeometry.scrollAreaClientWidth; for (const entry of entries) { if (entry.target === scrollArea) { + observedGeometry.scrollAreaClientWidth = + entry.contentBoxSize[0]?.inlineSize ?? entry.contentRect.width; observedGeometry.scrollAreaClientHeight = entry.contentBoxSize[0]?.blockSize ?? entry.contentRect.height; } else if (entry.target === scrollContentRef.current) { @@ -807,6 +876,32 @@ export function BottomAnchoredScrollBody({ entry.borderBoxSize[0]?.blockSize ?? entry.contentRect.height; } } + const widthChanged = + previousWidth !== null && + previousWidth > 0 && + observedGeometry.scrollAreaClientWidth !== null && + Math.abs(previousWidth - observedGeometry.scrollAreaClientWidth) > 1; + if ( + widthChanged && + !shouldStickToBottomRef.current && + scrollAnchorThreadId !== undefined + ) { + const anchor = store.get( + threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId), + ); + if (anchor && !anchor.atBottom) { + pendingScrollRestoreRef.current = { + anchor, + attemptsRemaining: SCROLL_ANCHOR_RESTORE_MAX_ATTEMPTS, + lastAppliedScrollTop: null, + clampToRow: true, + }; + setViewportRestore({ + threadId: scrollAnchorThreadId, + rowId: anchor.rowId, + }); + } + } let maxScrollOffset: number; if ( observedGeometry.scrollAreaClientHeight !== null && @@ -824,6 +919,7 @@ export function BottomAnchoredScrollBody({ resizeObserverHasDeliveredRef.current = true; shrankOntoBottomWhileDetached = cacheWasAuthoritative && + !widthChanged && !shouldStickToBottomRef.current && maxScrollOffset < previousMaxScrollOffset && isScrolledNearBottom(maxScrollOffset, scrollArea.scrollTop); @@ -849,7 +945,9 @@ export function BottomAnchoredScrollBody({ positionKeeper, queueBottomRestore, refreshMaxScrollOffset, + scrollAnchorThreadId, settleContentPositionHold, + store, writeScrollAnchor, ], ); @@ -866,10 +964,15 @@ export function BottomAnchoredScrollBody({ anchor, attemptsRemaining: SCROLL_ANCHOR_RESTORE_MAX_ATTEMPTS, lastAppliedScrollTop: null, + clampToRow: false, }; advancePendingScrollRestore(); }, [scrollAnchorThreadId, store, advancePendingScrollRestore]); + useLayoutEffect(() => { + if (viewportRestore !== null) advancePendingScrollRestore(); + }, [viewportRestore, advancePendingScrollRestore]); + const bottomAnchorContextValue = useMemo( () => ({ getScrollElement, @@ -968,6 +1071,7 @@ export function BottomAnchoredScrollBody({ handleScroll(); }; + const unobserveTouches = positionKeeper.observeTouches(scrollArea); let resizeObserver: ResizeObserver | undefined; if (typeof ResizeObserver !== "undefined") { resizeObserver = new ResizeObserver(handleScrollAreaResize); @@ -997,6 +1101,7 @@ export function BottomAnchoredScrollBody({ queueBottomRestore(); return () => { + unobserveTouches(); resizeObserver?.disconnect(); scrollArea.removeEventListener("scroll", handleScrollEvent); scrollArea.removeEventListener("wheel", markWheelScrollIntent); @@ -1021,6 +1126,7 @@ export function BottomAnchoredScrollBody({ markTouchMoveScrollIntent, markTouchStartScrollIntent, markWheelScrollIntent, + positionKeeper, queueBottomRestore, startPointerScrollIntent, ]); @@ -1028,7 +1134,7 @@ export function BottomAnchoredScrollBody({ return (
@@ -1046,6 +1152,7 @@ export function BottomAnchoredScrollBody({ > {}
+ Math.max( + VIEWPORT_HEIGHT, + rows.reduce((total, row) => total + row.height, 0), + ), + }); vi.spyOn(scrollElement, "getBoundingClientRect").mockReturnValue( new DOMRect(0, 0, 100, VIEWPORT_HEIGHT), ); @@ -46,7 +64,12 @@ function createTimeline(initialRows: LaidOutRow[]) { const offset = offsets.get(id); return offset === undefined ? new DOMRect(0, 0, 0, 0) - : new DOMRect(0, offset.top - scrollTop, 100, offset.height); + : new DOMRect( + 0, + offset.top - scrollTop + translatedOffset(list), + 100, + offset.height, + ); }); return element; }; @@ -75,6 +98,8 @@ function createTimeline(initialRows: LaidOutRow[]) { const keeperOptions = { active: true }; const keeper = new ScrollPositionKeeper({ + deferWritesWhileScrolling, + getDeferredOffsetElement: () => list, getScrollElement: () => scrollElement, getTopLevelRows: () => Array.from(list.children).filter( @@ -93,6 +118,9 @@ function createTimeline(initialRows: LaidOutRow[]) { scrollTo(value: number) { scrollTop = value; }, + get translatedOffset() { + return translatedOffset(list); + }, setRows(next: LaidOutRow[]) { rows = next; layout(); @@ -100,7 +128,7 @@ function createTimeline(initialRows: LaidOutRow[]) { viewportTopOf(id: string) { const offset = offsets.get(id); if (offset === undefined) throw new Error(`No row ${id}`); - return offset.top - scrollTop; + return offset.top - scrollTop + translatedOffset(list); }, }; } @@ -113,6 +141,7 @@ function rowsOf(count: number, height = 200, prefix = "row"): LaidOutRow[] { } afterEach(() => { + vi.useRealTimers(); document.body.replaceChildren(); vi.restoreAllMocks(); }); @@ -262,4 +291,81 @@ describe("ScrollPositionKeeper", () => { expect(timeline.viewportTopOf("row-6") + 50).toBe(bottomBefore); }); + + it("holds a correction in the rendered position while a touch is down and writes it after scrolling settles", () => { + vi.useFakeTimers(); + const timeline = createTimeline(rowsOf(10), { + deferWritesWhileScrolling: true, + }); + const unobserve = timeline.keeper.observeTouches(timeline.scrollElement); + timeline.scrollTo(900); + timeline.keeper.handleScroll(); + const before = timeline.viewportTopOf("row-5"); + timeline.scrollElement.dispatchEvent(new Event("touchstart")); + + timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + timeline.keeper.reconcile(); + + expect(timeline.scrollTop).toBe(900); + expect(timeline.translatedOffset).toBe(-1_200); + expect(timeline.keeper.getDeferredOffset()).toBe(1_200); + expect(timeline.viewportTopOf("row-5")).toBe(before); + + timeline.scrollElement.dispatchEvent(new Event("touchend")); + vi.advanceTimersByTime(200); + + expect(timeline.scrollTop).toBe(2_100); + expect(timeline.translatedOffset).toBe(0); + expect(timeline.keeper.getDeferredOffset()).toBe(0); + expect(timeline.viewportTopOf("row-5")).toBe(before); + unobserve(); + }); + + it("keeps holding while momentum moves the reader and keeps the distance it coasted", () => { + vi.useFakeTimers(); + const timeline = createTimeline(rowsOf(10), { + deferWritesWhileScrolling: true, + }); + timeline.scrollTo(900); + timeline.keeper.handleScroll(); + vi.advanceTimersByTime(200); + const before = timeline.viewportTopOf("row-5"); + + timeline.scrollTo(850); + timeline.keeper.handleScroll(); + timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + timeline.keeper.reconcile(); + for (const scrollTop of [800, 750, 700]) { + vi.advanceTimersByTime(100); + timeline.scrollTo(scrollTop); + timeline.keeper.handleScroll(); + expect(timeline.translatedOffset).toBe(-1_200); + } + vi.advanceTimersByTime(400); + + expect(timeline.translatedOffset).toBe(0); + expect(timeline.scrollTop).toBe(1_900); + expect(timeline.viewportTopOf("row-5")).toBe(before + 200); + }); + + it("writes a held correction before it stops keeping the position", () => { + vi.useFakeTimers(); + const timeline = createTimeline(rowsOf(10), { + deferWritesWhileScrolling: true, + }); + timeline.scrollTo(900); + timeline.keeper.handleScroll(); + timeline.scrollTo(850); + timeline.keeper.handleScroll(); + timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + timeline.keeper.reconcile(); + const before = timeline.viewportTopOf("row-5"); + + timeline.keeperOptions.active = false; + timeline.keeper.capture(); + + expect(timeline.translatedOffset).toBe(0); + expect(timeline.scrollTop).toBe(2_050); + expect(timeline.viewportTopOf("row-5")).toBe(before); + }); }); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index 36169030687..df6346cb8ef 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -18,6 +18,8 @@ type KeptAnchor = }; interface ScrollPositionKeeperOptions { + deferWritesWhileScrolling: boolean; + getDeferredOffsetElement: () => HTMLElement | null; getScrollElement: () => HTMLElement | null; getTopLevelRows: (scrollElement: HTMLElement) => ArrayLike; isActive: () => boolean; @@ -30,6 +32,8 @@ const DIRECT_ROW_SELECTOR = [ `:scope > [data-timeline-items] > ${ROW_SELECTOR}`, ].join(", "); const MIN_CORRECTION_PX = 0.5; +const SCROLL_SETTLE_MS = 150; +const TOUCH_LISTENER_OPTIONS = { capture: true, passive: true } as const; export function getDirectTimelineRows( list: Element, @@ -55,6 +59,12 @@ export class ScrollPositionKeeper { private readonly rowOffsetSources = new Set(); private readonly writeListeners = new Set<() => void>(); private overflowAnchorDisabled = false; + private deferredOffset = 0; + private deferredOffsetElement: HTMLElement | null = null; + private touching = false; + private observedScrollTop: number | null = null; + private scrollMovedAt = Number.NEGATIVE_INFINITY; + private settleTimeout: number | null = null; constructor(options: ScrollPositionKeeperOptions) { this.options = options; @@ -64,6 +74,41 @@ export class ScrollPositionKeeper { return this.options.isActive(); } + getDeferredOffset(): number { + return this.deferredOffset; + } + + observeTouches(scrollElement: HTMLElement): () => void { + const start = () => { + this.touching = true; + }; + const end = () => { + this.touching = false; + this.scheduleDeferredWrite(); + }; + scrollElement.addEventListener("touchstart", start, TOUCH_LISTENER_OPTIONS); + scrollElement.addEventListener("touchend", end, TOUCH_LISTENER_OPTIONS); + scrollElement.addEventListener("touchcancel", end, TOUCH_LISTENER_OPTIONS); + return () => { + scrollElement.removeEventListener( + "touchstart", + start, + TOUCH_LISTENER_OPTIONS, + ); + scrollElement.removeEventListener("touchend", end, TOUCH_LISTENER_OPTIONS); + scrollElement.removeEventListener( + "touchcancel", + end, + TOUCH_LISTENER_OPTIONS, + ); + this.touching = false; + if (this.settleTimeout !== null) { + window.clearTimeout(this.settleTimeout); + this.settleTimeout = null; + } + }; + } + registerRowOffsetSource(source: ScrollRowOffsetSource): () => void { this.rowOffsetSources.add(source); return () => { @@ -105,7 +150,9 @@ export class ScrollPositionKeeper { capture(): void { const scrollElement = this.options.getScrollElement(); if (scrollElement === null) return; + this.observeScrollMovement(scrollElement); if (!this.options.isActive()) { + this.writeDeferredOffset(scrollElement); this.anchor = null; this.holdUntil = 0; this.setOverflowAnchorDisabled(scrollElement, false); @@ -139,6 +186,9 @@ export class ScrollPositionKeeper { this.capture(); return; } + this.observeScrollMovement(scrollElement); + const deferWrite = this.shouldDeferWrite(scrollElement); + if (!deferWrite) this.writeDeferredOffset(scrollElement); const current = this.locate(scrollElement, anchor); if (current === null) { this.capture(); @@ -146,8 +196,78 @@ export class ScrollPositionKeeper { } const delta = current - anchor.offset; if (Math.abs(delta) < MIN_CORRECTION_PX) return; - anchor.offset = current; - scrollElement.scrollTop += delta; + if (deferWrite) { + this.setDeferredOffset(this.deferredOffset + delta); + this.scheduleDeferredWrite(); + } else { + anchor.offset = current; + scrollElement.scrollTop += delta; + this.observedScrollTop = scrollElement.scrollTop; + } + this.notifyScrollWrite(); + } + + private shouldDeferWrite(scrollElement: HTMLElement): boolean { + if (!this.options.deferWritesWhileScrolling) return false; + if (this.touching) return true; + if (window.performance.now() - this.scrollMovedAt < SCROLL_SETTLE_MS) { + return true; + } + const scrollTop = scrollElement.scrollTop; + return ( + scrollTop < 0 || + scrollTop > scrollElement.scrollHeight - scrollElement.clientHeight + ); + } + + private observeScrollMovement(scrollElement: HTMLElement): void { + const scrollTop = scrollElement.scrollTop; + const previous = this.observedScrollTop; + if (scrollTop === previous) return; + this.observedScrollTop = scrollTop; + if (previous !== null) this.scrollMovedAt = window.performance.now(); + } + + private scheduleDeferredWrite(): void { + if (this.deferredOffset === 0 || this.settleTimeout !== null) return; + this.settleTimeout = window.setTimeout(() => { + this.settleTimeout = null; + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null || this.deferredOffset === 0) return; + this.observeScrollMovement(scrollElement); + if (this.options.isActive() && this.shouldDeferWrite(scrollElement)) { + this.scheduleDeferredWrite(); + return; + } + this.writeDeferredOffset(scrollElement); + this.reconcile(); + this.capture(); + }, SCROLL_SETTLE_MS); + } + + private writeDeferredOffset(scrollElement: HTMLElement): void { + const offset = this.deferredOffset; + if (offset === 0) return; + this.setDeferredOffset(0); + if (this.anchor !== null) this.anchor.offset += offset; + scrollElement.scrollTop += offset; + this.observedScrollTop = scrollElement.scrollTop; + this.notifyScrollWrite(); + } + + private setDeferredOffset(offset: number): void { + this.deferredOffset = offset; + const element = + offset === 0 + ? this.deferredOffsetElement + : this.options.getDeferredOffsetElement(); + if (element === null) return; + element.style.transform = + offset === 0 ? "" : `translate3d(0, ${-offset}px, 0)`; + this.deferredOffsetElement = offset === 0 ? null : element; + } + + private notifyScrollWrite(): void { for (const listener of this.writeListeners) listener(); } diff --git a/apps/app/src/test/scroll-position-keeper.ts b/apps/app/src/test/scroll-position-keeper.ts index 8aebf259b3c..75a7fc0318b 100644 --- a/apps/app/src/test/scroll-position-keeper.ts +++ b/apps/app/src/test/scroll-position-keeper.ts @@ -2,6 +2,8 @@ import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; export function createInertScrollPositionKeeper(): ScrollPositionKeeper { return new ScrollPositionKeeper({ + deferWritesWhileScrolling: false, + getDeferredOffsetElement: () => null, getScrollElement: () => null, getTopLevelRows: () => [], isActive: () => false, diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 3441a8a3996..eb19c2e1436 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -201,3 +201,40 @@ the cache already covers do not show it. A response clears only sequences through its own `maxSeq`. The indicator appears after the timeline has stayed behind for one second, disappears as soon as the cache catches up, and renders as a row at the end of the timeline. + +## Browser scroll ownership + +The web timeline windows lists of 20 or more items on every platform, +including iOS Safari and the mobile app's WKWebView. The virtualizer keeps +visible rows, overscan, and interaction or navigation pins mounted. Loaded +history stays available without every rich row being mounted. Expanded detail +lists use their own scroll roots and the same windowing adapter. + +While the reader is scrolled away from the bottom, `ScrollPositionKeeper` is +the only writer of the reading position, for both the main timeline and nested +detail scrollers. It anchors the first row that starts in the viewport by its +offset in the content. When older pages load, rows measure, or a row resizes, +it applies the change above that row as a relative `scrollTop` adjustment. +TanStack's own scroll adjustments and native CSS scroll anchoring stay off while +the keeper holds a row. Stuck-to-bottom following is unchanged. + +iOS WebKit overrides a scroll write made while a finger is down, during +momentum, or during an edge bounce, and the content then sags and snaps back. +On iOS the keeper waits during those phases instead. It keeps the correction as +a transform on the scroll content, so rows stay in place visually. The +virtualizer reads the scroll offset plus the held correction, so the window +matches what is on screen. Once the touch has ended and the scroll position has +been still for 150 ms, the keeper writes the correction to `scrollTop` and +removes the transform in the same frame. It also writes before it stops +keeping the position, for example when the reader returns to the bottom. Other +browsers write immediately. + +When a detached reader's scrollport changes width (for example after a rotation), +the shell pins the saved reading row and restores it while measurements settle. +The restore is scoped to the thread, and it clamps an offset inside the row to +the row's new height. Height-only changes, such as the keyboard opening, keep the +existing path. A restore waits at the bottom until the saved row renders. It +does not stay wherever the new scroll root starts, because that position can +keep loading older pages. If the scroll position is past the cached scroll extent, the shell +reads the live extent first. A resize clamp or a correction past an outdated +extent therefore does not count as the reader returning to the bottom. diff --git a/package.json b/package.json index 0849c175041..d93b0b642ac 100644 --- a/package.json +++ b/package.json @@ -95,7 +95,6 @@ "react-native-webview@13.16.1": "patches/react-native-webview@13.16.1.patch", "@tiptap/extension-blockquote@3.26.0": "patches/@tiptap__extension-blockquote@3.26.0.patch", "@better-auth/api-key@1.6.23": "patches/@better-auth__api-key@1.6.23.patch", - "@tanstack/virtual-core@3.17.1": "patches/@tanstack__virtual-core@3.17.1.patch", "mermaid@11.15.0": "patches/mermaid@11.15.0.patch" } } diff --git a/patches/@tanstack__virtual-core@3.17.1.patch b/patches/@tanstack__virtual-core@3.17.1.patch deleted file mode 100644 index 81f1a988682..00000000000 --- a/patches/@tanstack__virtual-core@3.17.1.patch +++ /dev/null @@ -1,114 +0,0 @@ -diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjs -index e691366c4459a108c4ab8bb9d8e00a7df823fc81..71a6c81079b7e65e30fe21e7dadd3707fe78aeff 100644 ---- a/dist/cjs/index.cjs -+++ b/dist/cjs/index.cjs -@@ -111,6 +111,7 @@ const observeOffset = (instance, cb, readOffset) => { - element.addEventListener("scrollend", endHandler, addEventListenerOptions); - } - return () => { -+ fallback?.cancel(); - element.removeEventListener("scroll", handler); - if (registerScrollendEvent) { - element.removeEventListener("scrollend", endHandler); -diff --git a/dist/cjs/utils.cjs b/dist/cjs/utils.cjs -index eb9a544cb056944a290ad0050610cd6f22d143e1..a88d712e89e5f43ef382c17bfc0446f602a89a5d 100644 ---- a/dist/cjs/utils.cjs -+++ b/dist/cjs/utils.cjs -@@ -62,10 +62,12 @@ function notUndefined(value, msg) { - const approxEqual = (a, b) => Math.abs(a - b) < 1.01; - const debounce = (targetWindow, fn, ms) => { - let timeoutId; -- return function(...args) { -+ const debounced = function(...args) { - targetWindow.clearTimeout(timeoutId); - timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms); - }; -+ debounced.cancel = () => targetWindow.clearTimeout(timeoutId); -+ return debounced; - }; - exports.approxEqual = approxEqual; - exports.debounce = debounce; -diff --git a/dist/cjs/utils.d.cts b/dist/cjs/utils.d.cts -index 8af53b8d393dad4705e07f35dba3f0749beae6a5..e0c7de127bcd788580068d76eaac23f605bc14ac 100644 ---- a/dist/cjs/utils.d.cts -+++ b/dist/cjs/utils.d.cts -@@ -12,4 +12,7 @@ export declare function memo, TResult>(getDeps: - }; - export declare function notUndefined(value: T | undefined, msg?: string): T; - export declare const approxEqual: (a: number, b: number) => boolean; --export declare const debounce: (targetWindow: Window & typeof globalThis, fn: Function, ms: number) => (this: any, ...args: Array) => void; -+export declare const debounce: (targetWindow: Window & typeof globalThis, fn: Function, ms: number) => { -+ (this: any, ...args: Array): void; -+ cancel: () => void; -+}; -diff --git a/dist/esm/index.js b/dist/esm/index.js -index 25cf5bc1aff674ecbc5b2a032fd036a91699870c..a4d223158c7703207c59e262ef9a066cb402dc94 100644 ---- a/dist/esm/index.js -+++ b/dist/esm/index.js -@@ -109,6 +109,7 @@ const observeOffset = (instance, cb, readOffset) => { - element.addEventListener("scrollend", endHandler, addEventListenerOptions); - } - return () => { -+ fallback?.cancel(); - element.removeEventListener("scroll", handler); - if (registerScrollendEvent) { - element.removeEventListener("scrollend", endHandler); -diff --git a/dist/esm/utils.d.ts b/dist/esm/utils.d.ts -index 8af53b8d393dad4705e07f35dba3f0749beae6a5..e0c7de127bcd788580068d76eaac23f605bc14ac 100644 ---- a/dist/esm/utils.d.ts -+++ b/dist/esm/utils.d.ts -@@ -12,4 +12,7 @@ export declare function memo, TResult>(getDeps: - }; - export declare function notUndefined(value: T | undefined, msg?: string): T; - export declare const approxEqual: (a: number, b: number) => boolean; --export declare const debounce: (targetWindow: Window & typeof globalThis, fn: Function, ms: number) => (this: any, ...args: Array) => void; -+export declare const debounce: (targetWindow: Window & typeof globalThis, fn: Function, ms: number) => { -+ (this: any, ...args: Array): void; -+ cancel: () => void; -+}; -diff --git a/dist/esm/utils.js b/dist/esm/utils.js -index 5369a85f196d547cc760ff4b1c8d2a0b4857bf62..988c0d6b46f6e8c1fe34540bac630e4b10b9039d 100644 ---- a/dist/esm/utils.js -+++ b/dist/esm/utils.js -@@ -60,10 +60,12 @@ function notUndefined(value, msg) { - const approxEqual = (a, b) => Math.abs(a - b) < 1.01; - const debounce = (targetWindow, fn, ms) => { - let timeoutId; -- return function(...args) { -+ const debounced = function(...args) { - targetWindow.clearTimeout(timeoutId); - timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms); - }; -+ debounced.cancel = () => targetWindow.clearTimeout(timeoutId); -+ return debounced; - }; - export { - approxEqual, -diff --git a/src/index.ts b/src/index.ts -index 7af791d13a0b026c380272c0e09601dd1b38c246..3077a4cbc2a21f35ebb688d641b2da7853d12c20 100644 ---- a/src/index.ts -+++ b/src/index.ts -@@ -213,6 +213,7 @@ const observeOffset = ( - element.addEventListener('scrollend', endHandler, addEventListenerOptions) - } - return () => { -+ fallback?.cancel() - element.removeEventListener('scroll', handler) - if (registerScrollendEvent) { - element.removeEventListener('scrollend', endHandler) -diff --git a/src/utils.ts b/src/utils.ts -index 5e16080cd0f92c1814b082280a3513debed5e119..ed708a28d488c09eb2bf3210b72421645cb04788 100644 ---- a/src/utils.ts -+++ b/src/utils.ts -@@ -102,8 +102,10 @@ export const debounce = ( - ms: number, - ) => { - let timeoutId: number -- return function (this: any, ...args: Array) { -+ const debounced = function (this: any, ...args: Array) { - targetWindow.clearTimeout(timeoutId) - timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms) - } -+ debounced.cancel = () => targetWindow.clearTimeout(timeoutId) -+ return debounced - } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8348bf47f09..e14b3686900 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -21,9 +21,6 @@ patchedDependencies: '@react-native-cookies/cookies@6.2.1': hash: ujy2rsr7cvytwrazuebhhzq3zu path: patches/@react-native-cookies__cookies@6.2.1.patch - '@tanstack/virtual-core@3.17.1': - hash: rbxshoyvmdxb4nvhzl4v766pzu - path: patches/@tanstack__virtual-core@3.17.1.patch '@tiptap/extension-blockquote@3.26.0': hash: 5ybzdv3kkwrykbgdydwjdtpqom path: patches/@tiptap__extension-blockquote@3.26.0.patch @@ -247,8 +244,8 @@ importers: specifier: ^5.62.0 version: 5.90.20(react@19.2.4) '@tanstack/react-virtual': - specifier: ^3.14.2 - version: 3.14.3(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + specifier: 3.14.20 + version: 3.14.20(react-dom@19.2.4(react@19.2.4))(react@19.2.4) '@tiptap/core': specifier: ^3.26.0 version: 3.26.0(@tiptap/pm@3.26.0) @@ -10234,8 +10231,8 @@ packages: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - '@tanstack/react-virtual@3.14.3': - resolution: {integrity: sha512-k/cnHPVaOfn46hSbiY6n4Dzf4QjCGWSF40zR5QIIYUqPAjpA6TN7InfYmcMiDVQGP2iUn9xsRbAl8u1v3UmeVQ==} + '@tanstack/react-virtual@3.14.20': + resolution: {integrity: sha512-9hbhFlc0lznjXmWYDB/KEl7PJxEPz0Qnj2FzJFse98miGvXtx7jzjE5jlasmtczmZ6TxXsyI4v7PuyGQm2q1nQ==} peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 @@ -10304,8 +10301,8 @@ packages: '@tanstack/store@0.9.3': resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==} - '@tanstack/virtual-core@3.17.1': - resolution: {integrity: sha512-VZyW2Uiml5tmBZwPGrSD3Sz73OxzljQMCmzYHsUTPEuTsERf5xwa+uWb01xEzkz3ZSYTjj8NEb/mKHvgKxyZdA==} + '@tanstack/virtual-core@3.19.5': + resolution: {integrity: sha512-X/wq6DtSK/XClznMM+I4JE63yyIwmyPk4Ts83bD0VKaIbwHNdRsO5QipCPX+3OovqYyr0puQNpbmp8+SPhspNg==} '@tanstack/virtual-file-routes@1.162.0': resolution: {integrity: sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA==} @@ -22578,9 +22575,9 @@ snapshots: react-dom: 19.2.4(react@19.2.4) use-sync-external-store: 1.6.0(react@19.2.4) - '@tanstack/react-virtual@3.14.3(react-dom@19.2.4(react@19.2.4))(react@19.2.4)': + '@tanstack/react-virtual@3.14.20(react-dom@19.2.4(react@19.2.4))(react@19.2.4)': dependencies: - '@tanstack/virtual-core': 3.17.1(patch_hash=rbxshoyvmdxb4nvhzl4v766pzu) + '@tanstack/virtual-core': 3.19.5 react: 19.2.4 react-dom: 19.2.4(react@19.2.4) @@ -22742,7 +22739,7 @@ snapshots: '@tanstack/store@0.9.3': {} - '@tanstack/virtual-core@3.17.1(patch_hash=rbxshoyvmdxb4nvhzl4v766pzu)': {} + '@tanstack/virtual-core@3.19.5': {} '@tanstack/virtual-file-routes@1.162.0': {} From c07bf22cdfcb9bf0e672d4679e816c340b447de5 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 21 Oct 2026 12:52:39 -0700 Subject: [PATCH 2/7] Settle the timeline's auto-height wrapper before keeper corrections The timeline list sits in an AutoHeightContainer whose explicit height follows its content one ResizeObserver tick late. TimelineWindowedItems snapped it before TanStack's scroll writes, but since #5879 the ScrollPositionKeeper makes those writes and never snapped it. When an older page prepended rows, the keeper's correction was clamped to the old maximum: the reader lost their place and landed on the old bottom. The next scroll event then read that position as a return to the bottom, reattached, and the shell scrolled to the real bottom. The keeper now runs registered scroll extent syncs before any write past the current extent, and TimelineWindowedItems registers the auto-height snap. iOS hold timing is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../timeline/TimelineWindowedItems.test.tsx | 33 +++++++++++++++ .../thread/timeline/TimelineWindowedItems.tsx | 5 +++ .../ui/scroll-position-keeper.test.ts | 40 +++++++++++++++---- .../components/ui/scroll-position-keeper.ts | 23 +++++++++-- docs/timeline-pagination.md | 7 ++++ 5 files changed, 97 insertions(+), 11 deletions(-) diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx index 3d658376ebb..61ea49c5eb1 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx @@ -515,6 +515,39 @@ describe("TimelineWindowedItems", () => { expect(scrollElement.scrollTop).toBe(3_404); }); + it("settles the enclosing auto-height wrapper before the position keeper's correction", async () => { + let contentHeight = 0; + let wrapperHeight = 0; + clampScrollTopToContentHeight(() => wrapperHeight); + const positionKeeper = new ScrollPositionKeeper({ + deferWritesWhileScrolling: false, + getDeferredOffsetElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => [], + isActive: () => true, + }); + renderWindowedItems({ + positionKeeper, + snapAutoHeight: () => { + wrapperHeight = contentHeight; + }, + }); + await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); + contentHeight = readSpacerHeight(); + wrapperHeight = contentHeight; + scrollElement.scrollTop = 1_600; + fireEvent.scroll(scrollElement); + await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); + positionKeeper.hold(screen.getByTestId("wrapper-50"), "top", 10_000); + + renderedShift = -3_000; + contentHeight += 3_000; + positionKeeper.reconcile(); + + expect(wrapperHeight).toBe(6_200); + expect(scrollElement.scrollTop).toBe(4_600); + }); + it("keeps the end in place when a visible row grows while pinned to the end", async () => { clampScrollTopToContentHeight(readSpacerHeight); renderWindowedItems({ pinnedToEnd: true }); diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index 34657cfab95..f0fd01f8481 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -308,6 +308,11 @@ export function TimelineWindowedItems({ }); }, [positionKeeper, virtualizer]); + useLayoutEffect(() => { + if (positionKeeper === null || snapAutoHeight === null) return; + return positionKeeper.registerScrollExtentSync(snapAutoHeight); + }, [positionKeeper, snapAutoHeight]); + useLayoutEffect(reconcileScrollPosition); const updateScrollGeometry = useCallback(() => { 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 cd51028cee5..cabaf6ea5c9 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -20,7 +20,7 @@ function translatedOffset(element: HTMLElement): number { function createTimeline( initialRows: LaidOutRow[], - { deferWritesWhileScrolling = false } = {}, + { deferWritesWhileScrolling = false, lagScrollExtent = false } = {}, ) { const scrollElement = document.createElement("div"); const list = document.createElement("div"); @@ -29,12 +29,23 @@ function createTimeline( let scrollTop = 0; let rows = initialRows; const offsets = new Map(); + const contentHeight = () => + Math.max( + VIEWPORT_HEIGHT, + rows.reduce((total, row) => total + row.height, 0), + ); + let settledExtent = contentHeight(); + const scrollHeight = () => + lagScrollExtent ? settledExtent : contentHeight(); Object.defineProperty(scrollElement, "scrollTop", { configurable: true, get: () => scrollTop, set: (value: number) => { - scrollTop = Math.max(0, value); + const max = lagScrollExtent + ? scrollHeight() - VIEWPORT_HEIGHT + : Number.POSITIVE_INFINITY; + scrollTop = Math.min(Math.max(0, value), max); }, }); Object.defineProperty(scrollElement, "clientHeight", { @@ -43,11 +54,7 @@ function createTimeline( }); Object.defineProperty(scrollElement, "scrollHeight", { configurable: true, - get: () => - Math.max( - VIEWPORT_HEIGHT, - rows.reduce((total, row) => total + row.height, 0), - ), + get: scrollHeight, }); vi.spyOn(scrollElement, "getBoundingClientRect").mockReturnValue( new DOMRect(0, 0, 100, VIEWPORT_HEIGHT), @@ -125,6 +132,9 @@ function createTimeline( rows = next; layout(); }, + settleScrollExtent() { + settledExtent = contentHeight(); + }, viewportTopOf(id: string) { const offset = offsets.get(id); if (offset === undefined) throw new Error(`No row ${id}`); @@ -178,6 +188,22 @@ describe("ScrollPositionKeeper", () => { expect(timeline.viewportTopOf("row-1")).toBe(before); }); + it("settles a lagging scroll extent before a correction it cannot hold", () => { + const timeline = createTimeline(rowsOf(10), { lagScrollExtent: true }); + timeline.scrollTo(100); + timeline.keeper.handleScroll(); + const before = timeline.viewportTopOf("row-1"); + timeline.keeper.registerScrollExtentSync(() => + timeline.settleScrollExtent(), + ); + + timeline.setRows([...rowsOf(30, 200, "older"), ...rowsOf(10)]); + timeline.keeper.reconcile(); + + expect(timeline.scrollTop).toBe(6_100); + expect(timeline.viewportTopOf("row-1")).toBe(before); + }); + it("composes with scrolling that happens between layout changes", () => { const timeline = createTimeline(rowsOf(10)); timeline.scrollTo(900); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index df6346cb8ef..e4fbc78a265 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -57,6 +57,7 @@ export class ScrollPositionKeeper { private anchor: KeptAnchor | null = null; private holdUntil = 0; private readonly rowOffsetSources = new Set(); + private readonly scrollExtentSyncs = new Set<() => void>(); private readonly writeListeners = new Set<() => void>(); private overflowAnchorDisabled = false; private deferredOffset = 0; @@ -116,6 +117,13 @@ export class ScrollPositionKeeper { }; } + registerScrollExtentSync(sync: () => void): () => void { + this.scrollExtentSyncs.add(sync); + return () => { + this.scrollExtentSyncs.delete(sync); + }; + } + subscribeScrollWrites(listener: () => void): () => void { this.writeListeners.add(listener); return () => { @@ -201,8 +209,7 @@ export class ScrollPositionKeeper { this.scheduleDeferredWrite(); } else { anchor.offset = current; - scrollElement.scrollTop += delta; - this.observedScrollTop = scrollElement.scrollTop; + this.scrollBy(scrollElement, delta); } this.notifyScrollWrite(); } @@ -250,11 +257,19 @@ export class ScrollPositionKeeper { if (offset === 0) return; this.setDeferredOffset(0); if (this.anchor !== null) this.anchor.offset += offset; - scrollElement.scrollTop += offset; - this.observedScrollTop = scrollElement.scrollTop; + this.scrollBy(scrollElement, offset); this.notifyScrollWrite(); } + private scrollBy(scrollElement: HTMLElement, delta: number): void { + const target = scrollElement.scrollTop + delta; + if (target > scrollElement.scrollHeight - scrollElement.clientHeight) { + for (const sync of this.scrollExtentSyncs) sync(); + } + scrollElement.scrollTop = target; + this.observedScrollTop = scrollElement.scrollTop; + } + private setDeferredOffset(offset: number): void { this.deferredOffset = offset; const element = diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index eb19c2e1436..0dd53ebe702 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -218,6 +218,13 @@ it applies the change above that row as a relative `scrollTop` adjustment. TanStack's own scroll adjustments and native CSS scroll anchoring stay off while the keeper holds a row. Stuck-to-bottom following is unchanged. +The timeline list sits in an auto-height wrapper whose height follows its +content one resize-observer tick late. Before the keeper writes a correction +past the current scroll extent, for example after an older page prepends rows, +it snaps that wrapper to its content height. Otherwise the browser clamps the +write to the old bottom, the reader loses their place, and the shell reads the +clamped position as a return to the bottom and reattaches. + iOS WebKit overrides a scroll write made while a finger is down, during momentum, or during an edge bounce, and the content then sags and snaps back. On iOS the keeper waits during those phases instead. It keeps the correction as From 8df05bb492d6143edd3e3813345d5444d387df80 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Wed, 21 Oct 2026 20:28:59 -0700 Subject: [PATCH 3/7] Make one owner keep the timeline's reading position ScrollPositionKeeper now owns each scroll root's reading position as explicit state: attached to the bottom, or a row key with its offset from the top of the visible viewport. Every layout change is reconciled against that position before paint, from ResizeObservers on the root, its content and each mounted row, and from each windowed list's commit. Targets are computed from the fixed position, never as relative deltas. - A scroll counts as the reader's only during an input session (wheel, touch and momentum, scroll keys, pointer held on the scroller). Any other scroll, such as a clamp, is reconciled back to the position. Attach and detach follow the reader's direction; layout never changes them. - Windowed lists render rows in normal flow between spacers sized from retained measurements, keyed to a row instead of scrollTop, and mount the reading row. A viewport over a spacer renders synchronously. - iOS keeps the transform hold during touch, momentum and bounce. - Thread switches restore the saved row through the same position, and the controller keeps the loaded pages of the eight most recent threads per query client so the row is there on return. Deleted: AutoHeightContainer and its snap plumbing, TanStack in the timeline, CSS bottom scroll anchoring, the shell's intent timers, bottom-restore settle tail, restore attempt loop, width-change restore path, shrink re-attach, content hold timer, and the detail scroller's own stick heuristics and smooth follow. Co-Authored-By: Claude Opus 5.5 --- .../thread/timeline/TerminalOutputBlock.tsx | 36 - .../ThreadTimelineRows.height.test.tsx | 108 -- .../thread/timeline/ThreadTimelineRows.tsx | 107 +- .../thread/timeline/TimelineDetailScroll.tsx | 12 +- .../thread/timeline/TimelineFileDiffBlock.tsx | 4 - .../thread/timeline/TimelineRowDetails.tsx | 6 +- .../timeline/TimelineWindowedItems.test.tsx | 717 ++------ .../thread/timeline/TimelineWindowedItems.tsx | 716 +++++--- .../thread/timeline/ToolCallDetailBlock.tsx | 1 - .../thread/timeline/WorkflowWorkRowBody.tsx | 4 - .../timeline/useAutoLoadOlderRows.test.tsx | 146 +- .../thread/timeline/useAutoLoadOlderRows.ts | 93 +- .../timeline/useStickyBottomScroll.test.tsx | 144 -- .../thread/timeline/useStickyBottomScroll.ts | 165 +- .../useThreadTimelineController.test.tsx | 76 +- .../timeline/useThreadTimelineController.ts | 46 +- ...chored-scroll-body.coarse-pointer.test.tsx | 100 +- ...bottom-anchored-scroll-body.grid.test.tsx} | 27 - ...d-scroll-body.scroll-preservation.test.tsx | 1545 ----------------- ...-anchored-scroll-body.settle-tail.test.tsx | 304 ---- .../ui/bottom-anchored-scroll-body.test.tsx | 286 +++ .../ui/bottom-anchored-scroll-body.tsx | 996 ++--------- .../components/ui/height-transition.test.tsx | 141 +- .../src/components/ui/height-transition.tsx | 211 +-- .../ui/scroll-position-keeper.test.ts | 637 ++++--- .../components/ui/scroll-position-keeper.ts | 1004 ++++++++--- apps/app/src/components/ui/theme.css | 16 - apps/app/src/components/ui/theme.test.ts | 12 +- apps/app/src/test/fake-flow-layout.ts | 236 +++ apps/app/src/test/scroll-position-keeper.ts | 6 +- docs/timeline-pagination.md | 131 +- 31 files changed, 2697 insertions(+), 5336 deletions(-) delete mode 100644 apps/app/src/components/thread/timeline/ThreadTimelineRows.height.test.tsx delete mode 100644 apps/app/src/components/thread/timeline/useStickyBottomScroll.test.tsx rename apps/app/src/components/ui/{bottom-anchored-scroll-body.anchor-class.test.tsx => bottom-anchored-scroll-body.grid.test.tsx} (60%) delete mode 100644 apps/app/src/components/ui/bottom-anchored-scroll-body.scroll-preservation.test.tsx delete mode 100644 apps/app/src/components/ui/bottom-anchored-scroll-body.settle-tail.test.tsx create mode 100644 apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx create mode 100644 apps/app/src/test/fake-flow-layout.ts diff --git a/apps/app/src/components/thread/timeline/TerminalOutputBlock.tsx b/apps/app/src/components/thread/timeline/TerminalOutputBlock.tsx index af7f051f309..cb8bd924872 100644 --- a/apps/app/src/components/thread/timeline/TerminalOutputBlock.tsx +++ b/apps/app/src/components/thread/timeline/TerminalOutputBlock.tsx @@ -12,13 +12,6 @@ export interface TerminalOutputBlockProps { streaming: boolean; } -interface TerminalScrollContentKeyArgs { - commandLine: string; - exitCode: number | null; - metadataLines: readonly string[]; - output: string; -} - const ANSI_THEME_COLORS: Record = { 0: "var(--ansi-0)", 1: "var(--ansi-1)", @@ -65,28 +58,6 @@ const ANSI_TO_HTML = new Convert({ colors: ANSI_THEME_COLORS, }); -function stringLengthSum(values: readonly string[]): number { - let length = 0; - for (const value of values) { - length += value.length; - } - return length; -} - -function terminalScrollContentKey({ - commandLine, - exitCode, - metadataLines, - output, -}: TerminalScrollContentKeyArgs): string { - return [ - commandLine.length, - stringLengthSum(metadataLines), - output.length, - exitCode ?? "", - ].join(":"); -} - export function TerminalOutputBlock({ commandLine, exitCode, @@ -103,12 +74,6 @@ export function TerminalOutputBlock({ ); const showExitCode = exitCode !== null; - const outputContentKey = terminalScrollContentKey({ - commandLine, - exitCode, - metadataLines, - output, - }); return (
@@ -132,7 +97,6 @@ export function TerminalOutputBlock({ diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.height.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.height.test.tsx deleted file mode 100644 index 5f6dbf602bb..00000000000 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.height.test.tsx +++ /dev/null @@ -1,108 +0,0 @@ -// @vitest-environment jsdom - -import { cleanup, render } from "@testing-library/react"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { MemoryRouter } from "react-router-dom"; -import { afterEach, expect, it, vi } from "vitest"; -import { conversationRow, turnRow } from "@/test/fixtures/thread-timeline-rows"; -import { ThreadTimelineRows } from "./ThreadTimelineRows"; - -class ResizeObserverStub implements ResizeObserver { - constructor(readonly callback: ResizeObserverCallback) {} - - observe: ResizeObserver["observe"] = vi.fn(); - unobserve: ResizeObserver["unobserve"] = vi.fn(); - disconnect: ResizeObserver["disconnect"] = vi.fn(); -} - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - vi.restoreAllMocks(); -}); - -it("snap-syncs the timeline height when older rows are prepended", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation( - function (this: HTMLElement) { - return ( - this.querySelectorAll( - '[data-timeline-row-list="top-level"] > [data-timeline-items] > [data-timeline-row-id]', - ).length * 100 - ); - }, - ); - - const latestRows = [ - conversationRow({ - id: "newer_user", - role: "user", - seq: 20, - text: "Newest request", - }), - turnRow({ id: "newest_turn", seq: 21, status: "completed" }), - ]; - const olderRows = [ - conversationRow({ - id: "older_user", - role: "user", - seq: 10, - text: "Older request", - }), - turnRow({ id: "older_turn", seq: 11, status: "completed" }), - ]; - const queryClient = new QueryClient(); - const timeline = (rows: typeof latestRows) => ( - - - - - - ); - const view = render(timeline(latestRows)); - const rowList = view.container.querySelector( - '[data-timeline-row-list="top-level"]', - ); - const heightWrapper = rowList?.parentElement?.parentElement; - - expect(heightWrapper?.style.height).toBe("200px"); - - view.rerender(timeline([...olderRows, ...latestRows])); - - expect(heightWrapper?.style.height).toBe("400px"); - expect(heightWrapper?.style.transitionDuration).toBe("0s"); -}); - -it("snaps active timeline growth on fine-pointer browsers", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - vi.stubGlobal("CSS", { supports: () => true }); - const queryClient = new QueryClient(); - const rows = [turnRow({ id: "active_turn", seq: 1, status: "pending" })]; - const timeline = (active: boolean) => ( - - - - - - ); - const view = render(timeline(false)); - const rowList = view.container.querySelector( - '[data-timeline-row-list="top-level"]', - ); - const wrapper = rowList?.parentElement?.parentElement; - expect(wrapper?.style.transition).toContain("height 180ms"); - view.rerender(timeline(true)); - expect(wrapper?.style.transition).toContain("height 0ms"); - view.rerender(timeline(false)); - expect(wrapper?.style.transition).toContain("height 180ms"); -}); diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 8afdfdf1cad..6d7fface156 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -98,7 +98,6 @@ import { import { WorkRowBody } from "./TimelineRowDetails.js"; import { TimelineDetailScroll } from "./TimelineDetailScroll.js"; import { Button } from "@bb/shared-ui/button"; -import { AutoHeightContainer } from "../../ui/height-transition.js"; import { Icon, type IconName } from "@bb/shared-ui/icon"; import { presentationTintStyle } from "./presentation-display.js"; import { usePluginIconUrl } from "@/lib/plugin-logos"; @@ -109,7 +108,7 @@ import { } from "./PluginTimelineRendererBody.js"; import type { PromptMentionLinkResolver } from "@bb/client-core"; import { - TimelineScrollRestoreRowIdContext, + TimelineScrollRestoreContext, useBottomAnchoredScroll, } from "@/components/ui/bottom-anchored-scroll-body.js"; import { @@ -121,7 +120,6 @@ import { import { joinSignatureParts, timelineRowRenderSignature, - timelineRowsSignature, } from "@bb/client-core"; import { TOP_LEVEL_TIMELINE_ROW_INTRINSIC_SIZE_CLASS_NAME, @@ -553,23 +551,6 @@ function useTimelineSearchExpansionRowIds( }, [inheritedRowIds, rows, target, threadId]); } -function timelineHeightSnapRevision(rows: readonly TimelineRow[]): string { - const firstRowId = rows[0]?.id; - - for (let index = rows.length - 1; index >= 0; index -= 1) { - const row = rows[index]; - if (row?.kind === "turn") { - return joinSignatureParts([ - firstRowId, - row.id, - row.sourceSeqStart, - row.sourceSeqEnd, - ]); - } - } - return joinSignatureParts([firstRowId, "active"]); -} - function useTimelineViewRowsCache(): GetTimelineViewRows { const cacheRef = useRef(createTimelineViewRowsCache()); return useCallback( @@ -1113,7 +1094,6 @@ function TimelineSystemDetailBlock({
@@ -1201,11 +1181,7 @@ function TimelineExpandableBodyContent({
       const isFrontier =
         row.kind === "bundle-summary" && row.id === activeLatestBundleId;
       return (
-        
+        
           {list}
         
       );
@@ -1535,7 +1511,6 @@ function DelegationRowBody({ row }: { row: TimelineViewDelegationWorkRow }) {
     
       
@@ -2011,17 +1986,15 @@ function TimelineRowItemWrapper({ ref={composedRef} data-timeline-row-id={row.id} data-timeline-window-key={row.id} - data-index={windowedState.itemIndex} className={ isTopLevel && !windowedState.windowingEnabled ? TOP_LEVEL_TIMELINE_ROW_INTRINSIC_SIZE_CLASS_NAME : undefined } style={ - windowedState.itemStyle ?? - (isTopLevel && !windowedState.windowingEnabled + isTopLevel && !windowedState.windowingEnabled ? timelineRowContainmentStyle(row) - : undefined) + : undefined } > {children} @@ -2062,7 +2035,7 @@ function TimelineRowsList({ }: TimelineRowsListProps) { const { threadId } = useTimelineRendererStaticContext(); const bottomAnchor = useBottomAnchoredScroll(); - const scrollRestoreRowId = useContext(TimelineScrollRestoreRowIdContext); + const scrollRestore = useContext(TimelineScrollRestoreContext); const detailScrollRoot = useContext(TimelineWindowingScrollRootContext); const inheritedMeasurements = useContext( TimelineWindowingMeasurementsContext, @@ -2106,25 +2079,11 @@ function TimelineRowsList({ for (const rowId of stableSearchExpandedRowIds) { keys.add(rowId); } - if (spacing === "top-level" && scrollRestoreRowId !== null) { - keys.add(scrollRestoreRowId); - } if (spacing === "top-level" && navigationTargetRowId != null) { keys.add(navigationTargetRowId); } return keys; - }, [ - items, - rows, - scrollRestoreRowId, - spacing, - stableSearchExpandedRowIds, - navigationTargetRowId, - ]); - const getWindowingScrollElement = - detailScrollRoot?.getScrollElement ?? - bottomAnchor?.getScrollElement ?? - null; + }, [items, rows, spacing, stableSearchExpandedRowIds, navigationTargetRowId]); const isTopLevelList = spacing === "top-level"; const { measureRef: messageColumnWidthSourceRef, width: messageColumnWidth } = useMeasuredWidth({ enabled: isTopLevelList }); @@ -2157,7 +2116,9 @@ function TimelineRowsList({ : 28; }} gap={spacing === "bundle" ? 0 : 8} - getScrollElement={getWindowingScrollElement} + initialWindowAnchor={ + isTopLevelList && detailScrollRoot === null ? scrollRestore : null + } itemKeys={itemKeys} measurements={measurements} positionKeeper={ @@ -2180,9 +2141,7 @@ function TimelineRowsList({
getViewRows(props.timelineRows), [getViewRows, props.timelineRows], ); - const heightSnapRevision = timelineHeightSnapRevision(props.timelineRows); const latestActionableAssistantMessageId = useMemo( () => findLastActionableAssistantMessageId(rows), [rows], @@ -2480,32 +2438,27 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { value={windowingMeasurements} >
- - - + {hasSelectionActions ? (
({ - contentKey, - streaming, - }); + const sticky = useStickyBottomScroll({ streaming }); const overflow = useScrollOverflowState(); const maxHeightClassName = getDetailScrollMaxHeightClass(size); const { aboveOverflow, belowOverflow } = overflow; @@ -60,11 +55,6 @@ export function TimelineDetailScroll({ >
diff --git a/apps/app/src/components/thread/timeline/TimelineRowDetails.tsx b/apps/app/src/components/thread/timeline/TimelineRowDetails.tsx index 9a3963f5893..89447b50fa7 100644 --- a/apps/app/src/components/thread/timeline/TimelineRowDetails.tsx +++ b/apps/app/src/components/thread/timeline/TimelineRowDetails.tsx @@ -234,11 +234,7 @@ export function WorkRowBody({ return (
{row.stderr ? ( - + `row-${index}`); - -let scrollElement: HTMLDivElement; -let itemHeights = new Map(); -let renderedShift = 0; - -function rect(top: number, height: number): DOMRect { - return { - bottom: top + height, - height, - left: 0, - right: 320, - top, - width: 320, - x: 0, - y: top, - toJSON: () => ({}), - }; -} - -const resizeObserverCallbacks = new Set(); - -class ResizeObserverStub implements ResizeObserver { - constructor(private readonly callback: ResizeObserverCallback) { - resizeObserverCallbacks.add(callback); - } - disconnect(): void { - resizeObserverCallbacks.delete(this.callback); - } - observe(): void {} - unobserve(): void {} -} - -function reportItemResize(element: HTMLElement, height: number) { - const entry = { - target: element, - borderBoxSize: [{ blockSize: height, inlineSize: 320 }], - contentBoxSize: [{ blockSize: height, inlineSize: 320 }], - contentRect: rect(0, height), - devicePixelContentBoxSize: [], - } satisfies ResizeObserverEntry; - for (const callback of resizeObserverCallbacks) { - callback([entry], new ResizeObserverStub(callback)); - } -} - -function readSpacerHeight() { - const spacer = scrollElement.querySelector( - "[data-timeline-virtual-spacer]", - ); - return Number.parseFloat(spacer?.style.height ?? "") || 0; -} - -function clampScrollTopToContentHeight(readContentHeight: () => number) { - let scrollTop = 0; - const maxScrollTop = () => - Math.max(0, readContentHeight() - scrollElement.clientHeight); - Object.defineProperty(scrollElement, "scrollTop", { - configurable: true, - get: () => scrollTop, - set: (value: number) => { - scrollTop = Math.min(Math.max(0, value), maxScrollTop()); - }, - }); - scrollElement.scrollTo = ((options: ScrollToOptions) => { - if (options.top !== undefined) scrollElement.scrollTop = options.top; - }) as typeof scrollElement.scrollTo; -} - -function renderWindowedItems(options?: { - alwaysMountedKeys?: ReadonlySet; - clientHeight?: number; - measurements?: Map; - snapAutoHeight?: () => void; - pinnedToEnd?: boolean; - positionKeeper?: ScrollPositionKeeper; -}) { - const measurements = options?.measurements ?? new Map(); - Object.defineProperty(scrollElement, "clientHeight", { - configurable: true, - value: options?.clientHeight ?? 96, - }); - Object.defineProperty(scrollElement, "offsetHeight", { - configurable: true, - value: options?.clientHeight ?? 96, - }); - return { - ...render( - - 32} - gap={0} - getScrollElement={() => scrollElement} - itemKeys={ITEM_KEYS} - measurements={measurements} - positionKeeper={options?.positionKeeper ?? null} - pinnedToEnd={options?.pinnedToEnd ?? false} - renderItem={( - index: number, - state: TimelineWindowedItemRenderState, - ) => ( -
- -
- )} - /> -
, - { container: scrollElement }, - ), - measurements, - }; -} +import { installFakeFlowLayout } from "@/test/fake-flow-layout"; +import { TimelineWindowedItems } from "./TimelineWindowedItems.js"; -beforeEach(() => { - itemHeights = new Map(); - renderedShift = 0; - scrollElement = document.createElement("div"); - document.body.append(scrollElement); - Object.defineProperty(scrollElement, "clientWidth", { - configurable: true, - value: 320, - }); - Object.defineProperty(scrollElement, "offsetWidth", { - configurable: true, - value: 320, - }); - Object.defineProperty(scrollElement, "scrollHeight", { - configurable: true, - value: 3_200, - }); - vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation( - function (this: HTMLElement) { - if (this === scrollElement) return rect(0, scrollElement.clientHeight); - if (this.hasAttribute("data-timeline-virtual-spacer")) { - return rect( - -scrollElement.scrollTop - renderedShift, - Number.parseFloat(this.style.height) || 0, - ); - } - const index = Number(this.dataset.index); - if (Number.isInteger(index)) { - return rect( - index * 32 - scrollElement.scrollTop - renderedShift, - itemHeights.get(index) ?? 32, - ); - } - return rect(0, Number.parseFloat(this.style.height) || 0); - }, - ); - vi.stubGlobal("ResizeObserver", ResizeObserverStub); -}); +const VIEWPORT_HEIGHT = 600; +const cleanups: (() => void)[] = []; afterEach(() => { cleanup(); - resizeObserverCallbacks.clear(); - scrollElement.remove(); - vi.useRealTimers(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); + for (const run of cleanups.splice(0).reverse()) run(); + document.body.replaceChildren(); }); -describe("TimelineWindowedItems", () => { - it("never mounts the full history while the parent scroll ref is pending", async () => { - const rendered = new Set(); - let root: HTMLElement | null = null; - Object.defineProperty(scrollElement, "clientHeight", { value: 96 }); - Object.defineProperty(scrollElement, "offsetHeight", { value: 96 }); - render( -
{ - root = scrollElement; - }} - > - 32} - gap={0} - getScrollElement={() => root} - itemKeys={ITEM_KEYS} - measurements={new Map()} - positionKeeper={null} - pinnedToEnd={false} - renderItem={(index, state) => { - rendered.add(index); - return ( -
- ); - }} - /> -
, - { container: scrollElement }, - ); - await waitFor(() => expect(screen.getByTestId("pending-0")).toBeTruthy()); - expect(rendered.size).toBeLessThan(50); - scrollElement.scrollTop = 1_600; - await act(async () => { - await new Promise((resolve) => requestAnimationFrame(resolve)); - }); - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("pending-50")).toBeTruthy()); - expect(screen.queryByTestId("pending-0")).toBeNull(); - }); - - it("captures exact heights before the scrollport becomes usable", () => { - const measurements = new Map(); - - render( - 100} - gap={0} - getScrollElement={() => scrollElement} - itemKeys={ITEM_KEYS} - measurements={measurements} - positionKeeper={null} - pinnedToEnd={false} - renderItem={(index, state) => ( -
- )} - />, - { container: scrollElement }, - ); - - expect(measurements.get("row-0")).toBe(32); - expect(measurements.get("row-99")).toBe(32); - }); +function keys(count: number, prefix = "row"): string[] { + return Array.from({ length: count }, (_, index) => `${prefix}-${index}`); +} - it("preserves visible row identity when crossing the windowing threshold in either direction", async () => { - Object.defineProperty(scrollElement, "clientHeight", { - configurable: true, - value: 1_000, - }); - Object.defineProperty(scrollElement, "offsetHeight", { - configurable: true, - value: 1_000, - }); - const measurements = new Map(); - const getScrollElement = () => scrollElement; - const list = (count: number) => ( - 100} - gap={0} - getScrollElement={getScrollElement} - itemKeys={ITEM_KEYS.slice(0, count)} - measurements={measurements} - positionKeeper={null} - pinnedToEnd={false} - renderItem={(index, state) => ( +function setup({ + attached, + heightOf = (key: string) => 40 + ((key.length * 7) % 90), +}: { + attached: boolean; + heightOf?: (key: string) => number; +}) { + const scrollElement = document.createElement("div"); + const content = document.createElement("div"); + const list = document.createElement("div"); + list.setAttribute("data-timeline-row-list", "top-level"); + content.append(list); + scrollElement.append(content); + document.body.append(scrollElement); + const layout = installFakeFlowLayout({ + scrollElement, + viewportHeight: VIEWPORT_HEIGHT, + }); + const keeper = new ScrollPositionKeeper({ + bottomThresholdPx: 4, + deferWritesWhileScrolling: false, + getContentElement: () => content, + getFooterElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => + list.querySelectorAll( + ":scope > [data-timeline-items] > [data-timeline-row-id]", + ), + initiallyAttached: attached, + }); + const disconnect = keeper.connect(scrollElement); + cleanups.push(layout.restore, disconnect); + const measurements = new Map(); + const view = ( + itemKeys: string[], + { + alwaysMountedKeys, + pinnedToEnd = attached, + }: { alwaysMountedKeys?: ReadonlySet; pinnedToEnd?: boolean } = {}, + ) => ( + 60} + gap={8} + itemKeys={itemKeys} + measurements={measurements} + positionKeeper={keeper} + pinnedToEnd={pinnedToEnd} + renderItem={(index, state) => { + const key = itemKeys[index] ?? ""; + return (
- +
- )} - /> - ); - const view = render(list(19), { container: scrollElement }); - const inputs = screen.getAllByTestId(/^input-/); - fireEvent.change(inputs[0]!, { target: { value: "unsaved edit" } }); - - view.rerender(list(20)); - await waitFor(() => - expect(screen.getAllByTestId(/^input-/)).toHaveLength(20), + ); + }} + /> + ); + const mounted = () => + [...list.querySelectorAll("[data-timeline-row-id]")].map( + (row) => row.dataset.timelineRowId ?? "", ); - inputs.forEach((input, index) => { - expect(screen.getByTestId(`input-${index}`)).toBe(input); - }); - expect(screen.getByDisplayValue("unsaved edit")).toBe(inputs[0]); - expect( - scrollElement.querySelector("[data-timeline-virtual-spacer]") - ?.style.height, - ).toBe("640px"); - - view.rerender(list(19)); - inputs.forEach((input, index) => { - expect(screen.getByTestId(`input-${index}`)).toBe(input); + const topOf = (key: string) => { + const row = list.querySelector(`[data-timeline-row-id="${key}"]`); + if (row === null) throw new Error(`${key} is not mounted`); + return row.getBoundingClientRect().top; + }; + const visibleKeys = () => + mounted().filter((key) => { + const top = topOf(key); + return top < VIEWPORT_HEIGHT && top + heightOf(key) > 0; }); - expect(screen.getByDisplayValue("unsaved edit")).toBe(inputs[0]); - expect( - scrollElement.querySelector("[data-timeline-virtual-spacer]"), - ).toBeNull(); - }); + return { + heightOf, + keeper, + layout, + list, + measurements, + mounted, + topOf, + view, + visibleKeys, + }; +} - it("windows around the reader's rendered position while the keeper holds a correction", async () => { - const positionKeeper = new ScrollPositionKeeper({ - deferWritesWhileScrolling: true, - getDeferredOffsetElement: () => null, - getScrollElement: () => scrollElement, - getTopLevelRows: () => [], - isActive: () => true, +describe("TimelineWindowedItems", () => { + it("keeps the reader's rows mounted and in place when an older page turns windowing on", () => { + const harness = setup({ attached: false }); + const latest = keys(15); + const { rerender } = render(harness.view(latest), { + container: harness.list, }); - vi.spyOn(positionKeeper, "getDeferredOffset").mockReturnValue(1_600); - renderedShift = 1_600; - renderWindowedItems({ positionKeeper }); - - fireEvent.scroll(scrollElement); - - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - expect(screen.queryByTestId("content-0")).toBeNull(); - expect(scrollElement.scrollTop).toBe(0); - }); + act(() => harness.layout.userScrollTo(250)); + const anchor = harness.visibleKeys()[1] ?? ""; + const before = harness.topOf(anchor); - it("mounts only the visible TanStack range and removes offscreen wrappers", async () => { - renderWindowedItems(); + act(() => rerender(harness.view([...keys(40, "older"), ...latest]))); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - expect(screen.getAllByTestId(/^wrapper-/).length).toBeLessThan(30); - expect(screen.queryByTestId("wrapper-60")).toBeNull(); - expect( - scrollElement.querySelector("[data-timeline-virtual-spacer]") - ?.style.height, - ).toBe("3200px"); + expect(harness.mounted()).toContain(anchor); + expect(harness.topOf(anchor)).toBe(before); + expect(harness.mounted().length).toBeLessThan(55); }); - it("changes ranges on scroll without retaining the old rich rows", async () => { - renderWindowedItems(); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); + it("renders the rows under a scroll jump before the scroll handler returns", () => { + const harness = setup({ attached: true }); + const itemKeys = keys(400); + render(harness.view(itemKeys), { container: harness.list }); + expect(harness.mounted()).not.toContain("row-0"); - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); + harness.layout.userScrollTo(0); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - expect(screen.queryByTestId("wrapper-0")).toBeNull(); + expect(harness.visibleKeys()).toContain("row-0"); + expect(harness.visibleKeys().length).toBeGreaterThan(3); }); - it("preserves an existing scroll offset when a nested virtualizer mounts", async () => { - scrollElement.scrollTop = 1_600; + it("jumps far away from a detached reading row without a render loop", () => { + const harness = setup({ attached: true }); + render(harness.view(keys(400)), { container: harness.list }); + act(() => harness.layout.userScrollTo(harness.layout.maxScrollTop() - 900)); + expect(harness.keeper.isAttached()).toBe(false); - renderWindowedItems(); + harness.layout.userScrollTo(0); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - expect(scrollElement.scrollTop).toBe(1_600); + expect(harness.visibleKeys()).toContain("row-0"); }); - it("keeps search and interacted rows mounted outside the visible range", async () => { - renderWindowedItems({ alwaysMountedKeys: new Set(["row-80"]) }); - await waitFor(() => expect(screen.getByTestId("content-80")).toBeTruthy()); - fireEvent.click(screen.getByTestId("content-0")); + it("sizes spacers from retained measurements, so rows unmounting around the reader never shift it", () => { + const harness = setup({ attached: true }); + const itemKeys = keys(200); + for (const key of itemKeys) + harness.measurements.set(key, harness.heightOf(key)); + render(harness.view(itemKeys), { container: harness.list }); + const extent = harness.layout.maxScrollTop(); - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); + act(() => harness.layout.userScrollTo(extent - 3_000)); + const reader = harness.visibleKeys()[0] ?? ""; + const before = harness.topOf(reader); + act(() => harness.layout.userScrollTo(extent - 2_400)); + act(() => harness.layout.userScrollTo(extent - 3_600)); + act(() => harness.layout.userScrollTo(extent - 3_000)); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - expect(screen.getByTestId("content-0")).toBeTruthy(); - expect(screen.getByTestId("content-80")).toBeTruthy(); + expect(harness.layout.maxScrollTop()).toBe(extent); + expect(harness.layout.scrollTop).toBe(extent - 3_000); + expect(harness.topOf(reader)).toBe(before); }); - it("keeps visible content mounted during a programmatic scroll jump", async () => { - vi.useFakeTimers(); - renderWindowedItems(); - await act(async () => {}); - - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - await act(async () => {}); - - const content = screen.getByTestId("content-50"); - expect(content).toBeTruthy(); - - await act(async () => { - vi.advanceTimersByTime(300); + it("keeps the viewport covered after retained measurements for rows above the window are evicted", () => { + const harness = setup({ + attached: true, + heightOf: (key) => (Number(key.split("-")[1]) < 250 ? 300 : 80), }); - expect(screen.getByTestId("content-50")).toBe(content); - }); - - it("seeds its size model from measurements retained by the thread", async () => { - const measurements = new Map([["row-50", 64]]); - renderWindowedItems({ measurements }); - await waitFor(() => - expect( - scrollElement.querySelector( - "[data-timeline-virtual-spacer]", - )?.style.height, - ).toBe("3232px"), + const itemKeys = keys(300); + for (const key of itemKeys) + harness.measurements.set(key, harness.heightOf(key)); + render(harness.view(itemKeys), { container: harness.list }); + const firstMounted = harness.mounted()[0] ?? ""; + for (const key of itemKeys.slice(0, 250)) harness.measurements.delete(key); + const mountedRow = harness.list.querySelector( + `[data-timeline-row-id="${harness.mounted().at(-1) ?? ""}"]`, ); - }); - - it("starts its range at the end of the list when pinned to the bottom", async () => { - renderWindowedItems({ pinnedToEnd: true }); - - await waitFor(() => expect(screen.getByTestId("content-98")).toBeTruthy()); - expect(screen.queryByTestId("wrapper-0")).toBeNull(); - }); - - it("grows the list before compensating for a taller row above the viewport", async () => { - clampScrollTopToContentHeight(readSpacerHeight); - renderWindowedItems(); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - scrollElement.scrollTop = 3_104; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-98")).toBeTruthy()); - - itemHeights.set(95, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-95"), 332); - }); + mountedRow?.setAttribute("data-fake-height", "81"); + act(() => harness.layout.flushResizeObservers()); - expect( - scrollElement.querySelector("[data-timeline-virtual-spacer]") - ?.style.height, - ).toBe("3500px"); - expect(scrollElement.scrollTop).toBe(3_404); - }); - - it("keeps the reading position when a measured row above the viewport reloads while scrolling backward", async () => { - clampScrollTopToContentHeight(readSpacerHeight); - renderWindowedItems(); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - itemHeights.set(45, 40); - act(() => { - reportItemResize(screen.getByTestId("wrapper-45"), 40); - }); - scrollElement.scrollTop = 1_536; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-48")).toBeTruthy()); + act(() => + harness.layout.userScrollTo( + harness.layout.scrollTop + harness.topOf(firstMounted) - 900, + ), + ); - for (const height of [340, 40, 340]) { - const previousHeight = itemHeights.get(45) ?? 32; - const previousScrollTop = scrollElement.scrollTop; - itemHeights.set(45, height); - act(() => { - reportItemResize(screen.getByTestId("wrapper-45"), height); - }); - expect(scrollElement.scrollTop).toBe( - previousScrollTop + height - previousHeight, - ); - } + expect(harness.visibleKeys().length).toBeGreaterThan(0); }); - it("keeps a measured row's top fixed when it straddles the viewport top while scrolling backward", async () => { - renderWindowedItems(); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - itemHeights.set(48, 40); - act(() => { - reportItemResize(screen.getByTestId("wrapper-48"), 40); - }); - scrollElement.scrollTop = 1_552; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-48")).toBeTruthy()); - - itemHeights.set(48, 340); - act(() => { - reportItemResize(screen.getByTestId("wrapper-48"), 340); - }); + it("mounts a bounded window of a long history", () => { + const harness = setup({ attached: true }); + render(harness.view(keys(1_000)), { container: harness.list }); - expect(readSpacerHeight()).toBe(3_508); - expect(scrollElement.scrollTop).toBe(1_552); + expect(harness.mounted().length).toBeLessThan(40); + expect(harness.layout.scrollTop).toBe(harness.layout.maxScrollTop()); }); - it("settles the enclosing auto-height wrapper before compensating for a taller row", async () => { - let wrapperHeight = 0; - clampScrollTopToContentHeight(() => wrapperHeight); - renderWindowedItems({ - snapAutoHeight: () => { - wrapperHeight = readSpacerHeight(); - }, + it("keeps forced and interacted rows mounted outside the window", () => { + const harness = setup({ attached: true }); + const itemKeys = keys(300); + const forced = new Set(["row-3"]); + render(harness.view(itemKeys, { alwaysMountedKeys: forced }), { + container: harness.list, }); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - wrapperHeight = readSpacerHeight(); - scrollElement.scrollTop = 3_104; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-98")).toBeTruthy()); + const interacted = harness.visibleKeys()[0] ?? ""; + fireEvent.click(screen.getByRole("button", { name: interacted })); - itemHeights.set(95, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-95"), 332); - }); + act(() => harness.layout.userScrollTo(4_000)); + act(() => harness.layout.userScrollTo(2_000)); - expect(wrapperHeight).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_404); + expect(harness.mounted()).toContain("row-3"); + expect(harness.mounted()).toContain(interacted); }); - it("settles the enclosing auto-height wrapper before the position keeper's correction", async () => { - let contentHeight = 0; - let wrapperHeight = 0; - clampScrollTopToContentHeight(() => wrapperHeight); - const positionKeeper = new ScrollPositionKeeper({ - deferWritesWhileScrolling: false, - getDeferredOffsetElement: () => null, - getScrollElement: () => scrollElement, - getTopLevelRows: () => [], - isActive: () => true, - }); - renderWindowedItems({ - positionKeeper, - snapAutoHeight: () => { - wrapperHeight = contentHeight; - }, + it("keeps mounted row elements when crossing the windowing threshold in either direction", () => { + const harness = setup({ attached: true }); + const { rerender } = render(harness.view(keys(19)), { + container: harness.list, }); - await waitFor(() => expect(screen.getByTestId("content-0")).toBeTruthy()); - contentHeight = readSpacerHeight(); - wrapperHeight = contentHeight; - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - positionKeeper.hold(screen.getByTestId("wrapper-50"), "top", 10_000); - - renderedShift = -3_000; - contentHeight += 3_000; - positionKeeper.reconcile(); - - expect(wrapperHeight).toBe(6_200); - expect(scrollElement.scrollTop).toBe(4_600); - }); - - it("keeps the end in place when a visible row grows while pinned to the end", async () => { - clampScrollTopToContentHeight(readSpacerHeight); - renderWindowedItems({ pinnedToEnd: true }); - await waitFor(() => expect(screen.getByTestId("content-98")).toBeTruthy()); - scrollElement.scrollTop = 3_104; - - itemHeights.set(98, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-98"), 332); - }); - - expect(readSpacerHeight()).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_404); - }); - - it("leaves the growing last row to the scroll root while pinned to the end", async () => { - clampScrollTopToContentHeight(readSpacerHeight); - renderWindowedItems({ pinnedToEnd: true }); - await waitFor(() => expect(screen.getByTestId("content-99")).toBeTruthy()); - scrollElement.scrollTop = 3_104; - - itemHeights.set(99, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-99"), 332); - }); - - expect(readSpacerHeight()).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_104); - }); - - it("renders everything when its scrollport has no usable geometry", async () => { - renderWindowedItems({ clientHeight: 0 }); + const element = harness.list.querySelector( + '[data-timeline-row-id="row-18"]', + ); - await waitFor(() => - expect(screen.getAllByTestId(/^content-/)).toHaveLength(100), + act(() => rerender(harness.view(keys(20)))); + expect(harness.list.querySelector('[data-timeline-row-id="row-18"]')).toBe( + element, + ); + act(() => rerender(harness.view(keys(19)))); + expect(harness.list.querySelector('[data-timeline-row-id="row-18"]')).toBe( + element, ); }); }); diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index f0fd01f8481..cb39a73f669 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -1,28 +1,23 @@ import { createContext, useCallback, - useContext, useLayoutEffect, useMemo, useRef, useState, - type CSSProperties, type ReactNode, type SyntheticEvent, } from "react"; -import { useComposedRefs } from "@radix-ui/react-compose-refs"; -import { - defaultRangeExtractor, - elementScroll, - observeElementOffset, - useVirtualizer, - type Range, -} from "@tanstack/react-virtual"; -import { AutoHeightSnapContext } from "@/components/ui/height-transition"; +import { flushSync } from "react-dom"; import type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; export const DEFAULT_WINDOWING_MIN_ITEM_COUNT = 20; const MAX_MEASUREMENTS = 2_000; +const OVERSCAN_ITEMS = 8; +const EDGE_MARGIN_ITEMS = 2; +const TOP_MOUNT_VIEWPORTS = 2; +const MAX_INTERACTION_PINS = 24; +const MAX_WINDOW_UPDATES_PER_FRAME = 8; export function recordTimelineMeasurement( measurements: Map, @@ -52,17 +47,20 @@ export const TimelineWindowingMeasurementsContext = createContext | null>(null); export interface TimelineWindowedItemRenderState { - itemIndex: number | undefined; - itemRef: (node: HTMLDivElement | null) => void; - itemStyle: CSSProperties | undefined; + itemRef: (node: HTMLDivElement | null) => (() => void) | undefined; windowingEnabled: boolean; } +export interface TimelineWindowAnchor { + key: string; + offset: number; +} + export interface TimelineWindowedItemsProps { alwaysMountedKeys?: ReadonlySet; estimateItemHeight: (index: number) => number; gap: number; - getScrollElement: (() => HTMLElement | null) | null; + initialWindowAnchor?: TimelineWindowAnchor | null; itemKeys: readonly string[]; measurements: Map; positionKeeper: ScrollPositionKeeper | null; @@ -73,18 +71,120 @@ export interface TimelineWindowedItemsProps { pinnedToEnd: boolean; } -const TIMELINE_WINDOW_OVERSCAN_ITEMS = 8; -const TIMELINE_WINDOW_MAX_INTERACTION_PINS = 24; +interface LayoutModel { + heights: number[]; + offsets: number[]; + total: number; +} + +interface IndexRange { + start: number; + end: number; +} + +interface WindowState { + keys: ReadonlySet; + heights: ReadonlyMap; +} const EMPTY_KEY_SET: ReadonlySet = new Set(); -const GET_NO_SCROLL_ELEMENT = () => null; - -function measureBorderBox( - element: HTMLElement, - entry: ResizeObserverEntry | undefined, -): number { - const observedHeight = entry?.borderBoxSize[0]?.blockSize; - return observedHeight ?? element.getBoundingClientRect().height; +const WINDOW_KEY_ATTRIBUTE = "data-timeline-window-key"; + +function buildModel( + itemKeys: readonly string[], + heights: ReadonlyMap, + estimateItemHeight: (index: number) => number, + gap: number, +): LayoutModel { + const itemHeights = new Array(itemKeys.length); + const offsets = new Array(itemKeys.length); + let top = 0; + for (let index = 0; index < itemKeys.length; index += 1) { + const key = itemKeys[index]; + const height = + (key === undefined ? undefined : heights.get(key)) ?? + Math.max(1, estimateItemHeight(index)); + itemHeights[index] = height; + offsets[index] = top; + top += height + gap; + } + return { + heights: itemHeights, + offsets, + total: itemKeys.length === 0 ? 0 : top - gap, + }; +} + +function indexAtOffset(model: LayoutModel, offset: number): number { + let low = 0; + let high = model.offsets.length - 1; + let found = 0; + while (low <= high) { + const index = low + Math.floor((high - low) / 2); + if ((model.offsets[index] ?? 0) <= offset) { + found = index; + low = index + 1; + } else { + high = index - 1; + } + } + return found; +} + +function visibleRange( + model: LayoutModel, + localTop: number, + viewportHeight: number, +): IndexRange { + const count = model.offsets.length; + if (count === 0) return { start: 0, end: -1 }; + const start = indexAtOffset(model, Math.max(0, localTop)); + const end = indexAtOffset(model, Math.max(0, localTop + viewportHeight)); + return { start, end: Math.min(count - 1, Math.max(start, end)) }; +} + +function reachesListTop( + model: LayoutModel, + visible: IndexRange, + viewportHeight: number, +): boolean { + return ( + (model.offsets[visible.start] ?? 0) < TOP_MOUNT_VIEWPORTS * viewportHeight + ); +} + +function windowKeysAround( + itemKeys: readonly string[], + visible: IndexRange, + mountToTop: boolean, +): Set { + const keys = new Set(); + const start = mountToTop ? 0 : Math.max(0, visible.start - OVERSCAN_ITEMS); + const end = Math.min(itemKeys.length - 1, visible.end + OVERSCAN_ITEMS); + for (let index = start; index <= end; index += 1) { + const key = itemKeys[index]; + if (key !== undefined) keys.add(key); + } + return keys; +} + +function heldKeyOf(positionKeeper: ScrollPositionKeeper): string | null { + const position = positionKeeper.getPosition(); + return position.kind === "anchor" + ? position.key + : positionKeeper.pendingRestoreRowId(); +} + +function sameKeys(left: ReadonlySet, right: ReadonlySet) { + if (left.size !== right.size) return false; + for (const key of left) if (!right.has(key)) return false; + return true; +} + +function spacerHeight(model: LayoutModel, first: number, last: number) { + const top = model.offsets[first] ?? 0; + const bottom = (model.offsets[last] ?? 0) + (model.heights[last] ?? 0); + return Math.max(0, bottom - top); } function findOwnedWindowKey( @@ -94,7 +194,7 @@ function findOwnedWindowKey( ): string | null { let element = target instanceof Element ? target : null; while (element !== null && element !== container) { - const key = element.getAttribute("data-timeline-window-key"); + const key = element.getAttribute(WINDOW_KEY_ATTRIBUTE); if (key !== null && indexByKey.has(key)) return key; element = element.parentElement; } @@ -105,329 +205,369 @@ export function TimelineWindowedItems({ alwaysMountedKeys = EMPTY_KEY_SET, estimateItemHeight, gap, - getScrollElement, + initialWindowAnchor = null, itemKeys, measurements, positionKeeper, renderItem, pinnedToEnd, }: TimelineWindowedItemsProps) { - const configured = - itemKeys.length >= DEFAULT_WINDOWING_MIN_ITEM_COUNT && - getScrollElement !== null; - const [scrollRootStatus, setScrollRootStatus] = useState< - "pending" | "usable" | "unusable" - >("pending"); - const [initialRect] = useState(() => ({ - width: 0, - height: typeof window === "undefined" ? 800 : window.innerHeight, - })); - const [scrollMargin, setScrollMargin] = useState(0); + const windowingEnabled = + positionKeeper !== null && + itemKeys.length >= DEFAULT_WINDOWING_MIN_ITEM_COUNT; + const containerRef = useRef(null); + const [windowState, setWindowState] = useState(() => { + const heights = new Map(measurements); + if (itemKeys.length < DEFAULT_WINDOWING_MIN_ITEM_COUNT) { + return { keys: new Set(itemKeys), heights }; + } + const model = buildModel(itemKeys, heights, estimateItemHeight, gap); + const viewportHeight = + positionKeeper?.getViewportHeight() || window.innerHeight; + const anchorIndex = + initialWindowAnchor === null + ? -1 + : itemKeys.indexOf(initialWindowAnchor.key); + const localTop = + anchorIndex >= 0 && initialWindowAnchor !== null + ? (model.offsets[anchorIndex] ?? 0) - initialWindowAnchor.offset + : pinnedToEnd + ? model.total - viewportHeight + : 0; + const visible = visibleRange(model, localTop, viewportHeight); + return { + keys: windowKeysAround( + itemKeys, + visible, + reachesListTop(model, visible, viewportHeight), + ), + heights, + }; + }); const [interactionPins, setInteractionPins] = useState([]); - const containerElementRef = useRef(null); - const windowingEnabled = configured && scrollRootStatus !== "unusable"; - const resolvedGetScrollElement = getScrollElement ?? GET_NO_SCROLL_ELEMENT; const indexByKey = useMemo( () => new Map(itemKeys.map((key, index) => [key, index])), [itemKeys], ); - const forcedIndexes = useMemo(() => { + const renderModel = useMemo( + () => buildModel(itemKeys, windowState.heights, estimateItemHeight, gap), + [estimateItemHeight, gap, itemKeys, windowState.heights], + ); + const mountedIndexes = useMemo(() => { + if (!windowingEnabled) return itemKeys.map((_, index) => index); const indexes = new Set(); - for (const key of alwaysMountedKeys) { + const add = (key: string) => { const index = indexByKey.get(key); if (index !== undefined) indexes.add(index); + }; + for (const key of windowState.keys) add(key); + for (const key of alwaysMountedKeys) add(key); + for (const key of interactionPins) add(key); + return [...indexes].sort((left, right) => left - right); + }, [ + alwaysMountedKeys, + indexByKey, + interactionPins, + itemKeys, + windowState.keys, + windowingEnabled, + ]); + + const liveRef = useRef({ + estimateItemHeight, + gap, + indexByKey, + itemKeys, + mountedIndexes, + renderedHeights: windowState.heights, + windowKeys: windowState.keys, + windowingEnabled, + }); + useLayoutEffect(() => { + liveRef.current = { + estimateItemHeight, + gap, + indexByKey, + itemKeys, + mountedIndexes, + renderedHeights: windowState.heights, + windowKeys: windowState.keys, + windowingEnabled, + }; + }); + + const modelCacheRef = useRef<{ + itemKeys: readonly string[]; + mountedIndexes: readonly number[]; + renderedHeights: ReadonlyMap; + revision: number; + model: LayoutModel; + } | null>(null); + const measurementRevisionRef = useRef(0); + const renderedModel = useCallback((): LayoutModel => { + const live = liveRef.current; + const cached = modelCacheRef.current; + if ( + cached !== null && + cached.itemKeys === live.itemKeys && + cached.mountedIndexes === live.mountedIndexes && + cached.renderedHeights === live.renderedHeights && + cached.revision === measurementRevisionRef.current + ) { + return cached.model; } - for (const key of interactionPins) { - const index = indexByKey.get(key); - if (index !== undefined) indexes.add(index); + const heights = new Map(live.renderedHeights); + for (const index of live.mountedIndexes) { + const key = live.itemKeys[index]; + const height = key === undefined ? undefined : measurements.get(key); + if (key !== undefined && height !== undefined) heights.set(key, height); } - return indexes; - }, [alwaysMountedKeys, indexByKey, interactionPins]); + const model = buildModel( + live.itemKeys, + heights, + live.estimateItemHeight, + live.gap, + ); + modelCacheRef.current = { + itemKeys: live.itemKeys, + mountedIndexes: live.mountedIndexes, + renderedHeights: live.renderedHeights, + revision: measurementRevisionRef.current, + model, + }; + return model; + }, [measurements]); - const getItemKey = useCallback( - (index: number) => itemKeys[index] ?? index, - [itemKeys], - ); - const estimateSize = useCallback( - (index: number) => { - const key = itemKeys[index]; - return key === undefined - ? Math.max(1, estimateItemHeight(index)) - : (measurements.get(key) ?? Math.max(1, estimateItemHeight(index))); + const record = useCallback( + (key: string, height: number): boolean => { + if (height <= 0 || measurements.get(key) === height) return false; + recordTimelineMeasurement(measurements, key, height); + measurementRevisionRef.current += 1; + return true; }, - [estimateItemHeight, itemKeys, measurements], + [measurements], ); - const measureElement = useCallback( - ( - element: HTMLDivElement, - entry: ResizeObserverEntry | undefined, - ): number => { - const index = Number(element.dataset.index); - const height = measureBorderBox(element, entry); - const key = Number.isInteger(index) ? itemKeys[index] : undefined; - if (key !== undefined && height > 0) { - recordTimelineMeasurement(measurements, key, height); + + const observerRef = useRef(null); + const getObserver = useCallback((): ResizeObserver | null => { + if (observerRef.current !== null) return observerRef.current; + if (typeof ResizeObserver === "undefined") return null; + observerRef.current = new ResizeObserver((entries) => { + let changed = false; + for (const entry of entries) { + const key = entry.target.getAttribute(WINDOW_KEY_ATTRIBUTE); + if (key === null) continue; + const height = + entry.borderBoxSize?.[0]?.blockSize ?? + entry.target.getBoundingClientRect().height; + if (record(key, height)) changed = true; } - return height > 0 ? height : estimateSize(index); + if (changed) positionKeeper?.reconcile(); + }); + return observerRef.current; + }, [positionKeeper, record]); + + useLayoutEffect( + () => () => { + observerRef.current?.disconnect(); + observerRef.current = null; }, - [estimateSize, itemKeys, measurements], + [], ); - const rangeExtractor = useCallback( - (range: Range) => { - const indexes = new Set(defaultRangeExtractor(range)); - for (const index of forcedIndexes) indexes.add(index); - return [...indexes].sort((left, right) => left - right); + + const itemRef = useCallback( + (node: HTMLDivElement | null) => { + if (node === null) return undefined; + const key = node.getAttribute(WINDOW_KEY_ATTRIBUTE); + if (key !== null) record(key, node.getBoundingClientRect().height); + const observer = getObserver(); + observer?.observe(node); + return () => { + observer?.unobserve(node); + }; }, - [forcedIndexes], + [getObserver, record], ); - const initialOffset = useCallback(() => { - const scrollElement = resolvedGetScrollElement(); - if (!pinnedToEnd) { - return ( - (scrollElement?.scrollTop ?? 0) + - (positionKeeper?.getDeferredOffset() ?? 0) - ); - } - let estimatedEnd = scrollMargin; - for (let index = 0; index < itemKeys.length; index += 1) { - estimatedEnd += estimateSize(index) + (index > 0 ? gap : 0); + + const frameUpdatesRef = useRef({ count: 0, frame: null as number | null }); + const takeFrameUpdate = useCallback((): boolean => { + const budget = frameUpdatesRef.current; + if (budget.frame === null) { + budget.frame = requestAnimationFrame(() => { + budget.frame = null; + budget.count = 0; + }); } - const viewportHeight = scrollElement?.clientHeight || initialRect.height; - return Math.max(0, estimatedEnd - viewportHeight); - }, [ - estimateSize, - gap, - initialRect, - itemKeys, - positionKeeper, - resolvedGetScrollElement, - scrollMargin, - pinnedToEnd, - ]); - const snapAutoHeight = useContext(AutoHeightSnapContext); - const scrollToFn = useCallback>( - (offset, options, instance) => { - const container = containerElementRef.current; - if (container !== null) { - container.style.height = `${instance.getTotalSize()}px`; - } - snapAutoHeight?.(); - if (positionKeeper?.isActive() === true) return; - elementScroll(offset, options, instance); + budget.count += 1; + return budget.count <= MAX_WINDOW_UPDATES_PER_FRAME; + }, []); + useLayoutEffect( + () => () => { + const frame = frameUpdatesRef.current.frame; + if (frame !== null) cancelAnimationFrame(frame); }, - [positionKeeper, snapAutoHeight], + [], ); - const observeOffset = useCallback>( - (instance, callback) => { - const unobserve = observeElementOffset(instance, (offset, isScrolling) => - callback( - offset + (positionKeeper?.getDeferredOffset() ?? 0), - isScrolling, - ), - ); - const unsubscribe = positionKeeper?.subscribeScrollWrites(() => { - const scrollElement = instance.scrollElement; - if (scrollElement !== null) { - callback( - scrollElement.scrollTop + positionKeeper.getDeferredOffset(), - instance.isScrolling, - ); + + const syncWindow = useCallback( + (urgent: boolean) => { + const live = liveRef.current; + if (!live.windowingEnabled || positionKeeper === null) return; + const container = containerRef.current; + const scrollElement = positionKeeper.getScrollElement(); + if (container === null || scrollElement === null) return; + const viewportHeight = + positionKeeper.getViewportHeight() || scrollElement.clientHeight; + if (viewportHeight <= 0) return; + const model = renderedModel(); + const localTop = + scrollElement.getBoundingClientRect().top - + container.getBoundingClientRect().top; + const visible = visibleRange(model, localTop, viewportHeight); + if (visible.end < visible.start) return; + const mounted = new Set(live.mountedIndexes); + let uncovered = false; + for (let index = visible.start; index <= visible.end; index += 1) { + if (!mounted.has(index)) { + uncovered = true; + break; } - }); - return () => { - unobserve?.(); - unsubscribe?.(); - }; + } + const windowIndexes: number[] = []; + for (const key of live.windowKeys) { + const index = live.indexByKey.get(key); + if (index !== undefined) windowIndexes.push(index); + } + const first = windowIndexes.length ? Math.min(...windowIndexes) : 0; + const last = windowIndexes.length ? Math.max(...windowIndexes) : -1; + const mountToTop = reachesListTop(model, visible, viewportHeight); + const nearEdge = + (mountToTop && first > 0) || + (visible.start - first < EDGE_MARGIN_ITEMS && first > 0) || + (last - visible.end < EDGE_MARGIN_ITEMS && + last < live.itemKeys.length - 1) || + (!mountToTop && visible.start - first > 3 * OVERSCAN_ITEMS) || + last - visible.end > 3 * OVERSCAN_ITEMS; + if (!uncovered && !nearEdge) return; + const keys = windowKeysAround(live.itemKeys, visible, mountToTop); + const heldKey = heldKeyOf(positionKeeper); + if (heldKey !== null && live.indexByKey.has(heldKey)) keys.add(heldKey); + if (sameKeys(keys, live.windowKeys) || !takeFrameUpdate()) return; + const heights = new Map(); + for (const key of live.itemKeys) { + const height = + measurements.get(key) ?? live.renderedHeights.get(key); + if (height !== undefined) heights.set(key, height); + } + const apply = () => setWindowState({ keys, heights }); + if (urgent && uncovered) { + flushSync(apply); + } else { + apply(); + } }, - [positionKeeper], - ); - const reconcileScrollPosition = useCallback(() => { - positionKeeper?.reconcile(); - }, [positionKeeper]); - - const virtualizer = useVirtualizer({ - count: itemKeys.length, - directDomUpdates: true, - directDomUpdatesMode: "position", - enabled: windowingEnabled, - estimateSize, - gap, - getItemKey, - getScrollElement: resolvedGetScrollElement, - initialOffset, - initialRect, - measureElement, - observeElementOffset: observeOffset, - onChange: reconcileScrollPosition, - overscan: TIMELINE_WINDOW_OVERSCAN_ITEMS, - rangeExtractor, - scrollMargin, - scrollToFn, - useFlushSync: false, - }); - const containerRef = useComposedRefs( - containerElementRef, - virtualizer.containerRef, + [measurements, positionKeeper, renderedModel, takeFrameUpdate], ); - useLayoutEffect(() => { - virtualizer.shouldAdjustScrollPositionOnItemSizeChange = ( - item, - _delta, - instance, - ) => { - if (positionKeeper?.isActive() === true) return false; - if (pinnedToEnd) return item.index < instance.options.count - 1; - const scrollTop = resolvedGetScrollElement()?.scrollTop ?? 0; - if (item.start >= scrollTop) return false; - if (!instance.itemSizeCache.has(item.key)) return true; - return item.end <= scrollTop; - }; - }, [pinnedToEnd, positionKeeper, resolvedGetScrollElement, virtualizer]); - - const rowOffsetStateRef = useRef({ indexByKey, windowingEnabled }); - rowOffsetStateRef.current = { indexByKey, windowingEnabled }; useLayoutEffect(() => { if (positionKeeper === null) return; - return positionKeeper.registerRowOffsetSource((rowId) => { - const { indexByKey: keys, windowingEnabled: windowed } = - rowOffsetStateRef.current; - const index = keys.get(rowId); - const container = containerElementRef.current; - const scrollElement = virtualizer.scrollElement; - if (!windowed || index === undefined || container === null) return null; - if (scrollElement === null || !container.isConnected) return null; - const item = virtualizer.measurementsCache[index]; - if (item === undefined) return null; - const containerOffset = - container.getBoundingClientRect().top - - scrollElement.getBoundingClientRect().top + - scrollElement.scrollTop; - return containerOffset + item.start - virtualizer.options.scrollMargin; + return positionKeeper.registerList({ + itemAt: (viewportTop) => { + const live = liveRef.current; + const container = containerRef.current; + if (container === null || live.itemKeys.length === 0) return null; + const model = renderedModel(); + const containerTop = container.getBoundingClientRect().top; + const localTop = viewportTop - containerTop; + if (localTop > model.total) return null; + const index = indexAtOffset(model, Math.max(0, localTop)); + const key = live.itemKeys[index]; + if (key === undefined) return null; + return { key, top: containerTop + (model.offsets[index] ?? 0) }; + }, + onPositionChange: syncWindow, }); - }, [positionKeeper, virtualizer]); + }, [positionKeeper, renderedModel, syncWindow]); - useLayoutEffect(() => { - if (positionKeeper === null || snapAutoHeight === null) return; - return positionKeeper.registerScrollExtentSync(snapAutoHeight); - }, [positionKeeper, snapAutoHeight]); - - useLayoutEffect(reconcileScrollPosition); - - const updateScrollGeometry = useCallback(() => { - if (!configured) return; - const container = containerElementRef.current; - const scrollElement = resolvedGetScrollElement(); - if (container === null || scrollElement === null) return; - const nextMargin = - container.getBoundingClientRect().top - - scrollElement.getBoundingClientRect().top + - scrollElement.scrollTop - - scrollElement.clientTop + - (positionKeeper?.getDeferredOffset() ?? 0); - setScrollMargin((previous) => - Math.abs(previous - nextMargin) < 0.5 ? previous : nextMargin, - ); - }, [configured, positionKeeper, resolvedGetScrollElement]); + const mountHeldKey = useCallback((): boolean => { + if (positionKeeper === null) return false; + const live = liveRef.current; + const heldKey = heldKeyOf(positionKeeper); + if (heldKey === null || !live.windowingEnabled) return false; + const index = live.indexByKey.get(heldKey); + if (index === undefined || live.mountedIndexes.includes(index)) { + return false; + } + setWindowState((current) => ({ + keys: new Set([...current.keys, heldKey]), + heights: current.heights, + })); + return true; + }, [positionKeeper]); useLayoutEffect(() => { - if (!configured) return; - const updateRootUsability = () => { - const scrollElement = resolvedGetScrollElement(); - if (scrollElement !== null) { - setScrollRootStatus( - scrollElement.clientHeight > 0 ? "usable" : "unusable", - ); - } - }; - let frame: number | undefined; - let observer: ResizeObserver | undefined; - const attach = () => { - const scrollElement = resolvedGetScrollElement(); - if (scrollElement === null) { - frame = requestAnimationFrame(attach); - return; - } - updateRootUsability(); - updateScrollGeometry(); - if (typeof ResizeObserver === "undefined") return; - observer = new ResizeObserver(() => { - updateRootUsability(); - updateScrollGeometry(); - }); - observer.observe(scrollElement); - const containerParent = containerElementRef.current?.parentElement; - if (containerParent !== null && containerParent !== undefined) { - observer.observe(containerParent); - } - }; - attach(); - return () => { - if (frame !== undefined) cancelAnimationFrame(frame); - observer?.disconnect(); - }; - }, [configured, resolvedGetScrollElement, updateScrollGeometry]); - - useLayoutEffect(updateScrollGeometry); + if (positionKeeper === null || mountHeldKey()) return; + positionKeeper.reconcile(false); + syncWindow(false); + }); const retainInteractedItem = useCallback( (event: SyntheticEvent) => { - const container = containerElementRef.current; + const container = containerRef.current; if (container === null) return; const key = findOwnedWindowKey(event.target, container, indexByKey); if (key === null) return; setInteractionPins((previous) => { + if (previous.at(-1) === key) return previous; const next = previous.filter((candidate) => candidate !== key); next.push(key); - return next.slice(-TIMELINE_WINDOW_MAX_INTERACTION_PINS); + return next.slice(-MAX_INTERACTION_PINS); }); }, [indexByKey], ); - const virtualItemsByIndex = new Map( - virtualizer.getVirtualItems().map((item) => [item.index, item]), - ); - for (const index of forcedIndexes) { - const item = virtualizer.measurementsCache[index]; - if (item !== undefined) virtualItemsByIndex.set(index, item); + const children: ReactNode[] = []; + let previous = -1; + for (const index of mountedIndexes) { + if (index > previous + 1) { + children.push( +
, + ); + } + children.push(renderItem(index, { itemRef, windowingEnabled })); + previous = index; } - const virtualItems = [...virtualItemsByIndex.values()].sort( - (left, right) => left.index - right.index, - ); - const indexes = windowingEnabled - ? virtualItems.map((item) => item.index) - : itemKeys.map((_, index) => index); + if (mountedIndexes.length > 0 && previous < itemKeys.length - 1) { + children.push( +
, + ); + } + return (
- {indexes.map((index) => - renderItem(index, { - itemIndex: index, - itemRef: windowingEnabled - ? virtualizer.measureElement - : (element) => { - if (element === null) return; - const key = itemKeys[index]; - const height = element.getBoundingClientRect().height; - if (key !== undefined && height > 0) { - recordTimelineMeasurement(measurements, key, height); - } - }, - itemStyle: windowingEnabled - ? { position: "absolute", left: 0, width: "100%" } - : undefined, - windowingEnabled, - }), - )} + {children}
); } diff --git a/apps/app/src/components/thread/timeline/ToolCallDetailBlock.tsx b/apps/app/src/components/thread/timeline/ToolCallDetailBlock.tsx index 2f5ff135100..7d661de9227 100644 --- a/apps/app/src/components/thread/timeline/ToolCallDetailBlock.tsx +++ b/apps/app/src/components/thread/timeline/ToolCallDetailBlock.tsx @@ -95,7 +95,6 @@ export function ToolCallDetailBlock({ size="base" overflowX="hidden" streaming={streaming} - contentKey={output} scrollClassName="px-4 py-3 font-mono text-xs leading-tight text-foreground opacity-70" > diff --git a/apps/app/src/components/thread/timeline/WorkflowWorkRowBody.tsx b/apps/app/src/components/thread/timeline/WorkflowWorkRowBody.tsx index 29d66afe49f..1f3f30ba45d 100644 --- a/apps/app/src/components/thread/timeline/WorkflowWorkRowBody.tsx +++ b/apps/app/src/components/thread/timeline/WorkflowWorkRowBody.tsx @@ -21,14 +21,10 @@ export function WorkflowWorkRowBody({ ); } - const contentKey = row.workflow.agents - .map((agent) => `${agent.index}:${agent.state}:${agent.lastProgressAt}`) - .join("|"); return ( void; -} - -let observers: ObserverHandle[] = []; - -function installIntersectionObserverStub(): void { - class ControllableIntersectionObserver { - constructor(private readonly callback: IntersectionObserverCallback) { - observers.push({ - emit: (isIntersecting: boolean) => { - this.callback( - [{ isIntersecting } as IntersectionObserverEntry], - this as unknown as IntersectionObserver, - ); - }, - }); - } - observe(): void {} - unobserve(): void {} - disconnect(): void {} - takeRecords(): IntersectionObserverEntry[] { - return []; - } - } - vi.stubGlobal("IntersectionObserver", ControllableIntersectionObserver); -} - -function emitIntersection(isIntersecting: boolean): void { - act(() => { - for (const observer of observers) { - observer.emit(isIntersecting); - } - }); -} +import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; function createBottomAnchor( - scrollElement = document.createElement("div"), + scrollElement: HTMLElement = document.createElement("div"), ): BottomAnchorContextValue { + const positionKeeper = new ScrollPositionKeeper({ + bottomThresholdPx: 4, + deferWritesWhileScrolling: false, + getContentElement: () => null, + getFooterElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => [], + initiallyAttached: false, + }); return { getScrollElement: () => scrollElement, isAtBottom: false, scrollToBottom: vi.fn(), scrollElementIntoView: vi.fn(), scrollElementIntoViewClampedToMaxScroll: vi.fn(), - positionKeeper: createInertScrollPositionKeeper(), + positionKeeper, holdContentPosition: vi.fn(), }; } +function notifyPosition(anchor: BottomAnchorContextValue): void { + act(() => { + anchor.positionKeeper.reconcile(); + vi.runOnlyPendingTimers(); + }); +} + function mockElementRect( element: HTMLElement, { bottom, top }: { bottom: number; top: number }, @@ -97,32 +77,42 @@ function renderAutoLoad(args: { { initialProps: { isLoading: false }, wrapper }, ); const sentinel = document.createElement("div"); + document.body.append(sentinel); + mockElementRect(sentinel, { top: -2_000, bottom: -1_980 }); act(() => { result.result.current.sentinelRef(sentinel); }); return { ...result, sentinel }; } +function scrollElementAt(top: number, bottom: number): HTMLElement { + const scrollElement = document.createElement("div"); + mockElementRect(scrollElement, { top, bottom }); + return scrollElement; +} + beforeEach(() => { - observers = []; - installIntersectionObserverStub(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); }); afterEach(() => { cleanup(); - vi.unstubAllGlobals(); + document.body.replaceChildren(); + vi.useRealTimers(); + vi.restoreAllMocks(); }); describe("useAutoLoadOlderRows", () => { - it("loads the next page when the top of the window scrolls into view", async () => { + it("loads the next page when a position update brings the top of the window into range", () => { const onLoadOlderRows = vi.fn(() => Promise.resolve()); - const anchor = createBottomAnchor(); - const { result } = renderAutoLoad({ anchor, onLoadOlderRows }); + const anchor = createBottomAnchor(scrollElementAt(0, 500)); + const { result, sentinel } = renderAutoLoad({ anchor, onLoadOlderRows }); expect(result.current.isAutoLoadEnabled).toBe(true); expect(onLoadOlderRows).not.toHaveBeenCalled(); - emitIntersection(true); + mockElementRect(sentinel, { top: -400, bottom: -380 }); + notifyPosition(anchor); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); }); @@ -132,7 +122,6 @@ describe("useAutoLoadOlderRows", () => { const { result } = renderAutoLoad({ anchor: null, onLoadOlderRows }); expect(result.current.isAutoLoadEnabled).toBe(false); - emitIntersection(true); expect(onLoadOlderRows).not.toHaveBeenCalled(); act(() => { @@ -141,14 +130,13 @@ describe("useAutoLoadOlderRows", () => { expect(onLoadOlderRows).toHaveBeenCalledTimes(1); }); - it("keeps loading while the sentinel stays visible after a page settles", async () => { + it("keeps loading while the sentinel stays in range after a page settles", async () => { const onLoadOlderRows = vi.fn(() => Promise.resolve()); - const { rerender } = renderAutoLoad({ - anchor: createBottomAnchor(), - onLoadOlderRows, - }); + const anchor = createBottomAnchor(scrollElementAt(0, 500)); + const { rerender, sentinel } = renderAutoLoad({ anchor, onLoadOlderRows }); - emitIntersection(true); + mockElementRect(sentinel, { top: 100, bottom: 120 }); + notifyPosition(anchor); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); await act(async () => { @@ -162,39 +150,61 @@ describe("useAutoLoadOlderRows", () => { expect(onLoadOlderRows).toHaveBeenCalledTimes(2); }); - it("does not recapture from stale intersection state after a prepend moves the sentinel away", async () => { - const scrollElement = document.createElement("div"); - mockElementRect(scrollElement, { top: 0, bottom: 500 }); - const anchor = createBottomAnchor(scrollElement); + it("does not load again when a prepend moves the sentinel out of range", async () => { const onLoadOlderRows = vi.fn(() => Promise.resolve()); - const { rerender, sentinel } = renderAutoLoad({ - anchor, - onLoadOlderRows, - }); - mockElementRect(sentinel, { top: 100, bottom: 120 }); + const anchor = createBottomAnchor(scrollElementAt(0, 500)); + const { rerender, sentinel } = renderAutoLoad({ anchor, onLoadOlderRows }); - emitIntersection(true); + mockElementRect(sentinel, { top: 100, bottom: 120 }); + notifyPosition(anchor); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); await act(async () => { rerender({ isLoading: true }); }); - mockElementRect(sentinel, { top: -800, bottom: -780 }); + mockElementRect(sentinel, { top: -3_800, bottom: -3_780 }); await act(async () => { rerender({ isLoading: false }); }); + notifyPosition(anchor); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); }); + it("loads when the reader later scrolls back to the top after a prepend moved the sentinel away", async () => { + const onLoadOlderRows = vi.fn(() => Promise.resolve()); + const anchor = createBottomAnchor(scrollElementAt(48, 900)); + const { rerender, sentinel } = renderAutoLoad({ anchor, onLoadOlderRows }); + + mockElementRect(sentinel, { top: -540, bottom: -512 }); + notifyPosition(anchor); + await act(async () => { + rerender({ isLoading: true }); + }); + mockElementRect(sentinel, { top: -3_790, bottom: -3_762 }); + await act(async () => { + rerender({ isLoading: false }); + }); + expect(onLoadOlderRows).toHaveBeenCalledTimes(1); + + for (const top of [-2_400, -1_200, -564, 64]) { + mockElementRect(sentinel, { top, bottom: top + 28 }); + notifyPosition(anchor); + } + + expect(onLoadOlderRows).toHaveBeenCalledTimes(2); + }); + it("stops auto-loading after a failure instead of retrying in a loop", async () => { const onLoadOlderRows = vi.fn(() => Promise.reject(new Error("boom"))); - const { result, rerender } = renderAutoLoad({ - anchor: createBottomAnchor(), + const anchor = createBottomAnchor(scrollElementAt(0, 500)); + const { result, rerender, sentinel } = renderAutoLoad({ + anchor, onLoadOlderRows, }); - emitIntersection(true); + mockElementRect(sentinel, { top: 100, bottom: 120 }); + notifyPosition(anchor); await act(async () => {}); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); expect(result.current.isAutoLoadEnabled).toBe(false); @@ -202,7 +212,7 @@ describe("useAutoLoadOlderRows", () => { await act(async () => { rerender({ isLoading: false }); }); - emitIntersection(true); + notifyPosition(anchor); await act(async () => {}); expect(onLoadOlderRows).toHaveBeenCalledTimes(1); diff --git a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.ts b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.ts index 977b353374a..f257ab9c31b 100644 --- a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.ts +++ b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.ts @@ -1,4 +1,10 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; import { useBottomAnchoredScroll } from "@/components/ui/bottom-anchored-scroll-body.js"; const AUTO_LOAD_OLDER_ROWS_PREFETCH_MARGIN_PX = 600; @@ -38,14 +44,11 @@ export function useAutoLoadOlderRows({ }: UseAutoLoadOlderRowsArgs): AutoLoadOlderRows { const bottomAnchor = useBottomAnchoredScroll(); const sentinelNodeRef = useRef(null); - const isIntersectingRef = useRef(false); - const [sentinelVersion, setSentinelVersion] = useState(0); - const [intersectionTick, setIntersectionTick] = useState(0); + const loadInFlightRef = useRef(false); const [autoLoadFailed, setAutoLoadFailed] = useState(false); const sentinelRef = useCallback((node: HTMLElement | null) => { sentinelNodeRef.current = node; - setSentinelVersion((version) => version + 1); }, []); const isAutoLoadEnabled = @@ -58,11 +61,14 @@ export function useAutoLoadOlderRows({ if (!onLoadOlderRows) { return; } + loadInFlightRef.current = true; void (async () => { try { await onLoadOlderRows(); } catch { setAutoLoadFailed(true); + } finally { + loadInFlightRef.current = false; } })(); }, [onLoadOlderRows]); @@ -72,55 +78,60 @@ export function useAutoLoadOlderRows({ startLoad(); }, [startLoad]); - useEffect(() => { - if (!isAutoLoadEnabled) { - isIntersectingRef.current = false; - return; - } - const sentinel = sentinelNodeRef.current; - if (!sentinel) { - return; - } - const observer = new IntersectionObserver( - (entries) => { - const entry = entries.at(-1); - isIntersectingRef.current = entry?.isIntersecting ?? false; - if (isIntersectingRef.current) { - setIntersectionTick((tick) => tick + 1); - } - }, - { - root: bottomAnchor?.getScrollElement() ?? null, - rootMargin: `${AUTO_LOAD_OLDER_ROWS_PREFETCH_MARGIN_PX}px 0px 0px 0px`, - }, - ); - observer.observe(sentinel); - return () => observer.disconnect(); - }, [bottomAnchor, isAutoLoadEnabled, sentinelVersion]); + const liveRef = useRef({ + isAutoLoadEnabled, + isLoadingOlderTimelineRows, + startLoad, + }); + useLayoutEffect(() => { + liveRef.current = { + isAutoLoadEnabled, + isLoadingOlderTimelineRows, + startLoad, + }; + }); - useEffect(() => { + const loadIfSentinelInRange = useCallback(() => { + const live = liveRef.current; if ( - !isAutoLoadEnabled || - isLoadingOlderTimelineRows || - !isIntersectingRef.current + !live.isAutoLoadEnabled || + live.isLoadingOlderTimelineRows || + loadInFlightRef.current ) { return; } const sentinel = sentinelNodeRef.current; const scrollElement = bottomAnchor?.getScrollElement(); - if (!sentinel || !scrollElement) { + if (!sentinel?.isConnected || !scrollElement) { return; } - if (!isSentinelWithinPrefetchRange({ scrollElement, sentinel })) { - isIntersectingRef.current = false; - return; + if (isSentinelWithinPrefetchRange({ scrollElement, sentinel })) { + live.startLoad(); } - startLoad(); + }, [bottomAnchor]); + + const positionKeeper = bottomAnchor?.positionKeeper ?? null; + useEffect(() => { + if (positionKeeper === null) return; + let timeout: number | null = null; + const unsubscribe = positionKeeper.subscribePosition(() => { + timeout ??= window.setTimeout(() => { + timeout = null; + loadIfSentinelInRange(); + }, 0); + }); + return () => { + unsubscribe(); + if (timeout !== null) window.clearTimeout(timeout); + }; + }, [loadIfSentinelInRange, positionKeeper]); + + useEffect(() => { + loadIfSentinelInRange(); }, [ - bottomAnchor, - intersectionTick, isAutoLoadEnabled, isLoadingOlderTimelineRows, + loadIfSentinelInRange, startLoad, ]); diff --git a/apps/app/src/components/thread/timeline/useStickyBottomScroll.test.tsx b/apps/app/src/components/thread/timeline/useStickyBottomScroll.test.tsx deleted file mode 100644 index ae53163de5e..00000000000 --- a/apps/app/src/components/thread/timeline/useStickyBottomScroll.test.tsx +++ /dev/null @@ -1,144 +0,0 @@ -// @vitest-environment jsdom - -import { cleanup, fireEvent, render } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { useStickyBottomScroll } from "./useStickyBottomScroll"; - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function StickyScrollProbe({ contentKey }: { contentKey: string }) { - const sticky = useStickyBottomScroll({ - contentKey, - streaming: true, - }); - return ( -
-
-
- ); -} - -describe("useStickyBottomScroll", () => { - it("uses a cached maximum offset in the scroll handler", () => { - vi.stubGlobal("ResizeObserver", undefined); - const { getByTestId, rerender } = render( - , - ); - const scroll = getByTestId("scroll"); - let layoutReads = 0; - let scrollTop = 0; - Object.defineProperties(scroll, { - scrollHeight: { - configurable: true, - get: () => { - layoutReads += 1; - return 120; - }, - }, - clientHeight: { - configurable: true, - get: () => { - layoutReads += 1; - return 20; - }, - }, - scrollTop: { - configurable: true, - get: () => scrollTop, - set: (value: number) => { - scrollTop = value; - }, - }, - }); - - rerender(); - expect(scrollTop).toBe(100); - layoutReads = 0; - - scrollTop = 20; - fireEvent.wheel(scroll); - fireEvent.scroll(scroll); - - expect(layoutReads).toBe(0); - rerender(); - expect(scrollTop).toBe(20); - }); - - it("refreshes the cached maximum when only the content grows", () => { - const observed: Element[] = []; - let fireResize: (() => void) | undefined; - class StubResizeObserver { - constructor(callback: ResizeObserverCallback) { - fireResize = () => callback([], this as unknown as ResizeObserver); - } - observe(element: Element) { - observed.push(element); - } - unobserve() {} - disconnect() {} - } - vi.stubGlobal("ResizeObserver", StubResizeObserver); - - const { getByTestId, rerender } = render( - , - ); - const scroll = getByTestId("scroll"); - expect(observed).toContain(scroll); - expect(observed).toContain(getByTestId("content")); - - let scrollHeight = 120; - let scrollTop = 0; - Object.defineProperties(scroll, { - scrollHeight: { - configurable: true, - get: () => scrollHeight, - }, - clientHeight: { - configurable: true, - get: () => 20, - }, - scrollTop: { - configurable: true, - get: () => scrollTop, - set: (value: number) => { - scrollTop = value; - }, - }, - scrollTo: { - configurable: true, - value: (options: ScrollToOptions) => { - scrollTop = options.top ?? 0; - }, - }, - }); - - rerender(); - expect(scrollTop).toBe(100); - - scrollTop = 40; - fireEvent.wheel(scroll); - fireEvent.scroll(scroll); - - scrollHeight = 220; - fireResize?.(); - scrollTop = 100; - fireEvent.wheel(scroll); - fireEvent.scroll(scroll); - rerender(); - expect(scrollTop).toBe(100); - - scrollTop = 200; - fireEvent.scroll(scroll); - scrollHeight = 260; - rerender(); - expect(scrollTop).toBe(240); - }); -}); diff --git a/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts b/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts index cc3a45d6828..bfb94d0a2f6 100644 --- a/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts +++ b/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts @@ -1,14 +1,4 @@ -import { - useCallback, - useEffect, - useRef, - useState, - type PointerEventHandler, - type RefObject, - type TouchEventHandler, - type UIEventHandler, - type WheelEventHandler, -} from "react"; +import { useLayoutEffect, useRef, useState, type RefObject } from "react"; import { ScrollPositionKeeper, getDirectTimelineRows, @@ -17,23 +7,15 @@ import { isIOSWebKit } from "@/lib/ios-webkit"; interface StickyBottomScrollBinding { contentRef: RefObject; - onPointerDown: PointerEventHandler; - onScroll: UIEventHandler; - onTouchMove: TouchEventHandler; - onTouchStart: TouchEventHandler; - onWheel: WheelEventHandler; positionKeeper: ScrollPositionKeeper; ref: RefObject; } interface UseStickyBottomScrollArgs { - contentKey: string; streaming: boolean; } const STICKY_BOTTOM_THRESHOLD_PX = 4; -const USER_SCROLL_INTENT_MS = 350; -const SMOOTH_SCROLL_MIN_GAP_MS = 250; const ROW_LIST_SELECTOR = "[data-timeline-row-list]"; function getTopLevelRows(scrollElement: HTMLElement): ArrayLike { @@ -41,150 +23,39 @@ function getTopLevelRows(scrollElement: HTMLElement): ArrayLike { return list === null ? [] : getDirectTimelineRows(list); } -function getMaxScrollOffset(element: HTMLElement): number { - return Math.max(0, element.scrollHeight - element.clientHeight); -} - -function scrollToBottom( - element: HTMLElement, - top: number, - smooth: boolean, -): void { - if (smooth) { - element.scrollTo({ top, behavior: "smooth" }); - } else { - element.scrollTop = top; - } -} - export function useStickyBottomScroll({ - contentKey, streaming, }: UseStickyBottomScrollArgs): StickyBottomScrollBinding { const scrollRef = useRef(null); const contentRef = useRef(null); - const shouldStickToBottomRef = useRef(true); - const pointerScrollIntentRef = useRef(false); - const userScrollIntentUntilRef = useRef(0); - const lastScrollAtRef = useRef(0); - const isFirstScrollRef = useRef(true); - const wasStreamingRef = useRef(streaming); - const maxScrollOffsetRef = useRef(0); const [positionKeeper] = useState( () => new ScrollPositionKeeper({ + bottomThresholdPx: STICKY_BOTTOM_THRESHOLD_PX, deferWritesWhileScrolling: isIOSWebKit(navigator), - getDeferredOffsetElement: () => contentRef.current, + getContentElement: () => contentRef.current, + getFooterElement: () => null, getScrollElement: () => scrollRef.current, getTopLevelRows, - isActive: () => !shouldStickToBottomRef.current, + initiallyAttached: streaming, }), ); - const refreshMaxScrollOffset = useCallback((element: TElement): number => { - const nextOffset = getMaxScrollOffset(element); - maxScrollOffsetRef.current = nextOffset; - return nextOffset; - }, []); - - useEffect(() => { + useLayoutEffect(() => { const element = scrollRef.current; if (!element) return; - refreshMaxScrollOffset(element); - const unobserveTouches = positionKeeper.observeTouches(element); - if (typeof ResizeObserver === "undefined") return unobserveTouches; - - const observer = new ResizeObserver(() => { - positionKeeper.reconcile(); - refreshMaxScrollOffset(element); - positionKeeper.capture(); - }); - observer.observe(element); - const content = contentRef.current; - if (content) { - observer.observe(content); - } - return () => { - unobserveTouches(); - observer.disconnect(); - }; - }, [positionKeeper, refreshMaxScrollOffset]); - - useEffect(() => { - const wasStreaming = wasStreamingRef.current; - wasStreamingRef.current = streaming; - if (!streaming && !wasStreaming) { - return; - } - const element = scrollRef.current; - if (!element || !shouldStickToBottomRef.current) { - return; - } - const now = window.performance.now(); - const smooth = - !isFirstScrollRef.current && - now - lastScrollAtRef.current >= SMOOTH_SCROLL_MIN_GAP_MS; - scrollToBottom(element, refreshMaxScrollOffset(element), smooth); - lastScrollAtRef.current = now; - isFirstScrollRef.current = false; - }, [contentKey, refreshMaxScrollOffset, streaming]); - - const markUserScrollIntent = useCallback(() => { - userScrollIntentUntilRef.current = - window.performance.now() + USER_SCROLL_INTENT_MS; - }, []); - - const onPointerDown = useCallback>(() => { - pointerScrollIntentRef.current = true; - }, []); - - const onPointerEnd = useCallback(() => { - pointerScrollIntentRef.current = false; - }, []); - - const syncStickToBottom = useCallback((scrollTop: number) => { - if (maxScrollOffsetRef.current - scrollTop <= STICKY_BOTTOM_THRESHOLD_PX) { - shouldStickToBottomRef.current = true; - return; - } - - const hasUserScrollIntent = - pointerScrollIntentRef.current || - window.performance.now() <= userScrollIntentUntilRef.current; - if (hasUserScrollIntent) { - shouldStickToBottomRef.current = false; - } - }, []); - - const onScroll = useCallback>( - (event) => { - positionKeeper.reconcile(); - syncStickToBottom(event.currentTarget.scrollTop); - positionKeeper.capture(); - }, - [positionKeeper, syncStickToBottom], - ); - - useEffect(() => { - if (!streaming) { - return; + return positionKeeper.connect(element); + }, [positionKeeper]); + + useLayoutEffect(() => { + if ( + streaming && + positionKeeper.getPosition().kind === "free" && + !positionKeeper.hasUserScrolled() + ) { + positionKeeper.scrollToBottom(); } - window.addEventListener("pointerup", onPointerEnd); - window.addEventListener("pointercancel", onPointerEnd); - return () => { - window.removeEventListener("pointerup", onPointerEnd); - window.removeEventListener("pointercancel", onPointerEnd); - }; - }, [onPointerEnd, streaming]); + }, [positionKeeper, streaming]); - return { - contentRef, - onPointerDown, - onScroll, - onTouchMove: markUserScrollIntent, - onTouchStart: markUserScrollIntent, - onWheel: markUserScrollIntent, - positionKeeper, - ref: scrollRef, - }; + return { contentRef, positionKeeper, ref: scrollRef }; } diff --git a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx index cdaa38ada41..58cc4d57923 100644 --- a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx +++ b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx @@ -54,7 +54,7 @@ import { } from "./useThreadTimelineController"; import { makeThreadTimelineResponse as makeTimelineResponse } from "@/test/fixtures/thread-responses"; import { createQueryNotificationScheduler } from "@/test/queryNotificationScheduler"; -import { createInertScrollPositionKeeper } from "@/test/scroll-position-keeper"; +import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; const notifications = createQueryNotificationScheduler(); @@ -229,27 +229,26 @@ function makeSameSnapshotRealtimeResponse(): ThreadTimelineResponse { } function installAutoLoadEnvironment() { - const intersectionCallbacks: IntersectionObserverCallback[] = []; - vi.stubGlobal( - "IntersectionObserver", - class { - constructor(callback: IntersectionObserverCallback) { - intersectionCallbacks.push(callback); - } - observe(): void {} - disconnect(): void {} - }, - ); const scrollElement = document.createElement("div"); const sentinel = document.createElement("div"); + document.body.append(sentinel); vi.spyOn(scrollElement, "getBoundingClientRect").mockReturnValue( new DOMRect(0, 0, 100, 500), ); vi.spyOn(sentinel, "getBoundingClientRect").mockReturnValue( new DOMRect(0, 10, 100, 10), ); + const positionKeeper = new ScrollPositionKeeper({ + bottomThresholdPx: 4, + deferWritesWhileScrolling: false, + getContentElement: () => null, + getFooterElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => [], + initiallyAttached: false, + }); const anchor: BottomAnchorContextValue = { - positionKeeper: createInertScrollPositionKeeper(), + positionKeeper, holdContentPosition: vi.fn(), getScrollElement: () => scrollElement, isAtBottom: false, @@ -258,12 +257,7 @@ function installAutoLoadEnvironment() { scrollToBottom: vi.fn(), }; const emitIntersection = () => { - for (const callback of intersectionCallbacks) { - callback( - [{ isIntersecting: true } as IntersectionObserverEntry], - {} as IntersectionObserver, - ); - } + positionKeeper.reconcile(); }; return { anchor, emitIntersection, sentinel }; } @@ -382,6 +376,50 @@ function markTimelineHasNewEvents(queryClient: QueryClient): void { } describe("useThreadTimelineController", () => { + it("keeps the thread's loaded older pages when its timeline mounts again", async () => { + const olderRow = makeUserRow("thread-1:user-seed:1", 1); + const latestRow = makeUserRow("thread-1:user-seed:10", 10); + const latestPage = makeTimelineResponse({ + rows: [latestRow], + maxSeq: 10, + timelinePage: { + historySnapshot: "snapshot-1", + olderCursor: { anchorId: "cursor-10", anchorSeq: 10 }, + olderRowsSourceSeqEnd: null, + }, + }); + vi.mocked(sdk.threads.timeline) + .mockResolvedValueOnce(latestPage) + .mockResolvedValueOnce( + makeTimelineResponse({ + rows: [olderRow], + maxSeq: 10, + timelinePage: { historySnapshot: "snapshot-1" }, + }), + ) + .mockResolvedValue(latestPage); + const { wrapper } = createQueryClientTestHarness(); + const first = renderHook( + () => useThreadTimelineController({ threadId: "thread-1" }), + { wrapper }, + ); + await waitFor(() => { + expect(first.result.current.hasOlderTimelineRows).toBe(true); + }); + await act(async () => { + await first.result.current.loadOlderTimelineRows(); + }); + first.unmount(); + + const second = renderHook( + () => useThreadTimelineController({ threadId: "thread-1" }), + { wrapper }, + ); + + expect(rowIds(second.result.current)).toEqual([olderRow.id, latestRow.id]); + expect(second.result.current.hasOlderTimelineRows).toBe(false); + }); + it("replaces loaded rows when realtime data starts a new context epoch", async () => { const oldRow = makeUserRow("thread-1:user-seed:1", 1); vi.mocked(sdk.threads.timeline).mockResolvedValue( diff --git a/apps/app/src/components/thread/timeline/useThreadTimelineController.ts b/apps/app/src/components/thread/timeline/useThreadTimelineController.ts index 93cf9252859..fa13f306e65 100644 --- a/apps/app/src/components/thread/timeline/useThreadTimelineController.ts +++ b/apps/app/src/components/thread/timeline/useThreadTimelineController.ts @@ -1,6 +1,7 @@ -import { useCallback, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useQueryClient, + type QueryClient, type QueryObserverResult, } from "@tanstack/react-query"; import type { ThreadTimelineResponse, TimelineRow } from "@bb/server-contract"; @@ -71,6 +72,37 @@ interface ReconcileLoadedTimelineArgs { surfaceKey: string; } +const MAX_RETAINED_LOADED_TIMELINES = 8; +const retainedLoadedTimelines = new WeakMap< + QueryClient, + Map +>(); + +function retainedLoadedTimeline( + queryClient: QueryClient, + surfaceKey: string, +): LoadedTimelineState | undefined { + return retainedLoadedTimelines.get(queryClient)?.get(surfaceKey); +} + +function retainLoadedTimeline( + queryClient: QueryClient, + loaded: LoadedTimelineState, +): void { + let retained = retainedLoadedTimelines.get(queryClient); + if (retained === undefined) { + retained = new Map(); + retainedLoadedTimelines.set(queryClient, retained); + } + retained.delete(loaded.surfaceKey); + retained.set(loaded.surfaceKey, loaded); + while (retained.size > MAX_RETAINED_LOADED_TIMELINES) { + const oldest = retained.keys().next().value; + if (oldest === undefined) break; + retained.delete(oldest); + } +} + function isStaleTimelinePaginationCursorError(error: Error): boolean { return ( error instanceof BbHttpError && @@ -140,7 +172,9 @@ export function useThreadTimelineController({ useState(() => ({ latestTimeline, loaded: reconcileLoadedTimeline({ - current: buildEmptyLoadedTimelineState(surfaceKey), + current: + retainedLoadedTimeline(queryClient, surfaceKey) ?? + buildEmptyLoadedTimelineState(surfaceKey), latestTimeline, surfaceKey, }), @@ -151,12 +185,18 @@ export function useThreadTimelineController({ loadedTimeline.surfaceKey !== surfaceKey ) { loadedTimeline = reconcileLoadedTimeline({ - current: loadedTimelineTracker.loaded, + current: + loadedTimeline.surfaceKey === surfaceKey + ? loadedTimeline + : (retainedLoadedTimeline(queryClient, surfaceKey) ?? loadedTimeline), latestTimeline, surfaceKey, }); setLoadedTimelineTracker({ latestTimeline, loaded: loadedTimeline }); } + useEffect(() => { + retainLoadedTimeline(queryClient, loadedTimeline); + }, [loadedTimeline, queryClient]); const updateLoadedTimeline = useCallback( (update: (current: LoadedTimelineState) => LoadedTimelineState) => { setLoadedTimelineTracker((current) => { diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.coarse-pointer.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.coarse-pointer.test.tsx index 141f88ccf76..bfa871d239c 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.coarse-pointer.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.coarse-pointer.test.tsx @@ -6,17 +6,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll-body"; import { threadTimelineScrollAnchorAtomFamily } from "@/lib/thread-timeline-scroll-anchor"; -interface ScrollMetrics { - scrollHeight: number; - clientHeight: number; - scrollTop: number; -} - -interface RowRect { - top: number; - bottom: number; -} - const SCROLL_AREA_CLASS = "scroll-area"; class ResizeObserverMock implements ResizeObserver { @@ -34,12 +23,6 @@ class ResizeObserverMock implements ResizeObserver { } } -function getLatestResizeObserver(): ResizeObserverMock { - const instance = ResizeObserverMock.instances.at(-1); - if (!instance) throw new Error("Expected a ResizeObserver instance."); - return instance; -} - function stubMediaQueries(matching: ReadonlySet): void { vi.spyOn(window, "matchMedia").mockImplementation((query: string) => ({ matches: matching.has(query), @@ -53,30 +36,6 @@ function stubMediaQueries(matching: ReadonlySet): void { })); } -function setScrollMetrics(element: HTMLElement, metrics: ScrollMetrics) { - Object.defineProperty(element, "scrollHeight", { - configurable: true, - value: metrics.scrollHeight, - }); - Object.defineProperty(element, "clientHeight", { - configurable: true, - value: metrics.clientHeight, - }); - element.scrollTop = metrics.scrollTop; -} - -function mockScrollAreaRect(scrollArea: HTMLElement) { - vi.spyOn(scrollArea, "getBoundingClientRect").mockReturnValue( - new DOMRect(0, 0, 100, 100), - ); -} - -function mockRowRect(row: HTMLElement, rect: RowRect) { - vi.spyOn(row, "getBoundingClientRect").mockReturnValue( - new DOMRect(0, rect.top, 100, rect.bottom - rect.top), - ); -} - function requireHTMLElement(element: Element | null) { if (!(element instanceof HTMLElement)) { throw new Error("Expected HTMLElement."); @@ -132,7 +91,7 @@ afterEach(() => { cleanup(); vi.useRealTimers(); const store = getDefaultStore(); - for (const threadId of ["coarse-thread", "cache-thread"]) { + for (const threadId of ["coarse-thread"]) { store.set(threadTimelineScrollAnchorAtomFamily(threadId), null); } vi.unstubAllGlobals(); @@ -190,60 +149,3 @@ describe("BottomAnchoredScrollBody on coarse pointers", () => { }); }); }); - -describe("BottomAnchoredScrollBody row NodeList cache", () => { - it("reuses the cached rows across captures until a resize invalidates them", () => { - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); - const { scrollArea, rowElements } = renderTimeline("cache-thread", [ - "row-a", - "row-b", - "row-c", - ]); - mockScrollAreaRect(scrollArea); - mockRowRect(requireHTMLElement(rowElements.get("row-a")!), { - top: -120, - bottom: -20, - }); - mockRowRect(requireHTMLElement(rowElements.get("row-b")!), { - top: -20, - bottom: 80, - }); - mockRowRect(requireHTMLElement(rowElements.get("row-c")!), { - top: 80, - bottom: 180, - }); - setScrollMetrics(scrollArea, { - scrollHeight: 400, - clientHeight: 100, - scrollTop: 300, - }); - const queryRows = vi.spyOn(scrollArea, "querySelectorAll"); - - vi.advanceTimersByTime(1_000); - scrollArea.scrollTop = 150; - fireEvent.wheel(scrollArea); - fireEvent.scroll(scrollArea); - expect(readAnchor("cache-thread")).toEqual({ - rowId: "row-b", - offsetWithinRow: 20, - atBottom: false, - }); - expect(queryRows).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime(200); - scrollArea.scrollTop = 140; - fireEvent.scroll(scrollArea); - expect(queryRows).toHaveBeenCalledTimes(1); - - getLatestResizeObserver().trigger(); - vi.advanceTimersByTime(200); - scrollArea.scrollTop = 130; - fireEvent.scroll(scrollArea); - expect(queryRows).toHaveBeenCalledTimes(2); - expect(readAnchor("cache-thread")).toEqual({ - rowId: "row-b", - offsetWithinRow: 20, - atBottom: false, - }); - }); -}); diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.anchor-class.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx similarity index 60% rename from apps/app/src/components/ui/bottom-anchored-scroll-body.anchor-class.test.tsx rename to apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx index 0dfb1a5db3d..0938d49fd6b 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.anchor-class.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.grid.test.tsx @@ -24,33 +24,6 @@ function classTokens(className: string | undefined): string[] { return className?.split(/\s+/) ?? []; } -describe("BottomAnchoredScrollBody scroll-anchor exclusion", () => { - it("excludes only the content wrapper and keeps the sentinel outside it", () => { - vi.stubGlobal("CSS", { - supports: (property: string, value: string) => - property === "overflow-anchor" && value === "none", - }); - const markup = renderBody(); - const structure = markup.match( - /
]*>
row-a<\/div><\/div>} + maxWidthClassName="max-w-none" + scrollAnchorThreadId={threadId} + > + + + ); +} + +function setup(threadId: string, keys: string[]) { + restoreLayout?.(); + const layout = installFakeFlowLayout({ + scrollElement: () => + document.querySelector("[data-page-scroll-viewport]"), + viewportHeight: VIEWPORT_HEIGHT, + }); + restoreLayout = layout.restore; + const view = render(); + act(() => layout.flushResizeObservers()); + const topOf = (key: string) => { + const row = document.querySelector(`[data-timeline-row-id="${key}"]`); + if (row === null) throw new Error(`${key} is not mounted`); + return row.getBoundingClientRect().top; + }; + const firstVisible = () => + [...document.querySelectorAll("[data-timeline-row-id]")] + .map((row) => ({ + key: row.dataset.timelineRowId ?? "", + top: row.getBoundingClientRect().top, + })) + .find((row) => row.top >= 0)?.key ?? ""; + return { layout, topOf, firstVisible, view }; +} + +describe("BottomAnchoredScrollBody", () => { + it("restores the reading row exactly after switching threads and back", () => { + const keysA = rowKeys("thread-a", 120); + const first = setup("thread-a", keysA); + act(() => first.layout.userScrollTo(first.layout.maxScrollTop() - 2_500)); + const reader = first.firstVisible(); + const before = first.topOf(reader); + + first.view.rerender( + , + ); + first.view.unmount(); + const second = setup("thread-a", keysA); + + expect(second.topOf(reader)).toBe(before); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + }); + + it("returns to the end when the thread was left at the end", () => { + const keysA = rowKeys("thread-a", 120); + const first = setup("thread-a", keysA); + first.view.unmount(); + + const second = setup("thread-a", keysA); + + expect(second.layout.scrollTop).toBe(second.layout.maxScrollTop()); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + }); + + it("waits at the end for a saved row that has not loaded, then restores it when it arrives", () => { + const keysA = rowKeys("thread-a", 120); + const first = setup("thread-a", keysA); + act(() => first.layout.userScrollTo(400)); + const reader = first.firstVisible(); + const before = first.topOf(reader); + first.view.unmount(); + + const second = setup("thread-a", keysA.slice(60)); + expect(second.layout.scrollTop).toBe(second.layout.maxScrollTop()); + act(() => second.view.rerender()); + + expect(second.topOf(reader)).toBe(before); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + }); + + it("detaches when the reader scrolls up and re-attaches only when they scroll back down to the end", () => { + const { layout } = setup("thread-a", rowKeys("thread-a", 60)); + const end = layout.maxScrollTop(); + + act(() => layout.userScrollTo(end - 400)); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + act(() => layout.userScrollTo(end - 100)); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + act(() => layout.userScrollTo(end)); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + }); + + it("follows a scroll made without input when nothing changed size, such as find in page", () => { + vi.useFakeTimers({ + toFake: ["setTimeout", "clearTimeout", "performance"], + }); + const { layout, topOf, firstVisible } = setup( + "thread-a", + rowKeys("thread-a", 60), + ); + act(() => layout.userScrollTo(layout.maxScrollTop() - 1_500)); + act(() => vi.advanceTimersByTime(500)); + + act(() => layout.layoutScrollTo(layout.scrollTop - 300)); + const reader = firstVisible(); + const before = topOf(reader); + act(() => layout.flushResizeObservers()); + + expect(layout.scrollTop).toBe(layout.maxScrollTop() - 1_800); + expect(topOf(reader)).toBe(before); + }); + + it("treats a scroll without input that comes with a size change as layout, so it neither detaches nor moves the reader", () => { + vi.useFakeTimers({ + toFake: ["setTimeout", "clearTimeout", "performance"], + }); + const keys = rowKeys("thread-a", 60); + const { layout, topOf, firstVisible } = setup("thread-a", keys); + const last = keys.at(-1) ?? ""; + + document + .querySelector(`[data-timeline-row-id="${last}"]`) + ?.setAttribute("data-fake-height", "20"); + act(() => layout.layoutScrollTo(layout.maxScrollTop())); + act(() => layout.flushResizeObservers()); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + document + .querySelector(`[data-timeline-row-id="${last}"]`) + ?.setAttribute("data-fake-height", String(heightOf(last))); + act(() => layout.flushResizeObservers()); + expect(layout.scrollTop).toBe(layout.maxScrollTop()); + + act(() => layout.userScrollTo(layout.maxScrollTop() - 1_500)); + act(() => vi.advanceTimersByTime(500)); + const reader = firstVisible(); + const before = topOf(reader); + const above = document.querySelector( + `[data-timeline-row-id="${keys[keys.indexOf(reader) - 1]}"]`, + ); + above?.setAttribute("data-fake-height", "30"); + act(() => layout.layoutScrollTo(layout.scrollTop - 40)); + + expect(topOf(reader)).toBe(before); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + }); + + it("keeps the end and the composer still while an attached row expands", () => { + const keys = rowKeys("thread-a", 60); + const { layout, topOf } = setup("thread-a", keys); + const last = keys.at(-1) ?? ""; + const toggled = keys.at(-3) ?? ""; + const lastBefore = topOf(last); + const toggledBefore = topOf(toggled); + const growth = 260; + + act(() => + handles.setHeights((heights) => + heights.set(toggled, heightOf(toggled) + growth), + ), + ); + act(() => layout.flushResizeObservers()); + + expect(topOf(last)).toBe(lastBefore); + expect(topOf(toggled)).toBe(toggledBefore - growth); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + }); + + it("holds a collapsing row's bottom edge when the reader holds it", () => { + const keys = rowKeys("thread-a", 60); + const { layout, topOf, firstVisible } = setup("thread-a", keys); + act(() => layout.userScrollTo(layout.maxScrollTop() - 1_200)); + const key = firstVisible(); + const row = document.querySelector( + `[data-timeline-row-id="${key}"]`, + ); + if (row === null || handles.bottomAnchor === null) + throw new Error("not mounted"); + const bottomBefore = topOf(key) + heightOf(key); + const anchor = handles.bottomAnchor; + + act(() => + anchor.holdContentPosition({ + edge: "bottom", + element: row, + update: () => handles.setHeights((heights) => heights.set(key, 40)), + }), + ); + act(() => layout.flushResizeObservers()); + + expect(topOf(key) + 40).toBe(bottomBefore); + }); +}); 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 00b39231a7b..b43dde0df98 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx @@ -14,14 +14,9 @@ import { useStore } from "jotai"; import { cn } from "@bb/shared-ui/lib/utils"; import { usePointerCoarse } from "@bb/shared-ui/hooks/use-pointer-coarse"; import { PAGE_SHELL_CONTENT_STYLE } from "./page-shell-content-style.js"; -import { supportsScrollAnchoring } from "@/lib/scroll-anchoring-support"; import { PAGE_SCROLL_TO_TOP_EVENT } from "@/lib/page-scroll-to-top"; import { isIOSWebKit } from "@/lib/ios-webkit"; -import { - threadTimelineScrollAnchorAtomFamily, - type ScrollAnchor, -} from "@/lib/thread-timeline-scroll-anchor.js"; -import { layoutAnimationInFlightCountAtom } from "./layoutAnimationAtoms.js"; +import { threadTimelineScrollAnchorAtomFamily } from "@/lib/thread-timeline-scroll-anchor.js"; import { ScrollPositionKeeper, getDirectTimelineRows, @@ -40,6 +35,11 @@ export interface BottomAnchorContextValue { positionKeeper: ScrollPositionKeeper; } +export interface TimelineScrollRestore { + key: string; + offset: number; +} + interface BottomAnchoredScrollBodyProps { children: ReactNode; footer: ReactNode; @@ -65,162 +65,38 @@ interface HoldContentPositionArgs { update: () => void; } -interface ElementVisibilityArgs { - element: HTMLElement; - scrollArea: HTMLElement; -} - const BOTTOM_ANCHOR_THRESHOLD_PX = 4; -const USER_SCROLL_INTENT_MS = 1_000; const SCROLLBAR_IDLE_DELAY_MS = 600; -const BOTTOM_RESTORE_SETTLE_FRAME_COUNT = 3; const SCROLL_ANCHOR_CAPTURE_THROTTLE_MS = 100; const COARSE_SCROLL_ANCHOR_CAPTURE_THROTTLE_MS = 250; -const SCROLL_ANCHOR_RESTORE_MAX_ATTEMPTS = 8; -const CONTENT_POSITION_HOLD_MS = 250; const NATIVE_PAGE_SCROLL_KEYS = new Set(["PageDown", "PageUp", " "]); const EDITABLE_KEY_TARGET_SELECTOR = "input, textarea, select, [contenteditable]:not([contenteditable='false'])"; -const TIMELINE_ROW_ID_SELECTOR = "[data-timeline-row-id]"; const TOP_LEVEL_TIMELINE_ROW_LIST_SELECTOR = '[data-timeline-row-list="top-level"]'; -const TIMELINE_VIRTUAL_SPACER_SELECTOR = - ":scope > [data-timeline-virtual-spacer]"; -const SCROLL_INTENT_KEYS = new Set([ - "ArrowDown", - "ArrowUp", - "End", - "Home", - "PageDown", - "PageUp", - " ", -]); +const TIMELINE_ROW_ID_SELECTOR = "[data-timeline-row-id]"; export const BottomAnchorContext = createContext(null); -export const TimelineScrollRestoreRowIdContext = createContext( - null, -); +export const TimelineScrollRestoreContext = + createContext(null); export function useBottomAnchoredScroll(): BottomAnchorContextValue | null { return useContext(BottomAnchorContext); } -function getMaxScrollOffset(element: HTMLElement) { - return Math.max(0, element.scrollHeight - element.clientHeight); -} - -function isScrolledNearBottom(maxScrollOffset: number, scrollTop: number) { - return maxScrollOffset - scrollTop <= BOTTOM_ANCHOR_THRESHOLD_PX; -} - -function getScrollOffsetToRevealElement({ - element, - scrollArea, -}: ElementVisibilityArgs) { - const elementRect = element.getBoundingClientRect(); - const scrollAreaRect = scrollArea.getBoundingClientRect(); - return Math.max( - 0, - elementRect.top - scrollAreaRect.top + scrollArea.scrollTop, - ); -} - -interface TopMostVisibleRow { - rowId: string; - offsetWithinRow: number; -} - -interface ScrollAnchorRowQuery { - rows: NodeListOf; - windowed: boolean; -} - -function getScrollAnchorRows(scrollArea: HTMLElement): ScrollAnchorRowQuery { +function getTopLevelRows(scrollArea: HTMLElement): ArrayLike { const topLevelList = scrollArea.querySelector( TOP_LEVEL_TIMELINE_ROW_LIST_SELECTOR, ); - if (topLevelList) { - return { - rows: getDirectTimelineRows(topLevelList), - windowed: - topLevelList.querySelector(TIMELINE_VIRTUAL_SPACER_SELECTOR) !== null, - }; - } - return { - rows: scrollArea.querySelectorAll(TIMELINE_ROW_ID_SELECTOR), - windowed: false, - }; -} - -function getTopMostVisibleRow( - scrollArea: HTMLElement, - rows: NodeListOf, -): TopMostVisibleRow | null { - const scrollAreaTop = scrollArea.getBoundingClientRect().top; - let low = 0; - let high = rows.length - 1; - let visibleRow: HTMLElement | null = null; - let visibleRowRect: DOMRect | null = null; - - while (low <= high) { - const index = low + Math.floor((high - low) / 2); - const row = rows[index]; - if (!row) break; - const rowRect = row.getBoundingClientRect(); - if (rowRect.bottom <= scrollAreaTop + 1) { - low = index + 1; - continue; - } - visibleRow = row; - visibleRowRect = rowRect; - high = index - 1; - } - - const rowId = visibleRow?.dataset.timelineRowId; - if (!rowId || !visibleRowRect) return null; - return { - rowId, - offsetWithinRow: Math.max(0, scrollAreaTop - visibleRowRect.top), - }; -} - -function findTimelineRowElement( - scrollArea: HTMLElement, - rowId: string, -): HTMLElement | null { - const rows = scrollArea.querySelectorAll( - TIMELINE_ROW_ID_SELECTOR, - ); - for (const row of rows) { - if (row.dataset.timelineRowId === rowId) return row; - } - return null; -} - -function isEditableKeyboardTarget(target: EventTarget | null) { - if (!(target instanceof HTMLElement)) return false; - - return ( - target.tagName === "INPUT" || - target.tagName === "TEXTAREA" || - target.tagName === "SELECT" || - target.isContentEditable || - target.closest("[contenteditable='true']") !== null - ); + return topLevelList + ? getDirectTimelineRows(topLevelList) + : scrollArea.querySelectorAll(TIMELINE_ROW_ID_SELECTOR); } -function isKeyboardEventFromScrollArea( - event: KeyboardEvent, - scrollArea: HTMLElement, -) { - const target = event.target; - if (!(target instanceof Node)) return true; - if (target === document.body || target === document.documentElement) { - return true; - } - return scrollArea.contains(target); +function prefersReducedMotion(): boolean { + return window.matchMedia("(prefers-reduced-motion: reduce)").matches; } export function BottomAnchoredScrollBody({ @@ -239,211 +115,53 @@ export function BottomAnchoredScrollBody({ const pageContentRef = useRef(null); const scrollFooterRef = useRef(null); const hasFooter = Boolean(footer); - const shouldStickToBottomRef = useRef(true); - const scrollToTopInProgressRef = useRef(false); - const userScrollIntentUntilRef = useRef(0); - const pointerScrollIntentRef = useRef(false); - const restoreFrameRef = useRef(null); - const restoreFramesRemainingRef = useRef(0); - const restoreTailLiveReadRef = useRef(false); - const pendingScrollRestoreRef = useRef<{ - anchor: ScrollAnchor; - attemptsRemaining: number; - lastAppliedScrollTop: number | null; - clampToRow: boolean; - } | null>(null); - const contentPositionHoldUntilRef = useRef(0); const scrollAnchorCaptureThrottleRef = useRef<{ lastWriteAt: number; trailingTimeout: number | null; }>({ lastWriteAt: 0, trailingTimeout: null }); - const userDetachedFromBottomRef = useRef(false); - const maxScrollOffsetRef = useRef(0); - const resizeObserverHasDeliveredRef = useRef(false); - const observedScrollGeometryRef = useRef<{ - scrollAreaClientHeight: number | null; - scrollAreaClientWidth: number | null; - scrollContentHeight: number | null; - }>({ - scrollAreaClientHeight: null, - scrollAreaClientWidth: null, - scrollContentHeight: null, - }); - const scrollAnchorRowsRef = useRef | null>(null); - const [isAtBottom, setIsAtBottom] = useState(true); - const [viewportRestore, setViewportRestore] = useState<{ - threadId: string; - rowId: string; - } | null>(null); - const viewportRestoreRowId = - viewportRestore !== null && - viewportRestore.threadId === scrollAnchorThreadId - ? viewportRestore.rowId - : null; - const initialScrollRestoreRowId = useMemo(() => { + const initialRestore = useMemo(() => { if (scrollAnchorThreadId === undefined) return null; const anchor = store.get( threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId), ); - return anchor !== null && anchor !== undefined && !anchor.atBottom - ? anchor.rowId + return anchor !== null && !anchor.atBottom + ? { key: anchor.rowId, offset: -anchor.offsetWithinRow } : null; }, [scrollAnchorThreadId, store]); + const [isAtBottom, setIsAtBottom] = useState(true); const getScrollElement = useCallback(() => scrollAreaRef.current, []); - const getScrollAnchorRowsCached = useCallback((scrollArea: HTMLElement) => { - const cached = scrollAnchorRowsRef.current; - if ( - cached && - (cached.length === 0 || - (cached[0]?.isConnected === true && - cached[cached.length - 1]?.isConnected === true)) - ) { - return cached; - } - const { rows, windowed } = getScrollAnchorRows(scrollArea); - scrollAnchorRowsRef.current = windowed ? null : rows; - return rows; - }, []); - const [positionKeeper] = useState( () => new ScrollPositionKeeper({ + bottomThresholdPx: BOTTOM_ANCHOR_THRESHOLD_PX, deferWritesWhileScrolling: isIOSWebKit(navigator), - getDeferredOffsetElement: () => pageContentRef.current, + getContentElement: () => pageContentRef.current, + getFooterElement: () => scrollFooterRef.current, getScrollElement: () => scrollAreaRef.current, - getTopLevelRows: getScrollAnchorRowsCached, - isActive: () => - !shouldStickToBottomRef.current && - pendingScrollRestoreRef.current === null, + getTopLevelRows, + initiallyAttached: true, }), ); - const viewportWidthChanged = useCallback((scrollArea: HTMLElement) => { - const previousWidth = - observedScrollGeometryRef.current.scrollAreaClientWidth; - return ( - previousWidth !== null && - previousWidth > 0 && - scrollArea.clientWidth > 0 && - Math.abs(previousWidth - scrollArea.clientWidth) > 1 - ); - }, []); - - const refreshMaxScrollOffset = useCallback((scrollArea: HTMLElement) => { - const maxScrollOffset = getMaxScrollOffset(scrollArea); - maxScrollOffsetRef.current = maxScrollOffset; - return maxScrollOffset; - }, []); - - const readMaxScrollOffset = useCallback( - (scrollArea: HTMLElement) => - resizeObserverHasDeliveredRef.current - ? maxScrollOffsetRef.current - : refreshMaxScrollOffset(scrollArea), - [refreshMaxScrollOffset], + useLayoutEffect( + () => + positionKeeper.subscribe(() => { + setIsAtBottom(positionKeeper.isAttached()); + }), + [positionKeeper], ); - const cancelPendingScrollRestore = useCallback(() => { - pendingScrollRestoreRef.current = null; - }, []); - - const cancelQueuedRestore = useCallback(() => { - scrollToTopInProgressRef.current = false; - if (restoreFrameRef.current === null) return; - window.cancelAnimationFrame(restoreFrameRef.current); - restoreFrameRef.current = null; - restoreFramesRemainingRef.current = 0; - restoreTailLiveReadRef.current = false; - }, []); - - const restoreBottomOnce = useCallback(() => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea || !shouldStickToBottomRef.current) return false; - const maxScrollOffset = refreshMaxScrollOffset(scrollArea); - if (isScrolledNearBottom(maxScrollOffset, scrollArea.scrollTop)) { - return false; - } - scrollArea.scrollTop = maxScrollOffset; - return true; - }, [refreshMaxScrollOffset]); - - const restoreBottomFromCacheOnce = useCallback(() => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea || !shouldStickToBottomRef.current) return false; - const maxScrollOffset = readMaxScrollOffset(scrollArea); - if (isScrolledNearBottom(maxScrollOffset, scrollArea.scrollTop)) { - return false; - } - scrollArea.scrollTop = maxScrollOffset; - return true; - }, [readMaxScrollOffset]); - - const queueBottomRestore = useCallback(() => { - if (!shouldStickToBottomRef.current) return; - restoreBottomOnce(); - restoreFramesRemainingRef.current = BOTTOM_RESTORE_SETTLE_FRAME_COUNT; - restoreTailLiveReadRef.current = false; - if (restoreFrameRef.current !== null) return; - const runQueuedRestore = () => { - restoreFrameRef.current = null; - const useLiveRead = restoreTailLiveReadRef.current; - restoreTailLiveReadRef.current = false; - const restored = useLiveRead - ? restoreBottomOnce() - : restoreBottomFromCacheOnce(); - if (!restored) { - restoreFramesRemainingRef.current = 0; - return; - } - if (!useLiveRead) { - restoreTailLiveReadRef.current = true; - } - restoreFramesRemainingRef.current -= 1; - if (restoreFramesRemainingRef.current > 0) { - restoreFrameRef.current = - window.requestAnimationFrame(runQueuedRestore); - } - }; - restoreFrameRef.current = window.requestAnimationFrame(runQueuedRestore); - }, [restoreBottomOnce, restoreBottomFromCacheOnce]); - const scrollToBottom = useCallback(() => { - const scrollArea = scrollAreaRef.current; - scrollToTopInProgressRef.current = false; - cancelPendingScrollRestore(); - userScrollIntentUntilRef.current = 0; - pointerScrollIntentRef.current = false; - userDetachedFromBottomRef.current = false; - shouldStickToBottomRef.current = true; - positionKeeper.capture(); - setIsAtBottom(true); - if (scrollArea) { - scrollArea.scrollTop = refreshMaxScrollOffset(scrollArea); - } - queueBottomRestore(); - }, [ - cancelPendingScrollRestore, - positionKeeper, - queueBottomRestore, - refreshMaxScrollOffset, - ]); + positionKeeper.scrollToBottom(); + }, [positionKeeper]); const scrollElementIntoView = useCallback( ({ element, options }: ScrollElementIntoViewArgs) => { - const scrollArea = scrollAreaRef.current; - cancelPendingScrollRestore(); - shouldStickToBottomRef.current = false; - setIsAtBottom(false); - cancelQueuedRestore(); - const previousScrollTop = scrollArea?.scrollTop; - element.scrollIntoView(options); - if (scrollArea && scrollArea.scrollTop !== previousScrollTop) { - scrollArea.dispatchEvent(new Event("scroll")); - } + positionKeeper.revealElement(element, options ?? {}); }, - [cancelPendingScrollRestore, cancelQueuedRestore], + [positionKeeper], ); const scrollElementIntoViewClampedToMaxScroll = useCallback( @@ -453,144 +171,34 @@ export function BottomAnchoredScrollBody({ element.scrollIntoView({ block: "start", inline: "nearest" }); return; } - - cancelPendingScrollRestore(); - const maxScrollOffset = refreshMaxScrollOffset(scrollArea); - scrollArea.scrollTop = Math.min( - maxScrollOffset, - getScrollOffsetToRevealElement({ element, scrollArea }), - ); - - const targetIsAtBottom = isScrolledNearBottom( - maxScrollOffset, - scrollArea.scrollTop, + positionKeeper.scrollTo( + element.getBoundingClientRect().top - + scrollArea.getBoundingClientRect().top + + scrollArea.scrollTop, + "instant", ); - shouldStickToBottomRef.current = targetIsAtBottom; - setIsAtBottom(targetIsAtBottom); - - if (targetIsAtBottom) { - queueBottomRestore(); - return; - } - - cancelQueuedRestore(); }, - [ - cancelPendingScrollRestore, - cancelQueuedRestore, - queueBottomRestore, - refreshMaxScrollOffset, - ], + [positionKeeper], ); const holdContentPosition = useCallback( ({ edge, element, update }: HoldContentPositionArgs) => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) { - update(); - return; - } - cancelQueuedRestore(); - cancelPendingScrollRestore(); - shouldStickToBottomRef.current = false; - contentPositionHoldUntilRef.current = - window.performance.now() + CONTENT_POSITION_HOLD_MS; - store.set(layoutAnimationInFlightCountAtom, (count) => count + 1); - window.setTimeout(() => { - store.set(layoutAnimationInFlightCountAtom, (count) => - Math.max(0, count - 1), - ); - }, CONTENT_POSITION_HOLD_MS); - positionKeeper.hold(element, edge, CONTENT_POSITION_HOLD_MS); - flushSync(() => { - setIsAtBottom(false); - update(); - }); + positionKeeper.hold(element, edge); + flushSync(update); positionKeeper.reconcile(); }, - [cancelPendingScrollRestore, cancelQueuedRestore, positionKeeper, store], + [positionKeeper], ); - const hasRecentUserScrollIntent = useCallback(() => { - return ( - pointerScrollIntentRef.current || - window.performance.now() <= userScrollIntentUntilRef.current + const writeScrollAnchor = useCallback(() => { + if (scrollAnchorThreadId === undefined) return; + const saved = positionKeeper.savedPosition(); + if (saved === null) return; + store.set( + threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId), + saved, ); - }, []); - - const writeScrollAnchor = useCallback( - (scrollAreaOverride?: HTMLElement) => { - if (scrollAnchorThreadId === undefined) return; - const scrollArea = scrollAreaOverride ?? scrollAreaRef.current; - if ( - !scrollArea || - viewportWidthChanged(scrollArea) || - pendingScrollRestoreRef.current !== null - ) { - return; - } - let atBottomByGeometry = isScrolledNearBottom( - readMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - if ( - (atBottomByGeometry && - scrollArea.scrollTop > - maxScrollOffsetRef.current + BOTTOM_ANCHOR_THRESHOLD_PX) || - (!atBottomByGeometry && shouldStickToBottomRef.current) - ) { - atBottomByGeometry = isScrolledNearBottom( - refreshMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - } - const recentUserIntent = hasRecentUserScrollIntent(); - const anchorAtom = - threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId); - if (atBottomByGeometry && !scrollToTopInProgressRef.current) { - userDetachedFromBottomRef.current = false; - store.set(anchorAtom, { - rowId: "", - offsetWithinRow: 0, - atBottom: true, - }); - return; - } - if (recentUserIntent) { - userDetachedFromBottomRef.current = true; - } - if ( - shouldStickToBottomRef.current && - !userDetachedFromBottomRef.current - ) { - store.set(anchorAtom, { - rowId: "", - offsetWithinRow: 0, - atBottom: true, - }); - return; - } - const topMostRow = getTopMostVisibleRow( - scrollArea, - getScrollAnchorRowsCached(scrollArea), - ); - if (!topMostRow) return; - store.set(anchorAtom, { - rowId: topMostRow.rowId, - offsetWithinRow: topMostRow.offsetWithinRow, - atBottom: false, - }); - }, - [ - getScrollAnchorRowsCached, - hasRecentUserScrollIntent, - readMaxScrollOffset, - refreshMaxScrollOffset, - scrollAnchorThreadId, - store, - viewportWidthChanged, - ], - ); + }, [positionKeeper, scrollAnchorThreadId, store]); const scrollAnchorCaptureThrottleMs = isPointerCoarse ? COARSE_SCROLL_ANCHOR_CAPTURE_THROTTLE_MS @@ -614,407 +222,44 @@ export function BottomAnchoredScrollBody({ }, scrollAnchorCaptureThrottleMs - elapsed); }, [scrollAnchorCaptureThrottleMs, scrollAnchorThreadId, writeScrollAnchor]); - const applyScrollRestore = useCallback( - (anchor: ScrollAnchor, clampToRow: boolean): number | null => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) return null; - const rowElement = findTimelineRowElement(scrollArea, anchor.rowId); - if (!rowElement) return null; - shouldStickToBottomRef.current = false; - setIsAtBottom(false); - cancelQueuedRestore(); - const revealOffset = getScrollOffsetToRevealElement({ - element: rowElement, - scrollArea, - }); - const targetScrollTop = Math.min( - refreshMaxScrollOffset(scrollArea), - revealOffset + - (clampToRow - ? Math.min( - anchor.offsetWithinRow, - Math.max(0, rowElement.getBoundingClientRect().height - 1), - ) - : anchor.offsetWithinRow), - ); - scrollArea.scrollTop = targetScrollTop; - return targetScrollTop; - }, - [cancelQueuedRestore, refreshMaxScrollOffset], - ); - - const markUserScrollIntent = useCallback(() => { - scrollToTopInProgressRef.current = false; - contentPositionHoldUntilRef.current = 0; - positionKeeper.releaseHold(); - userScrollIntentUntilRef.current = - window.performance.now() + USER_SCROLL_INTENT_MS; - }, [positionKeeper]); - - useEffect(() => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) return; - const scrollToTop = (event: Event) => { - event.preventDefault(); - if (refreshMaxScrollOffset(scrollArea) === 0) return; - markUserScrollIntent(); - userDetachedFromBottomRef.current = true; - shouldStickToBottomRef.current = false; - setIsAtBottom(false); - cancelQueuedRestore(); - pendingScrollRestoreRef.current = null; - scrollToTopInProgressRef.current = scrollArea.scrollTop > 0; - scrollArea.scrollTo({ - top: 0, - behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches - ? "instant" - : "smooth", + useLayoutEffect(() => { + if (initialRestore !== null) { + positionKeeper.restore({ + rowId: initialRestore.key, + offsetWithinRow: -initialRestore.offset, + atBottom: false, }); - }; - scrollArea.addEventListener(PAGE_SCROLL_TO_TOP_EVENT, scrollToTop); - return () => { - scrollArea.removeEventListener(PAGE_SCROLL_TO_TOP_EVENT, scrollToTop); - }; - }, [cancelQueuedRestore, markUserScrollIntent, refreshMaxScrollOffset]); - - const markWheelScrollIntent = useCallback( - (event: WheelEvent) => { - const scrollArea = scrollAreaRef.current; - scrollToTopInProgressRef.current = false; - if (event.deltaY > 0 && scrollArea) { - const nearBottom = - isScrolledNearBottom( - readMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ) || - (shouldStickToBottomRef.current && - isScrolledNearBottom( - refreshMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - )); - if (nearBottom) { - userScrollIntentUntilRef.current = 0; - return; - } - } - markUserScrollIntent(); - }, - [markUserScrollIntent, readMaxScrollOffset, refreshMaxScrollOffset], - ); - - const markTouchStartScrollIntent = useCallback(() => { - markUserScrollIntent(); - }, [markUserScrollIntent]); - - const markTouchMoveScrollIntent = useCallback(() => { - markUserScrollIntent(); - }, [markUserScrollIntent]); - - const startPointerScrollIntent = useCallback(() => { - scrollToTopInProgressRef.current = false; - pointerScrollIntentRef.current = true; - }, []); - - const endPointerScrollIntent = useCallback(() => { - pointerScrollIntentRef.current = false; - }, []); - - const markKeyboardScrollIntent = useCallback( - (event: KeyboardEvent) => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) return; - if (!SCROLL_INTENT_KEYS.has(event.key)) return; - if (isEditableKeyboardTarget(event.target)) return; - if (!isKeyboardEventFromScrollArea(event, scrollArea)) return; - - markUserScrollIntent(); - }, - [markUserScrollIntent], - ); - - const attachToBottom = useCallback(() => { - userDetachedFromBottomRef.current = false; - shouldStickToBottomRef.current = true; - userScrollIntentUntilRef.current = 0; - setIsAtBottom(true); - pendingScrollRestoreRef.current = null; - positionKeeper.capture(); - }, [positionKeeper]); - - const settleContentPositionHold = useCallback((): boolean => { - const scrollArea = scrollAreaRef.current; - if ( - !scrollArea || - shouldStickToBottomRef.current || - window.performance.now() > contentPositionHoldUntilRef.current - ) { - contentPositionHoldUntilRef.current = 0; - return false; } - if ( - isScrolledNearBottom(maxScrollOffsetRef.current, scrollArea.scrollTop) - ) { - contentPositionHoldUntilRef.current = 0; - attachToBottom(); - return false; - } - userDetachedFromBottomRef.current = true; - return true; - }, [attachToBottom]); + }, [initialRestore, positionKeeper]); - const syncBottomStateFromScroll = useCallback(() => { + useLayoutEffect(() => { const scrollArea = scrollAreaRef.current; if (!scrollArea) return; - - if ( - !hasRecentUserScrollIntent() && - (viewportWidthChanged(scrollArea) || - pendingScrollRestoreRef.current !== null) - ) { - return; - } - - if (scrollToTopInProgressRef.current) { - if (scrollArea.scrollTop <= 0) scrollToTopInProgressRef.current = false; - return; - } - - let nearBottom = isScrolledNearBottom( - readMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - if ( - (nearBottom && - scrollArea.scrollTop > - maxScrollOffsetRef.current + BOTTOM_ANCHOR_THRESHOLD_PX) || - (!nearBottom && - shouldStickToBottomRef.current && - hasRecentUserScrollIntent()) - ) { - nearBottom = isScrolledNearBottom( - refreshMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - } - - if (nearBottom) { - attachToBottom(); - return; - } - - if (!hasRecentUserScrollIntent()) return; - - userDetachedFromBottomRef.current = true; - shouldStickToBottomRef.current = false; - setIsAtBottom(false); - cancelQueuedRestore(); - pendingScrollRestoreRef.current = null; - }, [ - attachToBottom, - cancelQueuedRestore, - hasRecentUserScrollIntent, - readMaxScrollOffset, - refreshMaxScrollOffset, - viewportWidthChanged, - ]); - - const handleScroll = useCallback(() => { - positionKeeper.reconcile(); - syncBottomStateFromScroll(); - positionKeeper.capture(); - captureScrollAnchorThrottled(); - }, [positionKeeper, syncBottomStateFromScroll, captureScrollAnchorThrottled]); - - const advancePendingScrollRestore = useCallback((): boolean => { - const pending = pendingScrollRestoreRef.current; - if (!pending) return false; - pending.attemptsRemaining -= 1; - const appliedScrollTop = applyScrollRestore( - pending.anchor, - pending.clampToRow, - ); - if (appliedScrollTop !== null) { - if (pending.lastAppliedScrollTop === appliedScrollTop) { - pendingScrollRestoreRef.current = null; - return true; - } - pending.lastAppliedScrollTop = appliedScrollTop; - } else if (pending.lastAppliedScrollTop === null) { - const scrollArea = scrollAreaRef.current; - if (scrollArea) scrollArea.scrollTop = refreshMaxScrollOffset(scrollArea); - } - if (pending.attemptsRemaining <= 0) { - pendingScrollRestoreRef.current = null; - if (appliedScrollTop === null) { - shouldStickToBottomRef.current = true; - setIsAtBottom(true); - queueBottomRestore(); - } - } - return true; - }, [applyScrollRestore, queueBottomRestore, refreshMaxScrollOffset]); - - const handleScrollAreaResize = useCallback( - (entries: ResizeObserverEntry[]) => { - const scrollArea = scrollAreaRef.current; - scrollAnchorRowsRef.current = null; - positionKeeper.reconcile(); - let shrankOntoBottomWhileDetached = false; - if (scrollArea) { - const previousMaxScrollOffset = maxScrollOffsetRef.current; - const cacheWasAuthoritative = resizeObserverHasDeliveredRef.current; - const observedGeometry = observedScrollGeometryRef.current; - const previousWidth = observedGeometry.scrollAreaClientWidth; - for (const entry of entries) { - if (entry.target === scrollArea) { - observedGeometry.scrollAreaClientWidth = - entry.contentBoxSize[0]?.inlineSize ?? entry.contentRect.width; - observedGeometry.scrollAreaClientHeight = - entry.contentBoxSize[0]?.blockSize ?? entry.contentRect.height; - } else if (entry.target === scrollContentRef.current) { - observedGeometry.scrollContentHeight = - entry.borderBoxSize[0]?.blockSize ?? entry.contentRect.height; - } - } - const widthChanged = - previousWidth !== null && - previousWidth > 0 && - observedGeometry.scrollAreaClientWidth !== null && - Math.abs(previousWidth - observedGeometry.scrollAreaClientWidth) > 1; - if ( - widthChanged && - !shouldStickToBottomRef.current && - scrollAnchorThreadId !== undefined - ) { - const anchor = store.get( - threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId), - ); - if (anchor && !anchor.atBottom) { - pendingScrollRestoreRef.current = { - anchor, - attemptsRemaining: SCROLL_ANCHOR_RESTORE_MAX_ATTEMPTS, - lastAppliedScrollTop: null, - clampToRow: true, - }; - setViewportRestore({ - threadId: scrollAnchorThreadId, - rowId: anchor.rowId, - }); - } - } - let maxScrollOffset: number; - if ( - observedGeometry.scrollAreaClientHeight !== null && - observedGeometry.scrollContentHeight !== null - ) { - maxScrollOffset = Math.max( - 0, - Math.round(observedGeometry.scrollContentHeight) - - Math.round(observedGeometry.scrollAreaClientHeight), - ); - maxScrollOffsetRef.current = maxScrollOffset; - } else { - maxScrollOffset = refreshMaxScrollOffset(scrollArea); - } - resizeObserverHasDeliveredRef.current = true; - shrankOntoBottomWhileDetached = - cacheWasAuthoritative && - !widthChanged && - !shouldStickToBottomRef.current && - maxScrollOffset < previousMaxScrollOffset && - isScrolledNearBottom(maxScrollOffset, scrollArea.scrollTop); - } - if (settleContentPositionHold()) { - positionKeeper.capture(); - return; - } - if (advancePendingScrollRestore()) { - positionKeeper.capture(); - return; - } - if (shrankOntoBottomWhileDetached && scrollArea) { - attachToBottom(); - writeScrollAnchor(scrollArea); - } - positionKeeper.capture(); - queueBottomRestore(); - }, - [ - advancePendingScrollRestore, - attachToBottom, - positionKeeper, - queueBottomRestore, - refreshMaxScrollOffset, - scrollAnchorThreadId, - settleContentPositionHold, - store, - writeScrollAnchor, - ], - ); - - useLayoutEffect(() => { - if (scrollAnchorThreadId === undefined) return; - const anchor = store.get( - threadTimelineScrollAnchorAtomFamily(scrollAnchorThreadId), - ); - if (!anchor || anchor.atBottom) return; - shouldStickToBottomRef.current = false; - setIsAtBottom(false); - pendingScrollRestoreRef.current = { - anchor, - attemptsRemaining: SCROLL_ANCHOR_RESTORE_MAX_ATTEMPTS, - lastAppliedScrollTop: null, - clampToRow: false, - }; - advancePendingScrollRestore(); - }, [scrollAnchorThreadId, store, advancePendingScrollRestore]); - - useLayoutEffect(() => { - if (viewportRestore !== null) advancePendingScrollRestore(); - }, [viewportRestore, advancePendingScrollRestore]); - - const bottomAnchorContextValue = useMemo( - () => ({ - getScrollElement, - isAtBottom, - scrollToBottom, - scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, - holdContentPosition, - positionKeeper, - }), - [ - getScrollElement, - isAtBottom, - scrollToBottom, - scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, - holdContentPosition, - positionKeeper, - ], - ); - - const flushScrollAnchorCapture = useCallback( - (scrollArea: HTMLElement) => { - const captureThrottle = scrollAnchorCaptureThrottleRef.current; + const captureThrottle = scrollAnchorCaptureThrottleRef.current; + const disconnect = positionKeeper.connect(scrollArea); + return () => { if (captureThrottle.trailingTimeout !== null) { window.clearTimeout(captureThrottle.trailingTimeout); captureThrottle.trailingTimeout = null; } - refreshMaxScrollOffset(scrollArea); - writeScrollAnchor(scrollArea); - }, - [refreshMaxScrollOffset, writeScrollAnchor], - ); + writeScrollAnchor(); + disconnect(); + }; + }, [positionKeeper, writeScrollAnchor]); - useLayoutEffect(() => { + useEffect(() => { const scrollArea = scrollAreaRef.current; if (!scrollArea) return; - + const scrollToTop = (event: Event) => { + event.preventDefault(); + if (scrollArea.scrollHeight <= scrollArea.clientHeight) return; + positionKeeper.scrollTo(0, prefersReducedMotion() ? "instant" : "smooth"); + }; + scrollArea.addEventListener(PAGE_SCROLL_TO_TOP_EVENT, scrollToTop); return () => { - flushScrollAnchorCapture(scrollArea); + scrollArea.removeEventListener(PAGE_SCROLL_TO_TOP_EVENT, scrollToTop); }; - }, [flushScrollAnchorCapture]); + }, [positionKeeper]); useLayoutEffect(() => { const scrollArea = scrollAreaRef.current; @@ -1053,8 +298,7 @@ export function BottomAnchoredScrollBody({ useEffect(() => { const scrollArea = scrollAreaRef.current; - const scrollContent = scrollContentRef.current; - if (!scrollArea || !scrollContent) return; + if (!scrollArea) return; let scrollbarIdleTimeout: number | null = null; const handleScrollEvent = () => { @@ -1068,74 +312,44 @@ export function BottomAnchoredScrollBody({ scrollbarIdleTimeout = null; scrollArea.removeAttribute("data-scrollbar-scrolling"); }, SCROLLBAR_IDLE_DELAY_MS); - handleScroll(); + captureScrollAnchorThrottled(); }; - - const unobserveTouches = positionKeeper.observeTouches(scrollArea); - let resizeObserver: ResizeObserver | undefined; - if (typeof ResizeObserver !== "undefined") { - resizeObserver = new ResizeObserver(handleScrollAreaResize); - resizeObserver.observe(scrollArea); - resizeObserver.observe(scrollContent); - } - scrollArea.addEventListener("scroll", handleScrollEvent, { passive: true, }); - scrollArea.addEventListener("wheel", markWheelScrollIntent, { - passive: true, - }); - scrollArea.addEventListener("touchstart", markTouchStartScrollIntent, { - passive: true, - }); - scrollArea.addEventListener("touchmove", markTouchMoveScrollIntent, { - passive: true, - }); - scrollArea.addEventListener("pointerdown", startPointerScrollIntent, { - passive: true, - }); - window.addEventListener("pointerup", endPointerScrollIntent); - window.addEventListener("pointercancel", endPointerScrollIntent); - window.addEventListener("keydown", markKeyboardScrollIntent); - - queueBottomRestore(); - return () => { - unobserveTouches(); - resizeObserver?.disconnect(); scrollArea.removeEventListener("scroll", handleScrollEvent); - scrollArea.removeEventListener("wheel", markWheelScrollIntent); - scrollArea.removeEventListener("touchstart", markTouchStartScrollIntent); - scrollArea.removeEventListener("touchmove", markTouchMoveScrollIntent); - scrollArea.removeEventListener("pointerdown", startPointerScrollIntent); - window.removeEventListener("pointerup", endPointerScrollIntent); - window.removeEventListener("pointercancel", endPointerScrollIntent); - window.removeEventListener("keydown", markKeyboardScrollIntent); if (scrollbarIdleTimeout !== null) { window.clearTimeout(scrollbarIdleTimeout); } scrollArea.removeAttribute("data-scrollbar-scrolling"); - cancelQueuedRestore(); }; - }, [ - cancelQueuedRestore, - endPointerScrollIntent, - handleScroll, - handleScrollAreaResize, - markKeyboardScrollIntent, - markTouchMoveScrollIntent, - markTouchStartScrollIntent, - markWheelScrollIntent, - positionKeeper, - queueBottomRestore, - startPointerScrollIntent, - ]); + }, [captureScrollAnchorThrottled]); + + const bottomAnchorContextValue = useMemo( + () => ({ + getScrollElement, + isAtBottom, + scrollToBottom, + scrollElementIntoView, + scrollElementIntoViewClampedToMaxScroll, + holdContentPosition, + positionKeeper, + }), + [ + getScrollElement, + isAtBottom, + scrollToBottom, + scrollElementIntoView, + scrollElementIntoViewClampedToMaxScroll, + holdContentPosition, + positionKeeper, + ], + ); return ( - +
- {}
{children}
-
{footer ? (
{footer}
@@ -1186,7 +396,7 @@ export function BottomAnchoredScrollBody({
) : null}
- + ); } diff --git a/apps/app/src/components/ui/height-transition.test.tsx b/apps/app/src/components/ui/height-transition.test.tsx index 435e909312d..32bd872a325 100644 --- a/apps/app/src/components/ui/height-transition.test.tsx +++ b/apps/app/src/components/ui/height-transition.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, render } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { AutoHeightContainer, HeightTransition } from "./height-transition"; +import { HeightTransition } from "./height-transition"; class ResizeObserverStub implements ResizeObserver { static instances: ResizeObserverStub[] = []; @@ -73,142 +73,3 @@ describe("HeightTransition", () => { expect(wrapper?.style.transitionDuration).toBe("0s"); }); }); - -function makeResizeEntry( - target: Element, - borderBoxBlockSize: number, - contentRectHeight: number, -): ResizeObserverEntry { - return { - target, - contentRect: new DOMRect(0, 0, 200, contentRectHeight), - borderBoxSize: [{ blockSize: borderBoxBlockSize, inlineSize: 200 }], - contentBoxSize: [{ blockSize: contentRectHeight, inlineSize: 200 }], - devicePixelContentBoxSize: [ - { blockSize: borderBoxBlockSize, inlineSize: 200 }, - ], - }; -} - -describe("AutoHeightContainer", () => { - it("sizes the wrapper from the observed border box", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - - const view = render( - - Streaming response - , - ); - const inner = view.getByText("Streaming response").parentElement; - const wrapper = inner?.parentElement; - const observer = ResizeObserverStub.instances[0]; - if (!inner || !wrapper || !observer) { - throw new Error("AutoHeightContainer did not render"); - } - - act(() => { - observer.callback([makeResizeEntry(inner, 120, 112)], observer); - }); - - expect(wrapper.style.height).toBe("120px"); - }); - - it("snap-syncs an authoritative layout revision", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - - const view = render( - - Streaming response - , - ); - const inner = view.getByText("Streaming response").parentElement; - const wrapper = inner?.parentElement; - const observer = ResizeObserverStub.instances[0]; - expect(inner).not.toBeNull(); - expect(wrapper?.style.height).toBe("0px"); - expect(observer).toBeDefined(); - - Object.defineProperty(inner, "offsetHeight", { - configurable: true, - value: 480, - }); - view.rerender( - - Completed response - , - ); - - expect(wrapper?.style.height).toBe("480px"); - expect(wrapper?.style.transitionDuration).toBe("0s"); - expect(ResizeObserverStub.instances).toEqual([observer]); - expect(observer?.disconnect).not.toHaveBeenCalled(); - }); -}); - -function stubMediaQueries(matching: ReadonlySet): void { - vi.spyOn(window, "matchMedia").mockImplementation((query: string) => ({ - matches: matching.has(query), - media: query, - onchange: null, - addListener: () => {}, - removeListener: () => {}, - addEventListener: () => {}, - removeEventListener: () => {}, - dispatchEvent: () => false, - })); -} - -function stubScrollAnchoringSupport(supported: boolean): void { - vi.stubGlobal("CSS", { - supports: (property: string, value: string) => - supported && property === "overflow-anchor" && value === "none", - }); -} - -describe("AutoHeightContainer growth easing", () => { - function renderWrapper(): HTMLElement { - const view = render( - - Streaming response - , - ); - const wrapper = - view.getByText("Streaming response").parentElement?.parentElement; - if (!wrapper) { - throw new Error("AutoHeightContainer wrapper was not rendered"); - } - return wrapper; - } - - it("eases growth on a fine pointer with scroll anchoring available", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - stubMediaQueries(new Set()); - stubScrollAnchoringSupport(true); - - expect(renderWrapper().style.transition).toContain("height 180ms"); - }); - - it("snaps growth on a coarse pointer", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - stubMediaQueries(new Set(["(pointer: coarse)"])); - stubScrollAnchoringSupport(true); - - expect(renderWrapper().style.transition).toContain("height 0ms"); - }); - - it("snaps growth under reduced motion", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - stubMediaQueries(new Set(["(prefers-reduced-motion: reduce)"])); - stubScrollAnchoringSupport(true); - - expect(renderWrapper().style.transition).toContain("height 0ms"); - }); - - it("snaps growth where the browser has no scroll anchoring", () => { - vi.stubGlobal("ResizeObserver", ResizeObserverStub); - stubMediaQueries(new Set()); - stubScrollAnchoringSupport(false); - - expect(renderWrapper().style.transition).toContain("height 0ms"); - }); -}); diff --git a/apps/app/src/components/ui/height-transition.tsx b/apps/app/src/components/ui/height-transition.tsx index fe14b44f19d..53ae3f9602d 100644 --- a/apps/app/src/components/ui/height-transition.tsx +++ b/apps/app/src/components/ui/height-transition.tsx @@ -1,19 +1,10 @@ import { useStore } from "jotai"; -import { - createContext, - useCallback, - useLayoutEffect, - useRef, - type ReactNode, -} from "react"; +import { useLayoutEffect, useRef, type ReactNode } from "react"; import { cn } from "@bb/shared-ui/lib/utils"; -import { usePrefersReducedMotion } from "@bb/shared-ui/hooks/use-media-query"; -import { usePointerCoarse } from "@bb/shared-ui/hooks/use-pointer-coarse"; import { isDocumentVisible, subscribeToDocumentVisibility, } from "@/lib/document-visibility"; -import { supportsScrollAnchoring } from "@/lib/scroll-anchoring-support"; import { observedBorderBoxBlockSize, observeSharedResize, @@ -30,18 +21,6 @@ interface SnapState { restoreFrame: number | null; } -interface IntrinsicHeightResizeState { - restoreTimerId: number | null; - usingIntrinsicHeight: boolean; -} - -interface ScheduleIntrinsicHeightRestoreArgs { - inner: HTMLElement; - snapState: SnapState; - target: HTMLElement; - resizeState: IntrinsicHeightResizeState; -} - function enterSnapMode(target: HTMLElement, state: SnapState): void { if (state.savedDuration === null) { state.savedDuration = target.style.transitionDuration; @@ -91,48 +70,6 @@ function cleanupSnapState(target: HTMLElement | null, state: SnapState): void { } } -function enterIntrinsicHeightMode( - target: HTMLElement, - resizeState: IntrinsicHeightResizeState, - snapState: SnapState, -): void { - enterSnapMode(target, snapState); - if (resizeState.usingIntrinsicHeight) { - return; - } - target.style.height = "auto"; - resizeState.usingIntrinsicHeight = true; -} - -function scheduleIntrinsicHeightRestore({ - inner, - resizeState, - snapState, - target, -}: ScheduleIntrinsicHeightRestoreArgs): void { - if (resizeState.restoreTimerId !== null) { - window.clearTimeout(resizeState.restoreTimerId); - } - resizeState.restoreTimerId = window.setTimeout(() => { - resizeState.restoreTimerId = null; - if (!resizeState.usingIntrinsicHeight) { - return; - } - resizeState.usingIntrinsicHeight = false; - applyHeight(target, `${inner.offsetHeight}px`, true, snapState); - }, AUTO_HEIGHT_WIDTH_RESIZE_SETTLE_MS); -} - -function cancelIntrinsicHeightRestore( - resizeState: IntrinsicHeightResizeState, -): void { - if (resizeState.restoreTimerId === null) { - return; - } - window.clearTimeout(resizeState.restoreTimerId); - resizeState.restoreTimerId = null; -} - function getObservedInnerHeight( entry: ResizeObserverEntry | undefined, inner: HTMLElement, @@ -216,149 +153,3 @@ export function HeightTransition({ visible, children }: HeightTransitionProps) {
); } - -export const AutoHeightSnapContext = createContext<(() => void) | null>(null); - -interface AutoHeightContainerProps { - children: ReactNode; - snapRevision?: string; - animateGrowth?: boolean; -} - -const AUTO_HEIGHT_INITIAL_SETTLE_MS = 250; -const AUTO_HEIGHT_WIDTH_RESIZE_SETTLE_MS = 120; - -function useSnapHeightGrowth(): boolean { - const isPointerCoarse = usePointerCoarse(); - const prefersReducedMotion = usePrefersReducedMotion(); - return isPointerCoarse || prefersReducedMotion || !supportsScrollAnchoring(); -} - -export function AutoHeightContainer({ - children, - snapRevision, - animateGrowth = true, -}: AutoHeightContainerProps) { - const snapGrowth = useSnapHeightGrowth(); - const durationMs = - snapGrowth || !animateGrowth ? 0 : HEIGHT_TRANSITION_DURATION_MS; - const wrapperRef = useRef(null); - const innerRef = useRef(null); - const snapToCurrentHeightRef = useRef<(() => void) | null>(null); - const previousSnapRevisionRef = useRef(snapRevision); - const store = useStore(); - const snapToContentHeight = useCallback(() => { - snapToCurrentHeightRef.current?.(); - }, []); - useLayoutEffect(() => { - const wrapper = wrapperRef.current; - const inner = innerRef.current; - if (!wrapper || !inner || typeof ResizeObserver === "undefined") return; - wrapper.style.height = `${inner.offsetHeight}px`; - let lastWidth: number | null = null; - let pendingVisibilitySnap = false; - let initialSettleComplete = false; - let initialSettleTimerId = window.setTimeout(() => { - initialSettleComplete = true; - }, AUTO_HEIGHT_INITIAL_SETTLE_MS); - const snapState: SnapState = { savedDuration: null, restoreFrame: null }; - const resizeState: IntrinsicHeightResizeState = { - restoreTimerId: null, - usingIntrinsicHeight: false, - }; - const snapToCurrentHeight = () => { - cancelIntrinsicHeightRestore(resizeState); - resizeState.usingIntrinsicHeight = false; - applyHeight(wrapper, `${inner.offsetHeight}px`, true, snapState); - }; - snapToCurrentHeightRef.current = snapToCurrentHeight; - const deferInitialSettleComplete = () => { - if (initialSettleComplete) { - return; - } - window.clearTimeout(initialSettleTimerId); - initialSettleTimerId = window.setTimeout(() => { - initialSettleComplete = true; - }, AUTO_HEIGHT_INITIAL_SETTLE_MS); - }; - const unobserveInner = observeSharedResize(inner, { - read: (entry) => { - const width = entry?.contentRect?.width; - const widthChanged = - lastWidth !== null && width !== undefined && width !== lastWidth; - const layoutAnimationActive = - store.get(layoutAnimationInFlightCountAtom) > 0; - const snap = - widthChanged || - pendingVisibilitySnap || - !initialSettleComplete || - layoutAnimationActive; - pendingVisibilitySnap = false; - if (width !== undefined) { - lastWidth = width; - } - if (widthChanged || resizeState.usingIntrinsicHeight) { - return { useIntrinsicHeight: true as const }; - } - return { - useIntrinsicHeight: false as const, - nextHeight: `${getObservedInnerHeight(entry, inner)}px`, - snap, - }; - }, - write: (sync) => { - if (sync.useIntrinsicHeight) { - enterIntrinsicHeightMode(wrapper, resizeState, snapState); - scheduleIntrinsicHeightRestore({ - inner, - resizeState, - snapState, - target: wrapper, - }); - deferInitialSettleComplete(); - return; - } - applyHeight(wrapper, sync.nextHeight, sync.snap, snapState); - deferInitialSettleComplete(); - }, - }); - const onVisibility = () => { - if (!isDocumentVisible()) return; - pendingVisibilitySnap = true; - snapToCurrentHeight(); - }; - const unsubscribeFromDocumentVisibility = - subscribeToDocumentVisibility(onVisibility); - return () => { - snapToCurrentHeightRef.current = null; - unobserveInner(); - unsubscribeFromDocumentVisibility(); - window.clearTimeout(initialSettleTimerId); - cancelIntrinsicHeightRestore(resizeState); - cleanupSnapState(wrapper, snapState); - }; - }, [store]); - useLayoutEffect(() => { - if (previousSnapRevisionRef.current === snapRevision) { - return; - } - previousSnapRevisionRef.current = snapRevision; - snapToCurrentHeightRef.current?.(); - }, [snapRevision]); - return ( - -
-
- {children} -
-
-
- ); -} 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 cabaf6ea5c9..ba62dd8cf20 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -1,397 +1,466 @@ // @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 VIEWPORT_HEIGHT = 500; -interface LaidOutRow { +interface RowSpec { id: string; height: number; - children?: LaidOutRow[]; + children?: RowSpec[]; } -function translatedOffset(element: HTMLElement): number { - const match = /translate3d\(0(?:px)?, (-?[\d.]+)px/u.exec( - element.style.transform, - ); - return match === null ? 0 : Number(match[1]); +let restoreLayout: (() => void) | null = null; + +afterEach(() => { + restoreLayout?.(); + restoreLayout = null; + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +function rowsOf(count: number, height = 200, prefix = "row"): RowSpec[] { + return Array.from({ length: count }, (_, index) => ({ + id: `${prefix}-${index}`, + height, + })); } function createTimeline( - initialRows: LaidOutRow[], - { deferWritesWhileScrolling = false, lagScrollExtent = false } = {}, + initialRows: RowSpec[], + { + deferWrites = false, + attached = false, + footerTop = null, + }: { + deferWrites?: boolean; + attached?: boolean; + footerTop?: number | null; + } = {}, ) { const scrollElement = document.createElement("div"); + const content = document.createElement("div"); const list = document.createElement("div"); - scrollElement.append(list); + list.setAttribute("data-timeline-row-list", "top-level"); + const items = document.createElement("div"); + items.setAttribute("data-timeline-items", ""); + list.append(items); + content.append(list); + scrollElement.append(content); document.body.append(scrollElement); - let scrollTop = 0; - let rows = initialRows; - const offsets = new Map(); - const contentHeight = () => - Math.max( - VIEWPORT_HEIGHT, - rows.reduce((total, row) => total + row.height, 0), - ); - let settledExtent = contentHeight(); - const scrollHeight = () => - lagScrollExtent ? settledExtent : contentHeight(); - - Object.defineProperty(scrollElement, "scrollTop", { - configurable: true, - get: () => scrollTop, - set: (value: number) => { - const max = lagScrollExtent - ? scrollHeight() - VIEWPORT_HEIGHT - : Number.POSITIVE_INFINITY; - scrollTop = Math.min(Math.max(0, value), max); - }, - }); - Object.defineProperty(scrollElement, "clientHeight", { - configurable: true, - value: VIEWPORT_HEIGHT, - }); - Object.defineProperty(scrollElement, "scrollHeight", { - configurable: true, - get: scrollHeight, + const layout = installFakeFlowLayout({ + scrollElement, + viewportHeight: VIEWPORT_HEIGHT, }); - vi.spyOn(scrollElement, "getBoundingClientRect").mockReturnValue( - new DOMRect(0, 0, 100, VIEWPORT_HEIGHT), - ); + restoreLayout = layout.restore; const elements = new Map(); - const elementFor = (id: string) => { - const existing = elements.get(id); - if (existing !== undefined) return existing; - const element = document.createElement("div"); - elements.set(id, element); - element.setAttribute("data-timeline-row-id", id); - vi.spyOn(element, "getBoundingClientRect").mockImplementation(() => { - const offset = offsets.get(id); - return offset === undefined - ? new DOMRect(0, 0, 0, 0) - : new DOMRect( - 0, - offset.top - scrollTop + translatedOffset(list), - 100, - offset.height, - ); - }); + const build = (row: RowSpec): HTMLElement => { + const element = elements.get(row.id) ?? document.createElement("div"); + elements.set(row.id, element); + element.setAttribute("data-timeline-row-id", row.id); + element.replaceChildren(...(row.children ?? []).map(build)); + if (row.children === undefined) setFakeHeight(element, row.height); + else element.removeAttribute("data-fake-height"); return element; }; - - const layout = () => { - offsets.clear(); - list.replaceChildren(); - let top = 0; - const place = (row: LaidOutRow, parent: HTMLElement) => { - const element = elementFor(row.id); - element.replaceChildren(); - parent.append(element); - offsets.set(row.id, { top, height: row.height }); - let childTop = top; - for (const child of row.children ?? []) { - const childElement = elementFor(child.id); - element.append(childElement); - offsets.set(child.id, { top: childTop, height: child.height }); - childTop += child.height; - } - top += row.height; - }; - for (const row of rows) place(row, list); + const setRows = (rows: RowSpec[]) => { + items.replaceChildren(...rows.map(build)); }; - layout(); + setRows(initialRows); + const footer = document.createElement("div"); + footer.getBoundingClientRect = () => + new DOMRect(0, footerTop ?? VIEWPORT_HEIGHT, 100, 80); - const keeperOptions = { active: true }; const keeper = new ScrollPositionKeeper({ - deferWritesWhileScrolling, - getDeferredOffsetElement: () => list, + bottomThresholdPx: 4, + deferWritesWhileScrolling: deferWrites, + getContentElement: () => content, + getFooterElement: () => (footerTop === null ? null : footer), getScrollElement: () => scrollElement, getTopLevelRows: () => - Array.from(list.children).filter( - (child): child is HTMLElement => child instanceof HTMLElement, - ), - isActive: () => keeperOptions.active, + items.querySelectorAll(":scope > [data-timeline-row-id]"), + initiallyAttached: attached, }); + const disconnect = keeper.connect(scrollElement); + const previousRestore = restoreLayout; + restoreLayout = () => { + disconnect(); + previousRestore?.(); + }; + + const topOf = (id: string) => { + const element = elements.get(id); + if (element === undefined) throw new Error(`No row ${id}`); + return element.getBoundingClientRect().top; + }; return { + content, keeper, - keeperOptions, + layout, scrollElement, - get scrollTop() { - return scrollTop; + setRows, + topOf, + resize(id: string, height: number) { + const element = elements.get(id); + if (element === undefined) throw new Error(`No row ${id}`); + setFakeHeight(element, height); }, - scrollTo(value: number) { - scrollTop = value; - }, - get translatedOffset() { - return translatedOffset(list); - }, - setRows(next: LaidOutRow[]) { - rows = next; - layout(); - }, - settleScrollExtent() { - settledExtent = contentHeight(); - }, - viewportTopOf(id: string) { - const offset = offsets.get(id); - if (offset === undefined) throw new Error(`No row ${id}`); - return offset.top - scrollTop + translatedOffset(list); + userScrollTo(top: number) { + layout.userScrollTo(top); }, }; } -function rowsOf(count: number, height = 200, prefix = "row"): LaidOutRow[] { - return Array.from({ length: count }, (_, index) => ({ - id: `${prefix}-${index}`, - height, - })); -} +describe("ScrollPositionKeeper", () => { + it("keeps the reading row in place when an older page is prepended", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(450); + const before = timeline.topOf("row-3"); -afterEach(() => { - vi.useRealTimers(); - document.body.replaceChildren(); - vi.restoreAllMocks(); -}); + timeline.setRows([...rowsOf(6, 150, "older"), ...rows]); + timeline.keeper.reconcile(); -describe("ScrollPositionKeeper", () => { - it("keeps the reading row still when older rows are prepended", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-5"); + expect(timeline.topOf("row-3")).toBe(before); + expect(timeline.keeper.isAttached()).toBe(false); + }); + + it("drives each reconcile to the same intent, so a clamped intermediate correction is not counted twice", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(450); + const before = timeline.topOf("row-3"); + + timeline.setRows(rows.slice(3)); + timeline.keeper.reconcile(); + expect(timeline.layout.scrollTop).toBe(0); - timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + timeline.setRows([...rowsOf(8, 100, "older"), ...rows]); + timeline.keeper.reconcile(); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(2_100); - expect(timeline.viewportTopOf("row-5")).toBe(before); + expect(timeline.topOf("row-3")).toBe(before); }); - it("keeps the position momentum scrolling reached before the rows arrive", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); + it("never attaches when content shrinks under a detached reader and the browser clamps to the end", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(1200); + + timeline.setRows(rows.slice(0, 7)); + timeline.keeper.reconcile(); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(false); + }); - timeline.scrollTo(400); - timeline.keeper.handleScroll(); - timeline.scrollTo(150); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-1"); + 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()); - timeline.setRows([...rowsOf(2, 500, "older"), ...rowsOf(10)]); + timeline.resize("row-9", 900); timeline.keeper.reconcile(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); - expect(timeline.scrollTop).toBe(1_150); - expect(timeline.viewportTopOf("row-1")).toBe(before); + timeline.resize("row-4", 20); + timeline.keeper.reconcile(); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); }); - it("settles a lagging scroll extent before a correction it cannot hold", () => { - const timeline = createTimeline(rowsOf(10), { lagScrollExtent: true }); - timeline.scrollTo(100); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-1"); - timeline.keeper.registerScrollExtentSync(() => - timeline.settleScrollExtent(), - ); + it("shifts content above an attached toggle by exactly the height change", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const lastBottom = () => timeline.topOf("row-9") + 200; + const bottomBefore = lastBottom(); + const toggledBefore = timeline.topOf("row-8"); - timeline.setRows([...rowsOf(30, 200, "older"), ...rowsOf(10)]); + timeline.resize("row-8", 450); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(6_100); - expect(timeline.viewportTopOf("row-1")).toBe(before); + expect(lastBottom()).toBe(bottomBefore); + expect(timeline.topOf("row-8")).toBe(toggledBefore - 250); }); - it("composes with scrolling that happens between layout changes", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); + it("keeps the reader in place through another visible row when the anchor row's key goes away", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(450); + const before = timeline.topOf("row-4"); - timeline.scrollTo(700); + timeline.setRows([ + ...rows.slice(0, 1), + { id: "row-1-and-2", height: 120 }, + { id: "row-3-renamed", height: 200 }, + ...rows.slice(4), + ]); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(700); + expect(timeline.topOf("row-4")).toBe(before); }); - it("corrects a foreign write that ignored a layout change above the reader", () => { + it("does not write when nothing changed above the reading row", () => { const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-5"); + timeline.userScrollTo(450); + const setter = vi.spyOn(timeline.scrollElement, "scrollTop", "set"); - timeline.setRows([{ id: "older", height: 3_000 }, ...rowsOf(10)]); - timeline.scrollTo(865); - timeline.keeper.handleScroll(); + timeline.resize("row-8", 600); + timeline.keeper.reconcile(); + timeline.keeper.reconcile(); - expect(timeline.viewportTopOf("row-5")).toBe(before + 35); + expect(setter).not.toHaveBeenCalled(); }); - it("locates an unmounted anchor through a registered row offset source", () => { + it("corrects a row above the reading row resizing within the same reconcile", () => { const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - timeline.keeper.registerRowOffsetSource((rowId) => - rowId === "row-5" ? 3_400 : null, - ); + timeline.userScrollTo(450); + const before = timeline.topOf("row-3"); - timeline.setRows(rowsOf(3, 1_000, "older")); + timeline.resize("row-1", 520); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(3_300); + expect(timeline.topOf("row-3")).toBe(before); + }); + + it("attaches only when the reader scrolls down into the end, and detaches when they scroll up out of it", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const max = timeline.layout.maxScrollTop(); + + timeline.userScrollTo(max - 2); + expect(timeline.keeper.isAttached()).toBe(true); + timeline.userScrollTo(max - 300); + expect(timeline.keeper.isAttached()).toBe(false); + timeline.userScrollTo(max - 200); + expect(timeline.keeper.isAttached()).toBe(false); + timeline.userScrollTo(max); + expect(timeline.keeper.isAttached()).toBe(true); + }); + + it("attributes layout that changed before a scroll event to layout, not to the reader's movement", () => { + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(450); + const before = timeline.topOf("row-3"); + + timeline.resize("row-1", 224); + timeline.userScrollTo(440); + + expect(timeline.topOf("row-3")).toBe(before + 10); }); - it("notifies write subscribers after it moves the scroll position", () => { + it("corrects a row above the reading row that grows while the lists re-render for a scroll", () => { const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - const listener = vi.fn(() => timeline.scrollTop); - timeline.keeper.subscribeScrollWrites(listener); + timeline.userScrollTo(450); + let grown = false; + timeline.keeper.registerList({ + itemAt: () => null, + onPositionChange: () => { + if (grown) return; + grown = true; + timeline.resize("row-1", 220); + }, + }); + const before = timeline.topOf("row-3"); + + timeline.userScrollTo(440); - timeline.setRows([{ id: "older", height: 120 }, ...rowsOf(10)]); + expect(timeline.topOf("row-3")).toBe(before + 10); + }); + + it("adopts the rows that mount under an estimated position instead of moving the view to the estimate", () => { + const timeline = createTimeline([]); + const spacer = document.createElement("div"); + setFakeHeight(spacer, 6_000); + timeline.content.prepend(spacer); timeline.keeper.reconcile(); + timeline.keeper.registerList({ + itemAt: (viewportTop) => ({ key: "row-1", top: viewportTop + 40 }), + onPositionChange: () => { + if (timeline.content.firstElementChild !== spacer) return; + spacer.remove(); + timeline.setRows(rowsOf(20)); + }, + }); + + timeline.userScrollTo(1_100); - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveReturnedWith(1_020); + expect(timeline.layout.scrollTop).toBe(1_100); + expect(timeline.topOf("row-5")).toBe(-100); + timeline.keeper.reconcile(); + expect(timeline.layout.scrollTop).toBe(1_100); }); - it("anchors to a nested row that starts inside the viewport", () => { + it("anchors the first top-level row that starts in the viewport, not a nested row above it", () => { const timeline = createTimeline([ + ...rowsOf(2), { - id: "turn", - height: 1_500, - children: rowsOf(5, 300, "step"), + id: "group", + height: 0, + children: [ + { id: "group-a", height: 300 }, + { id: "group-b", height: 300 }, + ], }, - ...rowsOf(5), + ...rowsOf(5, 200, "after"), ]); - timeline.scrollTo(250); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("step-1"); + timeline.userScrollTo(850); + const before = timeline.topOf("after-0"); - timeline.setRows([ - { - id: "turn", - height: 1_700, - children: [{ id: "step-0", height: 500 }, ...rowsOf(4, 300, "step").slice(1)], - }, - ...rowsOf(5), - ]); + timeline.resize("group-b", 340); timeline.keeper.reconcile(); - expect(timeline.viewportTopOf("step-1")).toBe(before); + expect(timeline.topOf("after-0")).toBe(before); }); - it("leaves scrolling and native anchoring to others while inactive", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - expect(timeline.scrollElement.style.overflowAnchor).toBe("none"); + it("anchors the row the reader can see, not one hidden behind the composer", () => { + const timeline = createTimeline(rowsOf(10, 450), { footerTop: 300 }); + timeline.userScrollTo(1_000); + const before = timeline.topOf("row-2"); - timeline.keeperOptions.active = false; - timeline.keeper.capture(); - timeline.setRows([{ id: "older", height: 400 }, ...rowsOf(10)]); + timeline.resize("row-2", 500); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(900); - expect(timeline.scrollElement.style.overflowAnchor).toBe(""); + expect(timeline.topOf("row-2")).toBe(before); }); - it("holds an element edge instead of the top row while a hold lasts", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - const element = timeline.scrollElement.querySelector( - '[data-timeline-row-id="row-6"]', - ); - if (element === null) throw new Error("Expected row-6"); - timeline.keeper.hold(element, "bottom", 250); - const bottomBefore = timeline.viewportTopOf("row-6") + 200; - - timeline.setRows([ - ...rowsOf(6), - { id: "row-6", height: 50 }, - ...rowsOf(10).slice(7), - ]); + it("holds a correction as a transform during a touch and writes it once scrolling settles", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const rows = rowsOf(10); + const timeline = createTimeline(rows, { deferWrites: true }); + timeline.userScrollTo(450); + vi.advanceTimersByTime(500); + const before = timeline.topOf("row-3"); + const setter = vi.spyOn(timeline.scrollElement, "scrollTop", "set"); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.setRows([...rowsOf(4, 100, "older"), ...rows]); timeline.keeper.reconcile(); + expect(setter).not.toHaveBeenCalled(); + expect(timeline.topOf("row-3")).toBe(before); - expect(timeline.viewportTopOf("row-6") + 50).toBe(bottomBefore); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + vi.advanceTimersByTime(400); + expect(setter).toHaveBeenCalled(); + expect(timeline.content.style.transform).toBe(""); + expect(timeline.topOf("row-3")).toBe(before); }); - it("holds a correction in the rendered position while a touch is down and writes it after scrolling settles", () => { - vi.useFakeTimers(); - const timeline = createTimeline(rowsOf(10), { - deferWritesWhileScrolling: true, - }); - const unobserve = timeline.keeper.observeTouches(timeline.scrollElement); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-5"); - timeline.scrollElement.dispatchEvent(new Event("touchstart")); + it("keeps a touch drag that delivered no scroll events as the reader's movement", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const timeline = createTimeline(rowsOf(10), { deferWrites: true }); + timeline.userScrollTo(600); + vi.advanceTimersByTime(500); - timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.bounceTo(400); + const after = timeline.topOf("row-3"); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + vi.advanceTimersByTime(400); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(900); - expect(timeline.translatedOffset).toBe(-1_200); - expect(timeline.keeper.getDeferredOffset()).toBe(1_200); - expect(timeline.viewportTopOf("row-5")).toBe(before); + expect(timeline.layout.scrollTop).toBe(400); + expect(timeline.topOf("row-3")).toBe(after); + }); - timeline.scrollElement.dispatchEvent(new Event("touchend")); - vi.advanceTimersByTime(200); + it("keeps fling momentum as the reader's movement after a long frame, while correcting layout that changed with it", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(600); + vi.advanceTimersByTime(500); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.layoutScrollTo(560); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + const before = timeline.topOf("row-3"); + vi.advanceTimersByTime(400); + + timeline.resize("row-0", 150); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 30); - expect(timeline.scrollTop).toBe(2_100); - expect(timeline.translatedOffset).toBe(0); - expect(timeline.keeper.getDeferredOffset()).toBe(0); - expect(timeline.viewportTopOf("row-5")).toBe(before); - unobserve(); + expect(timeline.topOf("row-3")).toBe(before + 30); }); - it("keeps holding while momentum moves the reader and keeps the distance it coasted", () => { - vi.useFakeTimers(); - const timeline = createTimeline(rowsOf(10), { - deferWritesWhileScrolling: true, - }); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - vi.advanceTimersByTime(200); - const before = timeline.viewportTopOf("row-5"); - - timeline.scrollTo(850); - timeline.keeper.handleScroll(); - timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + it("leaves an iOS edge bounce alone instead of holding it with a transform", () => { + const timeline = createTimeline(rowsOf(10), { deferWrites: true }); + timeline.userScrollTo(300); + const before = timeline.topOf("row-1"); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.bounceTo(-40); timeline.keeper.reconcile(); - for (const scrollTop of [800, 750, 700]) { - vi.advanceTimersByTime(100); - timeline.scrollTo(scrollTop); - timeline.keeper.handleScroll(); - expect(timeline.translatedOffset).toBe(-1_200); - } - vi.advanceTimersByTime(400); - expect(timeline.translatedOffset).toBe(0); - expect(timeline.scrollTop).toBe(1_900); - expect(timeline.viewportTopOf("row-5")).toBe(before + 200); + expect(timeline.content.style.transform).toBe(""); + expect(timeline.topOf("row-1")).toBe(before + 340); }); - it("writes a held correction before it stops keeping the position", () => { - vi.useFakeTimers(); - const timeline = createTimeline(rowsOf(10), { - deferWritesWhileScrolling: true, + it("restores a saved row at its saved offset once it mounts, and stays at the end until then", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows.slice(5), { attached: true }); + + timeline.keeper.restore({ + rowId: "row-3", + offsetWithinRow: 40, + atBottom: false, }); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); - timeline.scrollTo(850); - timeline.keeper.handleScroll(); - timeline.setRows([...rowsOf(4, 300, "older"), ...rowsOf(10)]); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + + timeline.setRows(rows); timeline.keeper.reconcile(); - const before = timeline.viewportTopOf("row-5"); - timeline.keeperOptions.active = false; - timeline.keeper.capture(); + expect(timeline.topOf("row-3")).toBe(-40); + expect(timeline.keeper.isAttached()).toBe(false); + expect(timeline.keeper.savedPosition()).toEqual({ + rowId: "row-4", + offsetWithinRow: -160, + atBottom: false, + }); + }); + + it("restores a saved row where it stays visible when the viewport is now shorter than its offset", () => { + const timeline = createTimeline(rowsOf(10), { footerTop: 120 }); + + timeline.keeper.restore({ + rowId: "row-4", + offsetWithinRow: -300, + atBottom: false, + }); + + expect(timeline.topOf("row-4")).toBe(72); + }); + + it("restores the exact view when the first row starting in it is too close to the bottom to restore there", () => { + const rows = rowsOf(10).map((row) => + row.id === "row-2" ? { ...row, height: 480 } : row, + ); + const first = createTimeline(rows); + first.userScrollTo(410); + expect(first.topOf("row-3")).toBe(470); + const saved = first.keeper.savedPosition(); + if (saved === null) throw new Error("No saved position"); + restoreLayout?.(); + document.body.replaceChildren(); + + const second = createTimeline(rows); + second.keeper.restore(saved); + + expect(second.topOf("row-2")).toBe(-10); + expect(second.topOf("row-3")).toBe(470); + }); + + it("keeps the reading row when every row reflows at a new width", () => { + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(450); + const before = timeline.topOf("row-3"); + + for (let index = 0; index < 10; index += 1) { + timeline.resize(`row-${index}`, 320); + } + timeline.keeper.reconcile(); - expect(timeline.translatedOffset).toBe(0); - expect(timeline.scrollTop).toBe(2_050); - expect(timeline.viewportTopOf("row-5")).toBe(before); + expect(timeline.topOf("row-3")).toBe(before); }); }); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index e4fbc78a265..d56a7cc7bd2 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -1,28 +1,52 @@ -export type ScrollRowOffsetSource = (rowId: string) => number | null; - export type ScrollHoldEdge = "top" | "bottom"; -type KeptAnchor = - | { - kind: "row"; - rowId: string; - element: HTMLElement; - offset: number; - topLevel: boolean; - } +export type ReadingPosition = + | { kind: "bottom" } + | { kind: "free" } | { - kind: "element"; - element: HTMLElement; + kind: "anchor"; + key: string; + element: HTMLElement | null; edge: ScrollHoldEdge; offset: number; + neighbors: readonly AnchorNeighbor[]; }; +interface AnchorNeighbor { + key: string; + delta: number; +} + +export interface SavedReadingPosition { + rowId: string; + offsetWithinRow: number; + atBottom: boolean; +} + +export interface ScrollWindowList { + itemAt: (viewportTop: number) => { key: string; top: number } | null; + onPositionChange: (urgent: boolean) => void; +} + interface ScrollPositionKeeperOptions { + bottomThresholdPx: number; deferWritesWhileScrolling: boolean; - getDeferredOffsetElement: () => HTMLElement | null; + getContentElement: () => HTMLElement | null; + getFooterElement: () => HTMLElement | null; getScrollElement: () => HTMLElement | null; getTopLevelRows: (scrollElement: HTMLElement) => ArrayLike; - isActive: () => boolean; + initiallyAttached: boolean; +} + +interface TopRow { + key: string; + element: HTMLElement; +} + +interface PendingRestore { + rowId: string; + offset: number; + expiresAt: number; } const ROW_ID_ATTRIBUTE = "data-timeline-row-id"; @@ -31,324 +55,571 @@ const DIRECT_ROW_SELECTOR = [ `:scope > ${ROW_SELECTOR}`, `:scope > [data-timeline-items] > ${ROW_SELECTOR}`, ].join(", "); -const MIN_CORRECTION_PX = 0.5; +const MIN_WRITE_PX = 0.5; +const MIN_VISIBLE_ANCHOR_PX = 48; +const MAX_ANCHOR_NEIGHBORS = 8; const SCROLL_SETTLE_MS = 150; -const TOUCH_LISTENER_OPTIONS = { capture: true, passive: true } as const; - -export function getDirectTimelineRows( - list: Element, -): NodeListOf { +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 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 FREE: ReadingPosition = { kind: "free" }; + +export function getDirectTimelineRows(list: Element): NodeListOf { return list.querySelectorAll(DIRECT_ROW_SELECTOR); } -function previousRowSibling(row: HTMLElement): HTMLElement | null { - let sibling = row.previousElementSibling; - while (sibling !== null) { - if (sibling instanceof HTMLElement && sibling.hasAttribute(ROW_ID_ATTRIBUTE)) { - return sibling; - } - sibling = sibling.previousElementSibling; +function findMountedRow( + scrollElement: HTMLElement, + rowId: string, +): HTMLElement | null { + for (const row of scrollElement.querySelectorAll(ROW_SELECTOR)) { + if (row.getAttribute(ROW_ID_ATTRIBUTE) === rowId) return row; } return null; } +function firstRowStartingInViewport( + rows: NodeListOf, + viewportTop: number, + viewportBottom: number, +): HTMLElement | null { + for (const row of rows) { + const top = row.getBoundingClientRect().top; + if (top >= viewportBottom) return null; + if (top >= viewportTop) return row; + } + return null; +} + +function isEditableTarget(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) return false; + return ( + target.tagName === "INPUT" || + target.tagName === "TEXTAREA" || + target.tagName === "SELECT" || + target.isContentEditable + ); +} + export class ScrollPositionKeeper { private readonly options: ScrollPositionKeeperOptions; - private anchor: KeptAnchor | null = null; - private holdUntil = 0; - private readonly rowOffsetSources = new Set(); - private readonly scrollExtentSyncs = new Set<() => void>(); - private readonly writeListeners = new Set<() => void>(); - private overflowAnchorDisabled = false; - private deferredOffset = 0; - private deferredOffsetElement: HTMLElement | null = null; + private position: ReadingPosition; + private pendingRestore: PendingRestore | null = null; + private ownScrollTop: number | null = null; + private maxScrollTop = 0; + private viewportHeight = 0; + private reconciledWidth = 0; + private reconciledScrollHeight = 0; + private topRow: TopRow | null = null; + private deferred = 0; + private deferredElement: HTMLElement | null = null; private touching = false; - private observedScrollTop: number | null = null; + private pointerDown = false; + private gestureScrolled = false; + private inputUntil = Number.NEGATIVE_INFINITY; + private userScrolled = false; private scrollMovedAt = Number.NEGATIVE_INFINITY; private settleTimeout: number | null = null; + private clampFrame: number | null = null; + private readonly lists = new Set(); + private readonly listeners = new Set<() => void>(); + private readonly positionListeners = new Set<() => void>(); constructor(options: ScrollPositionKeeperOptions) { this.options = options; + this.position = options.initiallyAttached ? { kind: "bottom" } : FREE; + } + + hasUserScrolled(): boolean { + return this.userScrolled; } - isActive(): boolean { - return this.options.isActive(); + isAttached(): boolean { + return this.position.kind === "bottom"; } - getDeferredOffset(): number { - return this.deferredOffset; + getPosition(): ReadingPosition { + return this.position; } - observeTouches(scrollElement: HTMLElement): () => void { - const start = () => { + getViewportHeight(): number { + return this.viewportHeight; + } + + getScrollElement(): HTMLElement | null { + return this.options.getScrollElement(); + } + + subscribe(listener: () => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + subscribePosition(listener: () => void): () => void { + this.positionListeners.add(listener); + return () => { + this.positionListeners.delete(listener); + }; + } + + registerList(list: ScrollWindowList): () => void { + this.lists.add(list); + return () => { + this.lists.delete(list); + }; + } + + connect(scrollElement: HTMLElement): () => void { + scrollElement.style.overflowAnchor = "none"; + this.ownScrollTop = scrollElement.scrollTop; + const onScroll = () => this.handleScroll(); + let touchStartScrollTop = 0; + const onTouchStart = () => { + if (!this.touching) { + this.gestureScrolled = false; + touchStartScrollTop = scrollElement.scrollTop; + } this.touching = true; }; - const end = () => { + const onTouchEnd = (event: TouchEvent) => { + if (event.touches.length > 0) return; this.touching = false; + if (Math.abs(scrollElement.scrollTop - touchStartScrollTop) >= 1) { + this.gestureScrolled = true; + this.scrollMovedAt = window.performance.now(); + } + if (this.gestureScrolled) { + this.extendInput(MOMENTUM_SESSION_MS); + this.handleScroll(); + } this.scheduleDeferredWrite(); }; - scrollElement.addEventListener("touchstart", start, TOUCH_LISTENER_OPTIONS); - scrollElement.addEventListener("touchend", end, TOUCH_LISTENER_OPTIONS); - scrollElement.addEventListener("touchcancel", end, TOUCH_LISTENER_OPTIONS); + const onPointerDown = (event: PointerEvent) => { + if (event.pointerType === "touch") return; + this.pointerDown = true; + this.gestureScrolled = false; + }; + const onPointerUp = () => { + if (!this.pointerDown) return; + this.pointerDown = false; + if (this.gestureScrolled) this.extendInput(SESSION_EXTENSION_MS); + }; + const onWheel = (event: WheelEvent) => { + this.extendInput(WHEEL_SESSION_MS); + if (event.deltaY > 0) this.attachIfAtEnd(); + }; + const onKeyDown = (event: KeyboardEvent) => { + if (!SCROLL_KEYS.has(event.key) || isEditableTarget(event.target)) { + return; + } + const target = event.target; + if ( + target instanceof Node && + target !== document.body && + !scrollElement.contains(target) + ) { + 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("touchend", onTouchEnd, PASSIVE_CAPTURE); + scrollElement.addEventListener("touchcancel", onTouchEnd, PASSIVE_CAPTURE); + scrollElement.addEventListener("pointerdown", onPointerDown, { + passive: true, + }); + window.addEventListener("pointerup", onPointerUp); + window.addEventListener("pointercancel", onPointerUp); + window.addEventListener("keydown", onKeyDown); + let observer: ResizeObserver | undefined; + if (typeof ResizeObserver !== "undefined") { + observer = new ResizeObserver(() => this.reconcile()); + observer.observe(scrollElement); + const content = this.options.getContentElement(); + if (content !== null) { + observer.observe(content); + const parent = content.parentElement; + if (parent !== null && parent !== scrollElement) { + observer.observe(parent); + } + } + } + this.reconcile(); return () => { + observer?.disconnect(); + scrollElement.removeEventListener("scroll", onScroll); + scrollElement.removeEventListener("wheel", onWheel); scrollElement.removeEventListener( "touchstart", - start, - TOUCH_LISTENER_OPTIONS, + onTouchStart, + PASSIVE_CAPTURE, + ); + scrollElement.removeEventListener( + "touchend", + onTouchEnd, + PASSIVE_CAPTURE, ); - scrollElement.removeEventListener("touchend", end, TOUCH_LISTENER_OPTIONS); scrollElement.removeEventListener( "touchcancel", - end, - TOUCH_LISTENER_OPTIONS, + onTouchEnd, + PASSIVE_CAPTURE, ); + scrollElement.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerup", onPointerUp); + window.removeEventListener("pointercancel", onPointerUp); + window.removeEventListener("keydown", onKeyDown); this.touching = false; - if (this.settleTimeout !== null) { - window.clearTimeout(this.settleTimeout); - this.settleTimeout = null; - } - }; - } - - registerRowOffsetSource(source: ScrollRowOffsetSource): () => void { - this.rowOffsetSources.add(source); - return () => { - this.rowOffsetSources.delete(source); + this.pointerDown = false; + if (this.settleTimeout !== null) window.clearTimeout(this.settleTimeout); + if (this.clampFrame !== null) + window.cancelAnimationFrame(this.clampFrame); + this.settleTimeout = null; + this.clampFrame = null; + this.setDeferred(0); }; } - registerScrollExtentSync(sync: () => void): () => void { - this.scrollExtentSyncs.add(sync); - return () => { - this.scrollExtentSyncs.delete(sync); - }; + scrollToBottom(): void { + this.pendingRestore = null; + this.setPosition({ kind: "bottom" }); + this.reconcile(); } - subscribeScrollWrites(listener: () => void): () => void { - this.writeListeners.add(listener); - return () => { - this.writeListeners.delete(listener); - }; + revealElement(element: HTMLElement, options: ScrollIntoViewOptions): void { + const scrollElement = this.options.getScrollElement(); + this.pendingRestore = null; + this.flushDeferred(); + element.scrollIntoView(options); + if (scrollElement === null) return; + this.ownScrollTop = scrollElement.scrollTop; + this.refreshExtent(scrollElement); + this.setPosition( + this.isAtEnd(scrollElement.scrollTop) + ? { kind: "bottom" } + : (this.capture(scrollElement) ?? FREE), + ); + this.notifyLists(); } - handleScroll(): void { - this.reconcile(); - this.capture(); + scrollTo(top: number, behavior: ScrollBehavior): void { + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null) return; + this.pendingRestore = null; + this.flushDeferred(); + if (this.position.kind === "bottom") { + this.setPosition(this.capture(scrollElement) ?? FREE); + } + if (behavior === "smooth") { + this.extendInput(PROGRAMMATIC_SMOOTH_SESSION_MS); + scrollElement.scrollTo({ top, behavior }); + return; + } + this.write(scrollElement, top); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.notifyLists(); } - hold(element: HTMLElement, edge: ScrollHoldEdge, durationMs: number): void { + hold(element: HTMLElement, edge: ScrollHoldEdge): void { const scrollElement = this.options.getScrollElement(); - if (scrollElement === null || !this.options.isActive()) return; - this.holdUntil = window.performance.now() + durationMs; - this.anchor = { - kind: "element", + if (scrollElement === null || this.position.kind === "bottom") return; + const key = element.getAttribute(ROW_ID_ATTRIBUTE); + if (key === null) return; + this.pendingRestore = null; + this.position = { + kind: "anchor", + key, element, edge, - offset: this.elementEdgeOffset(scrollElement, element, edge), + offset: this.edgeTop(scrollElement, element, edge), + neighbors: [], }; - this.setOverflowAnchorDisabled(scrollElement, true); - } - - releaseHold(): void { - if (this.holdUntil === 0) return; - this.holdUntil = 0; - this.capture(); } - capture(): void { - const scrollElement = this.options.getScrollElement(); - if (scrollElement === null) return; - this.observeScrollMovement(scrollElement); - if (!this.options.isActive()) { - this.writeDeferredOffset(scrollElement); - this.anchor = null; - this.holdUntil = 0; - this.setOverflowAnchorDisabled(scrollElement, false); + restore(saved: SavedReadingPosition): void { + if (saved.atBottom) { + this.scrollToBottom(); return; } - const anchor = this.anchor; - if ( - anchor?.kind === "element" && - window.performance.now() < this.holdUntil && - anchor.element.isConnected - ) { - anchor.offset = this.elementEdgeOffset( - scrollElement, - anchor.element, - anchor.edge, - ); - return; + this.pendingRestore = { + rowId: saved.rowId, + offset: -saved.offsetWithinRow, + expiresAt: window.performance.now() + RESTORE_WAIT_MS, + }; + this.reconcile(); + } + + pendingRestoreRowId(): string | null { + return this.pendingRestore?.rowId ?? null; + } + + savedPosition(): SavedReadingPosition | null { + if (this.pendingRestore !== null) { + return { + rowId: this.pendingRestore.rowId, + offsetWithinRow: -this.pendingRestore.offset, + atBottom: false, + }; } - this.holdUntil = 0; - if (anchor?.kind !== "row" || !this.isStillFirstRow(scrollElement, anchor)) { - this.anchor = this.findRowAnchor(scrollElement); + const position = this.position; + if (position.kind === "bottom") { + return { rowId: "", offsetWithinRow: 0, atBottom: true }; } - this.setOverflowAnchorDisabled(scrollElement, this.anchor !== null); + if (position.kind === "free") return null; + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null) return null; + const anchor = this.capture(scrollElement); + if (anchor === null || anchor.kind !== "anchor") return null; + const nested = + anchor.element?.parentElement?.closest(ROW_SELECTOR) !== null; + const viewportTop = scrollElement.getBoundingClientRect().top; + const restorableAnchor = + !nested && + anchor.element !== null && + anchor.element.getBoundingClientRect().top - viewportTop <= + this.visibleHeight(scrollElement) - MIN_VISIBLE_ANCHOR_PX; + const saved = restorableAnchor ? anchor : this.topRow; + if (saved === null || saved.element === null) return null; + return { + rowId: saved.key, + offsetWithinRow: viewportTop - saved.element.getBoundingClientRect().top, + atBottom: false, + }; } - reconcile(): void { - const anchor = this.anchor; - if (anchor === null) return; + handleScroll(): void { const scrollElement = this.options.getScrollElement(); - if (scrollElement === null || !this.options.isActive()) { - this.capture(); + if (scrollElement === null) return; + const scrollTop = scrollElement.scrollTop; + const previous = this.ownScrollTop; + if (previous !== null && Math.abs(scrollTop - previous) < MIN_WRITE_PX) { return; } - this.observeScrollMovement(scrollElement); - const deferWrite = this.shouldDeferWrite(scrollElement); - if (!deferWrite) this.writeDeferredOffset(scrollElement); - const current = this.locate(scrollElement, anchor); - if (current === null) { - this.capture(); - return; + if (!this.isInputSession()) { + const cachedMax = this.maxScrollTop; + if (Math.abs(this.refreshExtent(scrollElement) - cachedMax) >= 1) { + this.ownScrollTop = scrollTop; + this.apply(scrollElement, true); + return; + } } - const delta = current - anchor.offset; - if (Math.abs(delta) < MIN_CORRECTION_PX) return; - if (deferWrite) { - this.setDeferredOffset(this.deferredOffset + delta); - this.scheduleDeferredWrite(); + this.extendInput(SESSION_EXTENSION_MS); + if (this.touching || this.pointerDown) this.gestureScrolled = true; + this.ownScrollTop = scrollTop; + this.scrollMovedAt = window.performance.now(); + this.userScrolled = true; + this.pendingRestore = null; + const movedDown = previous === null || scrollTop > previous; + const position = this.position; + if (position.kind === "anchor" && previous !== null) { + position.offset -= scrollTop - previous; + } + if (position.kind === "bottom") { + if (!movedDown && !this.isAtEnd(scrollTop)) { + this.refreshExtent(scrollElement); + if (!this.isAtEnd(scrollTop)) { + this.setPosition(this.capture(scrollElement) ?? FREE); + } + } + } else if (movedDown && this.isAtEnd(scrollTop)) { + this.setPosition({ kind: "bottom" }); } else { - anchor.offset = current; - this.scrollBy(scrollElement, delta); + if (position.kind === "anchor") this.apply(scrollElement, false); + const current = this.position; + if (current.kind !== "anchor" || !this.isInView(scrollElement, current)) { + this.setPosition(this.capture(scrollElement) ?? FREE); + } + this.notifyLists(); + if (this.position.kind === "anchor") this.apply(scrollElement, false); + this.setPosition(this.capture(scrollElement) ?? FREE); } - this.notifyScrollWrite(); + if (this.deferred !== 0) this.scheduleDeferredWrite(); + this.notifyLists(); } - private shouldDeferWrite(scrollElement: HTMLElement): boolean { - if (!this.options.deferWritesWhileScrolling) return false; - if (this.touching) return true; - if (window.performance.now() - this.scrollMovedAt < SCROLL_SETTLE_MS) { - return true; - } - const scrollTop = scrollElement.scrollTop; - return ( - scrollTop < 0 || - scrollTop > scrollElement.scrollHeight - scrollElement.clientHeight - ); + reconcile(urgent = true): void { + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null) return; + this.apply(scrollElement, true, urgent); } - private observeScrollMovement(scrollElement: HTMLElement): void { + private apply( + scrollElement: HTMLElement, + notify: boolean, + urgent = true, + ): void { const scrollTop = scrollElement.scrollTop; - const previous = this.observedScrollTop; - if (scrollTop === previous) return; - this.observedScrollTop = scrollTop; - if (previous !== null) this.scrollMovedAt = window.performance.now(); - } - - private scheduleDeferredWrite(): void { - if (this.deferredOffset === 0 || this.settleTimeout !== null) return; - this.settleTimeout = window.setTimeout(() => { - this.settleTimeout = null; - const scrollElement = this.options.getScrollElement(); - if (scrollElement === null || this.deferredOffset === 0) return; - this.observeScrollMovement(scrollElement); - if (this.options.isActive() && this.shouldDeferWrite(scrollElement)) { + const max = this.refreshExtent(scrollElement); + const width = scrollElement.clientWidth; + if ( + this.reconciledWidth > 0 && + Math.abs(this.reconciledWidth - width) >= 1 + ) { + this.keepAnchorVisible(scrollElement); + } + this.reconciledWidth = width; + const previous = this.ownScrollTop; + if ( + previous !== null && + Math.abs(scrollTop - previous) >= MIN_WRITE_PX && + this.position.kind === "anchor" && + this.isInputSession() + ) { + this.position.offset -= scrollTop - previous; + this.scrollMovedAt = window.performance.now(); + } + this.ownScrollTop = scrollTop; + this.advancePendingRestore(scrollElement); + const scrollHeight = scrollElement.scrollHeight; + const extentChanged = scrollHeight !== this.reconciledScrollHeight; + this.reconciledScrollHeight = scrollHeight; + const defer = this.shouldDefer(scrollTop, max); + const bouncing = + defer && !extentChanged && (scrollTop <= 0 || scrollTop >= max - 1); + const settledAtEnd = + this.position.kind === "bottom" && + !extentChanged && + Math.abs(max - scrollTop) <= this.options.bottomThresholdPx; + const target = + bouncing || settledAtEnd + ? null + : this.targetScrollTop(scrollElement, scrollTop, max); + if (target !== null) { + const clamped = defer + ? Math.min( + Math.max(target, Math.min(0, scrollTop)), + Math.max(max, scrollTop), + ) + : Math.min(Math.max(target, 0), max); + if (defer) { + this.setDeferred(clamped - scrollTop); this.scheduleDeferredWrite(); - return; + } else { + this.setDeferred(0); + this.write(scrollElement, clamped); } - this.writeDeferredOffset(scrollElement); - this.reconcile(); - this.capture(); - }, SCROLL_SETTLE_MS); + if (Math.abs(clamped - target) >= 1 && this.position.kind === "anchor") { + this.scheduleClampSettle(); + } + } + if (notify) this.notifyLists(urgent); } - private writeDeferredOffset(scrollElement: HTMLElement): void { - const offset = this.deferredOffset; - if (offset === 0) return; - this.setDeferredOffset(0); - if (this.anchor !== null) this.anchor.offset += offset; - this.scrollBy(scrollElement, offset); - this.notifyScrollWrite(); + private isInView( + scrollElement: HTMLElement, + position: Extract, + ): boolean { + const element = position.element; + if (element === null || !element.isConnected) return false; + const height = element.getBoundingClientRect().height; + const viewportHeight = this.viewportHeight || scrollElement.clientHeight; + return position.offset > -height && position.offset < viewportHeight; } - private scrollBy(scrollElement: HTMLElement, delta: number): void { - const target = scrollElement.scrollTop + delta; - if (target > scrollElement.scrollHeight - scrollElement.clientHeight) { - for (const sync of this.scrollExtentSyncs) sync(); + private advancePendingRestore(scrollElement: HTMLElement): void { + const pending = this.pendingRestore; + if (pending === null) return; + const element = findMountedRow(scrollElement, pending.rowId); + if (element !== null) { + this.pendingRestore = null; + const height = element.getBoundingClientRect().height; + this.setPosition({ + kind: "anchor", + key: pending.rowId, + element, + edge: "top", + offset: Math.min( + Math.max(pending.offset, -Math.max(0, height - 1)), + Math.max( + 0, + this.visibleHeight(scrollElement) - MIN_VISIBLE_ANCHOR_PX, + ), + ), + neighbors: [], + }); + return; + } + if (window.performance.now() > pending.expiresAt) { + this.pendingRestore = null; } - scrollElement.scrollTop = target; - this.observedScrollTop = scrollElement.scrollTop; - } - - private setDeferredOffset(offset: number): void { - this.deferredOffset = offset; - const element = - offset === 0 - ? this.deferredOffsetElement - : this.options.getDeferredOffsetElement(); - if (element === null) return; - element.style.transform = - offset === 0 ? "" : `translate3d(0, ${-offset}px, 0)`; - this.deferredOffsetElement = offset === 0 ? null : element; } - private notifyScrollWrite(): void { - for (const listener of this.writeListeners) listener(); + private targetScrollTop( + scrollElement: HTMLElement, + scrollTop: number, + max: number, + ): number | null { + const position = this.position; + if (position.kind === "bottom") return max; + if (position.kind === "free") return null; + if (position.element === null) { + const mounted = this.capture(scrollElement); + if (mounted?.kind === "anchor" && mounted.element !== null) { + this.setPosition(mounted); + } + return null; + } + const edgeTop = this.locate(scrollElement, position); + const located = this.position; + if (edgeTop === null || located.kind !== "anchor") return null; + return scrollTop + this.deferred + edgeTop - located.offset; } private locate( scrollElement: HTMLElement, - anchor: KeptAnchor, + position: Extract, ): number | null { - if (anchor.kind === "element") { - return anchor.element.isConnected - ? this.elementEdgeOffset(scrollElement, anchor.element, anchor.edge) - : null; - } + let element = position.element; if ( - !anchor.element.isConnected || - anchor.element.getAttribute(ROW_ID_ATTRIBUTE) !== anchor.rowId || - !scrollElement.contains(anchor.element) + element === null || + !element.isConnected || + element.getAttribute(ROW_ID_ATTRIBUTE) !== position.key ) { - const element = this.findMountedRow(scrollElement, anchor.rowId); - if (element !== null) anchor.element = element; + element = findMountedRow(scrollElement, position.key); + if (element !== null) position.element = element; } - if (anchor.element.isConnected) { - return this.elementEdgeOffset(scrollElement, anchor.element, "top"); - } - for (const source of this.rowOffsetSources) { - const offset = source(anchor.rowId); - if (offset !== null) return offset; + if (element === null) { + for (const [index, neighbor] of position.neighbors.entries()) { + const fallback = findMountedRow(scrollElement, neighbor.key); + if (fallback === null) continue; + this.position = { + kind: "anchor", + key: neighbor.key, + element: fallback, + edge: "top", + offset: position.offset + neighbor.delta, + neighbors: position.neighbors.slice(index + 1).map((next) => ({ + key: next.key, + delta: next.delta - neighbor.delta, + })), + }; + return this.edgeTop(scrollElement, fallback, "top"); + } + return null; } - return null; + return this.edgeTop(scrollElement, element, position.edge); } - private isStillFirstRow( - scrollElement: HTMLElement, - anchor: Extract, - ): boolean { - const element = anchor.element; - if (!anchor.topLevel || !element.isConnected) return false; - if (!scrollElement.contains(element)) return false; + private capture(scrollElement: HTMLElement): ReadingPosition | null { const viewport = scrollElement.getBoundingClientRect(); - const top = element.getBoundingClientRect().top; - if (top < viewport.top || top >= viewport.bottom) return false; - const previous = previousRowSibling(element); - if (previous === null) return true; - const previousRect = previous.getBoundingClientRect(); - if (previousRect.bottom <= viewport.top) return true; - return ( - previousRect.top < viewport.top && - previous.querySelector(ROW_SELECTOR) === null + const viewportTop = viewport.top; + const footerTop = this.options + .getFooterElement() + ?.getBoundingClientRect().top; + const viewportBottom = Math.min( + viewportTop + (this.viewportHeight || scrollElement.clientHeight), + footerTop ?? Number.POSITIVE_INFINITY, ); - } - - private findMountedRow( - scrollElement: HTMLElement, - rowId: string, - ): HTMLElement | null { - for (const row of scrollElement.querySelectorAll( - ROW_SELECTOR, - )) { - if (row.getAttribute(ROW_ID_ATTRIBUTE) === rowId) return row; - } - return null; - } - - private findRowAnchor(scrollElement: HTMLElement): KeptAnchor | null { - const scrollRect = scrollElement.getBoundingClientRect(); - const viewportTop = scrollRect.top; - const viewportBottom = scrollRect.bottom; const rows = this.options.getTopLevelRows(scrollElement); let low = 0; let high = rows.length - 1; @@ -357,29 +628,39 @@ export class ScrollPositionKeeper { const index = low + Math.floor((high - low) / 2); const row = rows[index]; if (row === undefined) break; - if (row.getBoundingClientRect().bottom <= viewportTop) { + if (row.getBoundingClientRect().bottom <= viewportTop + 0.5) { low = index + 1; } else { straddling = index; high = index - 1; } } - if (straddling < 0) return null; - const first = rows[straddling]; - if (first === undefined) return null; - const firstTop = first.getBoundingClientRect().top; - let chosen: HTMLElement = first; - let topLevel = true; - if (firstTop < viewportTop) { - const nested = this.firstRowStartingInViewport( - first.querySelectorAll(ROW_SELECTOR), - viewportTop, - viewportBottom, - ); + const first = straddling < 0 ? undefined : rows[straddling]; + const firstTop = first?.getBoundingClientRect().top; + if ( + first === undefined || + firstTop === undefined || + firstTop >= viewportBottom + ) { + return this.captureFromLists(viewportTop); + } + const firstKey = first.getAttribute(ROW_ID_ATTRIBUTE); + if (firstKey !== null) { + this.topRow = { key: firstKey, element: first }; + } + let chosen = first; + if (firstTop < viewportTop - 0.5) { const next = rows[straddling + 1]; + const nested = + next !== undefined && next.getBoundingClientRect().top < viewportBottom + ? null + : firstRowStartingInViewport( + first.querySelectorAll(ROW_SELECTOR), + viewportTop, + viewportBottom, + ); if (nested !== null) { chosen = nested; - topLevel = false; } else if ( next !== undefined && next.getBoundingClientRect().top < viewportBottom @@ -387,31 +668,196 @@ export class ScrollPositionKeeper { chosen = next; } } - const rowId = chosen.getAttribute(ROW_ID_ATTRIBUTE); - if (rowId === null) return null; + const key = chosen.getAttribute(ROW_ID_ATTRIBUTE); + if (key === null) return null; + const chosenTop = chosen.getBoundingClientRect().top; + const neighbors: AnchorNeighbor[] = []; + for ( + let index = straddling; + index < rows.length && neighbors.length < MAX_ANCHOR_NEIGHBORS; + index += 1 + ) { + const row = rows[index]; + if (row === undefined || row === chosen) continue; + const top = row.getBoundingClientRect().top; + if (top >= viewportBottom) break; + const rowKey = row.getAttribute(ROW_ID_ATTRIBUTE); + if (rowKey !== null) + neighbors.push({ key: rowKey, delta: top - chosenTop }); + } return { - kind: "row", - rowId, + kind: "anchor", + key, element: chosen, - offset: this.elementEdgeOffset(scrollElement, chosen, "top"), - topLevel, + edge: "top", + offset: chosenTop - viewportTop, + neighbors, }; } - private firstRowStartingInViewport( - rows: NodeListOf, - viewportTop: number, - viewportBottom: number, - ): HTMLElement | null { - for (const row of rows) { - const top = row.getBoundingClientRect().top; - if (top >= viewportBottom) return null; - if (top >= viewportTop) return row; + private captureFromLists(viewportTop: number): ReadingPosition | null { + for (const list of this.lists) { + const item = list.itemAt(viewportTop); + if (item !== null) { + return { + kind: "anchor", + key: item.key, + element: null, + edge: "top", + offset: item.top - viewportTop, + neighbors: [], + }; + } } return null; } - private elementEdgeOffset( + private extendInput(durationMs: number): void { + this.inputUntil = Math.max( + this.inputUntil, + window.performance.now() + durationMs, + ); + } + + private isInputSession(): boolean { + return ( + this.touching || + this.pointerDown || + window.performance.now() <= this.inputUntil + ); + } + + 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 isAtEnd(scrollTop: number): boolean { + return ( + this.maxScrollTop - (scrollTop + this.deferred) <= + this.options.bottomThresholdPx + ); + } + + private keepAnchorVisible(scrollElement: HTMLElement): void { + if (this.position.kind !== "anchor" || this.position.edge !== "top") { + return; + } + this.position.offset = Math.min( + this.position.offset, + Math.max(0, this.visibleHeight(scrollElement) - MIN_VISIBLE_ANCHOR_PX), + ); + } + + private visibleHeight(scrollElement: HTMLElement): number { + const height = this.viewportHeight || scrollElement.clientHeight; + const footerTop = this.options + .getFooterElement() + ?.getBoundingClientRect().top; + if (footerTop === undefined) return height; + return Math.min( + height, + footerTop - scrollElement.getBoundingClientRect().top, + ); + } + + private refreshExtent(scrollElement: HTMLElement): number { + this.viewportHeight = scrollElement.clientHeight; + this.maxScrollTop = Math.max( + 0, + scrollElement.scrollHeight - this.viewportHeight, + ); + return this.maxScrollTop; + } + + private shouldDefer(scrollTop: number, max: number): boolean { + if (!this.options.deferWritesWhileScrolling) return false; + if (this.touching) return true; + if (window.performance.now() - this.scrollMovedAt < SCROLL_SETTLE_MS) { + return true; + } + return scrollTop < 0 || scrollTop > max; + } + + private scheduleDeferredWrite(): void { + if (this.deferred === 0 || this.settleTimeout !== null) return; + this.settleTimeout = window.setTimeout(() => { + this.settleTimeout = null; + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null || this.deferred === 0) return; + const scrollTop = scrollElement.scrollTop; + if (this.shouldDefer(scrollTop, this.maxScrollTop)) { + this.scheduleDeferredWrite(); + return; + } + this.flushDeferred(); + this.reconcile(); + }, SCROLL_SETTLE_MS); + } + + private flushDeferred(): void { + const scrollElement = this.options.getScrollElement(); + const offset = this.deferred; + if (scrollElement === null || offset === 0) return; + const target = scrollElement.scrollTop + offset; + this.setDeferred(0); + this.write(scrollElement, target); + } + + private scheduleClampSettle(): void { + if (this.clampFrame !== null) return; + this.clampFrame = window.requestAnimationFrame(() => { + this.clampFrame = null; + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null || this.position.kind !== "anchor") return; + const scrollTop = scrollElement.scrollTop; + const max = this.refreshExtent(scrollElement); + const target = this.targetScrollTop(scrollElement, scrollTop, max); + if (target === null || (target >= 0 && target <= max)) { + this.reconcile(); + return; + } + this.setPosition(this.capture(scrollElement) ?? FREE); + }); + } + + private write(scrollElement: HTMLElement, target: number): void { + if (Math.abs(scrollElement.scrollTop - target) >= MIN_WRITE_PX) { + scrollElement.scrollTop = target; + } + this.ownScrollTop = scrollElement.scrollTop; + } + + private setDeferred(offset: number): void { + const rounded = Math.abs(offset) < MIN_WRITE_PX ? 0 : offset; + if (rounded === this.deferred) return; + this.deferred = rounded; + const element = + rounded === 0 ? this.deferredElement : this.options.getContentElement(); + if (element === null) return; + element.style.transform = + rounded === 0 ? "" : `translate3d(0, ${-rounded}px, 0)`; + this.deferredElement = rounded === 0 ? null : element; + } + + private setPosition(next: ReadingPosition): void { + const wasAttached = this.position.kind === "bottom"; + this.position = next; + if (wasAttached !== (next.kind === "bottom")) { + for (const listener of this.listeners) listener(); + } + } + + private notifyLists(urgent = true): void { + for (const list of this.lists) list.onPositionChange(urgent); + for (const listener of this.positionListeners) listener(); + } + + private edgeTop( scrollElement: HTMLElement, element: HTMLElement, edge: ScrollHoldEdge, @@ -419,17 +865,7 @@ export class ScrollPositionKeeper { const rect = element.getBoundingClientRect(); return ( (edge === "top" ? rect.top : rect.bottom) - - scrollElement.getBoundingClientRect().top + - scrollElement.scrollTop + scrollElement.getBoundingClientRect().top ); } - - private setOverflowAnchorDisabled( - scrollElement: HTMLElement, - disabled: boolean, - ): void { - if (this.overflowAnchorDisabled === disabled) return; - this.overflowAnchorDisabled = disabled; - scrollElement.style.overflowAnchor = disabled ? "none" : ""; - } } diff --git a/apps/app/src/components/ui/theme.css b/apps/app/src/components/ui/theme.css index ea53acb5c7b..0f6f8fa65dc 100644 --- a/apps/app/src/components/ui/theme.css +++ b/apps/app/src/components/ui/theme.css @@ -1069,19 +1069,3 @@ body.sidebar-resizing [data-sidebar="panel"] { transition-property: opacity; } -/* - * Bottom-anchored scroll bodies (see bottom-anchored-scroll-body.tsx). The - * class goes on the content wrapper alone: scroll anchoring skips an excluded - * element's whole subtree, so no descendant rule is needed. A `*` descendant - * rule here would restyle every timeline node each time the class toggles. - * The sentinel is a sibling of the wrapper, so it stays eligible. - */ -.scroll-bottom-anchor-content { - overflow-anchor: none; -} - -.scroll-bottom-anchor { - height: 1px; - flex-shrink: 0; - overflow-anchor: auto; -} diff --git a/apps/app/src/components/ui/theme.test.ts b/apps/app/src/components/ui/theme.test.ts index be17c470395..720aa00448b 100644 --- a/apps/app/src/components/ui/theme.test.ts +++ b/apps/app/src/components/ui/theme.test.ts @@ -374,7 +374,7 @@ describe("theme.css sidebar width registration", () => { }); }); -describe("theme.css shimmer and scroll-anchor paint scope", () => { +describe("theme.css shimmer paint scope", () => { function ruleBody(selector: string, source = css): string { const at = source.indexOf(`${selector} {`); if (at === -1) throw new Error(`no ${selector} rule in theme.css`); @@ -464,14 +464,4 @@ describe("theme.css shimmer and scroll-anchor paint scope", () => { expect(rule).toMatch(/(? { - expect(css).not.toMatch(/\.scroll-bottom-anchor-content\s*\*/); - expect(ruleBody(".scroll-bottom-anchor-content")).toMatch( - /overflow-anchor:\s*none;/, - ); - expect(ruleBody(".scroll-bottom-anchor")).toMatch( - /overflow-anchor:\s*auto;/, - ); - }); }); diff --git a/apps/app/src/test/fake-flow-layout.ts b/apps/app/src/test/fake-flow-layout.ts new file mode 100644 index 00000000000..a2cc89c8664 --- /dev/null +++ b/apps/app/src/test/fake-flow-layout.ts @@ -0,0 +1,236 @@ +import { vi } from "vitest"; + +interface FakeFlowLayoutOptions { + scrollElement: HTMLElement | (() => HTMLElement | null); + viewportHeight: number; +} + +interface Box { + top: number; + height: number; +} + +type ObserverCallback = (entries: ResizeObserverEntry[]) => void; + +const HEIGHT_ATTRIBUTE = "data-fake-height"; + +function pixels(value: string): number { + const parsed = Number.parseFloat(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function translateY(element: HTMLElement): number { + const match = /translate3d\(0(?:px)?, (-?[\d.]+)px/u.exec( + element.style.transform, + ); + return match === null ? 0 : Number(match[1]); +} + +export function setFakeHeight(element: Element, height: number): void { + element.setAttribute(HEIGHT_ATTRIBUTE, String(height)); +} + +export function installFakeFlowLayout({ + scrollElement: scrollElementOption, + viewportHeight, +}: FakeFlowLayoutOptions) { + let scrollTop = 0; + const boxes = new Map(); + const resolveScrollElement = (): HTMLElement | null => + typeof scrollElementOption === "function" + ? scrollElementOption() + : scrollElementOption; + + const layout = () => { + boxes.clear(); + const place = (element: Element, top: number): number => { + const own = element.getAttribute(HEIGHT_ATTRIBUTE); + 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); + let childTop = top + shift; + for (const child of element.children) { + childTop += place(child, childTop); + } + } else if (style !== null && style.height !== "") { + height = pixels(style.height); + } else { + const gap = style === null ? 0 : pixels(style.gap); + let childTop = top + shift; + let used = 0; + let index = 0; + for (const child of element.children) { + const childHeight = place(child, childTop); + childTop += childHeight + gap; + used += childHeight + (index > 0 ? gap : 0); + index += 1; + } + height = used; + } + boxes.set(element, { top: top + shift, height }); + return height; + }; + const scrollElement = resolveScrollElement(); + if (scrollElement === null) return 0; + let top = 0; + for (const child of scrollElement.children) top += place(child, top); + return top; + }; + + const contentHeight = () => Math.max(viewportHeight, layout()); + const maxScrollTop = () => Math.max(0, contentHeight() - viewportHeight); + + const isScrollElement = (element: Element) => + element === resolveScrollElement(); + const scrollTopDescriptor = Object.getOwnPropertyDescriptor( + Element.prototype, + "scrollTop", + ); + const clientHeightDescriptor = Object.getOwnPropertyDescriptor( + Element.prototype, + "clientHeight", + ); + const scrollHeightDescriptor = Object.getOwnPropertyDescriptor( + Element.prototype, + "scrollHeight", + ); + Object.defineProperty(Element.prototype, "scrollTop", { + configurable: true, + get(this: Element) { + return isScrollElement(this) + ? scrollTop + : (scrollTopDescriptor?.get?.call(this) ?? 0); + }, + set(this: Element, value: number) { + if (isScrollElement(this)) { + scrollTop = Math.min(Math.max(0, value), maxScrollTop()); + } else { + scrollTopDescriptor?.set?.call(this, value); + } + }, + }); + Object.defineProperty(Element.prototype, "clientHeight", { + configurable: true, + get(this: Element) { + return isScrollElement(this) + ? viewportHeight + : (clientHeightDescriptor?.get?.call(this) ?? 0); + }, + }); + Object.defineProperty(Element.prototype, "scrollHeight", { + configurable: true, + get(this: Element) { + return isScrollElement(this) + ? contentHeight() + : (scrollHeightDescriptor?.get?.call(this) ?? 0); + }, + }); + + const rectSpy = vi + .spyOn(Element.prototype, "getBoundingClientRect") + .mockImplementation(function (this: Element) { + if (isScrollElement(this)) { + return new DOMRect(0, 0, 400, viewportHeight); + } + layout(); + const box = boxes.get(this); + if (box === undefined) return new DOMRect(0, 0, 0, 0); + return new DOMRect(0, box.top - scrollTop, 400, box.height); + }); + + const observers = new Set<{ + callback: ObserverCallback; + targets: Set; + sizes: Map; + }>(); + const OriginalResizeObserver = globalThis.ResizeObserver; + class FakeResizeObserver { + private readonly record: { + callback: ObserverCallback; + targets: Set; + sizes: Map; + }; + constructor(callback: ObserverCallback) { + this.record = { callback, targets: new Set(), sizes: new Map() }; + observers.add(this.record); + } + observe(target: Element) { + this.record.targets.add(target); + } + unobserve(target: Element) { + this.record.targets.delete(target); + this.record.sizes.delete(target); + } + disconnect() { + this.record.targets.clear(); + observers.delete(this.record); + } + } + globalThis.ResizeObserver = + FakeResizeObserver as unknown as typeof ResizeObserver; + + return { + get scrollTop() { + return scrollTop; + }, + maxScrollTop, + userScrollTo(value: number) { + const scrollElement = resolveScrollElement(); + if (scrollElement === null) throw new Error("No scroll element"); + const next = Math.min(Math.max(0, value), maxScrollTop()); + scrollElement.dispatchEvent( + new WheelEvent("wheel", { deltaY: next - scrollTop }), + ); + scrollTop = next; + scrollElement.dispatchEvent(new Event("scroll")); + }, + topOf(element: Element): number { + return element.getBoundingClientRect().top; + }, + flushResizeObservers() { + layout(); + for (const observer of [...observers]) { + const entries: ResizeObserverEntry[] = []; + for (const target of observer.targets) { + const height = boxes.get(target)?.height ?? 0; + if (observer.sizes.get(target) === height) continue; + observer.sizes.set(target, height); + entries.push({ + target, + borderBoxSize: [{ blockSize: height, inlineSize: 400 }], + contentBoxSize: [{ blockSize: height, inlineSize: 400 }], + contentRect: new DOMRect(0, 0, 400, height), + devicePixelContentBoxSize: [], + }); + } + if (entries.length > 0) { + observer.callback(entries); + } + } + }, + bounceTo(value: number) { + scrollTop = value; + }, + layoutScrollTo(value: number) { + const scrollElement = resolveScrollElement(); + if (scrollElement === null) throw new Error("No scroll element"); + scrollTop = Math.min(Math.max(0, value), maxScrollTop()); + scrollElement.dispatchEvent(new Event("scroll")); + }, + restore() { + rectSpy.mockRestore(); + for (const [name, descriptor] of [ + ["scrollTop", scrollTopDescriptor], + ["clientHeight", clientHeightDescriptor], + ["scrollHeight", scrollHeightDescriptor], + ] as const) { + if (descriptor !== undefined) { + Object.defineProperty(Element.prototype, name, descriptor); + } + } + globalThis.ResizeObserver = OriginalResizeObserver; + }, + }; +} diff --git a/apps/app/src/test/scroll-position-keeper.ts b/apps/app/src/test/scroll-position-keeper.ts index 75a7fc0318b..d5f0acb0ea1 100644 --- a/apps/app/src/test/scroll-position-keeper.ts +++ b/apps/app/src/test/scroll-position-keeper.ts @@ -2,10 +2,12 @@ import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; export function createInertScrollPositionKeeper(): ScrollPositionKeeper { return new ScrollPositionKeeper({ + bottomThresholdPx: 4, deferWritesWhileScrolling: false, - getDeferredOffsetElement: () => null, + getContentElement: () => null, + getFooterElement: () => null, getScrollElement: () => null, getTopLevelRows: () => [], - isActive: () => false, + initiallyAttached: true, }); } diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 0dd53ebe702..1896e4c9011 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -204,44 +204,101 @@ as a row at the end of the timeline. ## Browser scroll ownership -The web timeline windows lists of 20 or more items on every platform, -including iOS Safari and the mobile app's WKWebView. The virtualizer keeps -visible rows, overscan, and interaction or navigation pins mounted. Loaded -history stays available without every rich row being mounted. Expanded detail -lists use their own scroll roots and the same windowing adapter. - -While the reader is scrolled away from the bottom, `ScrollPositionKeeper` is -the only writer of the reading position, for both the main timeline and nested -detail scrollers. It anchors the first row that starts in the viewport by its -offset in the content. When older pages load, rows measure, or a row resizes, -it applies the change above that row as a relative `scrollTop` adjustment. -TanStack's own scroll adjustments and native CSS scroll anchoring stay off while -the keeper holds a row. Stuck-to-bottom following is unchanged. - -The timeline list sits in an auto-height wrapper whose height follows its -content one resize-observer tick late. Before the keeper writes a correction -past the current scroll extent, for example after an older page prepends rows, -it snaps that wrapper to its content height. Otherwise the browser clamps the -write to the old bottom, the reader loses their place, and the shell reads the -clamped position as a return to the bottom and reattaches. +Each scroll root has one owner of the reading position: `ScrollPositionKeeper`. +The thread timeline (`BottomAnchoredScrollBody`) and every expanded detail +scroller (`useStickyBottomScroll`) create one. It is the only code that writes +`scrollTop` on its root, apart from the reader and explicit navigation it +performs for callers (reveal a row, jump to the bottom, scroll to the top). +Native CSS scroll anchoring is off on the root. + +The reading position is explicit state: attached to the bottom, or a row key +with the distance from the top of the visible viewport to that row's top (or, +for a held element such as a collapsing message, its bottom). The visible +viewport ends at the sticky composer. The anchor is the first top-level row +that starts in the visible viewport, or a row nested in a row that covers the +whole viewport. The owner also records the other visible rows' offsets from the +anchor. If a merge replaces the anchor row's key, for example when an older page +regroups a turn, the first of those rows that is still mounted becomes the +anchor. The position changes only when: + +- the reader scrolls; +- a caller navigates; +- 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. + +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 +three seconds after the finger lifts, on every platform). 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 or End/PageDown at the end, attaches. Moving up +out of it detaches. Layout changes never attach or detach. + +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 +effect after a commit. Within one reconciliation: + +1. A scroll the owner did not make is folded into the position as the reader's + movement, before the layout is read. Changes that landed in the same forced + layout are therefore not mistaken for scrolling. They are reconciled against + the moved position first. Only then, if the anchor has left the viewport, + the owner picks a new anchor where the reader now is. +2. Windowed lists render the rows around a row key, never around a raw + `scrollTop`. A prepend keeps the same rows mounted, and the owner's anchor + row is always mounted. +3. The owner reads the anchor's position and computes the target `scrollTop` + from the fixed position. It is never a relative delta, so a clamped + intermediate write is not counted twice. +4. It writes the target, clamped to the scroll extent. Attached means the + maximum. +5. Lists check that the visible range is mounted. If the viewport would show a + spacer, they render the rows synchronously before paint. The check uses the + heights the spacers were rendered with and the measured heights of mounted + rows, so it describes what is on screen, not newer measurements the spacers + have not used yet. + +When the viewport lands on a spacer, the owner can only record which row the +list estimates is there. That estimate never moves the view: once real rows +mount, the owner takes its position from them. + +Lists of 20 or more items are windowed on every platform, including iOS Safari +and the mobile app's WKWebView. Rows stay in normal flow between spacers whose +heights come from the measurements the thread retains, so rows never overlap +and a row resize needs no positioning pass. The thread retains the 2,000 most +recent measurements; a spacer keeps the height it last rendered for a row whose +measurement was dropped. Only rows that have never mounted use an estimate. When such a row mounts above the reader, its real height +changes the content above, and step 3 corrects it. Visible rows, eight rows of +overscan on each side, search and navigation targets, the last row, and the 24 +most recently interacted rows stay mounted. Within two viewport heights of the +top of the list, every row above the viewport is mounted, so estimates are +corrected while there is still room to scroll. Expanded detail lists use their own +scroll roots and the same list. iOS WebKit overrides a scroll write made while a finger is down, during -momentum, or during an edge bounce, and the content then sags and snaps back. -On iOS the keeper waits during those phases instead. It keeps the correction as -a transform on the scroll content, so rows stay in place visually. The -virtualizer reads the scroll offset plus the held correction, so the window -matches what is on screen. Once the touch has ended and the scroll position has -been still for 150 ms, the keeper writes the correction to `scrollTop` and -removes the transform in the same frame. It also writes before it stops -keeping the position, for example when the reader returns to the bottom. Other +momentum, or during an edge bounce. On iOS the owner applies the correction as a +transform on the scroll content during those phases, so rows stay in place +visually, and lists window around the rendered position. Once the touch has +ended and the scroll position has been still for 150 ms, it writes the +correction to `scrollTop` and removes the transform in the same task. Other browsers write immediately. -When a detached reader's scrollport changes width (for example after a rotation), -the shell pins the saved reading row and restores it while measurements settle. -The restore is scoped to the thread, and it clamps an offset inside the row to -the row's new height. Height-only changes, such as the keyboard opening, keep the -existing path. A restore waits at the bottom until the saved row renders. It -does not stay wherever the new scroll root starts, because that position can -keep loading older pages. If the scroll position is past the cached scroll extent, the shell -reads the live extent first. A resize clamp or a correction past an outdated -extent therefore does not count as the reader returning to the bottom. +Older pages load when the "load older" sentinel above the list comes within +600 px of the viewport. The check runs after every position change the owner +reports, scrolls and reconciliations alike, rather than on intersection +changes, so a reader who returns to the top after a prepend always loads the +next page. + +A thread's position is saved when the reader scrolls and when the timeline +unmounts. Returning to the thread mounts the saved row's window and restores +the row at its saved offset, kept on screen if the viewport is now shorter. If +the row has not loaded yet, the timeline waits +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. + +Content shorter than the viewport is top-aligned. In that case a row that +expands moves the rows below it, including the latest row. From 73064c39f153f5d2b115fedc760fff7ea48bdf3d Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Thu, 22 Oct 2026 02:10:59 -0700 Subject: [PATCH 4/7] Measure message overflow before first paint so offscreen rows keep a stable size A message mounted above the viewport by an older-page prepend rendered one frame without its Show more control, and phones then skipped the row under content-visibility with that shorter remembered size. The control arrived from the shared ResizeObserver a frame later, so every forced layout of the skipped row flipped it between the two heights and moved the reader by about 24 px while scrolling. Measuring in the layout effect puts the control in the row's first frame. Co-Authored-By: Claude Opus 5.5 --- .../conversation-message-overflow.test.tsx | 24 ++++++++----------- .../conversation-message-overflow.tsx | 6 ++--- 2 files changed, 12 insertions(+), 18 deletions(-) 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 fba68dc530e..cdead28f9c6 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 @@ -37,7 +37,7 @@ function OverflowProbe({ name }: { name: string }) { } describe("useOverflowMeasurement", () => { - it("shares one observer and batches measurements for all rows", () => { + it("measures every row before its first paint and shares one observer for later changes", () => { let observerCallback: ResizeObserverCallback | null = null; const observe = vi.fn(); const unobserve = vi.fn(); @@ -79,13 +79,12 @@ describe("useOverflowMeasurement", () => { const first = screen.getByTestId("first"); const second = screen.getByTestId("second"); - expect(first.dataset.measurement).toBe("unmeasured"); - expect(second.dataset.measurement).toBe("unmeasured"); - expect(scrollHeight).not.toHaveBeenCalled(); - expect(clientHeight).not.toHaveBeenCalled(); - expect(scrollWidth).not.toHaveBeenCalled(); - expect(clientWidth).not.toHaveBeenCalled(); + expect(first.dataset.measurement).toBe("overflowing"); + expect(second.dataset.measurement).toBe("fits"); + expect(constructorSpy).toHaveBeenCalledOnce(); + expect(observe).toHaveBeenCalledTimes(2); + scrollHeight.mockReturnValue(20); act(() => { observerCallback?.( [ @@ -96,14 +95,11 @@ describe("useOverflowMeasurement", () => { ); }); - expect(constructorSpy).toHaveBeenCalledOnce(); - expect(observe).toHaveBeenCalledTimes(2); - expect(scrollHeight).toHaveBeenCalledTimes(2); - expect(clientHeight).toHaveBeenCalledTimes(2); - expect(scrollWidth).toHaveBeenCalledTimes(2); - expect(clientWidth).toHaveBeenCalledTimes(2); - expect(first.dataset.measurement).toBe("overflowing"); + expect(first.dataset.measurement).toBe("fits"); expect(second.dataset.measurement).toBe("fits"); + expect(clientHeight).toHaveBeenCalled(); + expect(scrollWidth).toHaveBeenCalled(); + expect(clientWidth).toHaveBeenCalled(); }); }); diff --git a/apps/app/src/components/thread/timeline/conversation-message-overflow.tsx b/apps/app/src/components/thread/timeline/conversation-message-overflow.tsx index 5d8a4699fed..97bf260c2e4 100644 --- a/apps/app/src/components/thread/timeline/conversation-message-overflow.tsx +++ b/apps/app/src/components/thread/timeline/conversation-message-overflow.tsx @@ -124,10 +124,8 @@ export function useOverflowMeasurement({ if (!element.isConnected) return; setMeasurement(nextMeasurement[axis] ? "overflowing" : "fits"); }; - if (typeof ResizeObserver === "undefined") { - applyMeasurement(readOverflowMeasurement(element)); - return; - } + applyMeasurement(readOverflowMeasurement(element)); + if (typeof ResizeObserver === "undefined") return; return observeOverflow(element, applyMeasurement); }, [elementRef, enabled, axis, measurementKey]); From 529b4a271c1bbc8c0e6ebd665fee526a2d4898bc Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Thu, 22 Oct 2026 07:46:50 -0700 Subject: [PATCH 5/7] Keep timeline windowing off on iOS WebKit, as on main WKWebView can drop a scroll correction that lands as a fling starts and apply it two frames later, which shows the wrong part of a windowed list for those frames. Until that is handled, iOS Safari and the mobile app's WKWebView keep every row mounted, matching main. The position keeper is unchanged; its iOS deferral still covers corrections from older pages and row resizes. Co-Authored-By: Claude Opus 5.5 --- .../timeline/ThreadTimelineRows.windowing.test.tsx | 2 +- .../thread/timeline/TimelineWindowedItems.test.tsx | 13 ++++++++++++- .../thread/timeline/TimelineWindowedItems.tsx | 5 +++++ docs/timeline-pagination.md | 6 +++--- 4 files changed, 21 insertions(+), 5 deletions(-) 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 96123593540..18f6a24d71f 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx @@ -220,7 +220,7 @@ describe("ThreadTimelineRows windowing", () => { expect(view.container.textContent).toContain( `Window message ${count - 1}`, ); - if (count < 20) { + if (count < 20 || iPhone) { expect(mountedRows.length).toBe(count); expect( view.container.querySelector("[data-timeline-virtual-spacer]"), diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx index ee7c3682285..defd34e9ac8 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx @@ -7,7 +7,7 @@ import { render, screen, } from "@testing-library/react"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; import { installFakeFlowLayout } from "@/test/fake-flow-layout"; import { TimelineWindowedItems } from "./TimelineWindowedItems.js"; @@ -17,6 +17,7 @@ const cleanups: (() => void)[] = []; afterEach(() => { cleanup(); + vi.restoreAllMocks(); for (const run of cleanups.splice(0).reverse()) run(); document.body.replaceChildren(); }); @@ -203,6 +204,16 @@ describe("TimelineWindowedItems", () => { expect(harness.visibleKeys().length).toBeGreaterThan(0); }); + it("keeps every row mounted on iOS WebKit", () => { + vi.spyOn(navigator, "userAgent", "get").mockReturnValue( + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Mobile/15E148 Safari/604.1", + ); + const harness = setup({ attached: true }); + render(harness.view(keys(300)), { container: harness.list }); + + expect(harness.mounted().length).toBe(300); + }); + it("mounts a bounded window of a long history", () => { const harness = setup({ attached: true }); render(harness.view(keys(1_000)), { container: harness.list }); diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index cb39a73f669..4e4d7628a40 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -9,6 +9,7 @@ import { type SyntheticEvent, } from "react"; import { flushSync } from "react-dom"; +import { isIOSWebKit } from "@/lib/ios-webkit"; import type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; export const DEFAULT_WINDOWING_MIN_ITEM_COUNT = 20; @@ -212,7 +213,11 @@ export function TimelineWindowedItems({ renderItem, pinnedToEnd, }: TimelineWindowedItemsProps) { + const [windowingSupported] = useState( + () => typeof navigator === "undefined" || !isIOSWebKit(navigator), + ); const windowingEnabled = + windowingSupported && positionKeeper !== null && itemKeys.length >= DEFAULT_WINDOWING_MIN_ITEM_COUNT; const containerRef = useRef(null); diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 1896e4c9011..ef7b0ae8812 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -265,8 +265,8 @@ When the viewport lands on a spacer, the owner can only record which row the list estimates is there. That estimate never moves the view: once real rows mount, the owner takes its position from them. -Lists of 20 or more items are windowed on every platform, including iOS Safari -and the mobile app's WKWebView. Rows stay in normal flow between spacers whose +Lists of 20 or more items are windowed everywhere except iOS WebKit (Safari and +the mobile app's WKWebView), where every row stays mounted. Rows stay in normal flow between spacers whose heights come from the measurements the thread retains, so rows never overlap and a row resize needs no positioning pass. The thread retains the 2,000 most recent measurements; a spacer keeps the height it last rendered for a row whose @@ -281,7 +281,7 @@ scroll roots and the same list. iOS WebKit overrides a scroll write made while a finger is down, during momentum, or during an edge bounce. On iOS the owner applies the correction as a transform on the scroll content during those phases, so rows stay in place -visually, and lists window around the rendered position. Once the touch has +visually. Once the touch has ended and the scroll position has been still for 150 ms, it writes the correction to `scrollTop` and removes the transform in the same task. Other browsers write immediately. From 8eeedfdd8c293eaa7165c8f467ff750efd556656 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Thu, 22 Oct 2026 09:15:46 -0700 Subject: [PATCH 6/7] Cover the timeline's startup, unmount and per-scroll cost guarantees The windowed list renders every row while its scroll root has no usable geometry and windows again once it does, as on main. Saving the reading position now folds in a scroll the reader made whose scroll event has not landed yet, so unmounting right after a wheel keeps the row they scrolled to, while a layout-only change during unmount still keeps the end. Tests pin: no full-history mount while the scroll root is pending, rendering everything without usable geometry, starting at the end when pinned, a nested windowed list mounting above the reader, unmounting during a transient off-bottom layout and before the scroll event lands, and a logarithmic number of row measurements per scroll event. Co-Authored-By: Claude Opus 5.5 --- .../timeline/TimelineWindowedItems.test.tsx | 128 +++++++++++++++++- .../thread/timeline/TimelineWindowedItems.tsx | 14 ++ .../ui/bottom-anchored-scroll-body.test.tsx | 38 ++++++ .../ui/scroll-position-keeper.test.ts | 20 +++ .../components/ui/scroll-position-keeper.ts | 18 +++ apps/app/src/test/fake-flow-layout.ts | 6 +- docs/timeline-pagination.md | 8 +- 7 files changed, 222 insertions(+), 10 deletions(-) diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx index defd34e9ac8..cbe4d585b7b 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx @@ -29,9 +29,13 @@ function keys(count: number, prefix = "row"): string[] { function setup({ attached, heightOf = (key: string) => 40 + ((key.length * 7) % 90), + viewportHeight = VIEWPORT_HEIGHT, + rootPending = false, }: { attached: boolean; heightOf?: (key: string) => number; + viewportHeight?: number; + rootPending?: boolean; }) { const scrollElement = document.createElement("div"); const content = document.createElement("div"); @@ -40,24 +44,26 @@ function setup({ content.append(list); scrollElement.append(content); document.body.append(scrollElement); - const layout = installFakeFlowLayout({ - scrollElement, - viewportHeight: VIEWPORT_HEIGHT, - }); + const layout = installFakeFlowLayout({ scrollElement, viewportHeight }); + let rootReady = !rootPending; const keeper = new ScrollPositionKeeper({ bottomThresholdPx: 4, deferWritesWhileScrolling: false, getContentElement: () => content, getFooterElement: () => null, - getScrollElement: () => scrollElement, + getScrollElement: () => (rootReady ? scrollElement : null), getTopLevelRows: () => list.querySelectorAll( ":scope > [data-timeline-items] > [data-timeline-row-id]", ), initiallyAttached: attached, }); - const disconnect = keeper.connect(scrollElement); - cleanups.push(layout.restore, disconnect); + let disconnect = rootPending ? () => undefined : keeper.connect(scrollElement); + cleanups.push(layout.restore, () => disconnect()); + const connectRoot = () => { + rootReady = true; + disconnect = keeper.connect(scrollElement); + }; const measurements = new Map(); const view = ( itemKeys: string[], @@ -105,6 +111,7 @@ function setup({ return top < VIEWPORT_HEIGHT && top + heightOf(key) > 0; }); return { + connectRoot, heightOf, keeper, layout, @@ -204,6 +211,113 @@ describe("TimelineWindowedItems", () => { expect(harness.visibleKeys().length).toBeGreaterThan(0); }); + it("never mounts the full history while the scroll root is still pending", () => { + const harness = setup({ attached: false, rootPending: true }); + const { rerender } = render(harness.view(keys(400)), { + container: harness.list, + }); + expect(harness.mounted().length).toBeLessThan(50); + + act(() => harness.connectRoot()); + act(() => harness.layout.userScrollTo(6_000)); + act(() => rerender(harness.view(keys(400)))); + + expect(harness.mounted().length).toBeLessThan(50); + expect(harness.visibleKeys().length).toBeGreaterThan(3); + }); + + it("renders every row while the scrollport has no usable geometry, and windows once it does", () => { + const harness = setup({ attached: false, viewportHeight: 0 }); + render(harness.view(keys(300)), { container: harness.list }); + expect(harness.mounted().length).toBe(300); + + harness.layout.setViewportHeight(VIEWPORT_HEIGHT); + act(() => harness.keeper.reconcile()); + + expect(harness.mounted().length).toBeLessThan(50); + expect(harness.visibleKeys().length).toBeGreaterThan(3); + }); + + it("starts at the end of the list when pinned to the bottom", () => { + const harness = setup({ attached: true }); + const itemKeys = keys(500); + render(harness.view(itemKeys), { container: harness.list }); + const last = itemKeys.at(-1) ?? ""; + + expect(harness.mounted()).toContain(last); + expect(harness.mounted()).not.toContain("row-0"); + expect(harness.topOf(last) + harness.heightOf(last)).toBe(VIEWPORT_HEIGHT); + }); + + it("keeps the reader in place when a nested windowed list mounts above it", () => { + const harness = setup({ attached: false }); + const outerKeys = keys(60); + const nestedKeys = keys(200, "nested"); + const nestedMeasurements = new Map(); + function Outer({ showNested }: { showNested: boolean }) { + return ( + 60} + gap={8} + itemKeys={outerKeys} + measurements={harness.measurements} + positionKeeper={harness.keeper} + pinnedToEnd={false} + renderItem={(index, state) => { + const key = outerKeys[index] ?? ""; + const nested = showNested && key === "row-5"; + return ( +
+ {nested ? ( + 30} + gap={4} + itemKeys={nestedKeys} + measurements={nestedMeasurements} + positionKeeper={harness.keeper} + pinnedToEnd={false} + renderItem={(nestedIndex, nestedState) => { + const nestedKey = nestedKeys[nestedIndex] ?? ""; + return ( +
+ ); + }} + /> + ) : ( + key + )} +
+ ); + }} + /> + ); + } + const { rerender } = render(, { + container: harness.list, + }); + act(() => harness.layout.userScrollTo(1_500)); + const reader = harness.visibleKeys()[0] ?? ""; + const before = harness.topOf(reader); + + act(() => rerender()); + act(() => harness.layout.flushResizeObservers()); + + expect(harness.topOf(reader)).toBe(before); + expect(harness.keeper.isAttached()).toBe(false); + }); + it("keeps every row mounted on iOS WebKit", () => { vi.spyOn(navigator, "userAgent", "get").mockReturnValue( "Mozilla/5.0 (iPhone; CPU iPhone OS 18_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Mobile/15E148 Safari/604.1", diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index 4e4d7628a40..c75ca4bf142 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -216,9 +216,13 @@ export function TimelineWindowedItems({ const [windowingSupported] = useState( () => typeof navigator === "undefined" || !isIOSWebKit(navigator), ); + const [scrollRootUsable, setScrollRootUsable] = useState( + null, + ); const windowingEnabled = windowingSupported && positionKeeper !== null && + scrollRootUsable !== false && itemKeys.length >= DEFAULT_WINDOWING_MIN_ITEM_COUNT; const containerRef = useRef(null); const [windowState, setWindowState] = useState(() => { @@ -286,6 +290,7 @@ export function TimelineWindowedItems({ itemKeys, mountedIndexes, renderedHeights: windowState.heights, + scrollRootUsable, windowKeys: windowState.keys, windowingEnabled, }); @@ -297,6 +302,7 @@ export function TimelineWindowedItems({ itemKeys, mountedIndexes, renderedHeights: windowState.heights, + scrollRootUsable, windowKeys: windowState.keys, windowingEnabled, }; @@ -418,6 +424,14 @@ export function TimelineWindowedItems({ const syncWindow = useCallback( (urgent: boolean) => { const live = liveRef.current; + const scrollRoot = positionKeeper?.getScrollElement() ?? null; + if (scrollRoot !== null) { + const usable = scrollRoot.clientHeight > 0; + if (usable !== live.scrollRootUsable) { + live.scrollRootUsable = usable; + setScrollRootUsable(usable); + } + } if (!live.windowingEnabled || positionKeeper === null) return; const container = containerRef.current; const scrollElement = positionKeeper.getScrollElement(); diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx index 33dc2c38009..a50e97fcdff 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx @@ -172,6 +172,44 @@ describe("BottomAnchoredScrollBody", () => { expect(handles.bottomAnchor?.isAtBottom).toBe(false); }); + it("saves the end when the timeline unmounts during a transient off-bottom layout", () => { + const keysA = rowKeys("thread-a", 60); + const first = setup("thread-a", keysA); + const last = keysA.at(-1) ?? ""; + document + .querySelector(`[data-timeline-row-id="${last}"]`) + ?.setAttribute("data-fake-height", String(heightOf(last) + 300)); + + first.view.unmount(); + + expect( + getDefaultStore().get(threadTimelineScrollAnchorAtomFamily("thread-a")), + ).toEqual({ rowId: "", offsetWithinRow: 0, atBottom: true }); + }); + + it("saves the row the reader scrolled to when the timeline unmounts before the scroll event lands", () => { + const keysA = rowKeys("thread-a", 120); + const first = setup("thread-a", keysA); + const scrollElement = document.querySelector( + "[data-page-scroll-viewport]", + ); + if (scrollElement === null) throw new Error("no scroll element"); + const target = first.layout.maxScrollTop() - 2_000; + scrollElement.dispatchEvent(new WheelEvent("wheel", { deltaY: -2_000 })); + first.layout.bounceTo(target); + const reader = first.firstVisible(); + const before = first.topOf(reader); + + first.view.unmount(); + const saved = getDefaultStore().get( + threadTimelineScrollAnchorAtomFamily("thread-a"), + ); + expect(saved?.atBottom).toBe(false); + const second = setup("thread-a", keysA); + + expect(second.topOf(reader)).toBe(before); + }); + it("detaches when the reader scrolls up and re-attaches only when they scroll back down to the end", () => { const { layout } = setup("thread-a", rowKeys("thread-a", 60)); const end = layout.maxScrollTop(); 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 ba62dd8cf20..49536a3130a 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -295,6 +295,26 @@ describe("ScrollPositionKeeper", () => { expect(timeline.layout.scrollTop).toBe(1_100); }); + it("measures a logarithmic number of rows per scroll event, however long the timeline is", () => { + const measuredPerScroll = (count: number) => { + const timeline = createTimeline(rowsOf(count, 120)); + timeline.userScrollTo(count * 60); + const reads = vi.spyOn(Element.prototype, "getBoundingClientRect"); + timeline.userScrollTo(count * 60 - 300); + const calls = reads.mock.calls.length; + reads.mockRestore(); + restoreLayout?.(); + restoreLayout = null; + document.body.replaceChildren(); + return calls; + }; + + const short = measuredPerScroll(100); + const long = measuredPerScroll(1_000); + + expect(long - short).toBeLessThanOrEqual(15); + }); + it("anchors the first top-level row that starts in the viewport, not a nested row above it", () => { const timeline = createTimeline([ ...rowsOf(2), diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index d56a7cc7bd2..f97e63386ed 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -371,6 +371,7 @@ export class ScrollPositionKeeper { atBottom: false, }; } + this.foldPendingInputScroll(); const position = this.position; if (position.kind === "bottom") { return { rowId: "", offsetWithinRow: 0, atBottom: true }; @@ -736,6 +737,23 @@ export class ScrollPositionKeeper { this.reconcile(); } + private foldPendingInputScroll(): void { + const scrollElement = this.options.getScrollElement(); + const previous = this.ownScrollTop; + if (scrollElement === null || previous === null || !this.isInputSession()) { + return; + } + const scrollTop = scrollElement.scrollTop; + 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), + ); + } + private isAtEnd(scrollTop: number): boolean { return ( this.maxScrollTop - (scrollTop + this.deferred) <= diff --git a/apps/app/src/test/fake-flow-layout.ts b/apps/app/src/test/fake-flow-layout.ts index a2cc89c8664..23848106764 100644 --- a/apps/app/src/test/fake-flow-layout.ts +++ b/apps/app/src/test/fake-flow-layout.ts @@ -32,8 +32,9 @@ export function setFakeHeight(element: Element, height: number): void { export function installFakeFlowLayout({ scrollElement: scrollElementOption, - viewportHeight, + viewportHeight: initialViewportHeight, }: FakeFlowLayoutOptions) { + let viewportHeight = initialViewportHeight; let scrollTop = 0; const boxes = new Map(); const resolveScrollElement = (): HTMLElement | null => @@ -210,6 +211,9 @@ export function installFakeFlowLayout({ } } }, + setViewportHeight(height: number) { + viewportHeight = height; + }, bounceTo(value: number) { scrollTop = value; }, diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index ef7b0ae8812..7ac822cf66f 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -266,7 +266,9 @@ list estimates is there. That estimate never moves the view: once real rows mount, the owner takes its position from them. Lists of 20 or more items are windowed everywhere except iOS WebKit (Safari and -the mobile app's WKWebView), where every row stays mounted. Rows stay in normal flow between spacers whose +the mobile app's WKWebView), where every row stays mounted. Every row also +mounts while the scroll root has no height, for example in a hidden pane, and +windowing resumes once it has one. Rows stay in normal flow between spacers whose heights come from the measurements the thread retains, so rows never overlap and a row resize needs no positioning pass. The thread retains the 2,000 most recent measurements; a spacer keeps the height it last rendered for a row whose @@ -293,7 +295,9 @@ changes, so a reader who returns to the top after a prepend always loads the next page. A thread's position is saved when the reader scrolls and when the timeline -unmounts. Returning to the thread mounts the saved row's window and restores +unmounts. Saving on unmount first takes in a scroll the reader made whose scroll +event has not arrived yet; a layout change alone keeps an attached reader at the +end. Returning to the thread mounts the saved row's window and restores the row at its saved offset, kept on screen if the viewport is now shorter. If the row has not loaded yet, the timeline waits at the bottom for up to a second. The timeline keeps the loaded pages of the From cacb7d2c53442907b790a14d50cf5159e5de9871 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Thu, 22 Oct 2026 11:58:44 -0700 Subject: [PATCH 7/7] Keep the reader attached after a send on touch devices The send button submits on pointerup and is replaced, so the tap's touchend never reaches the scroller. The keeper kept treating the touch as active and took the app's jump to the end for the reader's gesture, which armed the momentum window. The keyboard closing then clamped scrollTop and the keeper detached the reader at the end, so the reply stopped following. A touch now also ends on the last touch pointer's pointerup, caught on the window in the capture phase. Scrolling to the end ends the input session and resets the touch baseline. Co-Authored-By: Claude Opus 5.5 --- .../ui/scroll-position-keeper.test.ts | 66 +++++++++++++++++++ .../components/ui/scroll-position-keeper.ts | 43 ++++++++---- docs/timeline-pagination.md | 8 ++- 3 files changed, 105 insertions(+), 12 deletions(-) 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 49536a3130a..33ce366be18 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -404,6 +404,72 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before + 30); }); + it("ends a tap whose target left the document on pointerup, so content arriving after a send keeps the reader attached", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const send = document.createElement("button"); + timeline.content.append(send); + const pointer = (type: string) => + Object.assign(new Event(type, { bubbles: true }), { + pointerType: "touch", + pointerId: 7, + }); + send.dispatchEvent(pointer("pointerdown")); + send.dispatchEvent(new TouchEvent("touchstart", { bubbles: true })); + send.remove(); + window.dispatchEvent(pointer("pointerup")); + + timeline.setRows(rowsOf(12)); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 120); + + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + }); + + it("ends the reader's fling session when the app scrolls to the bottom, so a send right after a fling stays attached", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const timeline = createTimeline(rowsOf(10), { attached: true }); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 600); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + vi.advanceTimersByTime(1_000); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.keeper.scrollToBottom(); + timeline.setRows(rowsOf(12)); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 120); + + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + }); + + it("does not count a send button's jump to the end as the reader's gesture when the button handles pointerup itself", () => { + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(200); + expect(timeline.keeper.isAttached()).toBe(false); + const send = document.createElement("button"); + timeline.content.append(send); + const pointer = (type: string) => + Object.assign(new Event(type, { bubbles: true }), { + pointerType: "touch", + pointerId: 9, + }); + send.addEventListener("pointerup", (event) => { + event.stopPropagation(); + timeline.keeper.scrollToBottom(); + send.remove(); + }); + send.dispatchEvent(pointer("pointerdown")); + send.dispatchEvent(new TouchEvent("touchstart", { bubbles: true })); + send.dispatchEvent(pointer("pointerup")); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + + timeline.setRows(rowsOf(12)); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 120); + + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + }); + it("leaves an iOS edge bounce alone instead of holding it with a transform", () => { const timeline = createTimeline(rowsOf(10), { deferWrites: true }); timeline.userScrollTo(300); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index f97e63386ed..1cddb87f1a8 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -123,6 +123,7 @@ export class ScrollPositionKeeper { private pointerDown = false; private gestureScrolled = false; private inputUntil = Number.NEGATIVE_INFINITY; + private touchStartScrollTop = 0; private userScrolled = false; private scrollMovedAt = Number.NEGATIVE_INFINITY; private settleTimeout: number | null = null; @@ -181,18 +182,19 @@ export class ScrollPositionKeeper { scrollElement.style.overflowAnchor = "none"; this.ownScrollTop = scrollElement.scrollTop; const onScroll = () => this.handleScroll(); - let touchStartScrollTop = 0; const onTouchStart = () => { if (!this.touching) { this.gestureScrolled = false; - touchStartScrollTop = scrollElement.scrollTop; + this.touchStartScrollTop = scrollElement.scrollTop; } this.touching = true; }; - const onTouchEnd = (event: TouchEvent) => { - if (event.touches.length > 0) return; + const activeTouchPointers = new Set(); + const endTouch = () => { + if (!this.touching) return; + activeTouchPointers.clear(); this.touching = false; - if (Math.abs(scrollElement.scrollTop - touchStartScrollTop) >= 1) { + if (Math.abs(scrollElement.scrollTop - this.touchStartScrollTop) >= 1) { this.gestureScrolled = true; this.scrollMovedAt = window.performance.now(); } @@ -202,12 +204,25 @@ export class ScrollPositionKeeper { } this.scheduleDeferredWrite(); }; + const onTouchEnd = (event: TouchEvent) => { + if (event.touches.length > 0) return; + endTouch(); + }; const onPointerDown = (event: PointerEvent) => { - if (event.pointerType === "touch") return; + if (event.pointerType === "touch") { + activeTouchPointers.add(event.pointerId); + return; + } this.pointerDown = true; this.gestureScrolled = false; }; - const onPointerUp = () => { + const onPointerUp = (event: PointerEvent) => { + if (event.pointerType === "touch") { + if (event.type !== "pointerup") return; + activeTouchPointers.delete(event.pointerId); + if (activeTouchPointers.size === 0) endTouch(); + return; + } if (!this.pointerDown) return; this.pointerDown = false; if (this.gestureScrolled) this.extendInput(SESSION_EXTENSION_MS); @@ -239,8 +254,8 @@ export class ScrollPositionKeeper { scrollElement.addEventListener("pointerdown", onPointerDown, { passive: true, }); - window.addEventListener("pointerup", onPointerUp); - window.addEventListener("pointercancel", onPointerUp); + window.addEventListener("pointerup", onPointerUp, true); + window.addEventListener("pointercancel", onPointerUp, true); window.addEventListener("keydown", onKeyDown); let observer: ResizeObserver | undefined; if (typeof ResizeObserver !== "undefined") { @@ -276,8 +291,8 @@ export class ScrollPositionKeeper { PASSIVE_CAPTURE, ); scrollElement.removeEventListener("pointerdown", onPointerDown); - window.removeEventListener("pointerup", onPointerUp); - window.removeEventListener("pointercancel", onPointerUp); + window.removeEventListener("pointerup", onPointerUp, true); + window.removeEventListener("pointercancel", onPointerUp, true); window.removeEventListener("keydown", onKeyDown); this.touching = false; this.pointerDown = false; @@ -292,8 +307,14 @@ export class ScrollPositionKeeper { scrollToBottom(): void { this.pendingRestore = null; + this.inputUntil = Number.NEGATIVE_INFINITY; + this.gestureScrolled = false; this.setPosition({ kind: "bottom" }); this.reconcile(); + const scrollElement = this.options.getScrollElement(); + if (scrollElement !== null) { + this.touchStartScrollTop = scrollElement.scrollTop; + } } revealElement(element: HTMLElement, options: ScrollIntoViewOptions): void { diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 7ac822cf66f..5f312bd75de 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -230,7 +230,13 @@ anchor. The position changes only when: 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 -three seconds after the finger lifts, on every platform). Any other +three seconds after the finger lifts, on every platform). A touch ends on the +last touch pointer's `pointerup`, caught on the window in the capture phase, +or on `touchend`, whichever comes first. This means a tap on a control that +removes itself, such as the send button, still ends the touch. A drag counts +as scrolled only by the distance the reader moved. When the app scrolls to the +end, as a send does, the input session ends and the touch baseline is reset, +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