This repo provides a simple Toast component for SvelteKit. A simple $state rune provides a queue into which toast content is assigned. An $effect rune in the Toast component (which changes no state) displays the toast.
Builds used
The toast-installation.md for installation instructions.
The toast system has three parts: the Toast component, the toastStore, and the EmailToastCargo type.
Add <Toast /> to your root layout so it is available across all pages. It renders as a native popover and manages its own visibility.
<!-- src/routes/+layout.svelte -->
<script>
import Toast from '$lib/components/Toast.svelte';
</script>
{@render children()}
<Toast />
Each toast requires an EmailToastCargo object with four fields:
import type { EmailToastCargo } from '$lib/actionTypes';
const cargo: EmailToastCargo = {
title: 'Download link on its way', // Displayed as the toast heading
message: 'A link was emailed to you.', // Displayed as the toast body
email: '[email protected]', // The email address involved
persona: 'DOWNLOAD' // 'DOWNLOAD' | 'CONTACT_US'
};
Import toastStore and call toastStore.add(cargo) from any page or component:
<script>
import { toastStore } from '$lib/toastStore.svelte';
import type { EmailToastCargo } from '$lib/actionTypes';
const cargo: EmailToastCargo = { ... };
function showToast() {
toastStore.add(cargo);
}
</script>
<button onclick={showToast}>Notify me</button>
| Feature | Detail |
|---|---|
| Queueing | Multiple toastStore.add() calls queue toasts; they display one at a time |
| Auto-close | Toasts close automatically after AUTO_CLOSE_SECONDS (currently 40s) |
| Manual close | User can dismiss early via the close (✕) button |
| Dismiss | On close (either way), toastStore.dismiss() removes the toast from the queue and the next queued toast appears |
personaTo support a new toast category, add a value to the ToastPersona union in src/lib/actionTypes.ts:
export type ToastPersona = 'DOWNLOAD' | 'CONTACT_US' | 'YOUR_NEW_TYPE';