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

toast.tsx

811 lines31.5 KB

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 { Button, buttonVariants } from "~/components/ui/button";
30import { useComposerDraftStore } from "~/composerDraftStore";
31import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
32import { resolveThreadRouteTarget } from "~/threadRoutes";
33import {
34 buildVisibleToastLayout,
35 hasVisibleToastAction,
36 shouldHideCollapsedToastContent,
37 shouldRenderThreadScopedToast,
38} from "./toast.logic";
39import { Tooltip, TooltipPopup, TooltipTrigger } from "./tooltip";
40​
41export type ThreadToastData = {
42 threadRef?: ScopedThreadRef | null;
43 threadId?: ThreadId | null;
44 leadingIcon?: ReactNode;
45 tooltipStyle?: boolean;
46 onClose?: (() => void) | undefined;
47 dismissAfterVisibleMs?: number;
48 hideCopyButton?: boolean;
49 additionalActions?: ReadonlyArray<{
50 id: string;
51 props: ComponentPropsWithoutRef<"button">;
52 }>;
53 secondaryActionProps?: ComponentPropsWithoutRef<"button">;
54 secondaryActionVariant?:
55 | "default"
56 | "destructive"
57 | "destructive-outline"
58 | "ghost"
59 | "link"
60 | "outline"
61 | "secondary";
62 /** Optional extra body shown after toggling “Show details” (e.g. a list of pending RPCs). */
63 expandableContent?: ReactNode;
64 expandableLabels?: { expand?: string; collapse?: string };
65 /** When set with `expandableContent`, the summary + label act as one text disclosure (no separate chevron row). */
66 expandableDescriptionTrigger?: boolean;
67 actionLayout?: "inline" | "stacked-end";
68 actionVariant?:
69 | "default"
70 | "destructive"
71 | "destructive-outline"
72 | "ghost"
73 | "link"
74 | "outline"
75 | "secondary";
76};
77​
78const toastManager = Toast.createToastManager<ThreadToastData>();
79const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
80type ToastId = ReturnType<typeof toastManager.add>;
81const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
82​
83const TOAST_ICONS = {
84 error: CircleAlertIcon,
85 info: InfoIcon,
86 loading: LoaderCircleIcon,
87 success: CircleCheckIcon,
88 warning: TriangleAlertIcon,
89} as const;
90​
91/** Visually shorten long error bodies; clipboard copy still uses the full `description` string. */
92const ERROR_DESCRIPTION_CLAMP_MIN_CHARS = 180;
93function errorDescriptionClampClass(type: unknown, description: unknown): string | undefined {
94 if (type !== "error" || typeof description !== "string") {
95 return undefined;
96 }
97 if (description.length < ERROR_DESCRIPTION_CLAMP_MIN_CHARS) {
98 return undefined;
99 }
100 return "line-clamp-4";
102​
103/** Dismiss-only: circular control overlapping the card corner (iOS notification–style). */
104const toastCornerDismissClass = "absolute z-20 -top-1.5 -right-1.5";
105const toastCornerOrbClass = cn(
106 "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",
107 "transition-[color,background-color,box-shadow] hover:bg-popover hover:text-foreground",
108 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
109);
110​
111function handleToastDismissClick(
112 manager: typeof toastManager | typeof anchoredToastManager,
113 toastId: ToastId,
114 onClose: (() => void) | undefined,
115) {
116 onClose?.();
117 manager.close(toastId);
119​
120function CopyErrorButton({ text }: { text: string }) {
121 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "error-message" });
122 const label = isCopied ? "Copied error" : "Copy error";
123​
124 return (
125 <Tooltip>
126 <TooltipTrigger
127 render={
128 <Button
129 size="icon-micro"
130 variant="ghost-muted"
131 aria-label={label}
132 className="[--control-icon-color:currentColor] rounded-md text-muted-foreground/80 hover:bg-transparent hover:text-muted-foreground"
133 onClick={() => copyToClipboard(text)}
134 />
135 }
136 >
137 {isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
138 </TooltipTrigger>
139 <TooltipPopup side="top">{label}</TooltipPopup>
140 </Tooltip>
141 );
143​
144/** Scrollable cap for long expandable lists (~10rem); keeps the toast from growing without bound. */
145const toastExpandablePanelClassName =
146 "mt-2 max-h-40 min-h-0 overflow-y-auto overscroll-contain pr-0.5 select-text";
147​
148function ToastExpandableSection({
149 children,
150 labels,
151}: {
152 children: ReactNode;
153 labels: { expand?: string; collapse?: string };
154}) {
155 const [open, setOpen] = useState(false);
156 const expandLabel = labels.expand ?? "Show details";
157 const collapseLabel = labels.collapse ?? "Hide details";
158​
159 return (
160 <div className="min-w-0">
161 <button
162 aria-expanded={open}
163 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"
164 onClick={() => setOpen((prev) => !prev)}
165 type="button"
166 >
167 {open ? (
168 <ChevronUpIcon className="size-3.5 shrink-0 opacity-80" strokeWidth={2.25} />
169 ) : (
170 <ChevronDownIcon className="size-3.5 shrink-0 opacity-80" strokeWidth={2.25} />
171 )}
172 {open ? collapseLabel : expandLabel}
173 </button>
174 {open ? <div className={toastExpandablePanelClassName}>{children}</div> : null}
175 </div>
176 );
178​
179function ToastDescriptionAndExpandable({
180 toastData,
181 toastDescription,
182 toastType,
183}: {
184 toastData: ThreadToastData | undefined;
185 toastDescription: unknown;
186 toastType: unknown;
187}) {
188 const expandableContent = toastData?.expandableContent;
189 const labels = toastData?.expandableLabels ?? {};
190 const descriptionTrigger = toastData?.expandableDescriptionTrigger ?? false;
191 const descriptionClassName = cn(
192 "min-w-0 select-text wrap-break-word text-muted-foreground",
193 errorDescriptionClampClass(toastType, toastDescription),
194 );
195 const [open, setOpen] = useState(false);
196​
197 if (!expandableContent) {
198 return <Toast.Description className={descriptionClassName} data-slot="toast-description" />;
199 }
200​
201 if (!descriptionTrigger) {
202 return (
203 <>
204 <Toast.Description className={descriptionClassName} data-slot="toast-description" />
205 <ToastExpandableSection labels={labels}>{expandableContent}</ToastExpandableSection>
206 </>
207 );
208 }
209​
210 const expandLabel = labels.expand ?? "Show details";
211 const collapseLabel = labels.collapse ?? "Hide details";
212​
213 const toggle = () => setOpen((v) => !v);
214 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
215 if (event.key === "Enter" || event.key === " ") {
216 event.preventDefault();
217 toggle();
218 }
219 };
220​
221 return (
222 <>
223 <Tooltip>
224 <TooltipTrigger
225 render={
226 <div
227 aria-label={open ? collapseLabel : expandLabel}
228 aria-expanded={open}
229 className={cn(
230 "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",
231 "transition-colors hover:bg-muted/40",
232 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
233 )}
234 onClick={toggle}
235 onKeyDown={onKeyDown}
236 role="button"
237 tabIndex={0}
238 />
239 }
240 >
241 <div className="min-w-0 flex-1">
242 <Toast.Description
243 className={cn(
244 "min-w-0 select-none wrap-break-word text-muted-foreground",
245 errorDescriptionClampClass(toastType, toastDescription),
246 "underline-offset-2 decoration-muted-foreground/60 group-hover:underline",
247 )}
248 data-slot="toast-description"
249 />
250 </div>
251 {open ? (
252 <ChevronUpIcon
253 aria-hidden
254 className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
255 strokeWidth={2.25}
256 />
257 ) : (
258 <ChevronDownIcon
259 aria-hidden
260 className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
261 strokeWidth={2.25}
262 />
263 )}
264 </TooltipTrigger>
265 <TooltipPopup side="top">{open ? collapseLabel : expandLabel}</TooltipPopup>
266 </Tooltip>
267 {open ? <div className={toastExpandablePanelClassName}>{expandableContent}</div> : null}
268 </>
269 );
271​
272type ToastIconComponent = (typeof TOAST_ICONS)[keyof typeof TOAST_ICONS];
273​
274interface ToastBodyDescriptor {
275 readonly Icon: ToastIconComponent | null | undefined;
276 readonly stackedActionLayout: boolean;
277 readonly actionVariant: NonNullable<ThreadToastData["actionVariant"]>;
278 readonly secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]>;
279 readonly copyErrorText: string | null;
280 readonly hasTrailingControls: boolean;
281 readonly inlineContentEndPad: string;
283​
284function deriveToastBodyDescriptor(toast: {
285 readonly type?: string | undefined;
286 readonly description?: unknown;
287 readonly actionProps?: unknown;
288 readonly data?: ThreadToastData | undefined;
289}): ToastBodyDescriptor {
290 const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
291 const stackedActionLayout =
292 hasVisibleToastAction(toast.actionProps) && toast.data?.actionLayout === "stacked-end";
293 const actionVariant: NonNullable<ThreadToastData["actionVariant"]> =
294 toast.data?.actionVariant ?? "default";
295 const secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]> =
296 toast.data?.secondaryActionVariant ?? "outline";
297 const copyErrorText =
298 toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton
299 ? toast.description
300 : null;
301 const hasAdditionalActions = (toast.data?.additionalActions?.length ?? 0) > 0;
302 const hasSecondaryAction = toast.data?.secondaryActionProps !== undefined;
303 const hasTrailingControls =
304 copyErrorText !== null ||
305 hasVisibleToastAction(toast.actionProps) ||
306 hasAdditionalActions ||
307 hasSecondaryAction;
308 const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10";
309 return {
310 Icon,
311 stackedActionLayout,
312 actionVariant,
313 secondaryActionVariant,
314 copyErrorText,
315 hasTrailingControls,
316 inlineContentEndPad,
317 };
319​
320interface ToastBodyContentProps extends ToastBodyDescriptor {
321 readonly actionProps: { readonly children?: ReactNode } | undefined;
322 readonly toastData: ThreadToastData | undefined;
323 readonly toastDescription: unknown;
324 readonly toastType: unknown;
326​
327function ToastBodyContent({
328 stackedActionLayout,
329 Icon,
330 copyErrorText,
331 actionProps,
332 actionVariant,
333 secondaryActionVariant,
334 hasTrailingControls,
335 toastData,
336 toastDescription,
337 toastType,
338}: ToastBodyContentProps) {
339 const additionalActions = toastData?.additionalActions ?? [];
340 const secondaryActionProps = toastData?.secondaryActionProps;
341 const leadingIcon = toastData?.leadingIcon;
342 const { className: secondaryActionClassName, ...secondaryActionRest } =
343 secondaryActionProps ?? {};
344​
345 return (
346 <>
347 <div className={cn("flex min-w-0 gap-2", !stackedActionLayout && "flex-1")}>
348 {leadingIcon ? (
349 <div
350 className="flex h-lh w-4 shrink-0 items-center justify-center"
351 data-slot="toast-icon"
352 >
353 {leadingIcon}
354 </div>
355 ) : Icon ? (
356 <div
357 className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
358 data-slot="toast-icon"
359 >
360 <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" />
361 </div>
362 ) : null}
363 <div
364 className={cn(
365 "flex min-h-0 min-w-0 flex-1 flex-col gap-0.5",
366 stackedActionLayout && "pr-5",
367 )}
368 >
369 <Toast.Title className="min-w-0 wrap-break-word font-medium" data-slot="toast-title" />
370 <ToastDescriptionAndExpandable
371 toastData={toastData}
372 toastDescription={toastDescription}
373 toastType={toastType}
374 />
375 </div>
376 </div>
377 {hasTrailingControls ? (
378 <div
379 className={cn(
380 "flex items-center gap-1.5",
381 stackedActionLayout ? "w-full justify-end" : "shrink-0",
382 )}
383 >
384 {copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
385 {additionalActions.map(({ id, props: { className, ...props } }) => (
386 <Button
387 {...props}
388 className={className}
389 key={id}
390 size="xs"
391 type="button"
392 variant={secondaryActionVariant}
393 />
394 ))}
395 {secondaryActionProps ? (
396 <Button
397 {...secondaryActionRest}
398 className={secondaryActionClassName}
399 size="xs"
400 type="button"
401 variant={secondaryActionVariant}
402 />
403 ) : null}
404 {hasVisibleToastAction(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 );
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;
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]);
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;
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 );
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 );
703​
704function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
705 return (
706 <Toast.Provider toastManager={anchoredToastManager} {...props}>
707 {children}
708 <AnchoredToasts />
709 </Toast.Provider>
710 );
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 );
801​
802export { hiddenToastActionProps, stackedThreadToast } from "./toastHelpers";
803export type { StackedThreadToastOptions } from "./toastHelpers";
804​
805export {
806 ToastProvider,
807 type ToastPosition,
808 toastManager,
809 AnchoredToastProvider,
810 anchoredToastManager,
811};