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