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