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