Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

toast.tsx

443 lines19.5 KB

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