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