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