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