diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index d449c9d6f63cc..5f5e13972efe0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -147,6 +147,8 @@ import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer"; import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows"; import { useClientSettings } from "../../hooks/useSettings"; import { useStableFyiRuns } from "../../fork/fyi/useStableFyiRuns"; +import type { TimelineReaderLine } from "../../fork/timelineReaderLine"; +import { useTimelineReaderLine } from "../../fork/useTimelineReaderLine"; function timelineListStateFor(identity: string): { readonly identity: string; @@ -499,6 +501,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ ready: boolean; } | null>(null); const disclosureRevealFrameRef = useRef(null); + const readerLineRef = useRef(null); // Anchoring keeps the toggled row still, so content that expands below it // near the bottom would otherwise land under the composer. @@ -525,6 +528,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ composerOverlayHeight: contentInsetEndAdjustment, anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET, }); + if (delta > 0 && readerLineRef.current?.yieldToScroll(delta) === false) return; // Nested lists can finish measuring before their height reaches the outer scroller. if (pending.ready && element.scrollTop + delta <= element.scrollHeight - element.clientHeight) { disclosureRevealRef.current = null; @@ -1010,7 +1014,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ const rememberPosition = (followingEnd: boolean) => { const state = listRef.current?.getState?.(); if (restoringThreadPosition || state?.data !== rows) return; - const isAtEnd = resolveTimelineIsAtEnd(state); + const isAtEnd = readerLineRef.current?.keepsOffEnd() ? false : resolveTimelineIsAtEnd(state); const position = state.data.length ? resolveWorkGroupScrollAnchor(state) : undefined; if (position && isAtEnd !== undefined) { const index = state.indexByKey(position.rowId); @@ -1258,6 +1262,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; + const attachReaderLine = useTimelineReaderLine(readerLineRef, { + liveFollowEnabled, + findActive, + citationPositioning, + restoringThreadPosition, + listIdentityKey, + onHoldEnd: handleScroll, + }); // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1273,6 +1285,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; + const detachReaderLine = viewport ? attachReaderLine(viewport) : undefined; const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1293,6 +1306,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ contentSizeFrame = null; handleContentSizeChanged(laidOutData); revealExpandedDisclosure(); + readerLineRef.current?.refresh(); }); }; const stopListeningToContentSize = list @@ -1309,6 +1323,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ disclosureRevealFrameRef.current = null; } detachViewport?.(); + detachReaderLine?.(); viewport?.dispose(); if (viewportRef.current === viewport) viewportRef.current = null; if (minimapRefreshFrameRef.current !== null) { diff --git a/apps/web/src/fork/timelineReaderLine.browser.test.tsx b/apps/web/src/fork/timelineReaderLine.browser.test.tsx new file mode 100644 index 0000000000000..4cbbfbd8de2cd --- /dev/null +++ b/apps/web/src/fork/timelineReaderLine.browser.test.tsx @@ -0,0 +1,612 @@ +import type { LegendListRef } from "@legendapp/list/react"; +import { EnvironmentId, MessageId } from "@t3tools/contracts"; +import { createRef, useSyncExternalStore, type ComponentProps, type ReactElement } from "react"; +import { flushSync } from "react-dom"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { cdp } from "vite-plus/test/browser"; + +import "~/index.css"; + +import { render } from "../../test/render"; +import { MessagesTimeline } from "../components/chat/MessagesTimeline"; +import { forwardWheelToTimeline } from "../components/chat/timelineMinimapWheel"; +import { readTimelinePosition } from "../components/chat/timelineScrollAnchoring"; + +type TimelineProps = ComponentProps; +type Entry = TimelineProps["timelineEntries"][number]; + +const CREATED_AT = "2026-03-17T19:12:28.000Z"; +const WIDE = "900px"; +const NARROW = "520px"; +const WHEEL_PX = 300; +const GLIDE_LINES = 20; +// The product's probe points. +const PROBE = { laneFractions: [0.15, 0.3, 0.5], top: 30, bottom: 300, step: 6 }; + +function message( + id: string, + text: string, + role: "user" | "assistant" = "assistant", + streaming = false, +): Entry { + return { + id, + kind: "message", + createdAt: CREATED_AT, + message: { + id: MessageId.make(id), + role, + text, + runId: null, + createdAt: CREATED_AT, + updatedAt: CREATED_AT, + streaming, + }, + }; +} + +const tool = (id: string): Entry => ({ + id, + kind: "work", + createdAt: CREATED_AT, + entry: { id, createdAt: CREATED_AT, label: `Ran ${id}`, tone: "tool" }, +}); + +const words = (tag: string, count: number) => + Array.from({ length: count }, (_, index) => `${tag}w${index}`).join(" "); + +const history = (count: number, length: (index: number) => number) => + Array.from({ length: count }, (_, index) => + message(`m${index}`, words(`m${index}`, length(index))), + ); + +function props(listRef: TimelineProps["listRef"]): Omit { + return { + isWorking: false, + listRef, + latestRun: null, + turnDiffSummaries: [], + runs: [], + routeThreadKey: `environment-local:reader-line-${Math.random().toString(36).slice(2)}`, + onOpenTurnDiff: () => {}, + onOpenThread: () => {}, + onForkFromRun: async () => {}, + supportsConversationRollback: false, + onRevertToTurnCount: () => {}, + isRevertingCheckpoint: false, + onImageExpand: () => {}, + activeThreadEnvironmentId: EnvironmentId.make("environment-local"), + markdownCwd: undefined, + resolvedTheme: "light", + timestampFormat: "locale", + workspaceRoot: undefined, + anchorMessageId: null, + onAnchorReady: () => {}, + onAnchorSizeChanged: () => {}, + contentInsetEndAdjustment: 0, + emptyPlaceholderInset: 0, + liveFollowEnabled: false, + onIsAtEndChange: () => {}, + }; +} + +function liveText(initial: string) { + let text = initial; + const listeners = new Set<() => void>(); + return { + read: () => text, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => void listeners.delete(listener); + }, + append: (more: string) => { + text += more; + for (const listener of listeners) listener(); + }, + }; +} + +function LiveTimeline({ + live, + earlier, + ...rest +}: Omit & { + readonly live: ReturnType; + readonly earlier: ReadonlyArray; +}) { + const text = useSyncExternalStore(live.subscribe, live.read); + return ( + + ); +} + +async function renderTimeline( + width: string, + timeline: (listRef: TimelineProps["listRef"]) => ReactElement, + height = "600px", +) { + const listRef = createRef(); + const container = document.createElement("div"); + container.style.cssText = `height: ${height}; width: ${width}; display: flex; flex-direction: column;`; + const screen = await render(timeline(listRef), { container }); + return Object.assign(screen, { + list: () => listRef.current!, + scroller: () => listRef.current!.getScrollableNode() as HTMLElement, + }); +} + +// Settled once four reads 50 ms apart agree: the timeline treats a scroll under 100 ms old as +// still moving, and holds no line then. A read that scrolls must return something that differs. +async function settle(read: () => string) { + let previous: string | undefined; + let agreeing = 0; + await vi.waitFor( + () => { + const next = read(); + agreeing = next === previous ? agreeing + 1 : 0; + previous = next; + if (agreeing < 3) throw new Error(`still moving: ${next}`); + }, + { timeout: 5_000 }, + ); +} + +// Runs in the next frame's resize observations, after that frame's animation callbacks. +function inNextObservations(callback: () => void) { + const target = document.createElement("div"); + target.style.cssText = "position: fixed; width: 1px; height: 1px; pointer-events: none;"; + document.body.append(target); + const observer = new ResizeObserver(() => { + observer.disconnect(); + target.remove(); + callback(); + }); + observer.observe(target); +} + +// No product state shows the timeline sampled the last scroll; it does so before the next observations. +const nextRenderingUpdate = () => new Promise((resolve) => inNextObservations(resolve)); + +function mouse(type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) { + const frame = window.frameElement?.getBoundingClientRect(); + return cdp().send("Input.dispatchMouseEvent", { + type, + x: x + (frame?.left ?? 0), + y: y + (frame?.top ?? 0), + button: "left", + buttons: type === "mouseReleased" ? 0 : 1, + clickCount: 1, + }); +} + +const rowTop = (scroller: HTMLElement, rowId: string) => + scroller.querySelector(`[data-timeline-row-id="${rowId}"]`)!.getBoundingClientRect().top - + scroller.getBoundingClientRect().top; + +async function scrollRowTo( + screen: Awaited>, + rowId: string, + top: number, +) { + await vi.waitFor(() => expect(screen.list().getState().indexByKey(rowId)).toBeDefined()); + const scroller = screen.scroller(); + await settle(() => { + const row = scroller.querySelector(`[data-timeline-row-id="${rowId}"]`); + if (!row) { + const state = screen.list().getState(); + scroller.scrollTop = state.positionAtIndex(state.indexByKey(rowId)!) ?? 0; + throw new Error(`${rowId} is not mounted`); + } + const delta = row.getBoundingClientRect().top - scroller.getBoundingClientRect().top - top; + const moves = Math.abs(delta) > 0.5; + if (moves) scroller.scrollTop += delta; + return `${moves}|${scroller.scrollTop}|${scroller.scrollHeight}`; + }); + await nextRenderingUpdate(); +} + +// Rests the list `px` above its end, against LegendList's own scrolls to the end. +async function restFromEnd(scroller: HTMLElement, px: number) { + await settle(() => { + const away = distanceFromEnd(scroller) - px; + const moves = Math.abs(away) > 0.5; + if (moves) scroller.scrollTop += away; + return `${moves}|${scroller.scrollTop}|${scroller.scrollHeight}`; + }); + await nextRenderingUpdate(); +} + +// The first character fully in view at the product's probe points, which a paragraph gap can skip. +function readerMark(scroller: HTMLElement) { + const lane = scroller.querySelector("[data-timeline-root]")!.getBoundingClientRect(); + const view = scroller.getBoundingClientRect(); + for (let dy = PROBE.top; dy <= PROBE.bottom; dy += PROBE.step) { + const y = view.top + dy; + for (const fraction of PROBE.laneFractions) { + const caret = document.caretPositionFromPoint(lane.left + lane.width * fraction, y); + const node = caret?.offsetNode; + const row = node?.parentElement?.closest("[data-timeline-row-id]"); + if (!caret || !(node instanceof Text) || !row) continue; + const offset = [caret.offset, caret.offset - 1].find((at) => node.data[at]?.trim()); + if (offset === undefined) continue; + const range = document.createRange(); + range.setStart(node, offset); + range.setEnd(node, offset + 1); + const box = range.getBoundingClientRect(); + if (box.top > y || box.bottom < y || box.top < view.top || box.bottom > view.bottom) continue; + return { + row, + label: node.data.slice(Math.max(0, offset - 10), offset + 1), + top: () => range.getBoundingClientRect().top - scroller.getBoundingClientRect().top, + }; + } + } + throw new Error("no timeline text at the probe points"); +} + +async function expectLineHeld( + screen: Awaited>, + change: () => unknown, +) { + const scroller = screen.scroller(); + const mark = readerMark(scroller); + const before = mark.top(); + const widthBefore = mark.row.getBoundingClientRect().width; + const observed: number[] = []; + const sample = () => void observed.push(mark.top()); + // Made after the product's observer, so in each pass it reads what that observer left. + const observer = new ResizeObserver(sample); + observer.observe(mark.row); + // Read at the end of each scrolled frame: a scroll event comes before that frame's corrections + // and after any task between frames, so it can see a state that is never painted. + const sampleFrame = () => inNextObservations(sample); + scroller.addEventListener("scroll", sampleFrame, { passive: true }); + try { + await change(); + await vi.waitFor(() => expect(mark.row.getBoundingClientRect().width).not.toBe(widthBefore)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}|${mark.top()}`); + const drift = (top: number) => Math.round((top - before) * 10) / 10; + expect(drift(mark.top()), `final drift of "${mark.label}"`).toSatisfy( + (value: number) => Math.abs(value) <= 1, + ); + expect( + observed.map(drift).filter((value) => Math.abs(value) > 1), + `observed drift of "${mark.label}"`, + ).toEqual([]); + } finally { + observer.disconnect(); + scroller.removeEventListener("scroll", sampleFrame); + } +} + +const distanceFromEnd = (scroller: HTMLElement) => + scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop; + +const rows = history(30, (index) => 150 + (index % 3) * 30); + +describe("timeline reader line", () => { + it("keeps a partly visible top row's line in place when the chat narrows", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + await scrollRowTo(screen, "m16", 120); + await expectLineHeld(screen, () => { + screen.container.style.width = NARROW; + }); + }); + + it("keeps a partly visible top row's line in place when the chat widens", async () => { + await using screen = await renderTimeline(NARROW, (listRef) => ( + + )); + await scrollRowTo(screen, "m16", 120); + await expectLineHeld(screen, () => { + screen.container.style.width = WIDE; + }); + }); + + it("keeps the line inside a single tall row in place when the chat narrows", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + await scrollRowTo(screen, "tall", -2000); + await expectLineHeld(screen, () => { + screen.container.style.width = NARROW; + }); + }); + + it("keeps the line in place when the chat narrows after a selection dragged to the top edge", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + 400)} /> + )); + const scroller = screen.scroller(); + await scrollRowTo(screen, "m15", -300); + await using stack = new AsyncDisposableStack(); + stack.defer(async () => { + await mouse("mouseReleased", 0, 0); + document.getSelection()?.removeAllRanges(); + }); + const view = scroller.getBoundingClientRect(); + const lane = scroller.querySelector("[data-timeline-root]")!.getBoundingClientRect(); + const start = scroller.scrollTop; + await mouse("mousePressed", lane.left + 40, view.top + 120); + // Chromium autoscrolls while the pointer is just inside the top edge. + await mouse("mouseMoved", lane.left + 100, view.top + 5); + await vi.waitFor(() => expect(scroller.scrollTop).toBeLessThan(start - 120), { + timeout: 10_000, + }); + await mouse("mouseReleased", lane.left + 100, view.top + 5); + expect(document.getSelection()?.isCollapsed).toBe(false); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + await nextRenderingUpdate(); + await expectLineHeld(screen, () => { + screen.container.style.width = NARROW; + }); + }); + + it("lets a selection dragged to the bottom edge scroll the chat while it narrows", async () => { + // Rows this short never rewrap, so only the selection autoscroll moves the chat. + await using screen = await renderTimeline("700px", (listRef) => ( + 3)} /> + )); + const scroller = screen.scroller(); + await scrollRowTo(screen, "m30", 0); + await using stack = new AsyncDisposableStack(); + stack.defer(async () => { + await mouse("mouseReleased", 0, 0); + document.getSelection()?.removeAllRanges(); + }); + const view = scroller.getBoundingClientRect(); + const lane = scroller.querySelector("[data-timeline-root]")!; + const { left, width } = lane.getBoundingClientRect(); + await mouse("mousePressed", left + 20, view.top + 120); + await mouse("mouseMoved", left + 60, view.top + 300); + expect(document.getSelection()?.isCollapsed).toBe(false); + // A width that changes on every frame keeps any hold running through the drag. + screen.container.style.transition = "width 3s linear"; + screen.container.style.width = "500px"; + await vi.waitFor(() => expect(lane.getBoundingClientRect().width).toBeLessThan(width - 2)); + const start = scroller.scrollTop; + const moves: number[] = []; + const record = () => void moves.push(scroller.scrollTop - start); + scroller.addEventListener("scroll", record, { passive: true }); + stack.defer(() => scroller.removeEventListener("scroll", record)); + await mouse("mouseMoved", left + 60, view.bottom - 4); + // A slow runner's steps can be large enough to reach the end within a few. + const settledSteps = () => moves.length >= 10 || distanceFromEnd(scroller) <= 1; + await vi.waitFor(() => expect(settledSteps()).toBe(true), { timeout: 10_000 }); + const last = moves.slice(0, 10).at(-1); + expect(moves[0], "the first autoscroll step").toBeGreaterThan(0); + expect( + last, + `the scroll after ${Math.min(moves.length, 10)} steps, the first ${moves[0]} px`, + ).toBeGreaterThan(3 * moves[0]!); + }); + + it("lets a wheel scroll stand when the chat narrows in the same turn", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + const scroller = screen.scroller(); + await scrollRowTo(screen, "m16", 120); + const narrow = () => { + screen.container.style.width = NARROW; + }; + scroller.addEventListener("wheel", narrow, { once: true, passive: true }); + const view = scroller.getBoundingClientRect(); + const lane = scroller.querySelector("[data-timeline-root]")!.getBoundingClientRect(); + const frame = window.frameElement?.getBoundingClientRect(); + await cdp().send("Input.dispatchMouseEvent", { + type: "mouseWheel", + x: lane.left + 40 + (frame?.left ?? 0), + y: view.top + 200 + (frame?.top ?? 0), + deltaX: 0, + deltaY: WHEEL_PX, + }); + await vi.waitFor(() => expect(screen.container.style.width).toBe(NARROW)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}|${rowTop(scroller, "m16")}`); + expect( + rowTop(scroller, "m16"), + `m16's top after a ${WHEEL_PX} px wheel down from 120`, + ).toBeLessThan(120 - WHEEL_PX / 2); + }); + + it("lets a minimap wheel glide reach its target when the chat narrows during it", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + const scroller = screen.scroller(); + await scrollRowTo(screen, "m16", 120); + const glidePx = GLIDE_LINES * 16; + // The first scroll event follows the glide's first step; the width then changes after the + // next frame's step. + const narrowMidGlide = () => + inNextObservations(() => { + screen.container.style.width = NARROW; + }); + scroller.addEventListener("scroll", narrowMidGlide, { once: true, passive: true }); + forwardWheelToTimeline( + new WheelEvent("wheel", { + cancelable: true, + deltaMode: WheelEvent.DOM_DELTA_LINE, + deltaY: GLIDE_LINES, + }), + scroller, + ); + await vi.waitFor(() => expect(screen.container.style.width).toBe(NARROW)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}|${rowTop(scroller, "m16")}`); + expect( + rowTop(scroller, "m16"), + `m16's top after a ${glidePx} px glide down from 120`, + ).toBeLessThan(120 - glidePx * 0.9); + }); + + it("keeps the line in place when a press inside the chat narrows it in the same turn", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + const scroller = screen.scroller(); + await scrollRowTo(screen, "m16", 120); + const view = scroller.getBoundingClientRect(); + const lane = scroller.querySelector("[data-timeline-root]")!.getBoundingClientRect(); + const press = { x: lane.left + 40, y: view.top + 200 }; + await using stack = new AsyncDisposableStack(); + stack.defer(async () => { + await mouse("mouseReleased", press.x, press.y); + }); + // As a press on an attachment opens the side panel. + const openPanel = () => { + screen.container.style.width = NARROW; + }; + scroller.addEventListener("pointerdown", openPanel, { once: true, passive: true }); + await expectLineHeld(screen, () => mouse("mousePressed", press.x, press.y)); + }); + + it("keeps the line in place when the chat narrows after find closes with no scroll", async () => { + let base: Omit | undefined; + await using screen = await renderTimeline(WIDE, (listRef) => { + base = props(listRef); + return ; + }); + await scrollRowTo(screen, "m16", 120); + await screen.rerender(); + await nextRenderingUpdate(); + await expectLineHeld(screen, () => { + screen.container.style.width = NARROW; + }); + }); + + it("keeps the line in place when the chat narrows after a work group opened", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + const scroller = screen.scroller(); + // High enough that the opened group stays in view once the layout settles. + await scrollRowTo(screen, "work-toggle:t0", 120); + scroller.querySelector('[data-timeline-row-kind="work-toggle"] button')!.click(); + await vi.waitFor(() => + expect(scroller.querySelector('[data-timeline-row-id$=":details"]')).not.toBeNull(), + ); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + await nextRenderingUpdate(); + await expectLineHeld(screen, () => { + screen.container.style.width = NARROW; + }); + }); + + it("keeps the line in place when the chat narrows as text streams into its row", async () => { + const live = liveText(words("live", 2500)); + await using screen = await renderTimeline(WIDE, (listRef) => ( + 150)} /> + )); + await scrollRowTo(screen, "live", -1500); + await expectLineHeld(screen, () => { + flushSync(() => live.append(`\n\n${words("more", 80)}`)); + screen.container.style.width = NARROW; + }); + }); + + it("keeps the line in place and follow released when a widen rewraps only text below it into the end band", async () => { + const reports: boolean[] = []; + await using screen = await renderTimeline(WIDE, (listRef) => ( + 3), message("tail", words("tail", 160))]} + onIsAtEndChange={(atEnd) => reports.push(atEnd)} + /> + )); + const scroller = screen.scroller(); + const tailHeight = () => + scroller.querySelector('[data-timeline-row-id="tail"]')!.getBoundingClientRect().height; + await vi.waitFor(() => expect(distanceFromEnd(scroller)).toBeLessThanOrEqual(1)); + const wideTail = tailHeight(); + screen.container.style.width = NARROW; + await vi.waitFor(() => expect(tailHeight()).toBeGreaterThan(wideTail)); + const narrowTail = tailHeight(); + // The widen will leave the list 20 px from its end. + await restFromEnd(scroller, narrowTail - wideTail + 20); + expect(distanceFromEnd(scroller), "distance from the end before the widen").toBeGreaterThan(44); + const view = scroller.getBoundingClientRect(); + const line = [...scroller.querySelectorAll("[data-timeline-row-id]")].find( + (row) => row.getBoundingClientRect().top >= view.top, + )!.dataset.timelineRowId!; + const before = rowTop(scroller, line); + reports.length = 0; + screen.container.style.width = WIDE; + await vi.waitFor(() => expect(tailHeight()).toBeLessThan(narrowTail)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}|${rowTop(scroller, line)}`); + expect(rowTop(scroller, line) - before, `${line}'s move`).toSatisfy( + (value: number) => Math.abs(value) <= 1, + ); + expect(distanceFromEnd(scroller), "distance from the end after the widen").toBeLessThan(40); + expect(reports).not.toContain(true); + }); + + it("keeps follow released and the saved place off the end, through a later size change, when a widen leaves under 40 px to scroll", async () => { + const thread = `environment-local:reader-line-short-${Math.random().toString(36).slice(2)}`; + const reports: boolean[] = []; + const entries = (tail: string) => [message("s0", `${words("s0", 320)}${tail}`)]; + let base: Omit | undefined; + await using screen = await renderTimeline( + WIDE, + (listRef) => { + base = { + ...props(listRef), + routeThreadKey: thread, + onIsAtEndChange: (atEnd) => reports.push(atEnd), + }; + return ; + }, + "200px", + ); + const scroller = screen.scroller(); + const range = () => scroller.scrollHeight - scroller.clientHeight; + await settle(() => `${scroller.scrollHeight}`); + // The widen will leave 6 px to scroll, and the line added later stays inside the end band. + screen.container.style.height = `${scroller.scrollHeight - 6}px`; + screen.container.style.width = NARROW; + await vi.waitFor(() => expect(range()).toBeGreaterThan(110)); + await restFromEnd(scroller, 70); + + expect(range(), "scroll range before the widen").toBeGreaterThan(110); + const height = scroller.scrollHeight; + reports.length = 0; + screen.container.style.width = WIDE; + await vi.waitFor(() => expect(scroller.scrollHeight).toBeLessThan(height)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + expect(range(), "scroll range after the widen").toBeLessThan(40); + expect(reports).not.toContain(true); + expect(readTimelinePosition(thread)?.atEnd).toBe(false); + + const widened = scroller.scrollHeight; + await screen.rerender(); + await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(widened)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + expect(range(), "scroll range after the size change").toBeLessThan(40); + expect(reports).not.toContain(true); + expect(readTimelinePosition(thread)?.atEnd).toBe(false); + }); + + it("stays at the end when the chat narrows while following", async () => { + await using screen = await renderTimeline(WIDE, (listRef) => ( + + )); + const scroller = screen.scroller(); + await vi.waitFor(() => expect(distanceFromEnd(scroller)).toBeLessThanOrEqual(1)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + const height = scroller.scrollHeight; + screen.container.style.width = NARROW; + await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(height)); + await settle(() => `${scroller.scrollTop}|${scroller.scrollHeight}`); + expect(distanceFromEnd(scroller)).toBeLessThanOrEqual(1); + }); +}); diff --git a/apps/web/src/fork/timelineReaderLine.test.ts b/apps/web/src/fork/timelineReaderLine.test.ts new file mode 100644 index 0000000000000..a03b41a6ed3df --- /dev/null +++ b/apps/web/src/fork/timelineReaderLine.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { readerLineScrollTop } from "./timelineReaderLine"; + +// 3000 px of content in a 600 px view: the scroll range ends at 2400. +const geometry = (scrollTop: number) => ({ scrollTop, scrollHeight: 3000, clientHeight: 600 }); + +describe("readerLineScrollTop", () => { + it.each([ + { name: "moves down by the drift", scrollTop: 1000, drift: 51, target: 1051 }, + { name: "moves up by the drift", scrollTop: 1000, drift: -45, target: 955 }, + { name: "skips a move under half a pixel", scrollTop: 1000, drift: 0.4, target: null }, + { name: "keeps a half-pixel move", scrollTop: 1000, drift: -0.5, target: 999.5 }, + { name: "stops at the end", scrollTop: 2000, drift: 500, target: 2400 }, + { name: "leaves a list inside the end band in place", scrollTop: 2390, drift: 0, target: null }, + { name: "has nothing to move at the end", scrollTop: 2400, drift: 20, target: null }, + { name: "stops at the top", scrollTop: 300, drift: -500, target: 0 }, + { name: "has nothing to move at the top", scrollTop: 0, drift: -20, target: null }, + ])("$name", ({ scrollTop, drift, target }) => { + expect(readerLineScrollTop(geometry(scrollTop), drift)).toBe(target); + }); +}); diff --git a/apps/web/src/fork/timelineReaderLine.ts b/apps/web/src/fork/timelineReaderLine.ts new file mode 100644 index 0000000000000..1531bdde9bd28 --- /dev/null +++ b/apps/web/src/fork/timelineReaderLine.ts @@ -0,0 +1,526 @@ +import { resolveTimelineIsAtEnd } from "../components/chat/MessagesTimeline.logic"; +import type { TimelineViewport } from "../components/chat/timelineViewport"; +import { observeTimelineSelectionDrag } from "./timelineSelectionDrag"; + +const PROBE_TOP_PX = 30; +const PROBE_BOTTOM_PX = 300; +const PROBE_STEP_PX = 6; +const PROBE_LANE_FRACTIONS = [0.15, 0.3, 0.5] as const; +const PROBE_AGAIN_AFTER_PX = 24; +const PREFIX_LENGTH = 16; +const MIN_MOVE_PX = 0.5; +const QUIET_FRAMES = 2; +const MAX_FRAMES_AFTER_CHANGE = 30; +// An animated scroll writes one step per frame, so a scroll this recent may still be moving. +const MOVING_MS = 100; +// The timeline's own scroll can end with no scrollend, as when the browser cancels it. +const OWN_SCROLL_QUIET_MS = 250; +const ROW_SELECTOR = "[data-timeline-row-id]"; +const CONTROL_SELECTOR = + "button, input, select, textarea, [role='button'], [contenteditable=''], [contenteditable='true']"; +const MEDIA_SELECTOR = "img, video, iframe, canvas, svg"; + +/** Who moves the timeline: live follow, the reader, or the timeline positioning it (find, a restore). */ +export type TimelineScrollOwner = "follow" | "reader" | "positioning"; + +/** A character, which keeps its line when text rewraps, or the box of media with no text. */ +type Mark = + | { + readonly kind: "text"; + readonly node: Text; + readonly offset: number; + /** The marked character and the ones before it; streamed text may grow after them only. */ + readonly prefix: string; + } + | { readonly kind: "box"; readonly element: Element }; + +interface ProbeHit { + readonly mark: Mark; + readonly row: HTMLElement; +} + +/** What one probe point found: a mark in a row, or a control's bottom edge to scan past. */ +type ProbePoint = ProbeHit | { readonly skipTo: number }; + +interface ReaderLine extends ProbeHit { + readonly rowId: string | undefined; + readonly threadKey: string; + /** The mark's top, in px below the scroll node's top edge. */ + readonly y: number; + /** The row's width when `y` was read; any other width means the text rewrapped since. */ + readonly rowWidth: number; + readonly atEnd: boolean; +} + +type ReaderLineState = + | { readonly kind: "none" } + | { readonly kind: "watching"; readonly line: ReaderLine } + | { + readonly kind: "holding"; + readonly line: ReaderLine; + readonly frames: number; + readonly quiet: number; + }; + +export interface TimelineReaderLine { + /** Reads the line again on the next frame, after rows changed; a recent probe miss stands. */ + readonly refresh: () => void; + /** Takes the line afresh on the next frame, after the scroll came back to the reader. */ + readonly retake: () => void; + /** + * The timeline's own scroll by `top` px, smooth or instant, owns the scroll until it goes quiet + * or the reader navigates. False while a width change is held: the caller measured a layout + * still settling from that change, and skips its scroll. + */ + readonly yieldToScroll: (top: number) => boolean; + /** + * While true, the list counts as away from its end: during a hold, and after a hold that ended + * inside the end band until the reader navigates or follow resumes. + */ + readonly keepsOffEnd: () => boolean; + readonly dispose: () => void; +} + +/** + * Keeps the line the reader sees near the top of the timeline at the same place on screen when + * the text column changes width, while the reader owns the scroll, nothing else is scrolling it, + * and the list is not at its end. + */ +export function holdTimelineReaderLine({ + viewport, + scrollOwner, + threadKey, + onHoldEnd, +}: { + readonly viewport: Pick; + readonly scrollOwner: () => TimelineScrollOwner; + readonly threadKey: () => string; + /** Runs as a hold ends with the list in place, while `keepsOffEnd()` reports true. */ + readonly onHoldEnd: () => void; +}): TimelineReaderLine { + const { scrollNode } = viewport; + const doc = scrollNode.ownerDocument; + const range = doc.createRange(); + let state: ReaderLineState = { kind: "none" }; + let observer: ResizeObserver | null = null; + let observedRow: HTMLElement | null = null; + let refreshFrame: number | null = null; + let forceProbe = false; + let tickFrame: number | null = null; + let releaseWrite: (() => void) | null = null; + // Where the last probe found no text: the scrollTop, and the rows at the probe band's two ends. + let miss: { + readonly at: number; + readonly rows: ReadonlyArray; + readonly shape: string; + } | null = null; + // The scrollTop this module last read or wrote, and when anything else last moved it. + let knownTop = scrollNode.scrollTop; + let movedAt = Number.NEGATIVE_INFINITY; + // A quiet-spell timer, set while the timeline's own scroll owns the scroll. + let ownScrollQuiet: ReturnType | null = null; + // The thread whose last hold ended inside the end band. + let offEndThread: string | null = null; + const selectionDrag = observeTimelineSelectionDrag(scrollNode); + + // A hold would undo the timeline's own scroll, or the autoscroll of a selection being dragged. + const readerHolds = () => + scrollOwner() === "reader" && ownScrollQuiet === null && !selectionDrag.isDragging(); + const sampleScrollTop = () => { + const top = scrollNode.scrollTop; + if (Math.abs(top - knownTop) >= MIN_MOVE_PX) movedAt = performance.now(); + knownTop = top; + }; + const isMoving = () => performance.now() - movedAt < MOVING_MS; + const markRect = (mark: Mark) => { + if (mark.kind === "box") return mark.element.getBoundingClientRect(); + range.setStart(mark.node, mark.offset); + range.setEnd(mark.node, mark.offset + 1); + return range.getBoundingClientRect(); + }; + const markTop = (mark: Mark) => markRect(mark).top - scrollNode.getBoundingClientRect().top; + // A hold that ends inside the end band leaves the list counted as away from its end. + const isAtEnd = () => + offEndThread !== threadKey() && + resolveTimelineIsAtEnd({ + contentLength: scrollNode.scrollHeight, + scroll: scrollNode.scrollTop, + scrollLength: scrollNode.clientHeight, + }) === true; + const isValid = ({ mark, row, rowId, threadKey: key }: ReaderLine) => + row.isConnected && + row.dataset.timelineRowId === rowId && + key === threadKey() && + (mark.kind === "box" + ? row.contains(mark.element) + : row.contains(mark.node) && + mark.node.data.slice(mark.offset + 1 - mark.prefix.length, mark.offset + 1) === + mark.prefix); + + const releaseOwnWrite = () => { + releaseWrite?.(); + releaseWrite = null; + }; + const endHold = () => { + if (tickFrame !== null) cancelAnimationFrame(tickFrame); + tickFrame = null; + releaseOwnWrite(); + if (state.kind === "holding") state = { kind: "watching", line: state.line }; + }; + const finishHold = () => { + if (state.kind !== "holding") return; + const { line } = state; + onHoldEnd(); + endHold(); + if (isAtEnd()) offEndThread = line.threadKey; + state = { kind: "watching", line: { ...line, atEnd: false } }; + }; + const drop = () => { + endHold(); + if (observedRow) observer?.unobserve(observedRow); + observedRow = null; + state = { kind: "none" }; + }; + const watch = (line: ReaderLine) => { + if (line.row !== observedRow) { + // oxlint-disable-next-line t3code/no-raw-resize-observer -- sets no React state; it must run after LegendList's observer, which observeResize's shared one may precede + observer ??= new ResizeObserver(onRowResize); + if (observedRow) observer.unobserve(observedRow); + observedRow = line.row; + observer.observe(line.row, { box: "border-box" }); + } + state = { kind: "watching", line }; + }; + const scheduleRefresh = (force = false) => { + forceProbe ||= force; + refreshFrame ??= requestAnimationFrame(runRefresh); + }; + const stopYielding = () => { + if (ownScrollQuiet !== null) clearTimeout(ownScrollQuiet); + ownScrollQuiet = null; + }; + const endOwnScroll = () => { + if (ownScrollQuiet === null) return; + stopYielding(); + scheduleRefresh(true); + }; + const yieldUntilQuiet = () => { + stopYielding(); + ownScrollQuiet = setTimeout(endOwnScroll, OWN_SCROLL_QUIET_MS); + }; + + // Where the rows lie in the content, and their heights. + const shapeOf = (rows: ReadonlyArray) => { + const origin = scrollNode.getBoundingClientRect().top - scrollNode.scrollTop; + return rows + .map((row) => { + const rect = row?.getBoundingClientRect(); + return rect ? `${Math.round(rect.top - origin)}:${Math.round(rect.height)}` : "-"; + }) + .join(" "); + }; + const recordMiss = () => { + const view = scrollNode.getBoundingClientRect(); + const rows = [PROBE_TOP_PX, PROBE_BOTTOM_PX].map( + (dy) => + doc.elementFromPoint(view.left + view.width / 2, view.top + dy)?.closest(ROW_SELECTOR) ?? + null, + ); + return { at: scrollNode.scrollTop, rows, shape: shapeOf(rows) }; + }; + // A miss stands until the scroll moves far enough or the rows in the probe band change. + const recentMiss = () => + miss !== null && + Math.abs(scrollNode.scrollTop - miss.at) < PROBE_AGAIN_AFTER_PX && + shapeOf(miss.rows) === miss.shape; + + const probeAt = (x: number, y: number, view: DOMRect): ProbePoint | null => { + const caret = caretAt(doc, x, y); + if (caret?.node instanceof Text) { + const { node } = caret; + const element = node.parentElement; + const row = element?.closest(ROW_SELECTOR); + if (element && row && scrollNode.contains(row)) { + const control = element.closest(CONTROL_SELECTOR); + if (control) { + // The caret can snap to a control's text from a point beside it. + const rect = control.getBoundingClientRect(); + if (rect.top <= y && rect.bottom >= y) return { skipTo: rect.bottom }; + } else { + const scroller = nestedScroller(element, row); + if (scroller) return { mark: { kind: "box", element: scroller }, row }; + const offset = markOffset(node, caret.offset); + if (offset !== null) { + const prefix = node.data.slice(Math.max(0, offset - PREFIX_LENGTH), offset + 1); + const mark: Mark = { kind: "text", node, offset, prefix }; + if (spansInView(markRect(mark), y, view)) return { mark, row }; + } + } + } + } + const element = doc.elementFromPoint(x, y); + const row = element?.closest(ROW_SELECTOR); + if (!element || !row || !scrollNode.contains(row)) return null; + const control = element.closest(CONTROL_SELECTOR); + if (control) return { skipTo: control.getBoundingClientRect().bottom }; + const box = element.closest(MEDIA_SELECTOR) ?? nestedScroller(element, row); + return box && row.contains(box) ? { mark: { kind: "box", element: box }, row } : null; + }; + + // Scans 30 to 300 px below the top edge at three points across the lane for a character fully + // in view, past controls. With none, the first media box or nested scroller met stands in. + const probe = (): ProbeHit | null => { + const lane = scrollNode.querySelector("[data-timeline-root]")?.getBoundingClientRect(); + if (!lane) return null; + const view = scrollNode.getBoundingClientRect(); + const skipUntil = PROBE_LANE_FRACTIONS.map(() => Number.NEGATIVE_INFINITY); + let box: ProbeHit | null = null; + for (let dy = PROBE_TOP_PX; dy <= PROBE_BOTTOM_PX; dy += PROBE_STEP_PX) { + const y = view.top + dy; + for (const [index, fraction] of PROBE_LANE_FRACTIONS.entries()) { + if (y < skipUntil[index]!) continue; + const point = probeAt(lane.left + lane.width * fraction, y, view); + if (!point) continue; + if ("skipTo" in point) { + skipUntil[index] = point.skipTo; + } else if (point.mark.kind === "text") { + return point; + } else { + box ??= point; + skipUntil[index] = markRect(point.mark).bottom; + } + } + } + return box; + }; + + const runRefresh = () => { + if (refreshFrame !== null) cancelAnimationFrame(refreshFrame); + refreshFrame = null; + const force = forceProbe; + forceProbe = false; + if (state.kind === "holding") return; + // Sees a step that another frame callback, such as a glide, wrote since the last scroll event. + sampleScrollTop(); + if (scrollOwner() === "follow") { + offEndThread = null; + return drop(); + } + const line = state.kind === "watching" && isValid(state.line) ? state.line : null; + // The text already rewrapped and the observer has not reported it yet. + if (line && Math.abs(line.row.getBoundingClientRect().width - line.rowWidth) > MIN_MOVE_PX) + return; + if (line) { + const view = scrollNode.getBoundingClientRect(); + const rect = markRect(line.mark); + const y = rect.top - view.top; + // A text mark still under the first probe line is what a new probe would take. + const kept = + Math.abs(y - line.y) < MIN_MOVE_PX || + (line.mark.kind === "text" + ? spansInView(rect, view.top + PROBE_TOP_PX, view) + : !force && recentMiss()); + if (kept) { + state = { kind: "watching", line: { ...line, y, atEnd: isAtEnd() } }; + return; + } + } + if (!force && recentMiss()) return drop(); + const hit = probe(); + miss = hit?.mark.kind === "text" ? null : recordMiss(); + if (!hit) return drop(); + watch({ + ...hit, + rowId: hit.row.dataset.timelineRowId, + threadKey: threadKey(), + y: markTop(hit.mark), + rowWidth: hit.row.getBoundingClientRect().width, + atEnd: isAtEnd(), + }); + }; + + const correct = (line: ReaderLine) => { + const target = readerLineScrollTop( + { + scrollTop: scrollNode.scrollTop, + scrollHeight: scrollNode.scrollHeight, + clientHeight: scrollNode.clientHeight, + }, + markTop(line.mark) - line.y, + ); + if (target === null) return false; + const from = scrollNode.scrollTop; + releaseOwnWrite(); + releaseWrite = viewport.holdProgrammaticScroll(); + scrollNode.scrollTop = target; + knownTop = scrollNode.scrollTop; + // A write the browser rounds back to where it was fires no scroll event. + if (scrollNode.scrollTop === from) releaseOwnWrite(); + return Math.abs(scrollNode.scrollTop - from) >= MIN_MOVE_PX; + }; + // Requested again from each observer callback, so it queues after the frame work LegendList + // requested in that pass (its shrink measurement, its anchor-locked MVCP). + const scheduleTick = () => { + if (tickFrame !== null) cancelAnimationFrame(tickFrame); + tickFrame = requestAnimationFrame(tick); + }; + const tick = () => { + tickFrame = null; + // A write's scroll event comes before the next frame's callbacks, or never. + releaseOwnWrite(); + if (state.kind !== "holding") return; + const { line } = state; + if (!isValid(line) || !readerHolds()) { + finishHold(); + return scheduleRefresh(true); + } + const moved = correct(line); + const frames = state.frames + 1; + const quiet = moved ? 0 : state.quiet + 1; + state = { kind: "holding", line, frames, quiet }; + if (quiet >= QUIET_FRAMES || frames >= MAX_FRAMES_AFTER_CHANGE) finishHold(); + else scheduleTick(); + }; + + // Chrome runs observers in creation order; Firefox in the order of their first observe since + // they last had no targets. This one starts observing after LegendList's shared observer, which + // keeps its targets while the list is mounted, so in both it runs after LegendList's adjust. + function onRowResize(entries: ReadonlyArray) { + // LegendList's own adjust for this resize has just run; it is not reader movement. + knownTop = scrollNode.scrollTop; + const entry = entries.at(-1); + if (state.kind === "none" || entry?.target !== state.line.row) return; + const width = entry.borderBoxSize[0]?.inlineSize ?? entry.contentRect.width; + if (Math.abs(width - state.line.rowWidth) <= MIN_MOVE_PX) return; + if (scrollOwner() === "follow") { + offEndThread = null; + return drop(); + } + if (!isValid(state.line)) { + drop(); + return scheduleRefresh(true); + } + const line = { ...state.line, rowWidth: width }; + // A correction while another scroll is moving the list would undo part of that scroll. + const holds = readerHolds() && (state.kind === "holding" || (!line.atEnd && !isMoving())); + if (holds) { + state = { kind: "holding", line, frames: 0, quiet: 0 }; + correct(line); + return scheduleTick(); + } + if (state.kind === "holding") { + state = { ...state, line }; + finishHold(); + } else { + state = { kind: "watching", line }; + } + // The layout is current here, so the next width change holds from where the text is now. + forceProbe = true; + runRefresh(); + } + + const handleScroll = () => { + releaseOwnWrite(); + if (ownScrollQuiet !== null) yieldUntilQuiet(); + // Reader input during a hold comes as a navigation, which ends it. + if (state.kind === "holding") { + knownTop = scrollNode.scrollTop; + return; + } + sampleScrollTop(); + scheduleRefresh(); + }; + // Registered after the viewport's own listener, so it sees a write's hold before this releases it. + scrollNode.addEventListener("scroll", handleScroll, { passive: true }); + scrollNode.addEventListener("scrollend", endOwnScroll, { passive: true }); + const unsubscribe = viewport.subscribe((navigation) => { + // A press on content moves nothing, and may open a panel that narrows the chat this turn. + if (navigation.source === "pointer" && !navigation.onScrollbar) return; + stopYielding(); + movedAt = performance.now(); + offEndThread = null; + drop(); + scheduleRefresh(); + }); + + return { + refresh: () => scheduleRefresh(), + retake: () => scheduleRefresh(true), + yieldToScroll: (top) => { + if (state.kind === "holding") return false; + const end = scrollNode.scrollHeight - scrollNode.clientHeight; + const target = Math.max(0, Math.min(scrollNode.scrollTop + top, end)); + if (Math.abs(target - scrollNode.scrollTop) >= 1) yieldUntilQuiet(); + return true; + }, + keepsOffEnd: () => + state.kind === "holding" || (offEndThread === threadKey() && scrollOwner() !== "follow"), + dispose: () => { + endHold(); + if (refreshFrame !== null) cancelAnimationFrame(refreshFrame); + refreshFrame = null; + stopYielding(); + selectionDrag.dispose(); + observer?.disconnect(); + observedRow = null; + unsubscribe(); + scrollNode.removeEventListener("scroll", handleScroll); + scrollNode.removeEventListener("scrollend", endOwnScroll); + state = { kind: "none" }; + }, + }; +} + +/** + * The scrollTop that moves the reader's line by `drift` as far as the scroll range allows, or + * null when that moves it under half a pixel. + */ +export function readerLineScrollTop( + geometry: { + readonly scrollTop: number; + readonly scrollHeight: number; + readonly clientHeight: number; + }, + drift: number, +): number | null { + const end = geometry.scrollHeight - geometry.clientHeight; + const target = Math.max(0, Math.min(geometry.scrollTop + drift, end)); + return Math.abs(target - geometry.scrollTop) < MIN_MOVE_PX ? null : target; +} + +/** The standard caret API where it exists, else the WebKit one. */ +function caretAt(doc: Document, x: number, y: number) { + if (typeof doc.caretPositionFromPoint === "function") { + const position = doc.caretPositionFromPoint(x, y); + return position && { node: position.offsetNode, offset: position.offset }; + } + const caret = doc.caretRangeFromPoint(x, y); + return caret && { node: caret.startContainer, offset: caret.startOffset }; +} + +/** The character at the caret, or the one before it at a node end or before whitespace. */ +function markOffset(node: Text, caret: number): number | null { + for (const offset of [caret, caret - 1]) { + if (node.data[offset]?.trim()) return offset; + } + return null; +} + +/** Whether `rect` spans the line `y` and lies fully inside `view`. */ +function spansInView(rect: DOMRect, y: number, view: DOMRect) { + return rect.top <= y && rect.bottom >= y && rect.top >= view.top && rect.bottom <= view.bottom; +} + +/** A vertical scroller between `element` and its row: its inner scroll can move the text. */ +function nestedScroller(element: Element, row: Element): Element | null { + for (let current: Element | null = element; current && current !== row;) { + const { overflowY } = getComputedStyle(current); + if ( + (overflowY === "auto" || overflowY === "scroll") && + current.scrollHeight > current.clientHeight + 1 + ) + return current; + current = current.parentElement; + } + return null; +} diff --git a/apps/web/src/fork/timelineSelectionDrag.ts b/apps/web/src/fork/timelineSelectionDrag.ts index b4f7fdce8289d..4bf91ac564b44 100644 --- a/apps/web/src/fork/timelineSelectionDrag.ts +++ b/apps/web/src/fork/timelineSelectionDrag.ts @@ -3,10 +3,13 @@ const AUTOSCROLL_EDGE_DEVICE_PX = 20; /** - * Whether the browser is autoscrolling the timeline for a text selection the reader drags - * to its top edge. That scroll comes with no wheel, key or touch event. + * Watches the reader drag a text selection in the timeline. At an edge the browser autoscrolls + * it, with no wheel, key or touch event. */ export function observeTimelineSelectionDrag(scrollNode: HTMLElement): { + /** The primary button is down and a selection in the timeline is not collapsed. */ + readonly isDragging: () => boolean; + /** The drag is at the top edge, where the browser autoscrolls the timeline up. */ readonly isActive: () => boolean; readonly dispose: () => void; } { @@ -43,16 +46,17 @@ export function observeTimelineSelectionDrag(scrollNode: HTMLElement): { scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true }); // A release in another window or tab reaches this page as a blur only. window.addEventListener("blur", end); + const selectsInTimeline = () => { + const selection = scrollNode.ownerDocument.getSelection(); + return ( + selection !== null && !selection.isCollapsed && scrollNode.contains(selection.anchorNode) + ); + }; return { + isDragging: () => press !== null && selectsInTimeline(), // The browser's clamp after content shrinks moves scrollTop during a press too, but the // pointer is not dragging at the top edge then. - isActive: () => { - if (!press?.atEdge) return false; - const selection = scrollNode.ownerDocument.getSelection(); - return ( - selection !== null && !selection.isCollapsed && scrollNode.contains(selection.anchorNode) - ); - }, + isActive: () => press?.atEdge === true && selectsInTimeline(), dispose: () => { end(); scrollNode.removeEventListener("pointerdown", handlePointerDown); diff --git a/apps/web/src/fork/useTimelineReaderLine.ts b/apps/web/src/fork/useTimelineReaderLine.ts new file mode 100644 index 0000000000000..cf995adf6728e --- /dev/null +++ b/apps/web/src/fork/useTimelineReaderLine.ts @@ -0,0 +1,51 @@ +import { useLayoutEffect, type RefObject } from "react"; + +import type { TimelineViewport } from "../components/chat/timelineViewport"; +import { useStableCallback } from "~/hooks/useStableCallback"; +import { holdTimelineReaderLine, type TimelineReaderLine } from "./timelineReaderLine"; + +/** Attaches the reader-line hold, with who owns the scroll read from the timeline's own state. */ +export function useTimelineReaderLine( + readerLineRef: RefObject, + { + liveFollowEnabled, + findActive, + citationPositioning, + restoringThreadPosition, + listIdentityKey, + onHoldEnd, + }: { + readonly liveFollowEnabled: boolean; + readonly findActive: boolean; + readonly citationPositioning: boolean; + readonly restoringThreadPosition: boolean; + readonly listIdentityKey: string; + readonly onHoldEnd: () => void; + }, +) { + const readerOwnsScroll = + !liveFollowEnabled && !findActive && !citationPositioning && !restoringThreadPosition; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- find, a citation or a restore can hand the scroll back with no scroll event + useLayoutEffect(() => { + if (readerOwnsScroll) readerLineRef.current?.retake(); + }, [readerOwnsScroll, readerLineRef]); + const scrollOwner = useStableCallback(() => + liveFollowEnabled ? "follow" : readerOwnsScroll ? "reader" : "positioning", + ); + const threadKey = useStableCallback(() => listIdentityKey); + const handleHoldEnd = useStableCallback(onHoldEnd); + const attachReaderLine = useStableCallback((viewport: TimelineViewport) => { + const readerLine = holdTimelineReaderLine({ + viewport, + scrollOwner, + threadKey, + onHoldEnd: handleHoldEnd, + }); + readerLineRef.current = readerLine; + return () => { + readerLine.dispose(); + if (readerLineRef.current === readerLine) readerLineRef.current = null; + }; + }); + return attachReaderLine; +}