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