@coder-safal/toastack
v0.3.0
Published
Accessible, stacking, promise-aware toasts for React.
Readme
@coder-safal/toastack
Accessible, stacking, promise-aware toasts for React 18/19 and Next.js. JavaScript has no runtime dependencies beyond React; styles are imported separately.
Installation
Using npm:
npm install @coder-safal/toastackUsing pnpm:
pnpm add @coder-safal/toastackBoth commands install the same package. v0.3.0 adds exit animations, lifecycle callbacks, translatable labels, right-to-left support, classNames, multiple toasters, cancellable promise toasts, and notification history. Coming from v0.2? Read Upgrading to v0.3: the devtools import moved.
The package name is @coder-safal/toastack, under the same npm scope as @coder-safal/envguard. Publishing defaults to public access.
Examples: positions, swiping, updates, custom content, queues, promises, lifecycle callbacks, durations, grouping, multiple toasters, labels and translation, classNames, right-to-left, headless rendering, history, devtools.
Setup
import { Toaster, toast } from '@coder-safal/toastack';
import '@coder-safal/toastack/styles.css';
export function App() {
return (
<>
<button onClick={() => toast.success('Changes saved')}>Save</button>
<Toaster />
</>
);
}Mount one default <Toaster /> per app; add named toasters only when you need a second stack. Toasts appear at the bottom right by default, respect mobile safe areas, and use the system color scheme. Set position to move the stack.
Positions
Set position on the one <Toaster /> mounted in your app. It moves the entire stack, not individual toasts:
<Toaster position="top-center" />Choose one of these six configurations:
| Position | Example | Stack expands |
| --- | --- | --- |
| Top left | <Toaster position="top-left" /> | Downward |
| Top center | <Toaster position="top-center" /> | Downward |
| Top right | <Toaster position="top-right" /> | Downward |
| Bottom left | <Toaster position="bottom-left" /> | Upward |
| Bottom center | <Toaster position="bottom-center" /> | Upward |
| Bottom right (default) | <Toaster position="bottom-right" /> | Upward |
The table shows alternatives; mount only one toaster. All notifications use its selected position, with safe-area spacing on mobile. Change positions dynamically with state:
import { useState } from 'react';
import { Toaster, toast, type ToastPosition } from '@coder-safal/toastack';
import '@coder-safal/toastack/styles.css';
export function PositionedNotifications() {
const [position, setPosition] = useState<ToastPosition>('bottom-right');
return <>
<select aria-label="Notification position" value={position}
onChange={(event) => setPosition(event.target.value as ToastPosition)}>
<option value="top-left">Top left</option>
<option value="top-center">Top center</option>
<option value="top-right">Top right</option>
<option value="bottom-left">Bottom left</option>
<option value="bottom-center">Bottom center</option>
<option value="bottom-right">Bottom right</option>
</select>
<button onClick={() => toast.success('Position selected')}>Show notification</button>
<Toaster position={position} />
</>;
}Swipe to dismiss
<button onClick={() => toast.info('Swipe this card left or right')}>
Show swipeable toast
</button>No swipe option is required. Drag the card body horizontally with a mouse, pen, or touch. Swipes must cover at least 25% of the card width (minimum 48px); shorter gestures snap back. Buttons, links, form inputs, and editable content keep their normal behavior, and vertical gestures allow scrolling. The close button and keyboard dismissal remain available.
Upgrading to v0.3
Most apps need no changes. Check these:
- Devtools import moved. Change
import { ToastDevtools } from '@coder-safal/toastack'toimport { ToastDevtools } from '@coder-safal/toastack/devtools'. This keeps the inspector out of the main bundle. - Escape needs focus in the stack.
Escapenow dismisses the newest toast only while focus is inside the notification region (for example afterAlt+T), so closing your own dialog with Escape no longer removes a toast. - Groups are split by type.
toast.success('Synced', { group: 'sync' })andtoast.error('Sync failed', { group: 'sync' })now make two cards instead of one. - Dismissed cards animate out. A dismissed card stays in the DOM for about 200ms with
data-removed,aria-hidden, andinert, then unmounts. Role-based test queries (getByRole('listitem')) ignore it; tests that count.toastack-toastelements should wait for the exit to finish.
Upgrading from v0.1
Existing imports, CSS imports, toast() and typed toast calls, actions, promise handling, dismissal by id, and <Toaster /> continue to work. No migration is required. Defaults remain bottom-right positioning, six mounted toasts with oldest-toast eviction, no deduplication, five-second timers for regular toasts, and persistent loading toasts. Queueing, different positions, custom rendering, and deduplication require explicit options; swipe dismissal is also available on existing cards.
Next.js App Router
The published JavaScript preserves its "use client" boundary. Your root layout can remain a Server Component:
// app/layout.tsx
import { Toaster } from '@coder-safal/toastack';
import '@coder-safal/toastack/styles.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return <html lang="en"><body>{children}<Toaster /></body></html>;
}Call toast() from client event handlers, effects, or client utilities. Do not call it while rendering a component or from server code. Server snapshots are always empty to avoid leaking notifications into HTML or causing hydration mismatches. A minimal example is in examples/next.
API
const id = toast('Hello');
toast.success('Saved', { description: 'Your profile is up to date.' });
toast.error('Payment failed', { description: 'Please check your card.' });
toast.info('New version available');
toast.warning('Storage almost full');
toast.loading('Uploading…');
toast.update(id, { title: 'Updated', type: 'success' });
toast.dismiss(id);
toast.dismiss(); // dismiss allEvery creation call returns a string id. Grouped or deduplicated creation calls can reuse an existing id. Regular toasts dismiss after 5 seconds of active time. Loading toasts stay until dismissed or settled by toast.promise(). By default the stack keeps at most six notifications, evicting the oldest; three cards are visible when collapsed. Hover or focus expands every remaining card, with scrolling when needed on small screens.
Updates and deduplication
const id = toast.loading('Uploading…');
toast.update(id, { title: 'Upload complete', type: 'success' });
toast.info('New version available', { dedupe: true });toast.update(id, options) preserves the id and stack order, merges the supplied title, type, description, action, icon, className, onDismiss, or onAutoClose, and restarts the timer. Loading updates stay until dismissed or updated again. Explicit duration overrides survive updates; set duration: undefined to return to the current global default. Pass undefined to clear a description or action, and null to hide an icon. Unknown or dismissed ids are ignored. Queued updates wait until promotion to start their timer.
Deduplication is opt-in per creation call. An identical title, description, type, and effective duration reuses an existing visible or queued plain toast and refreshes its timer. Custom content, custom icons, action toasts, and promise notifications retain independent identities so callbacks and async outcomes cannot overwrite each other.
Custom JSX and icons
toast.success('Bookmarked', { icon: <span>★</span> });
toast.info('Quiet notification', { icon: null });
toast.custom((item) => (
<div>
<strong>New message</strong>
<p>Alex sent you a photo.</p>
<button onClick={() => toast.dismiss(item.id)}>Got it</button>
</div>
), { title: 'New message from Alex' });Custom content replaces the standard icon and message area, retaining the card, close button, progress indicator, and swipe behavior. The required plain text title supplies the screen reader announcement; do not put interactive controls in it. Custom controls become inert while their card is collapsed behind the front notification. Custom icons are decorative, so keep essential information in the title or description.
Limits and queue behavior
<Toaster maxVisible={3} overflow="queue" />maxVisible sets the maximum number of mounted cards, including those behind the front card. Values are clamped to 1–20 (default 6). With multiple toasters, the limit and queue apply to each toaster separately. The collapsed deck still shows up to three cards; hover or focus expands the mounted cards.
The default overflow="discard-oldest" removes the oldest visible toast when a new one arrives. With overflow="queue", new arrivals wait in FIFO order. Closing or expiring a visible toast promotes the next queued item to the front and gives it its full duration. Queued items are not rendered or announced, and have no active timer. The queue holds at most 100 items, dropping the oldest queued entry when full.
toast.dismiss(id) also removes a queued item. toast.dismiss() clears visible and queued items together. Reducing the visible limit moves overflow into the queue in queue mode, resetting its duration on promotion. Increasing it fills the available slots. Switching to discard mode clears pending entries. Mount one toaster before creating notifications so its queue configuration is applied.
Promises
const user = await toast.promise(saveProfile(data), {
loading: 'Saving…',
success: (result) => `Saved ${result.name}`,
error: (error) => error instanceof Error ? error.message : 'Could not save',
});The same toast changes from loading to success or error, then gets a fresh timer using its explicit duration or the current global default (5 seconds by default). Messages can be strings or functions; success values are inferred and errors are unknown. The exact original promise is returned, preserving its result and rejection. Handle rejections with try/catch or .catch() as usual. Dismissing a pending toast does not cancel the operation, and settlement will not recreate it. If a message formatter throws, the toast uses a fallback message.
Each message can also be an object with a description, and you can pass a function instead of a promise. The function runs right away and receives an AbortSignal. Add cancel to show a Cancel button on the loading toast:
await toast.promise((signal) => uploadFile(file, { signal }), {
loading: { title: 'Uploading…', description: file.name },
success: (result) => ({ title: 'Upload complete', description: `${result.size} bytes` }),
error: (error) => error instanceof Error ? error.message : 'Upload failed',
cancel: 'Cancel',
});Clicking Cancel aborts the signal and dismisses the toast; no error toast appears. Your operation should stop when the signal aborts. The returned promise then rejects (usually with an AbortError), so still handle the rejection. A plain string message replaces only the title and keeps the current description; an object replaces both. cancel is ignored when you pass a promise, because there is no signal to abort. After settlement, the toast shows your own action if you passed one, in place of Cancel.
Lifecycle callbacks
toast('Message archived', {
action: { label: 'Undo', onClick: () => restore(id) },
onAutoClose: () => archiveForGood(id), // the timer ran out
onDismiss: (item) => analytics.track('toast_dismissed', { id: item.id }),
});Every toast removal runs exactly one callback. onAutoClose runs when the timer expires. onDismiss runs for every other removal: the close button, a swipe, Escape, the action button, toast.dismiss(), eviction by maxVisible, or a full queue. Both receive the toast's latest record. They run after the stack has updated, so creating another toast inside them is safe. An error thrown by a callback is reported as an uncaught error and does not affect the stack. Promise toasts accept the same options.
Actions
toast('Item deleted', {
description: 'You can restore it.',
action: {
label: 'Undo',
onClick: () => restoreItem(id),
},
});The action dismisses its toast after the handler returns. For async actions, handle failures in your handler or start a separate promise toast.
Toaster options
<Toaster theme="dark" position="top-center" maxVisible={3} overflow="queue" label="Notifications" className="my-notifications" />| Prop | Default | Values |
| --- | --- | --- |
| theme | "system" | "light", "dark", "system" |
| label | "Notifications" | Accessible region label |
| className | — | Extra CSS class |
| position | "bottom-right" | "top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right" |
| maxVisible | 6 | Mounted cards, clamped to 1–20 |
| overflow | "discard-oldest" | "discard-oldest", "queue" |
| duration | 5000 | Default active milliseconds for regular toasts; Infinity for sticky |
| id | — | Name of a secondary toaster |
| labels | English | Translated text |
| classNames | — | Extra classes per part and type |
maxVisible, overflow, and duration are applied only when passed, so settings from toast.configure() are kept for any prop you omit. Removing a prop you passed earlier restores its built-in default.
Durations and sticky toasts
Set the global default on the toaster; override it for individual notifications:
<Toaster duration={8000} />toast.success('Quick confirmation', { duration: 2000 });
const id = toast.error('Connection lost', { duration: Infinity });
// The error stays until you dismiss it or update it.
toast.dismiss(id);
const sticky = toast.info('Keep this visible', { duration: Infinity });
toast.update(sticky, { title: 'Closing in three seconds', duration: 3000 });
toast.update(sticky, { duration: undefined }); // use the current global defaultDurations count active milliseconds and pause during the styled toaster's hover, focus, swipe, or hidden-tab interaction. Infinity removes the expiry timer and progress bar. 0 expires on the next timer tick; negative/NaN values fall back to the global default, and very large finite values are capped at the native timer limit. Loading toasts always remain sticky; their explicit duration applies when updated or settled to a regular type. Changing a global default affects new toasts and later updates, without resetting existing timers.
Promise durations apply after settlement:
await toast.promise(saveProfile(data), {
loading: 'Saving…',
success: 'Saved',
error: 'Could not save',
duration: 2500,
});Grouping
Use a shared group key to count related arrivals in one card:
const id = toast.info('New messages', { group: 'messages' });
toast.info('New messages', { group: 'messages' });
toast.info('New messages', { group: 'messages' });
// One card displays a count of 3 and announces "3 notifications. New messages".
toast.dismiss(id); // dismiss the groupGroups preserve the first id and stack position, increase count, show the latest title and description (a description omitted by the latest arrival is cleared), and restart the timer. An explicit duration from an earlier arrival is kept unless the latest one passes its own. Arrivals are grouped by key and type, so toast.error(…, { group: 'sync' }) never merges into a success card. Queued groups merge before they become visible. Dismissing or expiring a group resets its count on the next arrival. Grouping works on plain notifications; custom content, custom icons, action toasts, and promise calls keep independent identities, and a grouped toast that later gets an action or icon through toast.update() leaves its group. Unlike deduplication, grouping increments a count and can combine different titles under the same key.
Multiple toasters
Give a second toaster an id, then send toasts to it with the toaster option:
<Toaster />
<Toaster id="editor" position="top-left" label="Editor notifications" />toast.success('Saved'); // default toaster
toast.info('Draft autosaved', { toaster: 'editor' }); // editor toasterToasts without toaster go to the toaster without an id. maxVisible and the queue apply per toaster, and grouping and deduplication only match toasts in the same toaster. overflow and duration are shared settings, so set them on one toaster or with toast.configure(). Alt+T focuses the first mounted toaster that has notifications, and each toaster has its own live regions. Give each one a distinct label so screen reader users can tell them apart. A toast's toaster is fixed when it's created.
Labels and translation
The styled toaster's built-in text is in English. Override any of it with labels:
<Toaster
label="सूचनाहरू"
labels={{
list: 'सूचना सूची',
dismiss: 'सूचना हटाउनुहोस्',
count: (count) => `${count} सूचना`,
default: 'सूचना', success: 'सफल', error: 'त्रुटि',
info: 'जानकारी', warning: 'चेतावनी', loading: 'लोड हुँदैछ',
}}
/>label names the region. In labels, list names the list, dismiss is the close button's accessible name, count builds the grouped-count text, and the type keys are the prefixes screen readers hear before each title (for example "Success: Saved"). Keys you leave out keep their English defaults. Your own titles, descriptions, and action labels are never translated.
Styling with classNames
Add your own classes to any part of the card, per type, or per toast. This works well with Tailwind and shadcn/ui:
<Toaster classNames={{
toast: 'rounded-lg shadow-lg',
title: 'font-semibold',
description: 'text-sm opacity-80',
action: 'btn btn-primary',
close: 'opacity-60 hover:opacity-100',
error: 'border-red-500',
}} />toast.success('Payment received', { className: 'border-emerald-500' });Parts are toast, icon, content, title, description, count, action, close, and progress. Type keys (default, success, error, info, warning, loading) add a class to the card. Your classes are added alongside the built-in toastack-* classes, so the stacking layout keeps working. Your rules win when they are at least as specific as the defaults (for example .toastack .my-card) or load after the stylesheet. For full control, skip styles.css and use headless rendering.
Right-to-left layouts
Toasts follow the page's text direction. With <html dir="rtl"> (or dir="rtl" on any ancestor), the icon, text, and buttons run right to left, and the progress bar shrinks toward the start edge. Positions are screen corners, so bottom-right stays at the bottom right in both directions. Choose bottom-left if you want an RTL app's toasts on its start side. Swiping works in both directions.
Headless rendering
useToasts() returns the visible records in newest-first order. It subscribes to updates and has an empty SSR snapshot. You can use it without <Toaster /> or the default stylesheet:
'use client';
import { useEffect } from 'react';
import { toast, useToasts } from '@coder-safal/toastack';
export function CustomNotifications() {
const toasts = useToasts();
useEffect(() => {
toast.configure({ duration: 8000, maxVisible: 3, overflow: 'queue' });
}, []);
return <section aria-label="Notifications">
<button onClick={() => toast.success('Saved', { duration: Infinity })}>Show sticky toast</button>
<ul>{toasts.map((item) => <li key={item.id}>
<strong>{item.title}</strong>
{item.count > 1 && <span> ({item.count} notifications)</span>}
{item.description && <p>{item.description}</p>}
<button onClick={() => toast.dismiss(item.id)}>Dismiss {item.title}</button>
</li>)}</ul>
</section>;
}The hook only subscribes; your renderer owns styling, announcements, focus, and keyboard shortcuts. Store timers still expire and queued items still promote. These helpers support custom renderers:
useQueuedToasts()returns queued records, oldest first (the next one shown is first), with the same empty SSR snapshot.toast.pause()andtoast.resume()pause and resume every countdown, for example on hover or focus of your renderer. They don't interfere with the styled toaster's own pauses.toast.remaining(id)returns the active milliseconds left for a visible toast, orInfinitywhen it has no countdown (sticky, loading, queued, or unknown ids).
Use the styled <Toaster /> when you want its built-in accessibility and gesture behavior. toast.configure() applies partial defaults for a headless app; omitted options are preserved, while explicitly setting undefined restores that option's built-in default. A mounted <Toaster /> changes these same global settings only for the props it is passed.
Notification history
Import the history hook from its own entry point to build an inbox or unread badge:
'use client';
import { toastHistory, useToastHistory } from '@coder-safal/toastack/history';
export function Inbox() {
const { items, unread } = useToastHistory();
return <section aria-label="Notification history">
<h2>Notifications ({unread} unread)</h2>
<button onClick={() => toastHistory.markAllRead()}>Mark all read</button>
<ul>{items.map((item) => <li key={item.id}>
{!item.read && <span>New: </span>}{item.title}{item.count > 1 && ` (${item.count})`}
</li>)}</ul>
</section>;
}Recording starts when the module is first imported, so import it from a component that mounts early, such as your root layout. Toasts created before that import aren't recorded. Each item has the toast's id, title, description, type, count, and toaster, plus createdAt, updatedAt, read, and dismissed. Items are newest first, and history keeps the latest 50.
toastHistory.markRead(id)andtoastHistory.markAllRead()change read state. Another grouped arrival marks its item unread again; other updates keep its read state.toastHistory.clear()empties the history.toastHistory.setLimit(n)changes how many items are kept (minimum 1).toastHistory.getSnapshot()andtoastHistory.subscribe(listener)work outside React.
History is kept in memory only and resets on page reload. The server snapshot is empty. It records what the toast store shows; it is not a notification backend.
Optional devtools
import { Toaster } from '@coder-safal/toastack';
import { ToastDevtools } from '@coder-safal/toastack/devtools';
export function App() {
return <>
{/* Your app */}
<Toaster />
{import.meta.env.DEV && <ToastDevtools />}
</>;
}This is the Vite development flag. In Next.js, mount the inspector from a Client Component and use process.env.NODE_ENV === 'development'. The panel shows ids, titles, types, configured durations, and group counts for visible and queued records. Dismiss individual records or clear both the visible stack and queue. It does not mount a second toaster, reset configuration, or load a stylesheet. Because it has its own entry point, apps that never import it don't pay for it. The devtools and history entries share one toast store with the main entry, including with CommonJS.
Theme variables
Override variables on the container after importing the default stylesheet:
.my-notifications {
--toastack-bg: #ffffff;
--toastack-fg: #18181b;
--toastack-muted: #52525b;
--toastack-border: #e4e4e7;
--toastack-radius: 12px;
--toastack-success: #15803d;
--toastack-error: #dc2626;
--toastack-info: #2563eb;
--toastack-warning: #a16207;
}For explicit themes, match their specificity, for example .my-notifications[data-theme='dark']. Choose accessible foreground/background combinations when overriding colors.
Accessibility and interaction
- Swipe a card horizontally with touch, pen, or the primary mouse button to dismiss it. Short or canceled gestures snap back; vertical gestures remain available for scrolling. Swiping does not start on buttons, links, form fields, or editable content.
- The close button dismisses only its toast and stops the click from bubbling to parent popup handlers.
Alt+Tfocuses and expands the notification region. Tab reaches its action and dismiss buttons.- While focus is inside the notification region,
Escapedismisses the newest notification, unless the application already prevented the key event. Escape elsewhere on the page (for example, closing a dialog) leaves notifications alone. When the focused stack becomes empty, focus returns to the prior element when available. - Timers pause while hovered, while focus is inside, and while the browser tab is hidden. They resume with their remaining time.
- Separate polite
statusand assertivealertlive regions announce updates without re-announcing interactive buttons. Collapsed background cards are hidden from assistive technology until expanded. - Types have distinct icons and text labels. Buttons have accessible names and visible focus styles.
- Dismissed cards fade toward the screen edge, or keep sliding in the direction they were swiped, before unmounting. While leaving they are
inertand hidden from assistive technology. If a card is removed while it has focus, focus moves to the notification region instead of the page. - Reduced-motion preferences disable motion, exit transitions, and the animated progress indicator; timing behavior stays the same.
- All built-in text can be translated, and layouts follow right-to-left text direction.
Automated tests cover the store, timer ownership, promise outcomes and cancellation, lifecycle callbacks, multiple toasters, history, announcements, translated labels, focus, keyboard interaction, exit transitions, StrictMode, server rendering without browser globals, and hydration. Manual screen reader verification remains a release check.
Development
Using npm:
npm install
npm run dev # interactive Vite playground
npm run check # types, tests, package build, gzip budget
npm pack --dry-runUsing pnpm:
pnpm install --frozen-lockfile
pnpm run dev
pnpm run check
pnpm run build
pnpm packFor the browser checks, run npx playwright install chromium once, then npm run test:browser. With pnpm, use pnpm exec playwright install chromium and pnpm run test:browser. They cover all six positions, mouse and touch swipes, queue promotion, custom content, expanded card spacing, timer pauses, keyboard focus, promise transitions and cancellation, actions, exit transitions, a second toaster, translated labels, custom classes, right-to-left layout, history, dark theme, small screens, and reduced motion.
To try changes from this checkout in another app before they are published, run npm pack here and install the resulting tarball in that app.
Scope
Phase 2 adds swipe dismissal, six positions, custom JSX and icons, updates by id, opt-in deduplication, and configurable visible limits with queueing. The existing stacked layout, six toast styles, progress indicators, promise transitions, actions, keyboard navigation, announcements, and themes remain available. Phase 3 adds the headless hook, sticky notifications, per-toast/global duration controls, grouping with counts, and an optional devtools inspector. Phase 4 (v0.3.0) adds exit animations, lifecycle callbacks, translatable labels, right-to-left support, classNames, multiple toasters, promise factories with cancellation and per-state descriptions, notification history, and separate /devtools and /history entry points. All features have examples above; see Upgrading to v0.3 for the few behavior changes.
Build outputs include ESM, CommonJS, and TypeScript declarations for the main, /devtools, and /history entries, plus styles.css. CI checks React 18 and 19 and caps gzip output at 6 KiB JavaScript and 3 KiB CSS, excluding React.
MIT licensed.
