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

toast.tsx

845 lines32.1 KB

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 };
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";
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);
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 );
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 );
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 );
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;
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 };
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;
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 flex-wrap 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 );
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;
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;
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;
561​
562const consumeToastEscape: NonNullable<Toast.Root.Props["onKeyDown"]> = (event) => {
563 if (event.key !== "Escape" || !event.currentTarget.contains(document.activeElement)) return;
564 if (event.defaultPrevented || event.nativeEvent.isComposing || event.keyCode === 229)
565 return event.preventBaseUIHandler();
566 event.preventDefault();
567 event.nativeEvent.stopPropagation();
568};
569​
570function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
571 return (
572 <Toast.Provider toastManager={toastManager} {...props}>
573 {children}
574 <Toasts position={position} />
575 </Toast.Provider>
576 );
578​
579function Toasts({ position }: { position: ToastPosition }) {
580 const { toasts } = Toast.useToastManager<ThreadToastData>();
581 const activeThreadRef = useActiveThreadRefFromRoute();
582 const gt = useGT();
583 const isTop = position.startsWith("top");
584 const visibleToasts = toasts.filter((toast) =>
585 shouldRenderThreadScopedToast(toast.data, activeThreadRef),
586 );
587 const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
588​
589 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes the module-level remaining-time map of toasts the manager has dropped
590 useEffect(() => {
591 const activeToastIds = new Set(toasts.map((toast) => toast.id));
592 for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
593 if (!activeToastIds.has(toastId)) {
594 threadToastVisibleTimeoutRemainingMs.delete(toastId);
595 }
596 }
597 }, [toasts]);
598​
599 return (
600 <Toast.Portal data-slot="toast-portal">
601 <Toast.Viewport
602 aria-label={gt({ context: "screen reader name of the toast area" })`Notifications`}
603 className={cn(
604 "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)]",
605 "data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
606 "data-[position*=bottom]:bottom-(--toast-inset)",
607 "data-[position*=left]:left-(--toast-inset)",
608 "data-[position*=right]:right-(--toast-inset)",
609 "data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
610 )}
611 data-position={position}
612 data-slot="toast-viewport"
613 style={
614 {
615 "--toast-frontmost-height": `${visibleToastLayout.frontmostHeight}px`,
616 } as CSSProperties
617 }
618 >
619 {visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => {
620 const hideCollapsedContent = shouldHideCollapsedToastContent(
621 visibleIndex,
622 visibleToastLayout.items.length,
623 );
624 const bodyDescriptor = deriveToastBodyDescriptor(toast);
625 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
626​
627 return (
628 <Toast.Root
629 className={cn(
630 "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]",
631 "data-[position*=right]:right-0 data-[position*=right]:left-auto",
632 "data-[position*=left]:right-auto data-[position*=left]:left-0",
633 "data-[position*=center]:right-0 data-[position*=center]:left-0",
634 "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
635 "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
636 "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
637 "data-[position*=top]:after:top-full",
638 "data-[position*=bottom]:after:bottom-full",
639 visibleIndex > 0
640 ? "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))]"
641 : "[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]",
642 "[--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))]",
643 // Base UI measures with height:auto; --toast-height as min-height would prevent shrinking.
644 visibleIndex > 0
645 ? "not-data-expanded:h-(--toast-calc-height) data-expanded:h-auto"
646 : "h-auto",
647 "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
648 "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))]",
649 "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))]",
650 "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))]",
651 "data-limited:opacity-0",
652 "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
653 "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
654 "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
655 "data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
656 "data-ending-style:opacity-0",
657 "data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
658 "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))]",
659 "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))]",
660 "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))]",
661 "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
662 "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
663 "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))]",
664 "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))]",
665 "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
666 "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
667 )}
668 data-position={position}
669 key={toast.id}
670 onKeyDown={toast.transitionStatus === "ending" ? undefined : consumeToastEscape}
671 style={
672 {
673 "--toast-index": visibleIndex,
674 "--toast-offset-y": `${offsetY}px`,
675 } as CSSProperties
676 }
677 swipeDirection={
678 position.includes("center")
679 ? [isTop ? "up" : "down"]
680 : position.includes("left")
681 ? ["left", isTop ? "up" : "down"]
682 : ["right", isTop ? "up" : "down"]
683 }
684 toast={toast}
685 >
686 <ThreadToastVisibleAutoDismiss
687 dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
688 toastId={toast.id}
689 />
690 <div className={toastCornerDismissClass}>
691 <button
692 aria-label={gt`Dismiss notification`}
693 className={toastCornerOrbClass}
694 data-slot="toast-close"
695 onClick={() =>
696 handleToastDismissClick(toastManager, toast.id, toast.data?.onClose)
697 }
698 type="button"
699 >
700 <XIcon className="size-3" strokeWidth={2.25} />
701 </button>
702 </div>
703 <Toast.Content
704 className={cn(
705 // overflow-x:clip preserves visible vertical overflow; hidden would force overflow-y:auto
706 // and clip detail panels.
707 "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",
708 stackedActionLayout
709 ? "flex flex-col gap-2 py-2.5 pr-3.5"
710 : cn("py-3", "flex items-center justify-between gap-1.5", inlineContentEndPad),
711 hideCollapsedContent &&
712 "not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
713 )}
714 >
715 <ToastBodyContent
716 {...bodyDescriptor}
717 actionProps={toast.actionProps}
718 toastData={toast.data}
719 toastDescription={toast.description}
720 toastType={toast.type}
721 />
722 </Toast.Content>
723 </Toast.Root>
724 );
725 })}
726 </Toast.Viewport>
727 </Toast.Portal>
728 );
730​
731function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
732 return (
733 <Toast.Provider toastManager={anchoredToastManager} {...props}>
734 {children}
735 <AnchoredToasts />
736 </Toast.Provider>
737 );
739​
740function AnchoredToasts() {
741 const { toasts } = Toast.useToastManager<ThreadToastData>();
742 const activeThreadRef = useActiveThreadRefFromRoute();
743 const gt = useGT();
744​
745 return (
746 <Toast.Portal data-slot="toast-portal-anchored">
747 <Toast.Viewport
748 aria-label={undefined}
749 className="outline-none"
750 data-slot="toast-viewport-anchored"
751 role={undefined}
752 >
753 {toasts
754 .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
755 .map((toast) => {
756 const tooltipStyle = toast.data?.tooltipStyle ?? false;
757 const positionerProps = toast.positionerProps;
758 const bodyDescriptor = deriveToastBodyDescriptor(toast);
759 const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor;
760​
761 if (!positionerProps?.anchor) {
762 return null;
763 }
764​
765 return (
766 <Toast.Positioner
767 className="z-100 max-w-[min(--spacing(64),var(--available-width))]"
768 data-slot="toast-positioner"
769 key={toast.id}
770 sideOffset={positionerProps.sideOffset ?? 4}
771 toast={toast}
772 >
773 <Toast.Root
774 className={cn(
775 "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",
776 tooltipStyle ? "rounded-md" : "rounded-lg",
777 )}
778 data-slot="toast-popup"
779 onKeyDown={toast.transitionStatus === "ending" ? undefined : consumeToastEscape}
780 toast={toast}
781 >
782 {tooltipStyle ? (
783 <Toast.Content className="pointer-events-auto px-2 py-1">
784 <Toast.Title data-slot="toast-title" />
785 </Toast.Content>
786 ) : (
787 <>
788 <div className={toastCornerDismissClass}>
789 <button
790 aria-label={gt`Dismiss notification`}
791 className={toastCornerOrbClass}
792 data-slot="toast-close"
793 onClick={() =>
794 handleToastDismissClick(
795 anchoredToastManager,
796 toast.id,
797 toast.data?.onClose,
798 )
799 }
800 type="button"
801 >
802 <XIcon className="size-3" strokeWidth={2.25} />
803 </button>
804 </div>
805 <Toast.Content
806 className={cn(
807 "pointer-events-auto min-h-0 overflow-y-visible pl-3.5 text-sm [overflow-x:clip]",
808 stackedActionLayout
809 ? "flex flex-col gap-2 py-2.5 pr-3.5"
810 : cn(
811 "py-3",
812 "flex items-center justify-between gap-1.5",
813 inlineContentEndPad,
814 ),
815 )}
816 >
817 <ToastBodyContent
818 {...bodyDescriptor}
819 actionProps={toast.actionProps}
820 toastData={toast.data}
821 toastDescription={toast.description}
822 toastType={toast.type}
823 />
824 </Toast.Content>
825 </>
826 )}
827 </Toast.Root>
828 </Toast.Positioner>
829 );
830 })}
831 </Toast.Viewport>
832 </Toast.Portal>
833 );
835​
836export { stackedThreadToast } from "./toastHelpers";
837export type { StackedThreadToastOptions } from "./toastHelpers";
838​
839export {
840 ToastProvider,
841 type ToastPosition,
842 toastManager,
843 AnchoredToastProvider,
844 anchoredToastManager,
845};