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