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