Open History to see the last commit
1"use client";
2
3import { Toast } from "@base-ui/react/toast";
4import { useEffect, useMemo, type CSSProperties } from "react";
5import { useParams } from "@tanstack/react-router";
6import { type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
7import {
8 CheckIcon,
9 CircleAlertIcon,
10 CircleCheckIcon,
11 CopyIcon,
12 InfoIcon,
13 LoaderCircleIcon,
14 TriangleAlertIcon,
15} from "lucide-react";
16
17import { cn } from "~/lib/utils";
18import { buttonVariants } from "~/components/ui/button";
19import { useComposerDraftStore } from "~/composerDraftStore";
20import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
21import { resolveThreadRouteTarget } from "~/threadRoutes";
22import {
23 buildVisibleToastLayout,
24 shouldHideCollapsedToastContent,
25 shouldRenderThreadScopedToast,
26} from "./toast.logic";
27
28export type ThreadToastData = {
29 threadRef?: ScopedThreadRef | null;
30 threadId?: ThreadId | null;
31 tooltipStyle?: boolean;
32 dismissAfterVisibleMs?: number;
33 hideCopyButton?: boolean;
34};
35
36const toastManager = Toast.createToastManager<ThreadToastData>();
37const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
38type ToastId = ReturnType<typeof toastManager.add>;
39const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
40
41const TOAST_ICONS = {
42 error: CircleAlertIcon,
43 info: InfoIcon,
44 loading: LoaderCircleIcon,
45 success: CircleCheckIcon,
46 warning: TriangleAlertIcon,
47} as const;
48
49function CopyErrorButton({ text }: { text: string }) {
50 const { copyToClipboard, isCopied } = useCopyToClipboard();
51
52 return (
53 <button
54 className="shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-60 transition-opacity hover:opacity-100"
55 onClick={() => copyToClipboard(text)}
56 title="Copy error"
57 type="button"
58 >
59 {isCopied ? (
60 <CheckIcon className="size-3.5 text-success" />
61 ) : (
62 <CopyIcon className="size-3.5" />
63 )}
64 </button>
65 );
66}
67
68type ToastPosition =
69 | "top-left"
70 | "top-center"
71 | "top-right"
72 | "bottom-left"
73 | "bottom-center"
74 | "bottom-right";
75
76interface ToastProviderProps extends Toast.Provider.Props {
77 position?: ToastPosition;
78}
79
80function useActiveThreadRefFromRoute(): ScopedThreadRef | null {
81 const routeTarget = useParams({
82 strict: false,
83 select: (params) => resolveThreadRouteTarget(params),
84 });
85 const activeDraftSession = useComposerDraftStore((store) =>
86 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
87 );
88
89 return useMemo(() => {
90 if (routeTarget?.kind === "server") {
91 return routeTarget.threadRef;
92 }
93 if (routeTarget?.kind === "draft" && activeDraftSession) {
94 return {
95 environmentId: activeDraftSession.environmentId,
96 threadId: activeDraftSession.threadId,
97 };
98 }
99 return null;
100 }, [activeDraftSession, routeTarget]);
101}
102
103function ThreadToastVisibleAutoDismiss({
104 toastId,
105 dismissAfterVisibleMs,
106}: {
107 toastId: ToastId;
108 dismissAfterVisibleMs: number | undefined;
109}) {
110 useEffect(() => {
111 if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
112 if (typeof window === "undefined" || typeof document === "undefined") return;
113
114 let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
115 let startedAtMs: number | null = null;
116 let timeoutId: number | null = null;
117 let closed = false;
118
119 const clearTimer = () => {
120 if (timeoutId === null) return;
121 window.clearTimeout(timeoutId);
122 timeoutId = null;
123 };
124
125 const closeToast = () => {
126 if (closed) return;
127 closed = true;
128 threadToastVisibleTimeoutRemainingMs.delete(toastId);
129 toastManager.close(toastId);
130 };
131
132 const pause = () => {
133 if (startedAtMs === null) return;
134 remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
135 startedAtMs = null;
136 clearTimer();
137 threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
138 };
139
140 const start = () => {
141 if (closed || startedAtMs !== null) return;
142 if (remainingMs <= 0) {
143 closeToast();
144 return;
145 }
146 startedAtMs = Date.now();
147 clearTimer();
148 timeoutId = window.setTimeout(() => {
149 remainingMs = 0;
150 startedAtMs = null;
151 closeToast();
152 }, remainingMs);
153 };
154
155 const syncTimer = () => {
156 const shouldRun = document.visibilityState === "visible" && document.hasFocus();
157 if (shouldRun) {
158 start();
159 return;
160 }
161 pause();
162 };
163
164 syncTimer();
165 document.addEventListener("visibilitychange", syncTimer);
166 window.addEventListener("focus", syncTimer);
167 window.addEventListener("blur", syncTimer);
168
169 return () => {
170 document.removeEventListener("visibilitychange", syncTimer);
171 window.removeEventListener("focus", syncTimer);
172 window.removeEventListener("blur", syncTimer);
173 pause();
174 clearTimer();
175 };
176 }, [dismissAfterVisibleMs, toastId]);
177
178 return null;
179}
180
181function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
182 return (
183 <Toast.Provider toastManager={toastManager} {...props}>
184 {children}
185 <Toasts position={position} />
186 </Toast.Provider>
187 );
188}
189
190function Toasts({ position = "top-right" }: { position: ToastPosition }) {
191 const { toasts } = Toast.useToastManager<ThreadToastData>();
192 const activeThreadRef = useActiveThreadRefFromRoute();
193 const isTop = position.startsWith("top");
194 const visibleToasts = toasts.filter((toast) =>
195 shouldRenderThreadScopedToast(toast.data, activeThreadRef),
196 );
197 const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
198
199 useEffect(() => {
200 const activeToastIds = new Set(toasts.map((toast) => toast.id));
201 for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
202 if (!activeToastIds.has(toastId)) {
203 threadToastVisibleTimeoutRemainingMs.delete(toastId);
204 }
205 }
206 }, [toasts]);
207
208 return (
209 <Toast.Portal data-slot="toast-portal">
210 <Toast.Viewport
211 className={cn(
212 "fixed z-100 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-header-offset:52px] [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
213 // Vertical positioning
214 "data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
215 "data-[position*=bottom]:bottom-(--toast-inset)",
216 // Horizontal positioning
217 "data-[position*=left]:left-(--toast-inset)",
218 "data-[position*=right]:right-(--toast-inset)",
219 "data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
220 )}
221 data-position={position}
222 data-slot="toast-viewport"
223 style={
224 {
225 "--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
226 } as CSSProperties
227 }
228 >
229 {visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
230 const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
231 const hideCollapsedContent = shouldHideCollapsedToastContent(
232 visibleIndex,
233 visibleToastLayout.items.length,
234 );
235
236 return (
237 <Toast.Root
238 className={cn(
239 "absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
240 // Base positioning using data-position
241 "data-[position*=right]:right-0 data-[position*=right]:left-auto",
242 "data-[position*=left]:right-auto data-[position*=left]:left-0",
243 "data-[position*=center]:right-0 data-[position*=center]:left-0",
244 "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
245 "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
246 // Gap fill for hover
247 "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
248 "data-[position*=top]:after:top-full",
249 "data-[position*=bottom]:after:bottom-full",
250 // Define some variables
251 // Base UI exposes a shared front-most height for the collapsed stack.
252 // If that shared measurement is briefly stale, long content can render
253 // outside the card until hover expands the toast and swaps to its own height.
254 "[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
255 // Define offset-y variable
256 "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
257 "data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
258 // Default state transform
259 "data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
260 "data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
261 // Limited state
262 "data-limited:opacity-0",
263 // Expanded state
264 "data-expanded:h-(--toast-height)",
265 "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
266 // Starting and ending animations
267 "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
268 "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
269 "data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
270 "data-ending-style:opacity-0",
271 // Ending animations (direction-aware)
272 "data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
273 "data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
274 "data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
275 "data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
276 "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
277 "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
278 // Ending animations (expanded)
279 "data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
280 "data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
281 "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
282 "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
283 )}
284 data-position={position}
285 key={toast.id}
286 style={
287 {
288 "--toast-index": visibleIndex,
289 "--toast-offset-y": `${offsetY}px`,
290 } as CSSProperties
291 }
292 swipeDirection={
293 position.includes("center")
294 ? [isTop ? "up" : "down"]
295 : position.includes("left")
296 ? ["left", isTop ? "up" : "down"]
297 : ["right", isTop ? "up" : "down"]
298 }
299 toast={toast}
300 >
301 <ThreadToastVisibleAutoDismiss
302 dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
303 toastId={toast.id}
304 />
305 <Toast.Content
306 className={cn(
307 "pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
308 hideCollapsedContent &&
309 "not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
310 )}
311 >
312 <div className="flex min-w-0 flex-1 gap-2">
313 {Icon && (
314 <div
315 className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
316 data-slot="toast-icon"
317 >
318 <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
319 </div>
320 )}
321
322 <div className="flex min-w-0 flex-1 flex-col gap-0.5">
323 <div className="flex items-center justify-between gap-1">
324 <Toast.Title
325 className="min-w-0 wrap-break-word font-medium"
326 data-slot="toast-title"
327 />
328 {toast.type === "error" &&
329 typeof toast.description === "string" &&
330 !toast.data?.hideCopyButton && <CopyErrorButton text={toast.description} />}
331 </div>
332 <Toast.Description
333 className="min-w-0 select-text wrap-break-word text-muted-foreground"
334 data-slot="toast-description"
335 />
336 </div>
337 </div>
338 {toast.actionProps && (
339 <Toast.Action
340 className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
341 data-slot="toast-action"
342 >
343 {toast.actionProps.children}
344 </Toast.Action>
345 )}
346 </Toast.Content>
347 </Toast.Root>
348 );
349 })}
350 </Toast.Viewport>
351 </Toast.Portal>
352 );
353}
354
355function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
356 return (
357 <Toast.Provider toastManager={anchoredToastManager} {...props}>
358 {children}
359 <AnchoredToasts />
360 </Toast.Provider>
361 );
362}
363
364function AnchoredToasts() {
365 const { toasts } = Toast.useToastManager<ThreadToastData>();
366 const activeThreadRef = useActiveThreadRefFromRoute();
367
368 return (
369 <Toast.Portal data-slot="toast-portal-anchored">
370 <Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
371 {toasts
372 .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
373 .map((toast) => {
374 const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
375 const tooltipStyle = toast.data?.tooltipStyle ?? false;
376 const positionerProps = toast.positionerProps;
377
378 if (!positionerProps?.anchor) {
379 return null;
380 }
381
382 return (
383 <Toast.Positioner
384 className="z-100 max-w-[min(--spacing(64),var(--available-width))]"
385 data-slot="toast-positioner"
386 key={toast.id}
387 sideOffset={positionerProps.sideOffset ?? 4}
388 toast={toast}
389 >
390 <Toast.Root
391 className={cn(
392 "relative text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
393 tooltipStyle
394 ? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
395 : "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
396 )}
397 data-slot="toast-popup"
398 toast={toast}
399 >
400 {tooltipStyle ? (
401 <Toast.Content className="pointer-events-auto px-2 py-1">
402 <Toast.Title data-slot="toast-title" />
403 </Toast.Content>
404 ) : (
405 <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
406 <div className="flex min-w-0 flex-1 gap-2">
407 {Icon && (
408 <div
409 className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
410 data-slot="toast-icon"
411 >
412 <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
413 </div>
414 )}
415
416 <div className="flex min-w-0 flex-1 flex-col gap-0.5">
417 <div className="flex items-center gap-1">
418 <Toast.Title
419 className="min-w-0 wrap-break-word font-medium"
420 data-slot="toast-title"
421 />
422 {toast.type === "error" &&
423 typeof toast.description === "string" &&
424 !toast.data?.hideCopyButton && (
425 <CopyErrorButton text={toast.description} />
426 )}
427 </div>
428 <Toast.Description
429 className="min-w-0 select-text wrap-break-word text-muted-foreground"
430 data-slot="toast-description"
431 />
432 </div>
433 </div>
434 {toast.actionProps && (
435 <Toast.Action
436 className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
437 data-slot="toast-action"
438 >
439 {toast.actionProps.children}
440 </Toast.Action>
441 )}
442 </Toast.Content>
443 )}
444 </Toast.Root>
445 </Toast.Positioner>
446 );
447 })}
448 </Toast.Viewport>
449 </Toast.Portal>
450 );
451}
452
453export {
454 ToastProvider,
455 type ToastPosition,
456 toastManager,
457 AnchoredToastProvider,
458 anchoredToastManager,
459};