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