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 atEnd,
42 items,
43 stripMap,
44 onWheel,
45 onSelect,
46}: {
47 hasPersistentGutter: boolean;
48 hitStripWidth: number;
49 currentIndex: number | null;
50 atEnd: boolean;
51 items: ReadonlyArray<TimelineMinimapItem>;
52 stripMap: Map<string, HTMLSpanElement>;
53 onWheel: (event: WheelEvent) => void;
54 onSelect: (item: TimelineMinimapItem) => void;
55}) {
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 pressedOnStripRef = useRef(false);
64 const [passThrough, setPassThrough] = useState(false);
65
66 const resolvedActiveIndex =
67 activeIndex !== null && activeIndex < items.length ? activeIndex : null;
68 const activeItem = resolveTimelineMinimapPreview(
69 resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
70 );
71 const navigationInteractive =
72 resolveTimelineMinimapNavigationInteractive(hitStripWidth) && !passThrough;
73 const activeTopPercent =
74 resolvedActiveIndex === null
75 ? 0
76 : resolveTimelineMinimapTopPercent(resolvedActiveIndex, items.length);
77 const activeTooltipTranslate =
78 resolvedActiveIndex === null
79 ? "-50%"
80 : resolvedActiveIndex === 0
81 ? "0%"
82 : resolvedActiveIndex === items.length - 1
83 ? "-100%"
84 : "-50%";
85 const resolvedCurrentIndex =
86 currentIndex !== null && currentIndex >= 0 && currentIndex < items.length ? currentIndex : null;
87 const previousItem =
88 resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
89 const nextItem =
90 resolvedCurrentIndex === null || atEnd ? null : (items[resolvedCurrentIndex + 1] ?? null);
91
92 const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
93 const rect = event.currentTarget.getBoundingClientRect();
94 return resolveTimelineMinimapIndexFromPointer({
95 itemCount: items.length,
96 railTop: rect.top,
97 railHeight: rect.height,
98 pointerY: event.clientY,
99 });
100 };
101
102 const updateActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
103 const nextIndex = resolveActiveIndexFromPointer(event);
104 setActiveIndex(nextIndex);
105 };
106
107 const moveActiveIndex = (delta: number) => {
108 setActiveIndex((current) => {
109 const base = current ?? 0;
110 return Math.max(0, Math.min(items.length - 1, base + delta));
111 });
112 };
113
114 if (items.length < TIMELINE_MINIMAP_MIN_ITEMS) {
115 return null;
116 }
117
118 return (
119 <div
120 className={cn(
121 "group/minimap pointer-events-none absolute inset-y-0 left-0 z-40 w-18",
122 hasPersistentGutter
123 ? "opacity-100"
124 : "hidden opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100 [@media(pointer:fine)]:block",
125 )}
126 data-testid="timeline-minimap"
127 data-persistent-gutter={hasPersistentGutter ? "true" : "false"}
128 ref={wheelTargetRef}
129 >
130 <div className="relative h-full w-full select-none">
131 <div
132 className={cn(
133 "absolute top-1/2 left-3 -translate-y-1/2",
134 hitStripWidth > 0 && !passThrough ? "pointer-events-auto" : "pointer-events-none",
135 )}
136 onMouseDown={() => {
137 if (pressedOnStripRef.current) return;
138 pressedOnStripRef.current = true;
139 onMouseButtonsReleased(() => {
140 pressedOnStripRef.current = false;
141 });
142 }}
143 onMouseMove={(event) => {
144 if (event.buttons === 0 || pressedOnStripRef.current || passThrough) return;
145 setPassThrough(true);
146 onMouseButtonsReleased(() => setPassThrough(false));
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 "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",
224 activeDistance === 0 ? "bg-muted-foreground/60" : "bg-muted-foreground/25",
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 );
246 })}
247 {activeItem ? (
248 <span
249 className="pointer-events-auto absolute left-8 w-80 cursor-text select-text"
250 data-minimap-preview
251 onMouseMove={(event) => event.stopPropagation()}
252 style={{
253 top: `${activeTopPercent}%`,
254 transform: `translateY(${activeTooltipTranslate})`,
255 }}
256 >
257 <span className="dropdown-glass block rounded-xl p-3 text-left text-popover-foreground shadow-xl shadow-black/25">
258 <span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
259 {activeItem.userText ?? "User message"}
260 </span>
261 {activeItem.assistantText ? (
262 <span
263 className="mt-1 max-h-[3.75rem] overflow-hidden text-muted-foreground text-sm leading-5"
264 style={{
265 display: "-webkit-box",
266 WebkitBoxOrient: "vertical",
267 WebkitLineClamp: 3,
268 }}
269 >
270 {activeItem.assistantText}
271 </span>
272 ) : null}
273 </span>
274 </span>
275 ) : null}
276 </button>
277 <TimelineMinimapNavigationButton
278 direction="next"
279 disabled={nextItem === null}
280 interactive={navigationInteractive}
281 onClick={() => {
282 if (nextItem) onSelect(nextItem);
283 }}
284 />
285 </div>
286 </div>
287 </div>
288 );
289}
290
291function TimelineMinimapNavigationButton({
292 direction,
293 disabled,
294 interactive,
295 onClick,
296}: {
297 direction: "previous" | "next";
298 disabled: boolean;
299 interactive: boolean;
300 onClick: () => void;
301}) {
302 const previous = direction === "previous";
303 const label = previous ? "Previous turn" : "Next turn";
304 const Icon = previous ? ChevronUpIcon : ChevronDownIcon;
305
306 return (
307 <Tooltip>
308 <TooltipTrigger
309 render={
310 <span
311 className={cn(
312 "absolute left-1 z-10 inline-flex -translate-x-1/2 opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100",
313 interactive ? "pointer-events-auto" : "pointer-events-none",
314 previous ? "bottom-[calc(100%+2px)]" : "top-[calc(100%+2px)]",
315 )}
316 />
317 }
318 >
319 <Button
320 aria-label={label}
321 disabled={disabled}
322 onClick={onClick}
323 size="icon-micro"
324 type="button"
325 variant="ghost-muted"
326 >
327 <Icon className="size-4 text-foreground/90" />
328 </Button>
329 </TooltipTrigger>
330 <TooltipPopup side={previous ? "top" : "bottom"}>{label}</TooltipPopup>
331 </Tooltip>
332 );
333}