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