Open History to see the last commit
1import { resolveTimelineMinimapPreview, type TimelineMinimapItem } from "./timelineMinimapItems";
2import { useRef, useState, type MouseEvent } from "react";
3import { T, useGT } from "gt-react";
4import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
5import { Button } from "../ui/button";
6import {
7 resolveTimelineMinimapHeightStyle,
8 resolveTimelineMinimapIndexFromPointer,
9 resolveTimelineMinimapMarkCount,
10 resolveTimelineMinimapMarkIndex,
11 resolveTimelineMinimapNavigationInteractive,
12 resolveTimelineMinimapTopPercent,
13 TIMELINE_MINIMAP_MIN_ITEMS,
14} from "./MessagesTimeline.logic";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16import { cn } from "~/lib/utils";
17import { observeResize } from "~/lib/observeResize";
18
19// A release outside the window can skip `mouseup`, so the next button-free
20// `mousemove` also counts.
21function onMouseButtonsReleased(onRelease: () => void): () => void {
22 const check = (event: globalThis.MouseEvent) => {
23 if (event.buttons !== 0) return;
24 stop();
25 onRelease();
26 };
27 const stop = () => {
28 window.removeEventListener("mouseup", check);
29 window.removeEventListener("mousemove", check);
30 };
31 window.addEventListener("mouseup", check);
32 window.addEventListener("mousemove", check);
33 return stop;
34}
35
36export function TimelineMinimap({
37 hasPersistentGutter,
38 hitStrip: { left: hitStripLeft, width: hitStripWidth },
39 currentIndex,
40 atEnd,
41 items,
42 stripMap,
43 onWheel,
44 onSelect,
45}: {
46 hasPersistentGutter: boolean;
47 hitStrip: { left: number; width: number };
48 currentIndex: number | null;
49 atEnd: boolean;
50 items: ReadonlyArray<TimelineMinimapItem>;
51 stripMap: Map<string, HTMLSpanElement>;
52 onWheel: (event: WheelEvent) => void;
53 onSelect: (item: TimelineMinimapItem) => void;
54}) {
55 const gt = useGT();
56 const [activeIndex, setActiveIndex] = useState<number | null>(null);
57 const wheelTargetRef = (node: HTMLDivElement | null) => {
58 if (!node) return;
59 node.addEventListener("wheel", onWheel, { passive: false });
60 return () => node.removeEventListener("wheel", onWheel);
61 };
62
63 const [railHeight, setRailHeight] = useState(0);
64 const railRef = (node: HTMLDivElement | null) => {
65 if (!node) return;
66 setRailHeight(node.getBoundingClientRect().height);
67 return observeResize(node, ([entry]) => {
68 if (entry) setRailHeight(entry.contentRect.height);
69 });
70 };
71
72 const pressedOnStripRef = useRef(false);
73 const [passThrough, setPassThrough] = useState(false);
74
75 const resolvedActiveIndex =
76 activeIndex !== null && activeIndex < items.length ? activeIndex : null;
77 const activeItem = resolveTimelineMinimapPreview(
78 resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
79 );
80 const navigationInteractive =
81 resolveTimelineMinimapNavigationInteractive(hitStripWidth) && !passThrough;
82 const activeTopPercent =
83 resolvedActiveIndex === null
84 ? 0
85 : resolveTimelineMinimapTopPercent(resolvedActiveIndex, items.length);
86 const resolvedCurrentIndex =
87 currentIndex !== null && currentIndex >= 0 && currentIndex < items.length ? currentIndex : null;
88 const previousItem =
89 resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
90 const nextItem =
91 resolvedCurrentIndex === null || atEnd ? null : (items[resolvedCurrentIndex + 1] ?? null);
92
93 // A rail too short for every item groups neighbours onto one strip; the pointer and
94 // keyboard still resolve single items.
95 const markCount = resolveTimelineMinimapMarkCount(items.length, railHeight);
96 const marks: TimelineMinimapItem[][] = Array.from({ length: markCount }, () => []);
97 for (const [index, item] of items.entries()) {
98 marks[resolveTimelineMinimapMarkIndex(index, items.length, markCount)]?.push(item);
99 }
100 const activeMarkIndex =
101 resolvedActiveIndex === null
102 ? null
103 : resolveTimelineMinimapMarkIndex(resolvedActiveIndex, items.length, markCount);
104
105 const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
106 const rect = event.currentTarget.getBoundingClientRect();
107 return resolveTimelineMinimapIndexFromPointer({
108 itemCount: items.length,
109 railTop: rect.top,
110 railHeight: rect.height,
111 pointerY: event.clientY,
112 });
113 };
114
115 const updateActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
116 const nextIndex = resolveActiveIndexFromPointer(event);
117 setActiveIndex(nextIndex);
118 };
119
120 const moveActiveIndex = (delta: number) => {
121 setActiveIndex((current) => {
122 const base = current ?? 0;
123 return Math.max(0, Math.min(items.length - 1, base + delta));
124 });
125 };
126
127 if (items.length < TIMELINE_MINIMAP_MIN_ITEMS) {
128 return null;
129 }
130
131 return (
132 <div
133 className={cn(
134 "group/minimap pointer-events-none absolute bottom-0 left-0 top-[calc(-1*var(--chat-header-height,0px))] z-40 w-18",
135 hasPersistentGutter
136 ? "opacity-100"
137 : "hidden opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100 [@media(pointer:fine)]:block",
138 )}
139 data-testid="timeline-minimap"
140 data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
141 ref={wheelTargetRef}
142 >
143 <div className="relative h-full w-full select-none">
144 <div
145 className={cn(
146 "absolute top-1/2 -translate-y-1/2",
147 hitStripWidth > 0 && !passThrough ? "pointer-events-auto" : "pointer-events-none",
148 )}
149 ref={railRef}
150 onMouseDown={() => {
151 if (pressedOnStripRef.current) return;
152 pressedOnStripRef.current = true;
153 onMouseButtonsReleased(() => {
154 pressedOnStripRef.current = false;
155 });
156 }}
157 onMouseMove={(event) => {
158 if (event.buttons === 0 || pressedOnStripRef.current || passThrough) return;
159 setPassThrough(true);
160 onMouseButtonsReleased(() => setPassThrough(false));
161 }}
162 style={{
163 height: resolveTimelineMinimapHeightStyle(items.length),
164 left: hitStripLeft,
165 width: hitStripWidth,
166 }}
167 >
168 <TimelineMinimapNavigationButton
169 direction="previous"
170 disabled={previousItem === null}
171 interactive={navigationInteractive}
172 onClick={() => {
173 if (previousItem) onSelect(previousItem);
174 }}
175 />
176 <button
177 aria-label={gt`Jump to message: ${{ text: activeItem?.userText ?? gt`User message` }}`}
178 className="absolute inset-y-0 left-0 w-full cursor-pointer bg-transparent before:absolute before:inset-x-0 before:-inset-y-1 before:content-[''] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
179 onBlur={() => setActiveIndex(null)}
180 onClick={(event) => {
181 const nextIndex = resolveActiveIndexFromPointer(event);
182 const selectedItem = nextIndex === null ? null : (items[nextIndex] ?? null);
183 if (selectedItem) {
184 onSelect(selectedItem);
185 }
186 event.currentTarget.blur();
187 }}
188 onFocus={() => setActiveIndex((current) => current ?? resolvedCurrentIndex ?? 0)}
189 // Capture so Escape dismisses the preview before embedded side-chat bubble listeners.
190 onKeyDownCapture={(event) => {
191 if (event.key !== "Escape" || activeItem === null || event.defaultPrevented) return;
192 if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
193 event.preventDefault();
194 event.stopPropagation();
195 setActiveIndex(null);
196 }}
197 onKeyDown={(event) => {
198 if (event.key === "ArrowDown") {
199 event.preventDefault();
200 moveActiveIndex(1);
201 } else if (event.key === "ArrowUp") {
202 event.preventDefault();
203 moveActiveIndex(-1);
204 } else if (event.key === "Home") {
205 event.preventDefault();
206 setActiveIndex(0);
207 } else if (event.key === "End") {
208 event.preventDefault();
209 setActiveIndex(items.length - 1);
210 } else if (event.key === "Enter" || event.key === " ") {
211 event.preventDefault();
212 if (activeItem) {
213 onSelect(activeItem);
214 }
215 }
216 }}
217 onMouseLeave={() => setActiveIndex(null)}
218 onMouseMove={(event) => {
219 if (event.buttons !== 0 && !pressedOnStripRef.current) return;
220 updateActiveIndexFromPointer(event);
221 }}
222 onMouseDown={(event) => event.preventDefault()}
223 type="button"
224 >
225 {marks.map((markItems, index) => {
226 const top = `${resolveTimelineMinimapTopPercent(index, markCount)}%`;
227 const activeDistance =
228 activeMarkIndex === null ? null : Math.abs(index - activeMarkIndex);
229 return (
230 // Compositor-friendly on purpose: in-view state and the hover
231 // fisheye animate constantly (every scroll tick and streaming
232 // update flips a band of strips), so the strip animates only
233 // transform and opacity.
234 <span
235 aria-hidden="true"
236 className={cn(
237 "pointer-events-none absolute left-0 h-0.5 w-6 origin-left -translate-y-1/2 rounded-full transition-transform duration-150 after:absolute after:inset-0 after:rounded-full after:bg-foreground/55 after:opacity-0 after:transition-opacity after:duration-150 data-[in-view=true]:after:opacity-100",
238 activeDistance === 0 ? "bg-muted-foreground/60" : "bg-muted-foreground/25",
239 activeDistance === 0
240 ? "scale-x-100"
241 : activeDistance === 1
242 ? "scale-x-[0.667]"
243 : activeDistance === 2
244 ? "scale-x-[0.417]"
245 : "scale-x-[0.333]",
246 )}
247 data-in-view="false"
248 data-minimap-strip
249 key={markItems[0]?.id ?? index}
250 ref={(node) => {
251 if (!node) return;
252 for (const item of markItems) stripMap.set(item.id, node);
253 return () => {
254 for (const item of markItems) {
255 if (stripMap.get(item.id) === node) stripMap.delete(item.id);
256 }
257 };
258 }}
259 style={{ top }}
260 />
261 );
262 })}
263 {activeItem ? (
264 // Display-only: it overlaps the message column, and the strip keeps tracking beneath it.
265 <span
266 className="pointer-events-none absolute left-8 w-80 -translate-y-1/2"
267 style={{ top: `${activeTopPercent}%` }}
268 >
269 <span className="dropdown-glass block rounded-xl p-3 text-left text-popover-foreground shadow-xl shadow-black/25">
270 <span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
271 {activeItem.userText ?? <T>User message</T>}
272 </span>
273 {activeItem.assistantText ? (
274 <span
275 className="mt-1 max-h-[3.75rem] overflow-hidden text-muted-foreground text-sm leading-5"
276 style={{
277 display: "-webkit-box",
278 WebkitBoxOrient: "vertical",
279 WebkitLineClamp: 3,
280 }}
281 >
282 {activeItem.assistantText}
283 </span>
284 ) : null}
285 </span>
286 </span>
287 ) : null}
288 </button>
289 <TimelineMinimapNavigationButton
290 direction="next"
291 disabled={nextItem === null}
292 interactive={navigationInteractive}
293 onClick={() => {
294 if (nextItem) onSelect(nextItem);
295 }}
296 />
297 </div>
298 </div>
299 </div>
300 );
301}
302
303function TimelineMinimapNavigationButton({
304 direction,
305 disabled,
306 interactive,
307 onClick,
308}: {
309 direction: "previous" | "next";
310 disabled: boolean;
311 interactive: boolean;
312 onClick: () => void;
313}) {
314 const gt = useGT();
315 const previous = direction === "previous";
316 const label = previous ? gt`Previous turn` : gt`Next turn`;
317 const Icon = previous ? ChevronUpIcon : ChevronDownIcon;
318
319 return (
320 <Tooltip>
321 <TooltipTrigger
322 render={
323 <span
324 className={cn(
325 "absolute left-1 z-10 inline-flex -translate-x-1/2 opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
326 interactive ? "pointer-events-auto" : "pointer-events-none",
327 previous ? "bottom-[calc(100%+6px)]" : "top-[calc(100%+6px)]",
328 )}
329 />
330 }
331 >
332 <Button
333 aria-label={label}
334 disabled={disabled}
335 onClick={onClick}
336 size="icon-micro"
337 type="button"
338 variant="ghost-muted"
339 >
340 <Icon className="size-4 text-foreground/90" />
341 </Button>
342 </TooltipTrigger>
343 <TooltipPopup side={previous ? "top" : "bottom"}>{label}</TooltipPopup>
344 </Tooltip>
345 );
346}