Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

toast.tsx

772 lines29.8 KB

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