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

toast.tsx

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