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

toast.tsx

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