diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..57011676280c2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -693,6 +693,35 @@ describe("MessagesTimeline messages", () => { }); }); + it("lets the browser scroll the timeline for a wheel over the minimap", async () => { + setup(); + const props = baseProps(); + const entries = Array.from({ length: 16 }, (_, index) => [ + message(`Question ${index}`, {}, `user-${index}`), + message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`), + ]).flat(); + await using screen = await renderTimeline(entries, props); + const viewport = props.listRef.current!.getScrollableNode()!; + await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0)); + const start = viewport.scrollTop; + const reached: WheelEvent[] = []; + const record = (event: WheelEvent) => reached.push(event); + viewport.addEventListener("wheel", record); + using _listener = { [Symbol.dispose]: () => viewport.removeEventListener("wheel", record) }; + + await userEvent.wheel(screen.button(/^Jump to message/), { delta: { y: -100 } }); + + await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(start)); + expect( + reached.map((event) => [ + event.isTrusted, + event.target instanceof Element && + event.target.closest('[data-testid="timeline-minimap"]') !== null, + event.defaultPrevented, + ]), + ).toEqual([[true, true, false]]); + }); + it("enables the minimap's next turn button on a thread restored above its bottom", async () => { setup(); const base = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..0b6e69be21b96 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -316,8 +316,10 @@ const TIMELINE_MINIMAP_ITEM_SPACING = 8; export const TIMELINE_MINIMAP_MIN_ITEMS = 2; export const TIMELINE_MINIMAP_TARGET_OFFSET = 24; // Relative to the timeline, not the viewport, so an open terminal shrinks the rail and -// endpoint previews (centered on their strip) still fit above and below it. -const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "max(4rem, calc(100% - 14.75rem))"; +// endpoint previews (centered on their strip) still fit above and below it. The last term +// keeps the turn buttons inside a very short timeline and below its top fade. +const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = + "min(max(4rem, calc(100% - 14.75rem)), calc(100% - 6.25rem))"; const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48; export interface WorkGroupScrollAnchor { @@ -482,17 +484,26 @@ export function resolveTimelineMinimapHasPersistentGutter( const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12; const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; +// The turn buttons reach this far left of the rail. The minimap renders inside the +// scroller, which clips its scrollbar gutter, so a wide classic gutter pushes it right. +const TIMELINE_MINIMAP_BUTTON_OVERHANG = 6; +export const TIMELINE_MINIMAP_SHIFT_CSS = `max(0px, var(--chat-timeline-gutter, 0px) - ${TIMELINE_MINIMAP_HIT_STRIP_LEFT - TIMELINE_MINIMAP_BUTTON_OVERHANG}px)`; export function resolveTimelineMinimapHitStripWidth( viewportWidth: number, contentWidth: number, + scrollbarGutter: number, ): number { const sideGutter = resolveTimelineSideGutter(viewportWidth, contentWidth); + const shift = Math.max( + 0, + scrollbarGutter - (TIMELINE_MINIMAP_HIT_STRIP_LEFT - TIMELINE_MINIMAP_BUTTON_OVERHANG), + ); return Math.max( 0, Math.min( TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH, - Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT, + Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT - shift, ), ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 89cc3f8701c55..46b86100f73cc 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -104,7 +104,6 @@ import { type TimestampFormat } from "@t3tools/contracts/settings"; import { type HandoffTimelineRun } from "./V2LifecycleRow"; import { TimelineSystemDivider } from "./TimelineSystemDivider"; -import { forwardWheelToTimeline } from "./timelineMinimapWheel"; import { TimelineMinimap } from "./TimelineMinimap"; import { type TimelineRowSharedState, @@ -837,6 +836,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ const [timelineViewportElement, setTimelineViewportElement] = useState( null, ); + const [timelineScrollNode, setTimelineScrollNode] = useState(null); const { target: readyCitationRequest, positioning: citationPositioning, @@ -1060,7 +1060,11 @@ const ConversationTimeline = memo(function ConversationTimeline({ setMinimapHasPersistentGutter((current) => current === nextHasPersistentGutter ? current : nextHasPersistentGutter, ); - setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth)); + const scrollNode = listRef.current?.getScrollableNode(); + const scrollbarGutter = scrollNode ? (scrollNode.offsetWidth - scrollNode.clientWidth) / 2 : 0; + setMinimapHitStripWidth( + resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth, scrollbarGutter), + ); }; // Rows added, removed or rewrapped (chat width) change the content size, // which moves the scroll position, the overflow, and the content lane width. @@ -1257,6 +1261,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ listRef.current = list; const scrollNode: HTMLElement | null = list?.getScrollableNode() ?? null; registerTimeline?.(scrollNode); + setTimelineScrollNode(scrollNode); const viewport = scrollNode ? attachTimelineViewport(scrollNode, (frame) => { const rowId = frame.closest("[data-timeline-row-id]")?.dataset.timelineRowId; @@ -1311,6 +1316,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ } listRef.current = null; registerTimeline?.(null); + setTimelineScrollNode(null); }; }); @@ -1408,11 +1414,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ ); - const forwardMinimapWheel = (event: WheelEvent) => { - const scrollNode = listRef.current?.getScrollableNode(); - if (scrollNode) forwardWheelToTimeline(event, scrollNode); - }; - if (showsEmptyState) { if (hideEmptyPlaceholder) { return ( @@ -1444,7 +1445,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ {onCiteAssistantText && citationThreadRef ? ( @@ -1503,23 +1504,25 @@ const ConversationTimeline = memo(function ConversationTimeline({ ListHeaderComponent={listHeader} ListFooterComponent={timelineListFooter} /> - { - navigateTimeline(); - void listRef.current?.scrollToIndex({ - index: item.rowIndex, - animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches, - viewOffset: TIMELINE_MINIMAP_TARGET_OFFSET, - }); - }} - /> + {timelineScrollNode ? ( + { + navigateTimeline(); + void listRef.current?.scrollToIndex({ + index: item.rowIndex, + animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches, + viewOffset: TIMELINE_MINIMAP_TARGET_OFFSET, + }); + }} + /> + ) : null} diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 60d817c6dc108..aebe31d49e0cc 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -1,5 +1,6 @@ import { resolveTimelineMinimapPreview, type TimelineMinimapItem } from "./timelineMinimapItems"; import { useRef, useState, type MouseEvent } from "react"; +import { createPortal } from "react-dom"; import { T, useGT } from "gt-react"; import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; import { Button } from "../ui/button"; @@ -9,6 +10,7 @@ import { resolveTimelineMinimapNavigationInteractive, resolveTimelineMinimapTopPercent, TIMELINE_MINIMAP_MIN_ITEMS, + TIMELINE_MINIMAP_SHIFT_CSS, } from "./MessagesTimeline.logic"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; @@ -31,31 +33,26 @@ function onMouseButtonsReleased(onRelease: () => void): () => void { } export function TimelineMinimap({ + scrollNode, hasPersistentGutter, hitStripWidth, currentIndex, atEnd, items, stripMap, - onWheel, onSelect, }: { + scrollNode: HTMLElement; hasPersistentGutter: boolean; hitStripWidth: number; currentIndex: number | null; atEnd: boolean; items: ReadonlyArray; stripMap: Map; - onWheel: (event: WheelEvent) => void; onSelect: (item: TimelineMinimapItem) => void; }) { const gt = useGT(); const [activeIndex, setActiveIndex] = useState(null); - const wheelTargetRef = (node: HTMLDivElement | null) => { - if (!node) return; - node.addEventListener("wheel", onWheel, { passive: false }); - return () => node.removeEventListener("wheel", onWheel); - }; const pressedOnStripRef = useRef(false); const [passThrough, setPassThrough] = useState(false); @@ -104,19 +101,21 @@ export function TimelineMinimap({ return null; } - return ( + const minimap = (
-
+
); })} - {activeItem ? ( - // Display-only: it overlaps the message column, and the strip keeps tracking beneath it. - - - - {activeItem.userText ?? User message} - - {activeItem.assistantText ? ( - - {activeItem.assistantText} - - ) : null} - - - ) : null}
); + return ( + <> + {createPortal( +
{minimap}
, + scrollNode, + )} + {activeItem ? ( + // Display-only: it overlaps the message column, and the strip keeps tracking beneath it. +
+
+ + + + {activeItem.userText ?? User message} + + {activeItem.assistantText ? ( + + {activeItem.assistantText} + + ) : null} + + +
+
+ ) : null} + + ); } function TimelineMinimapNavigationButton({ diff --git a/apps/web/src/components/chat/timelineMinimapWheel.browser.test.ts b/apps/web/src/components/chat/timelineMinimapWheel.browser.test.ts deleted file mode 100644 index d107269da7b6f..0000000000000 --- a/apps/web/src/components/chat/timelineMinimapWheel.browser.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it, vi } from "vite-plus/test"; - -import { fakeTimers } from "../../../test/render"; -import { forwardWheelToTimeline } from "./timelineMinimapWheel"; - -function mountTimeline() { - const timeline = document.createElement("div"); - timeline.style.cssText = "height: 200px; overflow-y: auto;"; - const content = document.createElement("div"); - content.style.height = "2000px"; - timeline.append(content); - document.body.append(timeline); - return Object.assign(timeline, { [Symbol.dispose]: () => timeline.remove() }); -} - -function wheel(deltaY: number, wheelDeltaY: number): WheelEvent { - const init = { cancelable: true, deltaY, wheelDeltaY }; - return new WheelEvent("wheel", init); -} - -describe("forwardWheelToTimeline", () => { - it.each([ - ["macOS", -360], - ["Linux and Windows", -120], - ])("scrolls %s trackpad deltas immediately", (_platform, wheelDeltaY) => { - using timeline = mountTimeline(); - forwardWheelToTimeline(wheel(120, wheelDeltaY), timeline); - expect(timeline.scrollTop).toBe(120); - }); - - it("glides mouse wheel notches and accumulates them", () => { - using timeline = mountTimeline(); - using _timers = fakeTimers(); - forwardWheelToTimeline(wheel(100, -120), timeline); - forwardWheelToTimeline(wheel(100, -120), timeline); - expect(timeline.scrollTop).toBe(0); - vi.advanceTimersByTime(75); - expect(timeline.scrollTop).toBeGreaterThan(0); - expect(timeline.scrollTop).toBeLessThan(200); - vi.advanceTimersByTime(100); - expect(timeline.scrollTop).toBe(200); - }); - - it("stops gliding when the user clicks or navigates", () => { - using timeline = mountTimeline(); - using _timers = fakeTimers(); - forwardWheelToTimeline(wheel(100, -120), timeline); - vi.advanceTimersByTime(50); - timeline.scrollTop = 1000; - window.dispatchEvent(new PointerEvent("pointerdown")); - vi.advanceTimersByTime(200); - expect(timeline.scrollTop).toBe(1000); - }); -}); diff --git a/apps/web/src/components/chat/timelineMinimapWheel.ts b/apps/web/src/components/chat/timelineMinimapWheel.ts deleted file mode 100644 index 5befc4efb8100..0000000000000 --- a/apps/web/src/components/chat/timelineMinimapWheel.ts +++ /dev/null @@ -1,107 +0,0 @@ -const MOUSE_WHEEL_SCROLL_MS = 150; -const PRECISE_WHEEL_DELTA_RATIOS = [1, 3]; - -interface WheelGlide { - from: number; - to: number; - start: number; - written: number; - frame: number; - interruptions: AbortController; -} - -const glides = new WeakMap(); - -function isPreciseWheel(event: WheelEvent): boolean { - if (event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL) return false; - const { wheelDeltaY } = event as WheelEvent & { wheelDeltaY?: number }; - return ( - wheelDeltaY === undefined || - PRECISE_WHEEL_DELTA_RATIOS.some((ratio) => Math.abs(wheelDeltaY + ratio * event.deltaY) < 1) - ); -} - -function stopGlide(timeline: HTMLElement): WheelGlide | undefined { - const glide = glides.get(timeline); - if (!glide) return undefined; - cancelAnimationFrame(glide.frame); - glide.interruptions.abort(); - glides.delete(timeline); - return glide; -} - -function glideBy(timeline: HTMLElement, distance: number): void { - const current = stopGlide(timeline); - const scrollTop = timeline.scrollTop; - const base = current ? current.to + scrollTop - current.written : scrollTop; - const maxScrollTop = timeline.scrollHeight - timeline.clientHeight; - const glide: WheelGlide = { - from: scrollTop, - to: Math.max(0, Math.min(maxScrollTop, base + distance)), - start: performance.now(), - written: scrollTop, - frame: 0, - interruptions: new AbortController(), - }; - for (const type of ["pointerdown", "keydown"]) { - window.addEventListener(type, () => stopGlide(timeline), { - capture: true, - signal: glide.interruptions.signal, - }); - } - const step = (time: number) => { - if (!timeline.isConnected) { - stopGlide(timeline); - return; - } - const drift = timeline.scrollTop - glide.written; - glide.from += drift; - glide.to += drift; - const progress = Math.min(1, Math.max(0, (time - glide.start) / MOUSE_WHEEL_SCROLL_MS)); - timeline.scrollTop = glide.from + (glide.to - glide.from) * (1 - (1 - progress) ** 3); - glide.written = timeline.scrollTop; - if (progress < 1) { - glide.frame = requestAnimationFrame(step); - } else { - stopGlide(timeline); - } - }; - glide.frame = requestAnimationFrame(step); - glides.set(timeline, glide); -} - -export function forwardWheelToTimeline(event: WheelEvent, timeline: HTMLElement): void { - if (event.defaultPrevented || event.ctrlKey || event.deltaY === 0) return; - event.preventDefault(); - - const forwarded = new WheelEvent("wheel", { - bubbles: true, - cancelable: true, - deltaX: event.deltaX, - deltaY: event.deltaY, - deltaZ: event.deltaZ, - deltaMode: event.deltaMode, - clientX: event.clientX, - clientY: event.clientY, - screenX: event.screenX, - screenY: event.screenY, - altKey: event.altKey, - metaKey: event.metaKey, - shiftKey: event.shiftKey, - }); - if (!timeline.dispatchEvent(forwarded)) return; - - const pixelsPerUnit = - event.deltaMode === WheelEvent.DOM_DELTA_LINE - ? 16 - : event.deltaMode === WheelEvent.DOM_DELTA_PAGE - ? timeline.clientHeight - : 1; - const distance = event.deltaY * pixelsPerUnit; - if (isPreciseWheel(event) || window.matchMedia("(prefers-reduced-motion: reduce)").matches) { - stopGlide(timeline); - timeline.scrollBy({ top: distance }); - return; - } - glideBy(timeline, distance); -} diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..25c9b126bad67 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2613,6 +2613,13 @@ code { 0.75rem + var(--chat-lane-inset-end, 0px) - var(--chat-timeline-gutter, 0px) ); } + /* Lands on the timeline viewport's left edge from inside the scroller's content box, whose + inline padding differs only by the lane insets above. */ + .timeline-minimap-frame { + left: calc( + 50% - 50cqw + (var(--chat-lane-inset-end, 0px) - var(--chat-lane-inset-start, 0px)) / 2 + ); + } .chat-scroll-to-bottom, .chat-banner-lane { inset-inline-start: var(--chat-lane-inset-start, 0px);