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/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(); - -function rect(top: number, height: number): DOMRect { - return { - bottom: top + height, - height, - left: 0, - right: 320, - top, - width: 320, - x: 0, - y: top, - toJSON: () => ({}), - }; -} +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"; -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; -}) { - 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={null} - pinnedToEnd={options?.pinnedToEnd ?? false} - renderItem={( - index: number, - state: TimelineWindowedItemRenderState, - ) => ( -
- -
- )} - /> -
, - { container: scrollElement }, - ), - measurements, - }; -} - -beforeEach(() => { - itemHeights = new Map(); - 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, - Number.parseFloat(this.style.height) || 0, - ); - } - const index = Number(this.dataset.index); - if (Number.isInteger(index)) { - return rect( - index * 32 - scrollElement.scrollTop, - 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 }, - ); +function keys(count: number, prefix = "row"): string[] { + return Array.from({ length: count }, (_, index) => `${prefix}-${index}`); +} - expect(measurements.get("row-0")).toBe(32); - expect(measurements.get("row-99")).toBe(32); +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"); + 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 }); + let rootReady = !rootPending; + const keeper = new ScrollPositionKeeper({ + bottomThresholdPx: 4, + deferWritesWhileScrolling: false, + getContentElement: () => content, + getFooterElement: () => null, + getScrollElement: () => (rootReady ? scrollElement : null), + getTopLevelRows: () => + list.querySelectorAll( + ":scope > [data-timeline-items] > [data-timeline-row-id]", + ), + initiallyAttached: attached, }); - - 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) => ( + 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[], + { + 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); + 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]") - ?.style.height, - ).toBe("640px"); - - view.rerender(list(19)); - inputs.forEach((input, index) => { - expect(screen.getByTestId(`input-${index}`)).toBe(input); + return { + connectRoot, + heightOf, + keeper, + layout, + list, + measurements, + mounted, + topOf, + view, + visibleKeys, + }; +} + +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, }); - expect(screen.getByDisplayValue("unsaved edit")).toBe(inputs[0]); - expect( - scrollElement.querySelector("[data-timeline-virtual-spacer]"), - ).toBeNull(); - }); + 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")); - - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - - await waitFor(() => expect(screen.getByTestId("content-50")).toBeTruthy()); - expect(screen.getByTestId("content-0")).toBeTruthy(); - expect(screen.getByTestId("content-80")).toBeTruthy(); + 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(); + + 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)); + + 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 () => {}); + 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), + }); + 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) ?? ""}"]`, + ); + mountedRow?.setAttribute("data-fake-height", "81"); + act(() => harness.layout.flushResizeObservers()); - scrollElement.scrollTop = 1_600; - fireEvent.scroll(scrollElement); - await act(async () => {}); + act(() => + harness.layout.userScrollTo( + harness.layout.scrollTop + harness.topOf(firstMounted) - 900, + ), + ); - const content = screen.getByTestId("content-50"); - expect(content).toBeTruthy(); + expect(harness.visibleKeys().length).toBeGreaterThan(0); + }); - await act(async () => { - vi.advanceTimersByTime(300); + 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(screen.getByTestId("content-50")).toBe(content); - }); + expect(harness.mounted().length).toBeLessThan(50); - 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"), - ); + 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("starts its range at the end of the list when pinned to the bottom", async () => { - renderWindowedItems({ pinnedToEnd: true }); + 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()); - await waitFor(() => expect(screen.getByTestId("content-98")).toBeTruthy()); - expect(screen.queryByTestId("wrapper-0")).toBeNull(); + expect(harness.mounted().length).toBeLessThan(50); + expect(harness.visibleKeys().length).toBeGreaterThan(3); }); - 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); - }); + 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( - scrollElement.querySelector("[data-timeline-virtual-spacer]") - ?.style.height, - ).toBe("3500px"); - expect(scrollElement.scrollTop).toBe(3_404); + 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 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()); - - 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, + 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 + )} +
+ ); + }} + /> ); } - }); - - 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); + const { rerender } = render(, { + container: harness.list, }); - scrollElement.scrollTop = 1_552; - fireEvent.scroll(scrollElement); - await waitFor(() => expect(screen.getByTestId("content-48")).toBeTruthy()); + act(() => harness.layout.userScrollTo(1_500)); + const reader = harness.visibleKeys()[0] ?? ""; + const before = harness.topOf(reader); - itemHeights.set(48, 340); - act(() => { - reportItemResize(screen.getByTestId("wrapper-48"), 340); - }); + act(() => rerender()); + act(() => harness.layout.flushResizeObservers()); - expect(readSpacerHeight()).toBe(3_508); - expect(scrollElement.scrollTop).toBe(1_552); + expect(harness.topOf(reader)).toBe(before); + expect(harness.keeper.isAttached()).toBe(false); }); - it("settles the enclosing auto-height wrapper before compensating for a taller row", async () => { - let wrapperHeight = 0; - clampScrollTopToContentHeight(() => wrapperHeight); - renderWindowedItems({ - snapAutoHeight: () => { - wrapperHeight = readSpacerHeight(); - }, - }); - 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()); - - itemHeights.set(95, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-95"), 332); - }); + 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(wrapperHeight).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_404); + expect(harness.mounted().length).toBe(300); }); - 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; + it("mounts a bounded window of a long history", () => { + const harness = setup({ attached: true }); + render(harness.view(keys(1_000)), { container: harness.list }); - itemHeights.set(98, 332); - act(() => { - reportItemResize(screen.getByTestId("wrapper-98"), 332); - }); - - expect(readSpacerHeight()).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_404); + expect(harness.mounted().length).toBeLessThan(40); + expect(harness.layout.scrollTop).toBe(harness.layout.maxScrollTop()); }); - 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); + 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, }); + const interacted = harness.visibleKeys()[0] ?? ""; + fireEvent.click(screen.getByRole("button", { name: interacted })); + + act(() => harness.layout.userScrollTo(4_000)); + act(() => harness.layout.userScrollTo(2_000)); - expect(readSpacerHeight()).toBe(3_500); - expect(scrollElement.scrollTop).toBe(3_104); + expect(harness.mounted()).toContain("row-3"); + expect(harness.mounted()).toContain(interacted); }); - it("renders everything when its scrollport has no usable geometry", async () => { - renderWindowedItems({ clientHeight: 0 }); + 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, + }); + 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 147caf7b95b..c75ca4bf142 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -1,29 +1,24 @@ 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 type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; +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; 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, @@ -53,17 +48,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; @@ -74,18 +72,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( @@ -95,7 +195,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; } @@ -106,313 +206,387 @@ export function TimelineWindowedItems({ alwaysMountedKeys = EMPTY_KEY_SET, estimateItemHeight, gap, - getScrollElement, + initialWindowAnchor = null, itemKeys, measurements, positionKeeper, renderItem, pinnedToEnd, }: TimelineWindowedItemsProps) { - const [scrollAdjustmentsKeepMomentum] = useState( + const [windowingSupported] = useState( () => typeof navigator === "undefined" || !isIOSWebKit(navigator), ); - const configured = - scrollAdjustmentsKeepMomentum && - 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 [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(() => { + 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, + scrollRootUsable, + windowKeys: windowState.keys, + windowingEnabled, + }); + useLayoutEffect(() => { + liveRef.current = { + estimateItemHeight, + gap, + indexByKey, + itemKeys, + mountedIndexes, + renderedHeights: windowState.heights, + scrollRootUsable, + 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; - 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, - 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, callback); - const unsubscribe = positionKeeper?.subscribeScrollWrites(() => { - const scrollElement = instance.scrollElement; - if (scrollElement !== null) { - callback(scrollElement.scrollTop, instance.isScrolling); + + 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); } - }); - return () => { - unobserve?.(); - unsubscribe?.(); - }; + } + 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; + } + } + 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]); - - 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; - setScrollMargin((previous) => - Math.abs(previous - nextMargin) < 0.5 ? previous : nextMargin, - ); - }, [configured, resolvedGetScrollElement]); + }, [positionKeeper, renderedModel, syncWindow]); - 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]); + 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(updateScrollGeometry); + useLayoutEffect(() => { + 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 ( { - 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]); diff --git a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx index 77551c79fd7..5b71065af23 100644 --- a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx +++ b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx @@ -6,58 +6,38 @@ import type { ReactNode } from "react"; import { BottomAnchorContext } from "@/components/ui/bottom-anchored-scroll-body.js"; import type { BottomAnchorContextValue } from "@/components/ui/bottom-anchored-scroll-body.js"; import { useAutoLoadOlderRows } from "./useAutoLoadOlderRows.js"; -import { createInertScrollPositionKeeper } from "@/test/scroll-position-keeper"; - -interface ObserverHandle { - emit: (isIntersecting: boolean) => 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 7dc03d83f8f..bfb94d0a2f6 100644 --- a/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts +++ b/apps/app/src/components/thread/timeline/useStickyBottomScroll.ts @@ -1,38 +1,21 @@ -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, } from "@/components/ui/scroll-position-keeper"; +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 { @@ -40,144 +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), + 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); - if (typeof ResizeObserver === "undefined") return; - - const observer = new ResizeObserver(() => { - positionKeeper.reconcile(); - refreshMaxScrollOffset(element); - positionKeeper.capture(); - }); - observer.observe(element); - const content = contentRef.current; - if (content) { - observer.observe(content); - } - return () => 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("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(); + + 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 91a40fd9ff0..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,13 +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 { - threadTimelineScrollAnchorAtomFamily, - type ScrollAnchor, -} from "@/lib/thread-timeline-scroll-anchor.js"; -import { layoutAnimationInFlightCountAtom } from "./layoutAnimationAtoms.js"; +import { isIOSWebKit } from "@/lib/ios-webkit"; +import { threadTimelineScrollAnchorAtomFamily } from "@/lib/thread-timeline-scroll-anchor.js"; import { ScrollPositionKeeper, getDirectTimelineRows, @@ -39,6 +35,11 @@ export interface BottomAnchorContextValue { positionKeeper: ScrollPositionKeeper; } +export interface TimelineScrollRestore { + key: string; + offset: number; +} + interface BottomAnchoredScrollBodyProps { children: ReactNode; footer: ReactNode; @@ -64,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, - }; + return topLevelList + ? getDirectTimelineRows(topLevelList) + : scrollArea.querySelectorAll(TIMELINE_ROW_ID_SELECTOR); } -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 - ); -} - -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({ @@ -235,185 +112,56 @@ 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); - 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; - } | 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; - scrollContentHeight: number | null; - }>({ scrollAreaClientHeight: null, scrollContentHeight: null }); - const scrollAnchorRowsRef = useRef | null>(null); - const [isAtBottom, setIsAtBottom] = useState(true); - 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), + getContentElement: () => pageContentRef.current, + getFooterElement: () => scrollFooterRef.current, getScrollElement: () => scrollAreaRef.current, - getTopLevelRows: getScrollAnchorRowsCached, - isActive: () => - !shouldStickToBottomRef.current && - pendingScrollRestoreRef.current === null, + getTopLevelRows, + initiallyAttached: true, }), ); - 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( @@ -423,132 +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) return; - let atBottomByGeometry = isScrolledNearBottom( - readMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - if (!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, - ], - ); + }, [positionKeeper, scrollAnchorThreadId, store]); const scrollAnchorCaptureThrottleMs = isPointerCoarse ? COARSE_SCROLL_ANCHOR_CAPTURE_THROTTLE_MS @@ -572,346 +222,44 @@ export function BottomAnchoredScrollBody({ }, scrollAnchorCaptureThrottleMs - elapsed); }, [scrollAnchorCaptureThrottleMs, scrollAnchorThreadId, writeScrollAnchor]); - const applyScrollRestore = useCallback( - (anchor: ScrollAnchor): 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 + 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 (scrollToTopInProgressRef.current) { - if (scrollArea.scrollTop <= 0) scrollToTopInProgressRef.current = false; - return; - } - - let nearBottom = isScrolledNearBottom( - readMaxScrollOffset(scrollArea), - scrollArea.scrollTop, - ); - if ( - !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, - ]); - - 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); - if (appliedScrollTop !== null) { - if (pending.lastAppliedScrollTop === appliedScrollTop) { - pendingScrollRestoreRef.current = null; - return true; - } - pending.lastAppliedScrollTop = appliedScrollTop; - } - if (pending.attemptsRemaining <= 0) { - pendingScrollRestoreRef.current = null; - if (appliedScrollTop === null) { - shouldStickToBottomRef.current = true; - setIsAtBottom(true); - queueBottomRestore(); - } - } - return true; - }, [applyScrollRestore, queueBottomRestore]); - - 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; - for (const entry of entries) { - if (entry.target === scrollArea) { - observedGeometry.scrollAreaClientHeight = - entry.contentBoxSize[0]?.blockSize ?? entry.contentRect.height; - } else if (entry.target === scrollContentRef.current) { - observedGeometry.scrollContentHeight = - entry.borderBoxSize[0]?.blockSize ?? entry.contentRect.height; - } - } - 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 && - !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, - settleContentPositionHold, - 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, - }; - advancePendingScrollRestore(); - }, [scrollAnchorThreadId, store, 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; @@ -950,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 = () => { @@ -965,71 +312,44 @@ export function BottomAnchoredScrollBody({ scrollbarIdleTimeout = null; scrollArea.removeAttribute("data-scrollbar-scrolling"); }, SCROLLBAR_IDLE_DELAY_MS); - handleScroll(); + captureScrollAnchorThrottled(); }; - - 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 () => { - 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, - queueBottomRestore, - startPointerScrollIntent, - ]); + }, [captureScrollAnchorThrottled]); + + const bottomAnchorContextValue = useMemo( + () => ({ + getScrollElement, + isAtBottom, + scrollToBottom, + scrollElementIntoView, + scrollElementIntoViewClampedToMaxScroll, + holdContentPosition, + positionKeeper, + }), + [ + getScrollElement, + isAtBottom, + scrollToBottom, + scrollElementIntoView, + scrollElementIntoViewClampedToMaxScroll, + holdContentPosition, + positionKeeper, + ], + ); return ( - +
- {}
{children}
-
{footer ? (
{footer}
@@ -1079,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 00999973ec7..33ce366be18 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -1,265 +1,552 @@ // @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 createTimeline(initialRows: LaidOutRow[]) { +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: 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(); - - Object.defineProperty(scrollElement, "scrollTop", { - configurable: true, - get: () => scrollTop, - set: (value: number) => { - scrollTop = Math.max(0, value); - }, - }); - Object.defineProperty(scrollElement, "clientHeight", { - configurable: true, - value: VIEWPORT_HEIGHT, + 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, 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({ + 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; - }, - scrollTo(value: number) { - scrollTop = value; + setRows, + topOf, + resize(id: string, height: number) { + const element = elements.get(id); + if (element === undefined) throw new Error(`No row ${id}`); + setFakeHeight(element, height); }, - setRows(next: LaidOutRow[]) { - rows = next; - layout(); - }, - viewportTopOf(id: string) { - const offset = offsets.get(id); - if (offset === undefined) throw new Error(`No row ${id}`); - return offset.top - scrollTop; + 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(() => { - 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")); - timeline.scrollTo(400); - timeline.keeper.handleScroll(); - timeline.scrollTo(150); - timeline.keeper.handleScroll(); - const before = timeline.viewportTopOf("row-1"); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(false); + }); + + 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("composes with scrolling that happens between layout changes", () => { - const timeline = createTimeline(rowsOf(10)); - timeline.scrollTo(900); - timeline.keeper.handleScroll(); + 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.scrollTo(700); + timeline.resize("row-8", 450); timeline.keeper.reconcile(); - expect(timeline.scrollTop).toBe(700); + expect(lastBottom()).toBe(bottomBefore); + expect(timeline.topOf("row-8")).toBe(toggledBefore - 250); }); - it("corrects a foreign write that ignored a layout change above the reader", () => { + 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.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.topOf("row-4")).toBe(before); + }); + + 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); + + 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); - timeline.setRows([{ id: "older", height: 120 }, ...rowsOf(10)]); + 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("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(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveReturnedWith(1_020); + expect(long - short).toBeLessThanOrEqual(15); }); - 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.resize("row-2", 500); + timeline.keeper.reconcile(); + + expect(timeline.topOf("row-2")).toBe(before); + }); + + 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); + + 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); + }); - timeline.keeperOptions.active = false; - timeline.keeper.capture(); - timeline.setRows([{ id: "older", height: 400 }, ...rowsOf(10)]); + 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.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.scrollElement.style.overflowAnchor).toBe(""); + expect(timeline.layout.scrollTop).toBe(400); + expect(timeline.topOf("row-3")).toBe(after); }); - it("holds an element edge instead of the top row while a hold lasts", () => { + 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.scrollTo(900); - timeline.keeper.handleScroll(); - const element = timeline.scrollElement.querySelector( - '[data-timeline-row-id="row-6"]', + 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.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); + const before = timeline.topOf("row-1"); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.bounceTo(-40); + timeline.keeper.reconcile(); + + expect(timeline.content.style.transform).toBe(""); + expect(timeline.topOf("row-1")).toBe(before + 340); + }); + + 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, + }); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + + timeline.setRows(rows); + timeline.keeper.reconcile(); + + 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, ); - if (element === null) throw new Error("Expected row-6"); - timeline.keeper.hold(element, "bottom", 250); - const bottomBefore = timeline.viewportTopOf("row-6") + 200; + 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); + }); - timeline.setRows([ - ...rowsOf(6), - { id: "row-6", height: 50 }, - ...rowsOf(10).slice(7), - ]); + 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.viewportTopOf("row-6") + 50).toBe(bottomBefore); + 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 36169030687..1cddb87f1a8 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -1,26 +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; + 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"; @@ -29,191 +55,593 @@ 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 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 { +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 writeListeners = new Set<() => void>(); - private overflowAnchorDisabled = false; + 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 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; + 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; + } + + isAttached(): boolean { + return this.position.kind === "bottom"; } - isActive(): boolean { - return this.options.isActive(); + getPosition(): ReadingPosition { + return this.position; } - registerRowOffsetSource(source: ScrollRowOffsetSource): () => void { - this.rowOffsetSources.add(source); + getViewportHeight(): number { + return this.viewportHeight; + } + + getScrollElement(): HTMLElement | null { + return this.options.getScrollElement(); + } + + subscribe(listener: () => void): () => void { + this.listeners.add(listener); return () => { - this.rowOffsetSources.delete(source); + this.listeners.delete(listener); }; } - subscribeScrollWrites(listener: () => void): () => void { - this.writeListeners.add(listener); + subscribePosition(listener: () => void): () => void { + this.positionListeners.add(listener); return () => { - this.writeListeners.delete(listener); + this.positionListeners.delete(listener); }; } - handleScroll(): void { + 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(); + const onTouchStart = () => { + if (!this.touching) { + this.gestureScrolled = false; + this.touchStartScrollTop = scrollElement.scrollTop; + } + this.touching = true; + }; + const activeTouchPointers = new Set(); + const endTouch = () => { + if (!this.touching) return; + activeTouchPointers.clear(); + this.touching = false; + if (Math.abs(scrollElement.scrollTop - this.touchStartScrollTop) >= 1) { + this.gestureScrolled = true; + this.scrollMovedAt = window.performance.now(); + } + if (this.gestureScrolled) { + this.extendInput(MOMENTUM_SESSION_MS); + this.handleScroll(); + } + this.scheduleDeferredWrite(); + }; + const onTouchEnd = (event: TouchEvent) => { + if (event.touches.length > 0) return; + endTouch(); + }; + const onPointerDown = (event: PointerEvent) => { + if (event.pointerType === "touch") { + activeTouchPointers.add(event.pointerId); + return; + } + this.pointerDown = true; + this.gestureScrolled = false; + }; + 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); + }; + 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, true); + window.addEventListener("pointercancel", onPointerUp, true); + 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(); - this.capture(); + return () => { + observer?.disconnect(); + scrollElement.removeEventListener("scroll", onScroll); + scrollElement.removeEventListener("wheel", onWheel); + scrollElement.removeEventListener( + "touchstart", + onTouchStart, + PASSIVE_CAPTURE, + ); + scrollElement.removeEventListener( + "touchend", + onTouchEnd, + PASSIVE_CAPTURE, + ); + scrollElement.removeEventListener( + "touchcancel", + onTouchEnd, + PASSIVE_CAPTURE, + ); + scrollElement.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerup", onPointerUp, true); + window.removeEventListener("pointercancel", onPointerUp, true); + window.removeEventListener("keydown", onKeyDown); + this.touching = false; + 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); + }; } - hold(element: HTMLElement, edge: ScrollHoldEdge, durationMs: number): void { + 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.options.isActive()) return; - this.holdUntil = window.performance.now() + durationMs; - this.anchor = { - kind: "element", - element, - edge, - offset: this.elementEdgeOffset(scrollElement, element, edge), - }; - this.setOverflowAnchorDisabled(scrollElement, true); + if (scrollElement !== null) { + this.touchStartScrollTop = scrollElement.scrollTop; + } } - releaseHold(): void { - if (this.holdUntil === 0) return; - this.holdUntil = 0; - this.capture(); + 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(); } - capture(): void { + scrollTo(top: number, behavior: ScrollBehavior): void { const scrollElement = this.options.getScrollElement(); if (scrollElement === null) return; - if (!this.options.isActive()) { - this.anchor = null; - this.holdUntil = 0; - this.setOverflowAnchorDisabled(scrollElement, false); + 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; } - 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, - ); + this.write(scrollElement, top); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.notifyLists(); + } + + hold(element: HTMLElement, edge: ScrollHoldEdge): void { + const scrollElement = this.options.getScrollElement(); + 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.edgeTop(scrollElement, element, edge), + neighbors: [], + }; + } + + restore(saved: SavedReadingPosition): void { + if (saved.atBottom) { + this.scrollToBottom(); return; } - this.holdUntil = 0; - if (anchor?.kind !== "row" || !this.isStillFirstRow(scrollElement, anchor)) { - this.anchor = this.findRowAnchor(scrollElement); + 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.setOverflowAnchorDisabled(scrollElement, this.anchor !== null); + this.foldPendingInputScroll(); + const position = this.position; + if (position.kind === "bottom") { + return { rowId: "", offsetWithinRow: 0, atBottom: true }; + } + 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; } - 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; + } + } + 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 { + 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); } - const delta = current - anchor.offset; - if (Math.abs(delta) < MIN_CORRECTION_PX) return; - anchor.offset = current; - scrollElement.scrollTop += delta; - for (const listener of this.writeListeners) listener(); + if (this.deferred !== 0) this.scheduleDeferredWrite(); + this.notifyLists(); } - private locate( + reconcile(urgent = true): void { + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null) return; + this.apply(scrollElement, true, urgent); + } + + private apply( scrollElement: HTMLElement, - anchor: KeptAnchor, - ): number | null { - if (anchor.kind === "element") { - return anchor.element.isConnected - ? this.elementEdgeOffset(scrollElement, anchor.element, anchor.edge) - : null; - } + notify: boolean, + urgent = true, + ): void { + const scrollTop = scrollElement.scrollTop; + const max = this.refreshExtent(scrollElement); + const width = scrollElement.clientWidth; if ( - !anchor.element.isConnected || - anchor.element.getAttribute(ROW_ID_ATTRIBUTE) !== anchor.rowId || - !scrollElement.contains(anchor.element) + this.reconciledWidth > 0 && + Math.abs(this.reconciledWidth - width) >= 1 ) { - const element = this.findMountedRow(scrollElement, anchor.rowId); - if (element !== null) anchor.element = element; + this.keepAnchorVisible(scrollElement); } - if (anchor.element.isConnected) { - return this.elementEdgeOffset(scrollElement, anchor.element, "top"); + 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(); } - for (const source of this.rowOffsetSources) { - const offset = source(anchor.rowId); - if (offset !== null) return offset; + 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(); + } else { + this.setDeferred(0); + this.write(scrollElement, clamped); + } + if (Math.abs(clamped - target) >= 1 && this.position.kind === "anchor") { + this.scheduleClampSettle(); + } } - return null; + if (notify) this.notifyLists(urgent); } - private isStillFirstRow( + private isInView( scrollElement: HTMLElement, - anchor: Extract, + position: Extract, ): boolean { - const element = anchor.element; - if (!anchor.topLevel || !element.isConnected) return false; - if (!scrollElement.contains(element)) return false; - 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 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 findMountedRow( + 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; + } + } + + private targetScrollTop( scrollElement: HTMLElement, - rowId: string, - ): HTMLElement | null { - for (const row of scrollElement.querySelectorAll( - ROW_SELECTOR, - )) { - if (row.getAttribute(ROW_ID_ATTRIBUTE) === rowId) return row; + 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; } - 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, + position: Extract, + ): number | null { + let element = position.element; + if ( + element === null || + !element.isConnected || + element.getAttribute(ROW_ID_ATTRIBUTE) !== position.key + ) { + element = findMountedRow(scrollElement, position.key); + if (element !== null) position.element = element; + } + 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 this.edgeTop(scrollElement, element, position.edge); } - private findRowAnchor(scrollElement: HTMLElement): KeptAnchor | null { - const scrollRect = scrollElement.getBoundingClientRect(); - const viewportTop = scrollRect.top; - const viewportBottom = scrollRect.bottom; + private capture(scrollElement: HTMLElement): ReadingPosition | null { + const viewport = scrollElement.getBoundingClientRect(); + const viewportTop = viewport.top; + const footerTop = this.options + .getFooterElement() + ?.getBoundingClientRect().top; + const viewportBottom = Math.min( + viewportTop + (this.viewportHeight || scrollElement.clientHeight), + footerTop ?? Number.POSITIVE_INFINITY, + ); const rows = this.options.getTopLevelRows(scrollElement); let low = 0; let high = rows.length - 1; @@ -222,29 +650,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 @@ -252,31 +690,213 @@ 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 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) <= + 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, @@ -284,17 +904,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..23848106764 --- /dev/null +++ b/apps/app/src/test/fake-flow-layout.ts @@ -0,0 +1,240 @@ +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: initialViewportHeight, +}: FakeFlowLayoutOptions) { + let viewportHeight = initialViewportHeight; + 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); + } + } + }, + setViewportHeight(height: number) { + viewportHeight = height; + }, + 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 8aebf259b3c..d5f0acb0ea1 100644 --- a/apps/app/src/test/scroll-position-keeper.ts +++ b/apps/app/src/test/scroll-position-keeper.ts @@ -2,8 +2,12 @@ import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper"; export function createInertScrollPositionKeeper(): ScrollPositionKeeper { return new ScrollPositionKeeper({ + bottomThresholdPx: 4, + deferWritesWhileScrolling: false, + getContentElement: () => null, + getFooterElement: () => null, getScrollElement: () => null, getTopLevelRows: () => [], - isActive: () => false, + initiallyAttached: true, }); } diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 3441a8a3996..5f312bd75de 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -201,3 +201,114 @@ 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 + +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). 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 +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 everywhere except iOS WebKit (Safari and +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 +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. On iOS the owner applies the correction as a +transform on the scroll content during those phases, so rows stay in place +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. + +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. 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 +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. 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': {}