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

toast.tsx

775 lines29.7 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-3.5";
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
334 className={cn(
335 "flex min-w-0 gap-2",
336 !stackedActionLayout && !hasTrailingControls && "pr-6",
337 )}
338 >
339 {leadingIcon ? (
340 <div
341 className="flex h-lh w-4 shrink-0 items-center justify-center"
342 data-slot="toast-icon"
343 >
344 {leadingIcon}
345 </div>
346 ) : Icon ? (
347 <div
348 className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
349 data-slot="toast-icon"
350 >
351 <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" />
352 </div>
353 ) : null}
354 <Toast.Title className="min-w-0 wrap-break-word font-medium" data-slot="toast-title" />
355 </div>
356 <ToastDescriptionAndExpandable
357 toastData={toastData}
358 toastDescription={toastDescription}
359 toastType={toastType}
360 />
361 </div>
362 {hasTrailingControls ? (
363 <div
364 className={cn(
365 "flex items-center gap-1.5",
366 stackedActionLayout ? "w-full justify-end" : "shrink-0",
367 )}
368 >
369 {copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
370 {additionalActions.map(({ id, props: { className, ...props } }) => (
371 <Button
372 {...props}
373 className={className}
374 key={id}
375 size="xs"
376 type="button"
377 variant={secondaryActionVariant}
378 />
379 ))}
380 {secondaryActionProps ? (
381 <Button
382 {...secondaryActionRest}
383 className={secondaryActionClassName}
384 size="xs"
385 type="button"
386 variant={secondaryActionVariant}
387 />
388 ) : null}
389 {hasVisibleToastAction(actionProps) ? (
390 <Toast.Action
391 className={cn(buttonVariants({ size: "xs", variant: actionVariant }), "shrink-0")}
392 data-slot="toast-action"
393 >
394 {actionProps?.children}
395 </Toast.Action>
396 ) : null}
397 </div>
398 ) : null}
399 </>
400 );
402​
403type ToastPosition =
404 | "top-left"
405 | "top-center"
406 | "top-right"
407 | "bottom-left"
408 | "bottom-center"
409 | "bottom-right";
410​
411interface ToastProviderProps extends Toast.Provider.Props {
412 position?: ToastPosition;
414​
415function useActiveThreadRefFromRoute(): ScopedThreadRef | null {
416 const routeTarget = useThreadRouteTarget();
417 const activeDraftSession = useComposerDraftStore((store) =>
418 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
419 );
420​
421 if (routeTarget?.kind === "server") {
422 return routeTarget.threadRef;
423 }
424 if (routeTarget?.kind === "draft" && activeDraftSession) {
425 return {
426 environmentId: activeDraftSession.environmentId,
427 threadId: activeDraftSession.threadId,
428 };
429 }
430 return null;
432​
433function ThreadToastVisibleAutoDismiss({
434 toastId,
435 dismissAfterVisibleMs,
436}: {
437 toastId: ToastId;
438 dismissAfterVisibleMs: number | undefined;
439}) {
440 useEffect(() => {
441 if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
442 if (typeof window === "undefined" || typeof document === "undefined") return;
443​
444 let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
445 let startedAtMs: number | null = null;
446 let timeoutId: number | null = null;
447 let closed = false;
448​
449 const clearTimer = () => {
450 if (timeoutId === null) return;
451 window.clearTimeout(timeoutId);
452 timeoutId = null;
453 };
454​
455 const closeToast = () => {
456 if (closed) return;
457 closed = true;
458 threadToastVisibleTimeoutRemainingMs.delete(toastId);
459 toastManager.close(toastId);
460 };
461​
462 const pause = () => {
463 if (startedAtMs === null) return;
464 remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
465 startedAtMs = null;
466 clearTimer();
467 threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
468 };
469​
470 const start = () => {
471 if (closed || startedAtMs !== null) return;
472 if (remainingMs <= 0) {
473 closeToast();
474 return;
475 }
476 startedAtMs = Date.now();
477 clearTimer();
478 timeoutId = window.setTimeout(() => {
479 remainingMs = 0;
480 startedAtMs = null;
481 closeToast();
482 }, remainingMs);
483 };
484​
485 const syncTimer = () => {
486 const shouldRun = document.visibilityState === "visible" && document.hasFocus();
487 if (shouldRun) {
488 start();
489 return;
490 }
491 pause();
492 };
493​
494 syncTimer();
495 document.addEventListener("visibilitychange", syncTimer);
496 window.addEventListener("focus", syncTimer);
497 window.addEventListener("blur", syncTimer);
498​
499 return () => {
500 document.removeEventListener("visibilitychange", syncTimer);
501 window.removeEventListener("focus", syncTimer);
502 window.removeEventListener("blur", syncTimer);
503 pause();
504 clearTimer();
505 };
506 }, [dismissAfterVisibleMs, toastId]);
507​
508 return null;
510​
511function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
512 return (
513 <Toast.Provider toastManager={toastManager} {...props}>
514 {children}
515 <Toasts position={position} />
516 </Toast.Provider>
517 );
519​
520function Toasts({ position }: { position: ToastPosition }) {
521 const { toasts } = Toast.useToastManager<ThreadToastData>();
522 const activeThreadRef = useActiveThreadRefFromRoute();
523 const isTop = position.startsWith("top");
524 const visibleToasts = toasts.filter((toast) =>
525 shouldRenderThreadScopedToast(toast.data, activeThreadRef),
526 );
527 const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
528​
529 useEffect(() => {
530 const activeToastIds = new Set(toasts.map((toast) => toast.id));
531 for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
532 if (!activeToastIds.has(toastId)) {
533 threadToastVisibleTimeoutRemainingMs.delete(toastId);
534 }
535 }
536 }, [toasts]);
537​
538 return (
539 <Toast.Portal data-slot="toast-portal">
540 <Toast.Viewport
541 className={cn(
542 "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)]",
543 "data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
544 "data-[position*=bottom]:bottom-(--toast-inset)",
545 "data-[position*=left]:left-(--toast-inset)",
546 "data-[position*=right]:right-(--toast-inset)",
547 "data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
548 )}
549 data-position={position}
550 data-slot="toast-viewport"
551 style={
552 {
553 "--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
554 } as CSSProperties
555 }
556 >
557 {visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
558 const hideCollapsedContent = shouldHideCollapsedToastContent(
559 visibleIndex,
560 visibleToastLayout.items.length,
561 );
562 const bodyDescriptor = deriveToastBodyDescriptor(toast);
563 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
564​
565 return (
566 <Toast.Root
567 className={cn(
568 "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]",
569 "data-[position*=right]:right-0 data-[position*=right]:left-auto",
570 "data-[position*=left]:right-auto data-[position*=left]:left-0",
571 "data-[position*=center]:right-0 data-[position*=center]:left-0",
572 "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
573 "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
574 "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
575 "data-[position*=top]:after:top-full",
576 "data-[position*=bottom]:after:bottom-full",
577 visibleIndex > 0
578 ? "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))]"
579 : "[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]",
580 "[--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))]",
581 // Base UI measures with height:auto; --toast-height as min-height would prevent shrinking.
582 visibleIndex > 0
583 ? "not-data-expanded:h-(--toast-calc-height) data-expanded:h-auto"
584 : "h-auto",
585 "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
586 "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))]",
587 "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))]",
588 "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))]",
589 "data-limited:opacity-0",
590 "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
591 "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
592 "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
593 "data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
594 "data-ending-style:opacity-0",
595 "data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
596 "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))]",
597 "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))]",
598 "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))]",
599 "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
600 "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
601 "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))]",
602 "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))]",
603 "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
604 "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
605 )}
606 data-position={position}
607 key={toast.id}
608 style={
609 {
610 "--toast-index": visibleIndex,
611 "--toast-offset-y": `${offsetY}px`,
612 } as CSSProperties
613 }
614 swipeDirection={
615 position.includes("center")
616 ? [isTop ? "up" : "down"]
617 : position.includes("left")
618 ? ["left", isTop ? "up" : "down"]
619 : ["right", isTop ? "up" : "down"]
620 }
621 toast={toast}
622 >
623 <ThreadToastVisibleAutoDismiss
624 dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
625 toastId={toast.id}
626 />
627 <div className={toastCornerDismissClass}>
628 <button
629 aria-label="Dismiss notification"
630 className={toastCornerOrbClass}
631 data-slot="toast-close"
632 onClick={() =>
633 handleToastDismissClick(toastManager, toast.id, toast.data?.onClose)
634 }
635 type="button"
636 >
637 <XIcon className="size-3" strokeWidth={2.25} />
638 </button>
639 </div>
640 <Toast.Content
641 className={cn(
642 // overflow-x:clip preserves visible vertical overflow; hidden would force overflow-y:auto
643 // and clip detail panels.
644 "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",
645 stackedActionLayout
646 ? "flex flex-col gap-2 py-2.5 pr-3.5"
647 : cn("py-3", "flex items-center justify-between gap-1.5", inlineContentEndPad),
648 hideCollapsedContent &&
649 "not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
650 )}
651 >
652 <ToastBodyContent
653 {...bodyDescriptor}
654 actionProps={toast.actionProps}
655 toastData={toast.data}
656 toastDescription={toast.description}
657 toastType={toast.type}
658 />
659 </Toast.Content>
660 </Toast.Root>
661 );
662 })}
663 </Toast.Viewport>
664 </Toast.Portal>
665 );
667​
668function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
669 return (
670 <Toast.Provider toastManager={anchoredToastManager} {...props}>
671 {children}
672 <AnchoredToasts />
673 </Toast.Provider>
674 );
676​
677function AnchoredToasts() {
678 const { toasts } = Toast.useToastManager<ThreadToastData>();
679 const activeThreadRef = useActiveThreadRefFromRoute();
680​
681 return (
682 <Toast.Portal data-slot="toast-portal-anchored">
683 <Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
684 {toasts
685 .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
686 .map((toast) => {
687 const tooltipStyle = toast.data?.tooltipStyle ?? false;
688 const positionerProps = toast.positionerProps;
689 const bodyDescriptor = deriveToastBodyDescriptor(toast);
690 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
691​
692 if (!positionerProps?.anchor) {
693 return null;
694 }
695​
696 return (
697 <Toast.Positioner
698 className="z-100 max-w-[min(--spacing(64),var(--available-width))]"
699 data-slot="toast-positioner"
700 key={toast.id}
701 sideOffset={positionerProps.sideOffset ?? 4}
702 toast={toast}
703 >
704 <Toast.Root
705 className={cn(
706 "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",
707 tooltipStyle ? "rounded-md" : "rounded-lg",
708 )}
709 data-slot="toast-popup"
710 toast={toast}
711 >
712 {tooltipStyle ? (
713 <Toast.Content className="pointer-events-auto px-2 py-1">
714 <Toast.Title data-slot="toast-title" />
715 </Toast.Content>
716 ) : (
717 <>
718 <div className={toastCornerDismissClass}>
719 <button
720 aria-label="Dismiss notification"
721 className={toastCornerOrbClass}
722 data-slot="toast-close"
723 onClick={() =>
724 handleToastDismissClick(
725 anchoredToastManager,
726 toast.id,
727 toast.data?.onClose,
728 )
729 }
730 type="button"
731 >
732 <XIcon className="size-3" strokeWidth={2.25} />
733 </button>
734 </div>
735 <Toast.Content
736 className={cn(
737 "pointer-events-auto min-h-0 overflow-y-visible pl-3.5 text-sm [overflow-x:clip]",
738 stackedActionLayout
739 ? "flex flex-col gap-2 py-2.5 pr-3.5"
740 : cn(
741 "py-3",
742 "flex items-center justify-between gap-1.5",
743 inlineContentEndPad,
744 ),
745 )}
746 >
747 <ToastBodyContent
748 {...bodyDescriptor}
749 actionProps={toast.actionProps}
750 toastData={toast.data}
751 toastDescription={toast.description}
752 toastType={toast.type}
753 />
754 </Toast.Content>
755 </>
756 )}
757 </Toast.Root>
758 </Toast.Positioner>
759 );
760 })}
761 </Toast.Viewport>
762 </Toast.Portal>
763 );
765​
766export { stackedThreadToast } from "./toastHelpers";
767export type { StackedThreadToastOptions } from "./toastHelpers";
768​
769export {
770 ToastProvider,
771 type ToastPosition,
772 toastManager,
773 AnchoredToastProvider,
774 anchoredToastManager,
775};