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