The best way to control Claude Code, Codex and more from any computer or phone

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