Open History to see the last commit
1"use client";
2
3import { Toast } from "@base-ui/react/toast";
4import {
5 useEffect,
6 useMemo,
7 useState,
8 type CSSProperties,
9 type ComponentPropsWithoutRef,
10 type KeyboardEvent,
11 type ReactNode,
12} from "react";
13import { useParams } from "@tanstack/react-router";
14import { type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
15import {
16 CheckIcon,
17 ChevronDownIcon,
18 ChevronUpIcon,
19 CircleAlertIcon,
20 CircleCheckIcon,
21 CopyIcon,
22 InfoIcon,
23 LoaderCircleIcon,
24 TriangleAlertIcon,
25 XIcon,
26} from "lucide-react";
27
28import { cn } from "~/lib/utils";
29import { buttonVariants } from "~/components/ui/button";
30import { useComposerDraftStore } from "~/composerDraftStore";
31import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
32import { resolveThreadRouteTarget } from "~/threadRoutes";
33import {
34 buildVisibleToastLayout,
35 shouldHideCollapsedToastContent,
36 shouldRenderThreadScopedToast,
37} from "./toast.logic";
38
39export type ThreadToastData = {
40 threadRef?: ScopedThreadRef | null;
41 threadId?: ThreadId | null;
42 leadingIcon?: ReactNode;
43 tooltipStyle?: boolean;
44 onClose?: (() => void) | undefined;
45 dismissAfterVisibleMs?: number;
46 hideCopyButton?: boolean;
47 secondaryActionProps?: ComponentPropsWithoutRef<"button">;
48 secondaryActionVariant?:
49 | "default"
50 | "destructive"
51 | "destructive-outline"
52 | "ghost"
53 | "link"
54 | "outline"
55 | "secondary";
56 /** Optional extra body shown after toggling “Show details” (e.g. a list of pending RPCs). */
57 expandableContent?: ReactNode;
58 expandableLabels?: { expand?: string; collapse?: string };
59 /** When set with `expandableContent`, the summary + label act as one text disclosure (no separate chevron row). */
60 expandableDescriptionTrigger?: boolean;
61 actionLayout?: "inline" | "stacked-end";
62 actionVariant?:
63 | "default"
64 | "destructive"
65 | "destructive-outline"
66 | "ghost"
67 | "link"
68 | "outline"
69 | "secondary";
70};
71
72const toastManager = Toast.createToastManager<ThreadToastData>();
73const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
74type ToastId = ReturnType<typeof toastManager.add>;
75const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
76
77const TOAST_ICONS = {
78 error: CircleAlertIcon,
79 info: InfoIcon,
80 loading: LoaderCircleIcon,
81 success: CircleCheckIcon,
82 warning: TriangleAlertIcon,
83} as const;
84
85/** Visually shorten long error bodies; clipboard copy still uses the full `description` string. */
86const ERROR_DESCRIPTION_CLAMP_MIN_CHARS = 180;
87function errorDescriptionClampClass(type: unknown, description: unknown): string | undefined {
88 if (type !== "error" || typeof description !== "string") {
89 return undefined;
90 }
91 if (description.length < ERROR_DESCRIPTION_CLAMP_MIN_CHARS) {
92 return undefined;
93 }
94 return "line-clamp-4";
95}
96
97/** Dismiss-only: circular control overlapping the card corner (iOS notification–style). */
98const toastCornerDismissClass = "absolute z-20 -top-1.5 -right-1.5";
99const toastCornerOrbClass = cn(
100 "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border/60 bg-popover/92 text-muted-foreground shadow-sm outline-none backdrop-blur-sm",
101 "transition-[color,background-color,box-shadow] hover:bg-popover hover:text-foreground",
102 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
103);
104
105function handleToastDismissClick(
106 manager: typeof toastManager | typeof anchoredToastManager,
107 toastId: ToastId,
108 onClose: (() => void) | undefined,
109) {
110 onClose?.();
111 manager.close(toastId);
112}
113
114function CopyErrorButton({ text }: { text: string }) {
115 const { copyToClipboard, isCopied } = useCopyToClipboard();
116
117 return (
118 <button
119 className="inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md p-0 text-muted-foreground/80 transition-colors hover:text-muted-foreground"
120 onClick={() => copyToClipboard(text)}
121 title="Copy error"
122 type="button"
123 >
124 {isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
125 </button>
126 );
127}
128
129/** Scrollable cap for long expandable lists (~10rem); keeps the toast from growing without bound. */
130const toastExpandablePanelClassName =
131 "mt-2 max-h-40 min-h-0 overflow-y-auto overscroll-contain pr-0.5 select-text";
132
133function ToastExpandableSection({
134 children,
135 labels,
136}: {
137 children: ReactNode;
138 labels: { expand?: string; collapse?: string };
139}) {
140 const [open, setOpen] = useState(false);
141 const expandLabel = labels.expand ?? "Show details";
142 const collapseLabel = labels.collapse ?? "Hide details";
143
144 return (
145 <div className="min-w-0">
146 <button
147 aria-expanded={open}
148 className="inline-flex cursor-pointer items-center gap-1 rounded-md py-0.5 text-left text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
149 onClick={() => setOpen((prev) => !prev)}
150 type="button"
151 >
152 {open ? (
153 <ChevronUpIcon className="size-3.5 shrink-0 opacity-80" strokeWidth={2.25} />
154 ) : (
155 <ChevronDownIcon className="size-3.5 shrink-0 opacity-80" strokeWidth={2.25} />
156 )}
157 {open ? collapseLabel : expandLabel}
158 </button>
159 {open ? <div className={toastExpandablePanelClassName}>{children}</div> : null}
160 </div>
161 );
162}
163
164function ToastDescriptionAndExpandable({
165 toastData,
166 toastDescription,
167 toastType,
168}: {
169 toastData: ThreadToastData | undefined;
170 toastDescription: unknown;
171 toastType: unknown;
172}) {
173 const expandableContent = toastData?.expandableContent;
174 const labels = toastData?.expandableLabels ?? {};
175 const descriptionTrigger = toastData?.expandableDescriptionTrigger ?? false;
176 const descriptionClassName = cn(
177 "min-w-0 select-text wrap-break-word text-muted-foreground",
178 errorDescriptionClampClass(toastType, toastDescription),
179 );
180 const [open, setOpen] = useState(false);
181
182 if (!expandableContent) {
183 return <Toast.Description className={descriptionClassName} data-slot="toast-description" />;
184 }
185
186 if (!descriptionTrigger) {
187 return (
188 <>
189 <Toast.Description className={descriptionClassName} data-slot="toast-description" />
190 <ToastExpandableSection labels={labels}>{expandableContent}</ToastExpandableSection>
191 </>
192 );
193 }
194
195 const expandLabel = labels.expand ?? "Show details";
196 const collapseLabel = labels.collapse ?? "Hide details";
197
198 const toggle = () => setOpen((v) => !v);
199 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
200 if (event.key === "Enter" || event.key === " ") {
201 event.preventDefault();
202 toggle();
203 }
204 };
205
206 return (
207 <>
208 <div
209 aria-expanded={open}
210 className={cn(
211 "group flex min-w-0 w-full cursor-pointer select-none items-start gap-1.5 rounded-sm text-left outline-none ring-offset-background",
212 "transition-colors hover:bg-muted/40",
213 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
214 )}
215 onClick={toggle}
216 onKeyDown={onKeyDown}
217 role="button"
218 tabIndex={0}
219 title={open ? collapseLabel : expandLabel}
220 >
221 <div className="min-w-0 flex-1">
222 <Toast.Description
223 className={cn(
224 "min-w-0 select-none wrap-break-word text-muted-foreground",
225 errorDescriptionClampClass(toastType, toastDescription),
226 "underline-offset-2 decoration-muted-foreground/60 group-hover:underline",
227 )}
228 data-slot="toast-description"
229 />
230 </div>
231 {open ? (
232 <ChevronUpIcon
233 aria-hidden
234 className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
235 strokeWidth={2.25}
236 />
237 ) : (
238 <ChevronDownIcon
239 aria-hidden
240 className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
241 strokeWidth={2.25}
242 />
243 )}
244 </div>
245 {open ? <div className={toastExpandablePanelClassName}>{expandableContent}</div> : null}
246 </>
247 );
248}
249
250type ToastIconComponent = (typeof TOAST_ICONS)[keyof typeof TOAST_ICONS];
251
252interface ToastBodyDescriptor {
253 readonly Icon: ToastIconComponent | null | undefined;
254 readonly stackedActionLayout: boolean;
255 readonly actionVariant: NonNullable<ThreadToastData["actionVariant"]>;
256 readonly secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]>;
257 readonly copyErrorText: string | null;
258 readonly hasTrailingControls: boolean;
259 readonly inlineContentEndPad: string;
260}
261
262function deriveToastBodyDescriptor(toast: {
263 readonly type?: string | undefined;
264 readonly description?: unknown;
265 readonly actionProps?: unknown;
266 readonly data?: ThreadToastData | undefined;
267}): ToastBodyDescriptor {
268 const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
269 const stackedActionLayout =
270 toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end";
271 const actionVariant: NonNullable<ThreadToastData["actionVariant"]> =
272 toast.data?.actionVariant ?? "default";
273 const secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]> =
274 toast.data?.secondaryActionVariant ?? "outline";
275 const copyErrorText =
276 toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton
277 ? toast.description
278 : null;
279 const hasSecondaryAction = toast.data?.secondaryActionProps !== undefined;
280 const hasTrailingControls =
281 copyErrorText !== null || toast.actionProps !== undefined || hasSecondaryAction;
282 const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10";
283 return {
284 Icon,
285 stackedActionLayout,
286 actionVariant,
287 secondaryActionVariant,
288 copyErrorText,
289 hasTrailingControls,
290 inlineContentEndPad,
291 };
292}
293
294interface ToastBodyContentProps extends ToastBodyDescriptor {
295 readonly actionProps: { readonly children?: ReactNode } | undefined;
296 readonly toastData: ThreadToastData | undefined;
297 readonly toastDescription: unknown;
298 readonly toastType: unknown;
299}
300
301function ToastBodyContent({
302 stackedActionLayout,
303 Icon,
304 copyErrorText,
305 actionProps,
306 actionVariant,
307 secondaryActionVariant,
308 hasTrailingControls,
309 toastData,
310 toastDescription,
311 toastType,
312}: ToastBodyContentProps) {
313 const secondaryActionProps = toastData?.secondaryActionProps;
314 const leadingIcon = toastData?.leadingIcon;
315 const { className: secondaryActionClassName, ...secondaryActionRest } =
316 secondaryActionProps ?? {};
317
318 return (
319 <>
320 <div className={cn("flex min-w-0 gap-2", !stackedActionLayout && "flex-1")}>
321 {leadingIcon ? (
322 <div
323 className="flex h-lh w-4 shrink-0 items-center justify-center"
324 data-slot="toast-icon"
325 >
326 {leadingIcon}
327 </div>
328 ) : Icon ? (
329 <div
330 className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
331 data-slot="toast-icon"
332 >
333 <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" />
334 </div>
335 ) : null}
336 <div
337 className={cn(
338 "flex min-h-0 min-w-0 flex-1 flex-col gap-0.5",
339 stackedActionLayout && "pr-5",
340 )}
341 >
342 <Toast.Title className="min-w-0 wrap-break-word font-medium" data-slot="toast-title" />
343 <ToastDescriptionAndExpandable
344 toastData={toastData}
345 toastDescription={toastDescription}
346 toastType={toastType}
347 />
348 </div>
349 </div>
350 {hasTrailingControls ? (
351 <div
352 className={cn(
353 "flex items-center gap-1.5",
354 stackedActionLayout ? "w-full justify-end" : "shrink-0",
355 )}
356 >
357 {copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
358 {secondaryActionProps ? (
359 <button
360 {...secondaryActionRest}
361 className={cn(
362 buttonVariants({ size: "xs", variant: secondaryActionVariant }),
363 secondaryActionClassName,
364 )}
365 type="button"
366 />
367 ) : null}
368 {actionProps ? (
369 <Toast.Action
370 className={cn(buttonVariants({ size: "xs", variant: actionVariant }), "shrink-0")}
371 data-slot="toast-action"
372 >
373 {actionProps.children}
374 </Toast.Action>
375 ) : null}
376 </div>
377 ) : null}
378 </>
379 );
380}
381
382type ToastPosition =
383 | "top-left"
384 | "top-center"
385 | "top-right"
386 | "bottom-left"
387 | "bottom-center"
388 | "bottom-right";
389
390interface ToastProviderProps extends Toast.Provider.Props {
391 position?: ToastPosition;
392}
393
394function useActiveThreadRefFromRoute(): ScopedThreadRef | null {
395 const routeTarget = useParams({
396 strict: false,
397 select: (params) => resolveThreadRouteTarget(params),
398 });
399 const activeDraftSession = useComposerDraftStore((store) =>
400 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
401 );
402
403 return useMemo(() => {
404 if (routeTarget?.kind === "server") {
405 return routeTarget.threadRef;
406 }
407 if (routeTarget?.kind === "draft" && activeDraftSession) {
408 return {
409 environmentId: activeDraftSession.environmentId,
410 threadId: activeDraftSession.threadId,
411 };
412 }
413 return null;
414 }, [activeDraftSession, routeTarget]);
415}
416
417function ThreadToastVisibleAutoDismiss({
418 toastId,
419 dismissAfterVisibleMs,
420}: {
421 toastId: ToastId;
422 dismissAfterVisibleMs: number | undefined;
423}) {
424 useEffect(() => {
425 if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
426 if (typeof window === "undefined" || typeof document === "undefined") return;
427
428 let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
429 let startedAtMs: number | null = null;
430 let timeoutId: number | null = null;
431 let closed = false;
432
433 const clearTimer = () => {
434 if (timeoutId === null) return;
435 window.clearTimeout(timeoutId);
436 timeoutId = null;
437 };
438
439 const closeToast = () => {
440 if (closed) return;
441 closed = true;
442 threadToastVisibleTimeoutRemainingMs.delete(toastId);
443 toastManager.close(toastId);
444 };
445
446 const pause = () => {
447 if (startedAtMs === null) return;
448 remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
449 startedAtMs = null;
450 clearTimer();
451 threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
452 };
453
454 const start = () => {
455 if (closed || startedAtMs !== null) return;
456 if (remainingMs <= 0) {
457 closeToast();
458 return;
459 }
460 startedAtMs = Date.now();
461 clearTimer();
462 timeoutId = window.setTimeout(() => {
463 remainingMs = 0;
464 startedAtMs = null;
465 closeToast();
466 }, remainingMs);
467 };
468
469 const syncTimer = () => {
470 const shouldRun = document.visibilityState === "visible" && document.hasFocus();
471 if (shouldRun) {
472 start();
473 return;
474 }
475 pause();
476 };
477
478 syncTimer();
479 document.addEventListener("visibilitychange", syncTimer);
480 window.addEventListener("focus", syncTimer);
481 window.addEventListener("blur", syncTimer);
482
483 return () => {
484 document.removeEventListener("visibilitychange", syncTimer);
485 window.removeEventListener("focus", syncTimer);
486 window.removeEventListener("blur", syncTimer);
487 pause();
488 clearTimer();
489 };
490 }, [dismissAfterVisibleMs, toastId]);
491
492 return null;
493}
494
495function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
496 return (
497 <Toast.Provider toastManager={toastManager} {...props}>
498 {children}
499 <Toasts position={position} />
500 </Toast.Provider>
501 );
502}
503
504function Toasts({ position = "top-right" }: { position: ToastPosition }) {
505 const { toasts } = Toast.useToastManager<ThreadToastData>();
506 const activeThreadRef = useActiveThreadRefFromRoute();
507 const isTop = position.startsWith("top");
508 const visibleToasts = toasts.filter((toast) =>
509 shouldRenderThreadScopedToast(toast.data, activeThreadRef),
510 );
511 const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
512
513 useEffect(() => {
514 const activeToastIds = new Set(toasts.map((toast) => toast.id));
515 for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
516 if (!activeToastIds.has(toastId)) {
517 threadToastVisibleTimeoutRemainingMs.delete(toastId);
518 }
519 }
520 }, [toasts]);
521
522 return (
523 <Toast.Portal data-slot="toast-portal">
524 <Toast.Viewport
525 className={cn(
526 "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)]",
527 // Vertical positioning
528 "data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
529 "data-[position*=bottom]:bottom-(--toast-inset)",
530 // Horizontal positioning
531 "data-[position*=left]:left-(--toast-inset)",
532 "data-[position*=right]:right-(--toast-inset)",
533 "data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
534 )}
535 data-position={position}
536 data-slot="toast-viewport"
537 style={
538 {
539 "--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
540 } as CSSProperties
541 }
542 >
543 {visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
544 const hideCollapsedContent = shouldHideCollapsedToastContent(
545 visibleIndex,
546 visibleToastLayout.items.length,
547 );
548 const bodyDescriptor = deriveToastBodyDescriptor(toast);
549 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
550
551 return (
552 <Toast.Root
553 className={cn(
554 "absolute z-[calc(9999-var(--toast-index))] w-full overflow-visible 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%)]",
555 // Base positioning using data-position
556 "data-[position*=right]:right-0 data-[position*=right]:left-auto",
557 "data-[position*=left]:right-auto data-[position*=left]:left-0",
558 "data-[position*=center]:right-0 data-[position*=center]:left-0",
559 "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
560 "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
561 // Gap fill for hover
562 "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
563 "data-[position*=top]:after:top-full",
564 "data-[position*=bottom]:after:bottom-full",
565 // `--toast-calc-height`: behind + collapsed = peek height only (content `opacity-0`);
566 // max(front, own) there produced a tall empty shell for long bodies.
567 visibleIndex > 0
568 ? "not-data-expanded:[--toast-calc-height:var(--toast-frontmost-height)] data-expanded:[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]"
569 : "[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]",
570 "[--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))]",
571 // Root height: never `min-h-(--toast-height)` — Base UI measures height by briefly forcing
572 // `height: auto` on this node; an old `min-height` from `--toast-height` blocks shrinking,
573 // so `recalculateHeight` keeps the inflated value after an expandable closes.
574 // Behind + collapsed: fixed peek. Otherwise natural height (expand/collapse, hover stack).
575 visibleIndex > 0
576 ? "not-data-expanded:h-(--toast-calc-height) data-expanded:h-auto"
577 : "h-auto",
578 // Define offset-y variable
579 "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
580 "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))]",
581 // Default state transform
582 "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))]",
583 "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))]",
584 // Limited state
585 "data-limited:opacity-0",
586 // Expanded stack
587 "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
588 // Starting and ending animations
589 "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
590 "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
591 "data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
592 "data-ending-style:opacity-0",
593 // Ending animations (direction-aware)
594 "data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
595 "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))]",
596 "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))]",
597 "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))]",
598 "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
599 "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
600 // Ending animations (expanded)
601 "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))]",
602 "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))]",
603 "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
604 "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
605 )}
606 data-position={position}
607 key={toast.id}
608 style={
609 {
610 "--toast-index": visibleIndex,
611 "--toast-offset-y": `${offsetY}px`,
612 } as CSSProperties
613 }
614 swipeDirection={
615 position.includes("center")
616 ? [isTop ? "up" : "down"]
617 : position.includes("left")
618 ? ["left", isTop ? "up" : "down"]
619 : ["right", isTop ? "up" : "down"]
620 }
621 toast={toast}
622 >
623 <ThreadToastVisibleAutoDismiss
624 dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
625 toastId={toast.id}
626 />
627 <div className={toastCornerDismissClass}>
628 <button
629 aria-label="Dismiss notification"
630 className={toastCornerOrbClass}
631 data-slot="toast-close"
632 onClick={() =>
633 handleToastDismissClick(toastManager, toast.id, toast.data?.onClose)
634 }
635 type="button"
636 >
637 <XIcon className="size-3" strokeWidth={2.25} />
638 </button>
639 </div>
640 <Toast.Content
641 className={cn(
642 // `overflow-x: clip` avoids the CSS quirk where pairing `hidden` + `y: visible`
643 // forces `y` to `auto`. Expandable detail panels can extend below without being cut off.
644 "pointer-events-auto min-h-0 overflow-y-visible pl-3.5 text-sm transition-opacity duration-250 [overflow-x:clip] data-expanded:opacity-100",
645 stackedActionLayout
646 ? "flex flex-col gap-2 py-2.5 pr-3.5"
647 : cn("py-3", "flex items-center justify-between gap-1.5", inlineContentEndPad),
648 hideCollapsedContent &&
649 "not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
650 )}
651 >
652 <ToastBodyContent
653 {...bodyDescriptor}
654 actionProps={toast.actionProps}
655 toastData={toast.data}
656 toastDescription={toast.description}
657 toastType={toast.type}
658 />
659 </Toast.Content>
660 </Toast.Root>
661 );
662 })}
663 </Toast.Viewport>
664 </Toast.Portal>
665 );
666}
667
668function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
669 return (
670 <Toast.Provider toastManager={anchoredToastManager} {...props}>
671 {children}
672 <AnchoredToasts />
673 </Toast.Provider>
674 );
675}
676
677function AnchoredToasts() {
678 const { toasts } = Toast.useToastManager<ThreadToastData>();
679 const activeThreadRef = useActiveThreadRefFromRoute();
680
681 return (
682 <Toast.Portal data-slot="toast-portal-anchored">
683 <Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
684 {toasts
685 .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
686 .map((toast) => {
687 const tooltipStyle = toast.data?.tooltipStyle ?? false;
688 const positionerProps = toast.positionerProps;
689 const bodyDescriptor = deriveToastBodyDescriptor(toast);
690 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
691
692 if (!positionerProps?.anchor) {
693 return null;
694 }
695
696 return (
697 <Toast.Positioner
698 className="z-100 max-w-[min(--spacing(64),var(--available-width))]"
699 data-slot="toast-positioner"
700 key={toast.id}
701 sideOffset={positionerProps.sideOffset ?? 4}
702 toast={toast}
703 >
704 <Toast.Root
705 className={cn(
706 "relative overflow-visible 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%)]",
707 tooltipStyle
708 ? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
709 : "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
710 )}
711 data-slot="toast-popup"
712 toast={toast}
713 >
714 {tooltipStyle ? (
715 <Toast.Content className="pointer-events-auto px-2 py-1">
716 <Toast.Title data-slot="toast-title" />
717 </Toast.Content>
718 ) : (
719 <>
720 <div className={toastCornerDismissClass}>
721 <button
722 aria-label="Dismiss notification"
723 className={toastCornerOrbClass}
724 data-slot="toast-close"
725 onClick={() =>
726 handleToastDismissClick(
727 anchoredToastManager,
728 toast.id,
729 toast.data?.onClose,
730 )
731 }
732 type="button"
733 >
734 <XIcon className="size-3" strokeWidth={2.25} />
735 </button>
736 </div>
737 <Toast.Content
738 className={cn(
739 "pointer-events-auto min-h-0 overflow-y-visible pl-3.5 text-sm [overflow-x:clip]",
740 stackedActionLayout
741 ? "flex flex-col gap-2 py-2.5 pr-3.5"
742 : cn(
743 "py-3",
744 "flex items-center justify-between gap-1.5",
745 inlineContentEndPad,
746 ),
747 )}
748 >
749 <ToastBodyContent
750 {...bodyDescriptor}
751 actionProps={toast.actionProps}
752 toastData={toast.data}
753 toastDescription={toast.description}
754 toastType={toast.type}
755 />
756 </Toast.Content>
757 </>
758 )}
759 </Toast.Root>
760 </Toast.Positioner>
761 );
762 })}
763 </Toast.Viewport>
764 </Toast.Portal>
765 );
766}
767
768export { stackedThreadToast } from "./toastHelpers";
769export type { StackedThreadToastOptions } from "./toastHelpers";
770
771export {
772 ToastProvider,
773 type ToastPosition,
774 toastManager,
775 AnchoredToastProvider,
776 anchoredToastManager,
777};