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