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