# Toaster

Shows the toasts: short messages that appear in a corner of the screen and close by themselves. Mount it once, in the root layout; then call the functions from any component or `.ts` file: `addToast(options)`, `addSuccessToast`, `addErrorToast`, `addWarningToast`, `addInfoToast` (a string is the title, or pass `{ title, description, duration, action, loading, progress, icon, closable, onclose }`), `updateToast(id, patch)` and `removeToast(id)`. Each `add*` returns the toast id. A toast closes after `duration` (5000 ms by default, `0` keeps it open), pauses while the pointer or the focus is on it and while the tab is hidden, and the same message shown twice restarts its timer instead of stacking. Beyond `limit` the oldest toasts close. Screen readers announce new toasts: errors and warnings right away, the others politely. While a `Dialog` or `Drawer` is open the toasts show inside it, because a modal dialog makes the rest of the page inert. The toasts are `AlertBanner`s on an opaque surface, styled with the `--toast-*` variables or replaced with `toastSnippet`.

```ts
import { Toaster } from '@likable-hair/svelte';
```

Category: simple. Source: `src/lib/components/simple/notifiers/Toaster.svelte`.

## Examples

### Variants

Mount `<Toaster />` once in the root layout (these docs do, at the top right), then call the functions from anywhere, `.ts` files included. A string is the title; an object adds a `description` and more.

```svelte
<script lang="ts">
	import { addErrorToast, addInfoToast, addSuccessToast, addWarningToast, Button } from '@likable-hair/svelte';
</script>

<div class="row">
	<Button variant="secondary" onclick={() => addSuccessToast('Appointment saved')}>Success</Button>
	<Button
		variant="secondary"
		onclick={() =>
			addErrorToast({ title: 'Payment failed', description: 'The card was declined by the issuer.' })}
	>
		Error
	</Button>
	<Button
		variant="secondary"
		onclick={() =>
			addWarningToast({ title: 'Low stock', description: '3 products are below the minimum level.' })}
	>
		Warning
	</Button>
	<Button
		variant="secondary"
		onclick={() => addInfoToast({ title: 'New version available', duration: 0 })}
	>
		Info that stays
	</Button>
</div>

<style>
	.row {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}
</style>
```

### Actions, loading and progress

`action` adds a button that runs a callback and closes the toast. A `loading` toast stays open until `updateToast` turns it into a result; `progress` shows a bar that `updateToast` moves.

```svelte
<script lang="ts">
	import { addSuccessToast, addToast, Button, updateToast } from '@likable-hair/svelte';

	function remove() {
		addToast({
			title: 'Client deleted',
			description: 'Giulia Rossi was moved to the bin.',
			action: { label: 'Undo', onclick: () => addSuccessToast('Client restored') }
		});
	}

	function sync() {
		const id = addToast({ title: 'Importing clients…', loading: true, closable: false });
		setTimeout(() => {
			updateToast(id, {
				variant: 'success',
				title: '248 clients imported',
				loading: false,
				closable: true
			});
		}, 2500);
	}

	function upload() {
		const id = addToast({ title: 'Uploading photos', progress: 0, duration: 0 });
		let value = 0;
		const timer = setInterval(() => {
			value += 10;
			updateToast(id, { progress: value });
			if (value < 100) return;
			clearInterval(timer);
			updateToast(id, { variant: 'success', title: '12 photos uploaded', progress: undefined, duration: 4000 });
		}, 300);
	}
</script>

<div class="row">
	<Button variant="secondary" onclick={remove}>With action</Button>
	<Button variant="secondary" onclick={sync}>Loading</Button>
	<Button variant="secondary" onclick={upload}>Progress</Button>
</div>

<style>
	.row {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}
</style>
```

### Inside a dialog

A modal `Dialog` or `Drawer` makes the rest of the page inert, so while one is open the toasts show inside it and stay clickable.

```svelte
<script lang="ts">
	import { addSuccessToast, Button, Dialog } from '@likable-hair/svelte';

	let open = $state(false);
</script>

<Button variant="secondary" onclick={() => (open = true)}>Open dialog</Button>

<Dialog bind:open title="Edit appointment" closable>
	<p>Save the changes: the toast appears on top of the dialog.</p>
	{#snippet actionsSnippet()}
		<Button
			onclick={() =>
				addSuccessToast({ title: 'Changes saved', action: { label: 'View', onclick: () => {} } })}
		>
			Save
		</Button>
	{/snippet}
</Dialog>
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `position` | `'top-start' \| 'top-center' \| 'top-end' \| 'bottom-start' \| 'bottom-center' \| 'bottom-end'` | `'bottom-end'` | Corner or edge of the screen. On screens up to 640px wide the toasts take the full width. |
| `limit` | `number` | `5` | Maximum number of toasts on screen. When a new one exceeds it, the oldest that would close by itself closes. |
| `closeLabel` | `string` |  | Accessible name of the close buttons. Defaults to "Dismiss", in the language of `locale`. |
| `label` | `string` |  | Accessible name of the toast region. Defaults to "Notifications", in the language of `locale`. |
| `locale` | `string` |  | BCP 47 locale of the texts: `it` and `en` are built in, other languages fall back to English. Defaults to the one set with `setDefaultLocale`, else `en`. It also names the progress bar of a toast without a title ("Loading", "Progress"). |
| `class` | `string` |  | Extra classes on the element that holds the toasts. |

## Snippets

| Name | Parameters | Description |
| --- | --- | --- |
| `toastSnippet` | `{ toast: Toast; close: () => void }` | Replaces each toast. `close` closes it. |

## Types

Exported by the package: `import type { Toast, ToastOptions, ToastVariant, ToastCloseReason } from '@likable-hair/svelte';`

### Toast

`type Toast = ToastOptions & { … }`

| Name | Type | Description |
| --- | --- | --- |
| `id` (required) | `number` |  |
| `variant` (required) | `ToastVariant` |  |

### ToastOptions

`type ToastOptions = { … }`

| Name | Type | Description |
| --- | --- | --- |
| `variant` | `ToastVariant` | Color and default icon. Default `info`. |
| `title` | `string` | Bold first line. |
| `description` | `string` | Text under the title. |
| `icon` | `string` | SVG path of the icon, instead of the default one of the variant. An empty string removes it. |
| `duration` | `number` | Milliseconds before the toast closes by itself; `0` keeps it open. Default 5000, or `0` while `loading`. |
| `closable` | `boolean` | Shows the close button. Default `true`. |
| `action` | `{ label: string; href?: string; onclick?: (event: MouseEvent) => void }` | Button on the right. A click closes the toast, unless `onclick` calls `event.preventDefault()`. With `href` the button is a link to that URL, which SvelteKit preloads like any link. |
| `loading` | `boolean` | Shows a spinner and a sliding bar, for work in progress. Update the toast when it ends. |
| `progress` | `number` | Shows a progress bar at this percentage (0–100). |
| `onclose` | `(reason: ToastCloseReason) => void` | Called when the toast closes, with the reason. |

### ToastVariant

`type ToastVariant = 'info' \| 'success' \| 'warning' \| 'error'`

### ToastCloseReason

Why a toast closed: its time ran out, the user closed it, the user clicked its action, or `removeToast` / the limit removed it.

`type ToastCloseReason = 'timeout' \| 'dismiss' \| 'action' \| 'remove'`
