# Toast
Brief feedback after an action, fired from React or plain code.
Source page: https://dinachi.dev/docs/components/toast

## Installation
```bash
npx @dinachi/cli@latest add toast
```
Adds to your project:
- `components/ui/toast/toast.tsx`
- `components/ui/toast/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `class-variance-authority` ^0.7.1
- `lucide-react` ^0.552.0

## Usage
```tsx
import { Toast, useToastManager } from "@/components/ui/toast"
import { Button } from "@/components/ui/button"

function SaveButton() {
  const toast = useToastManager()
  return (
    <Button onClick={() => toast.add({ title: "Saved", description: "Your changes are live.", type: "success" })}>
      Save
    </Button>
  )
}

export function App() {
  return (
    <Toast>
      <SaveButton />
    </Toast>
  )
}
```

## Anatomy
```tsx
<ToastProvider>
  <ToastPortal>
    <ToastViewport>
      <ToastRoot>
        <ToastContent>
          <ToastTitle />
          <ToastDescription />
          <ToastAction />
          <ToastClose />
        </ToastContent>
      </ToastRoot>
    </ToastViewport>
  </ToastPortal>
</ToastProvider>
```
- `Toast`: Provider, portal, viewport and list in one.
- `ToastProvider`: Holds the toasts in a custom setup.
- `ToastPortal`: Renders the viewport into the body.
- `ToastViewport`: The fixed stack corner, bottom right by default.
- `ToastList`: A `ToastRoot` per toast, variant from type.
- `ToastRoot`: One toast card.
- `ToastContent`: The inner row, hidden when stacked behind.
- `ToastTitle`: Heading and accessible name.
- `ToastDescription`: Body text and accessible description.
- `ToastAction`: A button built from the toast's `actionProps`.
- `ToastClose`: The dismiss button, top right.
- `ToastPositioner`: Anchors a toast to an element.
- `ToastArrow`: Pointer from anchored toast to anchor.

## Examples

### Default
A success toast from a button.
```tsx
import { ToastProvider, ToastPortal, ToastViewport, ToastList, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';

const toastManager = createToastManager();

export function Example() {
  const showToast = () => {
    toastManager.add({
      title: "Success",
      description: "Your message has been sent successfully.",
      type: "success"
    });
  };

  return (
    <ToastProvider toastManager={toastManager}>
      <Button onClick={showToast}>Show Toast</Button>
      <ToastPortal>
        <ToastViewport>
          <ToastList />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}
```

### Variants
One toast for each type.
```tsx
import { ToastProvider, ToastPortal, ToastViewport, ToastList, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';

const toastManager = createToastManager();

export function Example() {
  const variants = {
    success: { title: "Success!", description: "Action completed.", type: "success" },
    error: { title: "Error", description: "Something went wrong.", type: "error" },
    warning: { title: "Warning", description: "Please review your input.", type: "warning" }
  };

  return (
    <ToastProvider toastManager={toastManager}>
      <div className="flex gap-2">
        {Object.entries(variants).map(([key, toast]) => (
          <Button key={key} onClick={() => toastManager.add(toast)} variant="outline">
            {key}
          </Button>
        ))}
      </div>
      <ToastPortal>
        <ToastViewport>
          <ToastList />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}
```

### Loading
Toasts that update, with promise tracking and retry.
```tsx
import { ToastProvider, ToastPortal, ToastViewport, ToastList, useToastManager, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';

const toastManager = createToastManager();

function LoadingToastButtons() {
  const manager = useToastManager();

  const handleUpdate = () => {
    const id = manager.add({
      title: "Saving changes...",
      description: "Please wait while we save your data.",
      type: "loading",
      timeout: 0,
    });

    setTimeout(() => {
      manager.update(id, {
        title: "Changes saved",
        description: "Your data has been saved successfully.",
        type: "success",
        timeout: 5000,
      });
    }, 2000);
  };

  const handleUpdateWithError = () => {
    const id = manager.add({
      title: "Uploading file...",
      description: "Please wait while we upload your file.",
      type: "loading",
      timeout: 0,
    });

    setTimeout(() => {
      manager.update(id, {
        title: "Upload failed",
        description: "The file could not be uploaded.",
        type: "error",
        timeout: 5000,
        actionProps: {
          children: "Retry",
          onClick: () => {
            manager.update(id, {
              title: "Retrying upload...",
              description: "Attempting to upload again.",
              type: "loading",
              timeout: 0,
              actionProps: undefined,
            });
            setTimeout(() => {
              manager.update(id, {
                title: "Upload complete",
                description: "Your file has been uploaded.",
                type: "success",
                timeout: 5000,
              });
            }, 1500);
          },
        },
      });
    }, 2000);
  };

  const handlePromise = () => {
    const fakeRequest = new Promise((resolve) =>
      setTimeout(() => resolve("Done!"), 2500)
    );

    manager.promise(fakeRequest, {
      loading: {
        title: "Processing...",
        description: "Running your request.",
      },
      success: (result) => ({
        title: "Complete",
        description: `Request finished: ${result}`,
      }),
      error: (err) => ({
        title: "Request failed",
        description: err?.message || "Something went wrong.",
      }),
    });
  };

  return (
    <div className="flex gap-2 flex-wrap">
      <Button onClick={handleUpdate} variant="outline">
        Loading → Success
      </Button>
      <Button onClick={handleUpdateWithError} variant="outline">
        Loading → Error → Retry
      </Button>
      <Button onClick={handlePromise} variant="outline">
        Promise Toast
      </Button>
    </div>
  );
}

export function Example() {
  return (
    <ToastProvider toastManager={toastManager}>
      <LoadingToastButtons />
      <ToastPortal>
        <ToastViewport>
          <ToastList />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}
```

### Custom render
Custom icons through renderToast.
```tsx
import { ToastProvider, ToastPortal, ToastViewport, ToastList, ToastContent, ToastTitle, ToastDescription, ToastClose, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';
import { CheckCircle2Icon, AlertCircleIcon, InfoIcon, Loader2Icon } from 'lucide-react';

const toastManager = createToastManager();

const typeIcons = {
  success: <CheckCircle2Icon className="h-5 w-5 text-green-500" />,
  error: <AlertCircleIcon className="h-5 w-5 text-red-500" />,
  loading: <Loader2Icon className="h-5 w-5 animate-spin text-blue-500" />,
};

export function Example() {
  const showToast = (type) => {
    toastManager.add({
      title: type === "success" ? "Saved" : type === "error" ? "Failed" : "Saving...",
      description: type === "success" ? "Your changes have been saved." : type === "error" ? "Could not save changes." : "Please wait...",
      type,
    });
  };

  return (
    <ToastProvider toastManager={toastManager}>
      <div className="flex gap-2">
        <Button onClick={() => showToast("success")} variant="outline">Success</Button>
        <Button onClick={() => showToast("error")} variant="outline">Error</Button>
        <Button onClick={() => showToast("loading")} variant="outline">Loading</Button>
      </div>
      <ToastPortal>
        <ToastViewport>
          <ToastList renderToast={(toast) => (
            <ToastContent>
              <div className="flex items-start gap-3">
                <div className="mt-0.5">
                  {typeIcons[toast.type] ?? <InfoIcon className="h-5 w-5 text-muted-foreground" />}
                </div>
                <div className="grid gap-1">
                  {toast.title && <ToastTitle>{toast.title}</ToastTitle>}
                  {toast.description && <ToastDescription>{toast.description}</ToastDescription>}
                </div>
              </div>
              <ToastClose />
            </ToastContent>
          )} />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}
```

### Close all
manager.close() with no id dismisses every toast.
```tsx
import { ToastProvider, ToastPortal, ToastViewport, ToastList, useToastManager, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';

const toastManager = createToastManager();

function CloseAllButtons() {
  const manager = useToastManager();
  let counter = 0;

  const addMultiple = () => {
    for (let i = 0; i < 3; i++) {
      counter++;
      manager.add({
        title: `Toast #${counter}`,
        description: "This is a queued toast.",
        type: "default",
      });
    }
  };

  return (
    <div className="flex gap-2">
      <Button onClick={addMultiple} variant="outline">
        Add 3 Toasts
      </Button>
      <Button onClick={() => manager.close()} variant="destructive">
        Close All
      </Button>
    </div>
  );
}

export function Example() {
  return (
    <ToastProvider toastManager={toastManager}>
      <CloseAllButtons />
      <ToastPortal>
        <ToastViewport>
          <ToastList />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}
```

## Notes

### The toast manager
`useToastManager()` inside React and `createToastManager()` outside it both return `add`, `update`, `close` and `promise`. The hook also returns the current `toasts`.

```tsx
const id = manager.add({ title: "Uploading", type: "loading", timeout: 0 })

// Change it in place: title, description, type, timeout or action.
manager.update(id, { title: "Upload complete", type: "success", timeout: 5000 })

manager.close(id) // one toast
manager.close()   // every toast
```

`promise` runs a toast through loading, success and error. Each state takes a string, toast options, or a function of the result or error.

```tsx
manager.promise(fetch("/api/save", { method: "POST" }), {
  loading: "Saving...",
  success: { title: "Saved", description: "Changes applied." },
  error: (err) => ({ title: "Error", description: err.message }),
})
```

### Toast options
`add` and `update` take the same options.

```tsx
{
  title: ReactNode,
  description: ReactNode,
  type: "success" | "error" | "warning" | "loading" | string,
  timeout: number,          // 0 keeps it until dismissed
  priority: "low" | "high",
  actionProps: ButtonHTMLAttributes,
  data: object,             // anything renderToast needs
  onClose: () => void,
  onRemove: () => void,
}
```

The type sets the variant: `error` maps to `destructive`; `success`, `warning` and `loading` keep their names; anything else is `default`. `getVariantFromType` does this mapping for a custom list.

### Toasts from outside React
`dinachi add toast` also writes `lib/toast.ts` with a shared manager. Pass it to `Toast` once, then call it from API clients and error handlers.

```tsx
// lib/toast.ts, written by the CLI
import { createToastManager } from "@/components/ui/toast"
export const toastManager = createToastManager()
```

```tsx
// providers.tsx
import { Toast } from "@/components/ui/toast"
import { toastManager } from "@/lib/toast"

export function Providers({ children }: { children: React.ReactNode }) {
  return <Toast toastManager={toastManager}>{children}</Toast>
}
```

```ts
// api-client.ts
import { toastManager } from "@/lib/toast"

export async function apiCall() {
  try {
    const res = await fetch("/api/data")
    if (!res.ok) throw new Error("Request failed")
    return res.json()
  } catch (err) {
    toastManager.add({ title: (err as Error).message, type: "error" })
    throw err
  }
}
```

### Custom rendering
Pass `renderToast` to `Toast` or `ToastList`. Anything passed as `data` to `add` is on `toast.data`.

```tsx
manager.add({ title: "New message", data: { avatarUrl: "/img/user.png", sender: "Alice" } })

<Toast
  renderToast={(toast) => (
    <ToastContent>
      <img src={toast.data?.avatarUrl} alt={toast.data?.sender} />
      <div>
        <ToastTitle>{toast.title}</ToastTitle>
        <ToastDescription>{toast.description}</ToastDescription>
      </div>
      <ToastClose />
    </ToastContent>
  )}
/>
```

Keep `ToastClose` in a custom layout: it is the only non-swipe dismiss and the button the agent presses.

### The stack
- Collapsed, toasts behind the front one are scaled back and offset, and cut to its height.
- Hovering or focusing the stack expands it into a column.
- `limit` sets how many it holds; more than about three stops reading as depth.

### Timing
`timeout` on the provider or on a single `add()` sets how long a toast lasts; `timeout: 0` keeps it until dismissed. Hovering or focusing the viewport pauses every timer.

```tsx
<Toast timeout={5000}>

// Stays until dismissed.
add({ title: "Quota at 90%", timeout: 0 })
```

## API reference
Props marked **agent** change what an agent reads or may do.

### Toast
Provider, portal, viewport and list in one.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `limit` | `number` | `3` | Most toasts held at once. |
| `timeout` | `number` | `5000` | Milliseconds before a toast closes. `0` keeps it until dismissed. |
| `toastManager` | `ToastManager` | - | A manager from `createToastManager()`, for firing toasts outside React. |
| `renderToast` | `(toast) => ReactNode` | - | Custom layout for each toast. |
| `className` | `string` | - | Viewport classes, for example to move the stack. |

### ToastProvider
Holds the toasts in a custom setup.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `limit` | `number` | `3` | Most toasts held at once. |
| `timeout` | `number` | `5000` | Milliseconds before a toast closes. `0` keeps it until dismissed. |
| `toastManager` | `ToastManager` | - | A manager from `createToastManager()`. |

### ToastPortal
Renders the viewport into the body.

Takes the props of the element it renders.

### ToastViewport
The fixed stack corner, bottom right by default.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - | Moves or resizes the stack. |

### ToastList
A `ToastRoot` per toast, variant from type.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `renderToast` | `(toast) => ReactNode` | - | Custom layout inside each `ToastRoot`. |

### ToastRoot
One toast card.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `toast` | `ToastObject` | - | The toast from the manager. Required. |
| `variant` | `"default" \| "destructive" \| "success" \| "warning" \| "loading"` | `"default"` | The accent border. `ToastList` sets it from the type. |
| `swipeDirection` | `("up" \| "down" \| "left" \| "right")[]` | `["down", "right"]` | Swipe directions that dismiss it. |

### ToastContent
The inner row, hidden when stacked behind.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | - | Title, description and buttons. |

### ToastTitle
Heading and accessible name.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Defaults to the toast's title. The agent reads it as label. |

### ToastDescription
Body text and accessible description.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Defaults to the toast's description. The agent reads it as value. |

### ToastAction
A button built from the toast's `actionProps`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | - | Used when `actionProps` has no children. |

### ToastClose
The dismiss button, top right.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | `<XIcon />` | Replaces the icon. The agent's dismiss presses this button. |

### ToastPositioner
Anchors a toast to an element.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `toast` | `ToastObject` | - | The toast to place. Required. |
| `anchor` | `Element \| null` | - | The element to place it against. |
| `side` | `"top" \| "bottom" \| "left" \| "right" \| "inline-start" \| "inline-end"` | `"top"` | Side of the anchor. |
| `align` | `"start" \| "center" \| "end"` | `"center"` | Alignment along that side. |
| `sideOffset` | `number` | `0` | Gap to the anchor, in pixels. |

### ToastArrow
Pointer from anchored toast to anchor.

Takes the props of the element it renders.

## Agent
Inside an `AgentProvider`, Toast appears in `agent.snapshot()` as `toast`.
Reads:
- `label`: The toast's title, or `toast` when it has none.
- `value`: The description.
- `type`: The toast's type, such as `success` or `error`.
Actions:
- `dismiss()`: Presses the toast's `ToastClose` button.
Nothing to refuse: dismiss presses the close button as a person would. Without `ToastClose` in a custom layout, dismiss fails with a message. Action buttons are listed separately as `button` and take `press` without approval, even at high priority.
```ts
await agent.act({
  steps: [{ ref: "Success", action: "dismiss" }],
})
```

## Accessibility
- The viewport is a region labelled Notifications, aria-live polite.
- `priority: "high"` toasts are also announced assertively. Do not announce them again yourself.
- Each toast is a dialog named by `ToastTitle` and described by `ToastDescription`; omit both and it is an empty dialog.
- Put any action in a real button inside the toast, so F6 then Tab reaches it.
- Hover or focus on the viewport pauses every countdown.
- Use `timeout: 0` for anything that must be acted on.
- The stack expands on focus too. Swiping is pointer only, so keep a close button.
### Keyboard
| Keys | Does |
| --- | --- |
| `F6` | Moves focus to the toast viewport from anywhere on the page |
| `Tab` | Moves between toasts and their buttons |
| `Esc` | Closes the focused toast |

## Source
`components/ui/toast/toast.tsx`
```tsx
"use client";

import * as React from "react";
import { Toast as BaseToast } from "@base-ui/react/toast";
import { cn } from "@/lib/utils";
import { type VariantProps, cva } from "class-variance-authority";
import { XIcon } from "lucide-react";

// Toast Provider
const ToastProvider = BaseToast.Provider;

export type ToastViewportProps = React.ComponentProps<
  typeof BaseToast.Viewport
>;

// Toast Viewport
const ToastViewport = React.forwardRef<HTMLDivElement, ToastViewportProps>(
  ({ className, ...props }, ref) => (
    <BaseToast.Viewport
      data-slot="toast-viewport"
      ref={ref}
      className={cn(
        "fixed z-10 top-auto right-4 bottom-4 mx-auto flex w-[250px] sm:right-8 sm:bottom-8 sm:w-[300px]",
        className
      )}
      {...props}
    />
  )
);
ToastViewport.displayName = "ToastViewport";

// Toast Portal
const ToastPortal: typeof BaseToast.Portal = BaseToast.Portal;

// Toast variants for different types
const toastVariants = cva(
  [
    // CSS variables for stacking
    "[--gap:1rem] [--peek:0.75rem]",
    "[--scale:calc(max(0,1-(var(--toast-index)*0.1)))]",
    "[--shrink:calc(1-var(--scale))]",
    "[--height:var(--toast-frontmost-height,var(--toast-height))]",
    "[--offset-y:calc(var(--toast-offset-y)*-1+(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))]",
    // Positioning
    "absolute right-0 bottom-0 left-auto z-[calc(1000-var(--toast-index))] mr-0 w-full",
    // Transform (collapsed stacking with peek/shrink)
    "[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))]",
    // Height management (collapse to frontmost height)
    "h-[var(--height)]",
    // Appearance. No `overflow-hidden` here: the gap pseudo-element below sits past the
    // card's bottom edge, and clipping it breaks the reach between stacked toasts.
    "origin-bottom cursor-default rounded-xl border bg-clip-padding bg-background p-4 shadow-lg select-none",
    // Transition (includes height for expand/collapse animation)
    "[transition:transform_0.5s_cubic-bezier(0.22,1,0.36,1),opacity_0.5s,height_0.15s]",
    // Gap pseudo-element for hover detection between stacked toasts
    "after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-['']",
    // Ending style (fade out)
    "data-[ending-style]:opacity-0",
    // Expanded state (full height, offset positioning)
    "data-[expanded]:[transform:translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
    "data-[expanded]:h-[var(--toast-height)]",
    // Limited (exceeded limit)
    "data-[limited]:opacity-0",
    // Starting style (enter from below)
    "data-[starting-style]:[transform:translateY(150%)]",
    // Default ending style (slide out, but not when limited or swiped)
    "[&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)]",
    // Swipe direction ending styles
    "data-[ending-style]:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
    "data-[expanded]:data-[ending-style]:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
    "data-[ending-style]:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
    "data-[expanded]:data-[ending-style]:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
    "data-[ending-style]:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
    "data-[expanded]:data-[ending-style]:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
    "data-[ending-style]:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
    "data-[expanded]:data-[ending-style]:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
  ],
  {
    variants: {
      variant: {
        default: "border-border bg-background text-foreground",
        destructive:
          "border-destructive border-l-4 bg-background text-foreground",
        success: "border-success border-l-4 bg-background text-foreground",
        warning: "border-warning border-l-4 bg-background text-foreground",
        loading:
          "border-primary/50 border-l-4 bg-background text-foreground",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
);

export interface ToastProps
  extends React.ComponentPropsWithoutRef<typeof BaseToast.Root>,
    VariantProps<typeof toastVariants> {}

// Toast Root
const ToastRoot = React.forwardRef<HTMLDivElement, ToastProps>(
  ({ className, variant, ...props }, ref) => (
    <BaseToast.Root
      data-slot="toast-root"
      ref={ref}
      className={cn(toastVariants({ variant }), className)}
      {...props}
    />
  )
);
ToastRoot.displayName = "ToastRoot";

// Toast Title
const ToastTitle = React.forwardRef<
  HTMLHeadingElement,
  React.ComponentProps<typeof BaseToast.Title>
>(({ className, ...props }, ref) => (
  <BaseToast.Title
    data-slot="toast-title"
    ref={ref}
    className={cn("text-[0.975rem] leading-5 font-medium", className)}
    {...props}
  />
));
ToastTitle.displayName = "ToastTitle";

// Toast Description
const ToastDescription = React.forwardRef<
  HTMLParagraphElement,
  React.ComponentProps<typeof BaseToast.Description>
>(({ className, ...props }, ref) => (
  <BaseToast.Description
    data-slot="toast-description"
    ref={ref}
    className={cn("text-[0.925rem] leading-5 opacity-90", className)}
    {...props}
  />
));
ToastDescription.displayName = "ToastDescription";

// Toast Content — the row inside the card, and what fades while the toast is behind another.
// `pr-6` keeps the row clear of the close button, which is positioned against the card
// rather than laid out in the row, so nothing here would otherwise leave it room.
const ToastContent = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseToast.Content>
>(({ className, ...props }, ref) => (
  <BaseToast.Content
    data-slot="toast-content"
    ref={ref}
    className={cn(
      "flex items-start gap-3 overflow-hidden pr-6 transition-opacity [transition-duration:250ms]",
      "data-[behind]:pointer-events-none data-[behind]:opacity-0",
      "data-[expanded]:pointer-events-auto data-[expanded]:opacity-100",
      className
    )}
    {...props}
  />
));
ToastContent.displayName = "ToastContent";

// Toast Action
const ToastAction = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof BaseToast.Action>
>(({ className, ...props }, ref) => (
  <BaseToast.Action
    data-slot="toast-action"
    ref={ref}
    className={cn(
      "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors",
      "hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring",
      "disabled:pointer-events-none disabled:opacity-50",
      className
    )}
    {...props}
  />
));
ToastAction.displayName = "ToastAction";

// Toast Close — renders XIcon by default, overridable via children
const ToastClose = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof BaseToast.Close>
>(({ className, children, ...props }, ref) => (
  <BaseToast.Close
    data-slot="toast-close"
    ref={ref}
    aria-label="Close"
    data-agent-dismiss=""
    data-agent-part=""
    className={cn(
      "absolute top-2 right-2 flex h-5 w-5 items-center justify-center rounded border-none bg-transparent opacity-60 transition-opacity",
      "hover:opacity-100 focus:outline-none focus:ring-1 focus:ring-ring",
      "disabled:pointer-events-none",
      className
    )}
    {...props}
  >
    {children ?? <XIcon className="h-4 w-4" />}
  </BaseToast.Close>
));
ToastClose.displayName = "ToastClose";

// Toast Positioner — positions a toast relative to an anchor element
const ToastPositioner = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseToast.Positioner>
>(({ className, ...props }, ref) => (
  <BaseToast.Positioner
    data-slot="toast-positioner"
    ref={ref}
    className={cn("z-50", className)}
    {...props}
  />
));
ToastPositioner.displayName = "ToastPositioner";

// Toast Arrow — decorative arrow for anchored toasts
const ToastArrow = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseToast.Arrow>
>(({ className, ...props }, ref) => (
  <BaseToast.Arrow
    data-slot="toast-arrow"
    ref={ref}
    className={cn(
      "fill-background [stroke-width:1px] stroke-border",
      "data-[side=bottom]:top-[-8px]",
      "data-[side=left]:right-[-8px]",
      "data-[side=right]:left-[-8px]",
      "data-[side=top]:bottom-[-8px]",
      className
    )}
    {...props}
  />
));
ToastArrow.displayName = "ToastArrow";

// Hook for using toast manager
const useToastManager = BaseToast.useToastManager;

// Create toast manager for global usage
const createToastManager = BaseToast.createToastManager;

// Helper function to get variant from toast type
function getVariantFromType(
  type?: string
): VariantProps<typeof toastVariants>["variant"] {
  switch (type) {
    case "success":
      return "success";
    case "error":
      return "destructive";
    case "warning":
      return "warning";
    case "loading":
      return "loading";
    default:
      return "default";
  }
}

// Toast object type from Base UI
type ToastObject = React.ComponentProps<typeof BaseToast.Root>["toast"];

// renderToast callback type
type RenderToastFn = (toast: ToastObject) => React.ReactNode;

// Default ToastList component for easy usage
// Returns toast roots directly without a wrapper — Base UI requires
// Toast.Root elements as direct children of Toast.Viewport.
function ToastList({ renderToast }: { renderToast?: RenderToastFn }) {
  const { toasts } = useToastManager();

  return toasts.map((toast) => (
    <ToastRoot
      key={toast.id}
      toast={toast}
      variant={getVariantFromType(toast.type)}
      swipeDirection={["down", "right"]}
    >
      {renderToast ? (
        renderToast(toast)
      ) : (
        <ToastContent>
          <div className="grid flex-1 gap-1">
            {toast.title && <ToastTitle>{toast.title}</ToastTitle>}
            {toast.description && (
              <ToastDescription>{toast.description}</ToastDescription>
            )}
          </div>
          {toast.actionProps && <ToastAction />}
          <ToastClose />
        </ToastContent>
      )}
    </ToastRoot>
  ));
}

// Complete Toast component for easy setup
interface ToastComponentProps {
  children?: React.ReactNode;
  className?: string;
  limit?: number;
  timeout?: number;
  toastManager?: ReturnType<typeof createToastManager>;
  renderToast?: RenderToastFn;
}

const Toast = React.forwardRef<HTMLDivElement, ToastComponentProps>(
  (
    {
      children,
      className,
      limit = 3,
      timeout = 5000,
      toastManager,
      renderToast,
      ...props
    },
    ref
  ) => (
    <ToastProvider limit={limit} timeout={timeout} toastManager={toastManager}>
      {children}
      <ToastPortal>
        <ToastViewport data-slot="toast" ref={ref} className={className} {...props}>
          <ToastList renderToast={renderToast} />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  )
);
Toast.displayName = "Toast";

export {
  Toast,
  ToastProvider,
  ToastViewport,
  ToastPortal,
  ToastRoot,
  ToastContent,
  ToastTitle,
  ToastDescription,
  ToastAction,
  ToastClose,
  ToastPositioner,
  ToastArrow,
  ToastList,
  useToastManager,
  createToastManager,
  toastVariants,
  getVariantFromType,
};

export type { ToastComponentProps, RenderToastFn, ToastObject };
```
