Toast for Astro
Astro notifications with status icons, actions, and promise states.
Installation
bunx --bun shadcn@latest add @gnostic/toastnpx shadcn@latest add @gnostic/toastpnpm dlx shadcn@latest add @gnostic/toastComponent classes: Default Gnostic.
Complete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/toastCopy the files
src/components/ui/toast/index.ts
export { default as Toast } from './toast.astro'
export { default as ToastAction } from './toast-action.astro'
export { default as ToastClose } from './toast-close.astro'
export { default as ToastContent } from './toast-content.astro'
export { default as ToastDescription } from './toast-description.astro'
export { default as ToastIcon } from './toast-icon.astro'
export { default as ToastItem } from './toast-item.astro'
export { default as ToastTemplate } from './toast-template.astro'
export { default as ToastTitle } from './toast-title.astro'
export { default as ToastViewport } from './toast-viewport.astro'
export type { ToastProps } from './types.ts'
src/components/ui/toast/toast-action.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { buttonVariants } from "../button/button-variants.ts"
type Props = HTMLAttributes<"button">
const { class: className, type = "button", ...props } = Astro.props
---
<button
data-slot="toast-action"
type={type}
class={cn("shrink-0", buttonVariants({ size: "xs" }), className)}
{...props}
>
<slot />
</button>
src/components/ui/toast/toast-close.astro
---
import type { HTMLAttributes } from "astro/types"
import XIcon from "@lucide/astro/icons/x"
import { cn } from "cn"
type Props = HTMLAttributes<"button">
const {
class: className,
type = "button",
"aria-label": label = "Close notification",
...props
} = Astro.props
---
<button
data-slot="toast-close"
type={type}
aria-label={label}
class={cn("inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4", className)}
{...props}
>
<slot>
<XIcon aria-hidden="true" />
</slot>
</button>
src/components/ui/toast/toast-content.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="toast-content"
class={cn("flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", className)}
{...props}
>
<slot />
</div>
src/components/ui/toast/toast-description.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="toast-description"
class={cn("text-muted-foreground wrap-anywhere", className)}
{...props}
>
<slot />
</div>
src/components/ui/toast/toast-icon.astro
---
import type { HTMLAttributes } from "astro/types"
import CircleAlertIcon from "@lucide/astro/icons/circle-exclamation-point"
import CircleCheckIcon from "@lucide/astro/icons/circle-check"
import InfoIcon from "@lucide/astro/icons/info"
import LoaderCircleIcon from "@lucide/astro/icons/loader-circle"
import TriangleAlertIcon from "@lucide/astro/icons/triangle-exclamation-point"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="toast-icon"
aria-hidden="true"
class={cn("shrink-0 self-center group-has-[[data-slot=toast-description]:not([hidden])]/toast:self-start group-data-[type=default]/toast:hidden [&_svg]:pointer-events-none [&_svg]:hidden [&_svg]:h-lh [&_svg]:w-4 group-data-[type=success]/toast:text-success group-data-[type=error]/toast:text-destructive group-data-[type=info]/toast:text-info group-data-[type=warning]/toast:text-warning group-data-[type=loading]/toast:opacity-80 group-data-[type=success]/toast:[&>[data-toast-icon=success]]:block group-data-[type=error]/toast:[&>[data-toast-icon=error]]:block group-data-[type=info]/toast:[&>[data-toast-icon=info]]:block group-data-[type=warning]/toast:[&>[data-toast-icon=warning]]:block group-data-[type=loading]/toast:[&>[data-toast-icon=loading]]:block group-data-[type=loading]/toast:[&>[data-toast-icon=loading]]:animate-spin motion-reduce:[&_svg]:animate-none", className)}
{...props}
>
<slot>
<CircleCheckIcon data-toast-icon="success" />
<CircleAlertIcon data-toast-icon="error" />
<InfoIcon data-toast-icon="info" />
<TriangleAlertIcon data-toast-icon="warning" />
<LoaderCircleIcon data-toast-icon="loading" />
</slot>
</div>
src/components/ui/toast/toast-item.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"li">
const { class: className, ...props } = Astro.props
---
<li
data-slot="toast-item"
role="status"
aria-atomic="true"
class={cn("rounded-lg pointer-events-auto absolute inset-x-0 bottom-0 flex w-full touch-none items-center gap-2 border bg-popover px-3.5 py-3 text-sm text-popover-foreground opacity-0 shadow-lg/5 outline-none select-none origin-bottom not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] group-data-[position*=top]/toast-viewport:top-0 group-data-[position*=top]/toast-viewport:bottom-auto group-data-[position*=top]/toast-viewport:origin-top [--toast-base-y:0px] [--toast-scale:1] [--toast-x:var(--toast-swipe-amount-x,0px)] [--toast-y:calc(var(--toast-lift,-1)*-100%)] transform-[translate3d(var(--toast-x),var(--toast-y),0)_scale(var(--toast-scale))] [transition:transform_.32s_cubic-bezier(.22,1,.36,1),opacity_.32s,height_.15s] data-[mounted=true]:[--toast-y:calc(var(--toast-base-y)+var(--toast-swipe-amount-y,0px))] [&[data-mounted=true][data-visible=true]:not([data-removed=true])]:opacity-100 [&[data-front=false][data-expanded=false]]:[--toast-base-y:calc(var(--toast-collapsed-offset-y,0px)*var(--toast-lift,-1))] [&[data-front=false][data-expanded=false]]:[--toast-scale:calc(max(0,1-var(--toast-index,0)*.05))] [&[data-front=false][data-expanded=false]]:h-(--toast-front-height) data-[expanded=true]:[--toast-base-y:calc(var(--toast-offset,0px)*var(--toast-lift,-1))] data-[expanded=true]:h-(--toast-initial-height) [&[data-front=false][data-expanded=false]]:*:opacity-0 [&[data-front=false][data-expanded=false]]:*:pointer-events-none data-[visible=false]:pointer-events-none data-[removed=true]:[--toast-y:calc(var(--toast-base-y)+var(--toast-lift,-1)*-100%)] [&[data-removed=true][data-swipe-out=true]]:[--toast-x:var(--toast-swipe-end-x,0px)] [&[data-removed=true][data-swipe-out=true]]:[--toast-y:calc(var(--toast-base-y)+var(--toast-swipe-end-y,0px))] data-[swiping=true]:transition-none after:absolute after:left-0 after:bottom-full after:h-[calc(var(--toast-gap)+1px)] after:w-full group-data-[position*=top]/toast-viewport:after:top-full group-data-[position*=top]/toast-viewport:after:bottom-auto motion-reduce:transition-none group/toast", className)}
{...props}
>
<slot />
</li>
src/components/ui/toast/toast-template.astro
---
import { cn } from "cn"
import ToastAction from "./toast-action.astro"
import ToastClose from "./toast-close.astro"
import ToastContent from "./toast-content.astro"
import ToastDescription from "./toast-description.astro"
import ToastIcon from "./toast-icon.astro"
import ToastItem from "./toast-item.astro"
import ToastTitle from "./toast-title.astro"
type Props = astroHTML.JSX.HTMLAttributes
const { class: className, ...props } = Astro.props
---
<template data-slot="toast-template" class={cn(className)} {...props}>
<slot>
<ToastItem>
<ToastIcon />
<ToastContent>
<ToastTitle />
<ToastDescription />
</ToastContent>
<ToastAction />
<ToastClose />
</ToastItem>
</slot>
</template>
src/components/ui/toast/toast-title.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div data-slot="toast-title" class={cn("font-medium wrap-anywhere", className)} {...props}>
<slot />
</div>
src/components/ui/toast/toast-viewport.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"ol">
const {
class: className,
"aria-label": label = "Notifications",
...props
} = Astro.props
---
<ol
data-slot="toast-viewport"
role="region"
aria-label={label}
class={cn("pointer-events-none fixed z-60 m-0 h-[var(--toast-stack-size,0px)] w-[calc(100%-var(--toast-inset)*2)] max-w-90 list-none p-0 font-sans [--toast-inset:--spacing(4)] [--toast-gap:12px] [--toast-collapsed-peek:12px] sm:[--toast-inset:--spacing(8)] data-[position*=top]:top-(--toast-inset) data-[position*=bottom]:bottom-(--toast-inset) data-[position*=left]:left-(--toast-inset) data-[position*=right]:right-(--toast-inset) data-[position*=center]:left-1/2 data-[position*=center]:-translate-x-1/2 group/toast-viewport", className)}
{...props}
>
<slot />
</ol>
src/components/ui/toast/toast.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import ToastTemplate from "./toast-template.astro"
import ToastViewport from "./toast-viewport.astro"
import type { ToastProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & ToastProps
const {
class: className,
position = "bottom-right",
limit = 3,
duration = 5000,
pauseOnHover = true,
pauseOnFocus = true,
portal = true,
...props
} = Astro.props
---
<div
data-slot="toast"
data-position={position}
data-limit={limit}
data-duration={duration}
data-pause-on-hover={String(pauseOnHover)}
data-pause-on-focus={String(pauseOnFocus)}
data-portal={String(portal)}
class={cn(className)}
{...props}
>
<slot>
<ToastTemplate />
<ToastViewport />
</slot>
</div>
<script>
import { createToast, type ToastController } from "@data-slot/toast"
const controllers = new Map<Element, ToastController>()
const init = () => {
for (const [root, controller] of controllers) {
if (!root.isConnected) {
controller.destroy()
controllers.delete(root)
}
}
document.querySelectorAll('[data-slot="toast"]').forEach((root) => {
if (!controllers.has(root)) controllers.set(root, createToast(root))
})
}
init()
document.addEventListener("astro:page-load", init)
document.addEventListener("astro:before-swap", () => {
for (const controller of controllers.values()) controller.destroy()
controllers.clear()
})
</script>
src/components/ui/toast/types.ts
import type { ToastPosition } from '@data-slot/toast'
import type {
ToastShowOptions as ToastShowOptionsType,
ToastAction as ToastActionType,
ToastUpdateOptions as ToastUpdateOptionsType,
ToastPromiseOptions as ToastPromiseOptionsType,
ToastOptions as ToastOptionsType,
} from '@data-slot/toast'
export type ToastAction = ToastActionType
export type ToastUpdateOptions = ToastUpdateOptionsType
export type ToastPromiseOptions<T> = ToastPromiseOptionsType<T>
export type ToastOptions = ToastOptionsType
export type ToastShowOptions = ToastShowOptionsType
/** Options for a notification stack. */
export interface ToastProps {
/**
* Position of the stack in the page viewport.
* @default "bottom-right"
*/
position?: ToastPosition
/**
* Maximum number of visible notifications.
* @default 3
*/
limit?: number
/**
* Time before dismissal, in milliseconds. Use 0 to keep a toast open.
* @default 5000
*/
duration?: number
/**
* Pause dismissal while the pointer is over the stack.
* @default true
*/
pauseOnHover?: boolean
/**
* Pause dismissal while focus is inside the stack.
* @default true
*/
pauseOnFocus?: boolean
/**
* Move the viewport to document.body to escape clipping containers.
* @default true
*/
portal?: boolean
}
Usage
Place one Toast in your layout. It supplies the template, status icons, close button, and notification viewport. Its script initializes the data-slot controller.
---
import { Toast } from "@/components/ui/toast"
---
<Toast data-app-toast />
<script>
import { createToast } from "@data-slot/toast"
const root = document.querySelector("[data-app-toast]")!
const toaster = createToast(root)
toaster.show({
title: "Changes saved",
description: "Your project settings are up to date.",
type: "success",
})
</script>
Call show() from your application event handler after the root is in the document. createToast(root) returns the existing controller when the root is already initialized. Each root has an independent stack. With Astro navigation, find the current root before you use the controller; the component destroys its old controllers before a page swap.
Examples
With an action
An action dismisses its toast after the callback runs. Call event.preventDefault() in the callback to keep it open.
Promise states
Use promise() to change one notification from loading to success or error. The examples simulate a request. Call the returned handle’s unwrap() when your application also needs the result or error.
Position
Use position to select one of six viewport positions. Notifications expand when hovered or focused. Older notifications remain mounted but become hidden and inert when the visible limit is exceeded.
Custom template
The default slot replaces both the template and viewport. Keep one ToastTemplate and one ToastViewport inside the root. ToastTemplate has its own default content, which you can replace with the exported parts:
<Toast>
<ToastTemplate>
<ToastItem>
<ToastContent>
<ToastTitle />
<ToastDescription />
</ToastContent>
<ToastAction />
<ToastClose aria-label="Dismiss notification" />
</ToastItem>
</ToastTemplate>
<ToastViewport aria-label="Project notifications" />
</Toast>
Import these parts from @/components/ui/toast. The primitive fills the title, description, and action with text. It hides an empty description or action. Keep these slots free of child markup that must survive an update. Avoid fixed IDs inside the template because each notification clones it.
API reference
ToastProps
position?ToastPosition
Position of the stack in the page viewport.
ToastPosition"bottom-right"limit?number
Maximum number of visible notifications.
number3duration?number
Time before dismissal, in milliseconds. Use 0 to keep a toast open.
number5000pauseOnHover?boolean
Pause dismissal while the pointer is over the stack.
booleantruepauseOnFocus?boolean
Pause dismissal while focus is inside the stack.
booleantrueportal?boolean
Move the viewport to document.body to escape clipping containers.
booleantrueToastShowOptions
id?string
stringtitlestring
stringdescription?string
stringtype?ToastType
ToastTypeduration?number
numberaction?ToastAction
ToastActiondismissible?boolean
booleancloseButtonAriaLabel?string
stringtestId?string
stringToastUpdateOptions
title?string
stringdescription?string
stringtype?ToastType
ToastTypeduration?number
numberaction?ToastAction
ToastActiondismissible?boolean
booleancloseButtonAriaLabel?string
stringtestId?string
stringToastAction
labelstring
stringonClick?(event: ToastActionEvent) => void
Call `event.preventDefault()` to keep the toast open after the action.
(event: ToastActionEvent) => voidvalue?string
stringToastPromiseOptions
loadingstring | ToastPromiseState
string | ToastPromiseStatesuccess?ToastPromiseStateValue<T>
ToastPromiseStateValue<T>error?ToastPromiseErrorValue
ToastPromiseErrorValuedescription?string
stringOther parts accept their native HTML attributes and class. ToastViewport is an ordered list. ToastItem is a list item. ToastAction and ToastClose are buttons. ToastIcon supplies the status icons, including the loading indicator.
Events
Dispatch these events on the toast root. The root emits the outbound events.
Outbound events
| Event | Detail |
|---|---|
toast:change |
{ id: string, action: "show" | "dismiss" } |
toast:action |
{ id: string, value: string | undefined } |
Inbound events
| Event | Detail |
|---|---|
toast:show |
ToastShowOptions |
toast:update |
{ id: string } & ToastUpdateOptions |
toast:dismiss |
{ id: string } or string |
toast:clear |
none |
Controller
Import createToast and controller types from @data-slot/toast. Use show, update, promise, dismiss, and dismissAll to control notifications. A repeated show() ID replaces the old toast; update(id, patch) changes it in place. Set duration: 0 to keep a notification open until dismissed.
The root also accepts toast:show, toast:update, toast:dismiss, and toast:clear custom events. It emits toast:change and toast:action. See the data-slot Toast API for options and event details.
Read the installed source for all exported parts.
Accessibility and limits
The primitive announces errors and warnings as alerts. Other notifications use polite status announcements. Keep essential errors next to the affected field as well. Timers pause on hover, focus, window blur, and a hidden document. Users can close a toast with its labeled button or a swipe. dismissible: false disables swiping; it does not remove the close button.
The styles adapt Coss Toast to Astro and data-slot. This component uses the data-slot API. Anchored toasts, Base UI providers, F6 viewport focus, and Escape dismissal are not supplied. Animation follows the reduced-motion preference.
portal defaults to true in this Astro component, so the viewport can escape clipping containers. The primitive itself defaults to false. Set portal={false} to retain the viewport in its original parent; it still uses fixed positioning unless you supply a different layout class.
Theme and layout
Toast styles use the project preset. Keep messages short enough to read at phone widths, and choose a viewport position that does not cover the main page action. Portalled toasts can escape clipping containers. Use an Alert for feedback that must remain in the page content.