diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md
new file mode 100644
index 000000000..e561feb73
--- /dev/null
+++ b/.changeset/sticky-error-toasts.md
@@ -0,0 +1,28 @@
+---
+"@tailor-platform/app-shell": minor
+---
+
+Error toasts, and toasts with an `action`, now stay until the user closes them. `useToast` gives `toast.error(...)`, the error state of `toast.promise(...)`, and any call with an `action` the defaults `duration: Infinity` and `closeButton: true`. Before, Sonner closed every toast after 4 seconds, so a failed save could disappear before the user read it, and an Undo could vanish while the user reached for it.
+
+This changes what users see after the update. To keep the previous behavior, or to set your own defaults, use the new `toastDefaults` prop of `AppShell`. A field set there replaces that field only; fields and kinds left out keep the new default. An empty object such as `error: {}` is a type error. See the migration guide (`docs/migrations.md`, 1.21.0).
+
+```tsx
+// The previous behavior (4 seconds, no close button) for both kinds
+
+```
+
+A `duration` or `closeButton` passed to the call still wins:
+
+```ts
+toast.error("Retrying in 5s", { duration: 5000 }); // closes after 5 seconds
+```
+
+A call without an `action` that updates one of these toasts by `id` resets `duration` and `closeButton` to Sonner's defaults unless it passes its own. `toast.custom`, toasts with `dismissible: false`, and success, info, warning and plain toasts without an `action` keep Sonner's defaults. The position (bottom right), the number of visible toasts (3) and the z-index are unchanged. A `toast` imported from `sonner` directly does not get the new defaults.
+
+The toast docs (`patterns/interaction-toast`, `api/use-toast`) now describe the real position, count and durations. They used to say top right, one at a time, and 3 seconds for success.
diff --git a/docs-manifest.json b/docs-manifest.json
index 2c68be482..d7047c862 100644
--- a/docs-manifest.json
+++ b/docs-manifest.json
@@ -115,10 +115,10 @@
"claims": [],
"symbols": ["AppShell", "AppShellProps"],
"hashes": {
- "typeSurface": "51313066e142afc2",
- "outline": "25fb9b8ab6949331",
+ "typeSurface": "5214717584b72041",
+ "outline": "9b3b04b96cf99581",
"snapshot": null,
- "outputMd": "cd57abd4909118a4",
+ "outputMd": "4f56932d1dab938a",
"examples": null
}
},
@@ -1028,9 +1028,9 @@
"symbols": [],
"hashes": {
"typeSurface": null,
- "outline": "45b23abe90e466b2",
+ "outline": "4ede6f17c870d838",
"snapshot": null,
- "outputMd": "f68bdab855730f48",
+ "outputMd": "fbdc96bd3d3d0140",
"examples": "7089e7331b95df31"
}
},
@@ -1130,9 +1130,9 @@
"symbols": [],
"hashes": {
"typeSurface": null,
- "outline": "e88bb360eb853c34",
+ "outline": "aa7644812db897fd",
"snapshot": null,
- "outputMd": "19ca77c7802ca5f6",
+ "outputMd": "597b3a3b3f96a89c",
"examples": null
}
},
@@ -1790,9 +1790,9 @@
"symbols": [],
"hashes": {
"typeSurface": null,
- "outline": "9100b0606aa15761",
+ "outline": "0fc65140da8f7dff",
"snapshot": null,
- "outputMd": "3f763c8074704709",
+ "outputMd": "90d80eef666e4cb4",
"examples": "0dce35625d5e56cf"
}
},
@@ -1828,7 +1828,7 @@
"packages/core/skills/app-shell-patterns/references/components/activity-card.md": "230039d9f96fd264",
"packages/core/skills/app-shell-patterns/references/components/ai-chat.md": "008761ccc93ef0fe",
"packages/core/skills/app-shell-patterns/references/components/alert.md": "9b237d9c19b54102",
- "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "cd57abd4909118a4",
+ "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "4f56932d1dab938a",
"packages/core/skills/app-shell-patterns/references/components/appearance-switcher.md": "b55f1d538651d467",
"packages/core/skills/app-shell-patterns/references/components/attachment.md": "8922f126009ee1df",
"packages/core/skills/app-shell-patterns/references/components/autocomplete.md": "f3179004d35f8c88",
@@ -1897,7 +1897,7 @@
"packages/core/skills/app-shell-patterns/references/api/use-route-error.md": "1a44180ec84ce4b9",
"packages/core/skills/app-shell-patterns/references/api/use-theme.md": "000e2603cef83d47",
"packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "717d6989930fb8c8",
- "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "3f763c8074704709",
+ "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "90d80eef666e4cb4",
"packages/core/skills/app-shell-patterns/references/patterns/form-composer.md": "ed187ac3a0773d3d",
"packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "a0d3c952b0b10351",
"packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c",
@@ -1906,11 +1906,11 @@
"packages/core/skills/app-shell-patterns/references/patterns/i18n-labels.md": "d9f0851d9c98ecfe",
"packages/core/skills/app-shell-patterns/references/patterns/interaction-confirm.md": "2db70f423c6fdf97",
"packages/core/skills/app-shell-patterns/references/patterns/interaction-multi-select.md": "253fcea1c4e5a42c",
- "packages/core/skills/app-shell-patterns/references/patterns/interaction-toast.md": "f68bdab855730f48",
+ "packages/core/skills/app-shell-patterns/references/patterns/interaction-toast.md": "fbdc96bd3d3d0140",
"packages/core/skills/app-shell-patterns/references/pages/document-collection.md": "e79d9120d86db198",
"packages/core/skills/app-shell-patterns/references/pages/document-detail.md": "e07c7fee2478a21d",
"packages/core/skills/app-shell-patterns/SKILL.md": "18efee79280174e7",
- "packages/core/skills/app-shell-upgrade/references/migrations.md": "9bd2735c34fd35e3",
+ "packages/core/skills/app-shell-upgrade/references/migrations.md": "565afc6a837ba8da",
"packages/core/skills/app-shell-upgrade/SKILL.md": "f9be942f3e596c00"
}
}
diff --git a/docs-src/components/app-shell.docs.outline.md b/docs-src/components/app-shell.docs.outline.md
index f879726c0..cd7ebb8c4 100644
--- a/docs-src/components/app-shell.docs.outline.md
+++ b/docs-src/components/app-shell.docs.outline.md
@@ -228,6 +228,22 @@ Supported locales: `en`, `ja`
Access the configured timezone in components using [`useTimeZone`](../api/use-time-zone.md).
+### toastDefaults
+
+- **Type:** `{ error?: ToastDefault; action?: ToastDefault }` where `ToastDefault` is `{ duration?: number; closeButton?: boolean }` with at least one field set (optional)
+- **Default:** `error` and `action` both `{ duration: Infinity, closeButton: true }`
+- **Description:** Options [`useToast`](../api/use-toast.md) applies to a toast when the call does not set them. `error` covers `toast.error(...)` and the error state of `toast.promise(...)`; `action` covers any toast with an `action`. With the defaults, these toasts stay until the user closes them and show a close button. A field set here replaces that field only; fields and kinds left out keep the default. An empty object such as `error: {}` is a type error; leave the kind out instead.
+
+```tsx
+// Errors close after 4 seconds without a close button, as before 1.21.0;
+// toasts with an action still stay.
+
+ {/* ... */}
+
+```
+
+Toasts with `dismissible: false` always keep sonner's defaults, and a `duration` or `closeButton` passed to the call always wins. See [useToast → Defaults](../api/use-toast.md#defaults).
+
### errorBoundary
- **Type:** `ErrorBoundaryComponent` (optional)
diff --git a/docs-src/guides/migrations.docs.outline.md b/docs-src/guides/migrations.docs.outline.md
index 8387819fe..fb465fa1e 100644
--- a/docs-src/guides/migrations.docs.outline.md
+++ b/docs-src/guides/migrations.docs.outline.md
@@ -15,6 +15,7 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| Version | Change |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| 1.21.0 | [Error and action toasts stay until the user closes them](#1210-error-and-action-toasts-stay-until-the-user-closes-them) |
| 1.21.0 | [Testing helpers deprecated in favour of TestingProvider](#1210-testing-helpers-deprecated-in-favour-of-testingprovider) |
| 1.20.0 | [z-index tokens renamed; old names are aliases](#1200-z-index-tokens-renamed-old-names-are-aliases) |
| 1.18.0 | [Destructive colours now resolve to the danger roles](#1180-destructive-colours-now-resolve-to-the-danger-roles) |
@@ -30,6 +31,34 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| 1.0.2 | [`Toaster` no longer accepts `richColors`](#102-toaster-no-longer-accepts-richcolors) |
| before 1.0 | [Pre-1.0 breaking changes](#before-10) |
+## 1.21.0: error and action toasts stay until the user closes them
+
+**Applies to:** apps that show toasts through `useToast`.
+
+Before 1.21.0, every toast closed after 4 seconds and had no close button, because AppShell passed no options and Sonner's defaults applied. From 1.21.0, `toast.error(...)`, the error state of `toast.promise(...)`, and any toast with an `action` get `duration: Infinity` and `closeButton: true`: they stay until the user closes them. Success, info, warning and plain toasts without an `action` are unchanged. Nothing errors; the change is only visible on screen.
+
+How to detect it: search the app for `toast.error(`, `toast.promise(` and toasts with `action:`. Look for places that show many errors in a row (for example, one per rejected edit): up to 3 toasts are visible, and with sticky errors they now stay until closed. Also check code that relied on an error toast closing by itself.
+
+What to change:
+
+- To keep the previous behavior, set both fields for the kind in the `toastDefaults` prop of `AppShell`. A field set there replaces that field only, so both fields are needed:
+
+ ```tsx
+
+ ```
+
+- To change one field, set only that field. `toastDefaults={{ error: { duration: 10_000 } }}` closes errors after 10 seconds and keeps the close button.
+- To change a single call, pass `duration` or `closeButton` to it. The call's options win over `toastDefaults`.
+- If a screen shows many errors in a row, give the call an `id` so that the new toast replaces the previous one: `toast.error(message, { id: "price-error" })`.
+
+An empty object for a kind, such as `error: {}`, is a type error. The prop is documented in [AppShell](./components/app-shell.md#toastdefaults), and the toast rules in [`useToast`](./api/use-toast.md).
+
## 1.21.0: testing helpers deprecated in favour of TestingProvider
**Applies to:** tests importing `AppShell` or `TestAppShellProps` from `@tailor-platform/app-shell/testing`.
diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md
index 9f198f37e..721ad8d5a 100644
--- a/docs-src/hooks/use-toast.docs.outline.md
+++ b/docs-src/hooks/use-toast.docs.outline.md
@@ -7,7 +7,7 @@ description: Hook for displaying toast notifications
# useToast
-React hook to display toast notifications for user feedback. It returns the `toast` function exported by [sonner](https://sonner.emilkowal.ski/toast). The built-in layouts (`SidebarLayout`, `GlobalHeaderLayout`) already render the toaster, so no provider setup is needed.
+React hook to display toast notifications for user feedback. It returns the `toast` function exported by [sonner](https://sonner.emilkowal.ski/toast), with the [defaults](#defaults) below for errors and toasts that carry an action. The built-in layouts (`SidebarLayout`, `GlobalHeaderLayout`) already render the toaster, so no provider setup is needed.
## Signature
@@ -25,6 +25,44 @@ toast.promise(promise, { loading, success, error });
toast.dismiss(id?);
```
+## Defaults
+
+The toaster uses sonner's defaults: bottom right (full width at the bottom at 600px and below), up to three toasts visible, 4 seconds per toast. `useToast` changes two of sonner's per-toast defaults so that a message the user must act on does not disappear on its own:
+
+| Call | `duration` | `closeButton` |
+| ----------------------------------------------------------------- | ---------- | ------------- |
+| `toast.error(...)`, and the error state of `toast.promise(...)` | `Infinity` | `true` |
+| Any call with an `action` (`toast(...)`, `toast.success(...)`, …) | `Infinity` | `true` |
+| Everything else, including `toast.custom(...)` | sonner's | sonner's |
+
+An option passed to the call wins over these defaults:
+
+```typescript
+toast.error("Retrying in 5s", { duration: 5000 }); // closes after 5 seconds
+toast.error("Failed to save", { closeButton: false }); // stays; swipe, or Escape while it has focus, dismisses it
+```
+
+For `toast.promise`, a `duration` or `closeButton` on the call applies to the error state, and an `error` result object (`{ message, duration, closeButton, ... }`) wins over both. An `action` on the call is shown in the loading and success states, so those states get the action defaults too.
+
+A toast with `dismissible: false` keeps sonner's defaults (no close button, closes after 4 seconds): the user cannot close it, so `useToast` does not keep it open. If the caller closes it with `toast.dismiss(id)`, pass `duration: Infinity`.
+
+Because these toasts stay, an error that can fire again for the same operation (a retry, a repeated save, one per rejected edit) stacks up a toast for each call. Give the call a stable `id` so the new toast replaces the previous one: `toast.error(message, { id: "save-error" })`.
+
+A call without an `action` that updates an existing toast by `id`, such as `toast.success("Saved", { id })` after `toast.error`, resets `duration` and `closeButton` to sonner's defaults unless it passes its own, so the updated toast closes by itself.
+
+An app changes these defaults with the [`toastDefaults`](../components/app-shell.md#toastdefaults) prop of `AppShell`. A field set there replaces that field only; fields and kinds left out keep the default:
+
+```tsx
+// Errors close after 4 seconds without a close button, as before 1.21.0;
+// toasts with an action still stay.
+
+
+// Errors close after 10 seconds and keep the close button; the action default is unchanged.
+
+```
+
+These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them.
+
## Parameters
### ExternalToast
@@ -73,6 +111,7 @@ function DeleteButton() {
try {
await deleteItem();
} catch (error) {
+ // Stays until the user closes it (see Defaults)
toast.error(`Failed to delete: ${(error as Error).message}`);
}
};
@@ -81,6 +120,25 @@ function DeleteButton() {
}
```
+### Toast with an Action
+
+A toast with an `action` stays until the user closes it. Do not make it the only way to do something: if the toast offers Undo, the page offers a way back too.
+
+```typescript
+function ArchiveButton({ item }: { item: Item }) {
+ const toast = useToast();
+
+ const handleArchive = async () => {
+ await archiveItem(item.id);
+ toast(`${item.name} archived`, {
+ action: { label: "Undo", onClick: () => restoreItem(item.id) },
+ });
+ };
+
+ return ;
+}
+```
+
### Custom Duration
diff --git a/docs-src/patterns/interaction-toast.docs.outline.md b/docs-src/patterns/interaction-toast.docs.outline.md
index 3c88d0944..0b344fb41 100644
--- a/docs-src/patterns/interaction-toast.docs.outline.md
+++ b/docs-src/patterns/interaction-toast.docs.outline.md
@@ -40,12 +40,16 @@ dont:
## Constraints
-- Toast renders as a top-right overlay; mobile (<1024) anchors to bottom-center
-- Stack max one visible at a time; replace prior toast on new emission
-- Success auto-dismisses after 3s; Error is sticky (no auto-dismiss)
+- Toasts render at the bottom right. At 600px and below they span the bottom of the viewport
+- Up to three stay visible; older ones collapse behind the newest and leave as new ones arrive
+- Success, info and plain toasts close by themselves after 4s
+- Error toasts, and any toast with an `action`, stay until the user closes them and show a close button. `useToast` sets this; a `duration` or `closeButton` passed to the call wins
+- An error that can fire again for the same operation (a retry, a repeated save, one per rejected edit) passes a stable `id`, so the new toast replaces the previous one instead of stacking another toast the user has to close
+- Never make a toast the only way to do something. If a toast offers Undo, the page offers a way back too. While a dialog or sheet is open, the keyboard reaches a toast only through sonner's hotkey (Alt+T)
## Anti-patterns
- Toast on every navigation — creates noise; reserve for mutation feedback
-- More than one toast stacking — replace, don't accumulate
+- One toast per item in a bulk operation — one toast that sums up the result
+- An Undo or Retry that exists only in the toast — the page needs the same way back
- Blocking the UI on a toast — toasts are non-modal by definition
diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md
index af89fdc00..0b569677a 100644
--- a/docs/api/use-toast.md
+++ b/docs/api/use-toast.md
@@ -7,7 +7,7 @@ description: Hook for displaying toast notifications
# useToast
-React hook to display toast notifications for user feedback. It returns the `toast` function exported by [sonner](https://sonner.emilkowal.ski/toast). The built-in layouts (`SidebarLayout`, `GlobalHeaderLayout`) already render the toaster, so no provider setup is needed.
+React hook to display toast notifications for user feedback. It returns the `toast` function exported by [sonner](https://sonner.emilkowal.ski/toast), with the [defaults](#defaults) below for errors and toasts that carry an action. The built-in layouts (`SidebarLayout`, `GlobalHeaderLayout`) already render the toaster, so no provider setup is needed.
## Signature
@@ -25,6 +25,44 @@ toast.promise(promise, { loading, success, error });
toast.dismiss(id?);
```
+## Defaults
+
+The toaster uses sonner's defaults: bottom right (full width at the bottom at 600px and below), up to three toasts visible, 4 seconds per toast. `useToast` changes two of sonner's per-toast defaults so that a message the user must act on does not disappear on its own:
+
+| Call | `duration` | `closeButton` |
+| ----------------------------------------------------------------- | ---------- | ------------- |
+| `toast.error(...)`, and the error state of `toast.promise(...)` | `Infinity` | `true` |
+| Any call with an `action` (`toast(...)`, `toast.success(...)`, …) | `Infinity` | `true` |
+| Everything else, including `toast.custom(...)` | sonner's | sonner's |
+
+An option passed to the call wins over these defaults:
+
+```typescript
+toast.error("Retrying in 5s", { duration: 5000 }); // closes after 5 seconds
+toast.error("Failed to save", { closeButton: false }); // stays; swipe, or Escape while it has focus, dismisses it
+```
+
+For `toast.promise`, a `duration` or `closeButton` on the call applies to the error state, and an `error` result object (`{ message, duration, closeButton, ... }`) wins over both. An `action` on the call is shown in the loading and success states, so those states get the action defaults too.
+
+A toast with `dismissible: false` keeps sonner's defaults (no close button, closes after 4 seconds): the user cannot close it, so `useToast` does not keep it open. If the caller closes it with `toast.dismiss(id)`, pass `duration: Infinity`.
+
+Because these toasts stay, an error that can fire again for the same operation (a retry, a repeated save, one per rejected edit) stacks up a toast for each call. Give the call a stable `id` so the new toast replaces the previous one: `toast.error(message, { id: "save-error" })`.
+
+A call without an `action` that updates an existing toast by `id`, such as `toast.success("Saved", { id })` after `toast.error`, resets `duration` and `closeButton` to sonner's defaults unless it passes its own, so the updated toast closes by itself.
+
+An app changes these defaults with the [`toastDefaults`](../components/app-shell.md#toastdefaults) prop of `AppShell`. A field set there replaces that field only; fields and kinds left out keep the default:
+
+```tsx
+// Errors close after 4 seconds without a close button, as before 1.21.0;
+// toasts with an action still stay.
+
+
+// Errors close after 10 seconds and keep the close button; the action default is unchanged.
+
+```
+
+These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them.
+
## Parameters
### ExternalToast
@@ -84,6 +122,7 @@ function DeleteButton() {
try {
await deleteItem();
} catch (error) {
+ // Stays until the user closes it (see Defaults)
toast.error(`Failed to delete: ${(error as Error).message}`);
}
};
@@ -92,6 +131,25 @@ function DeleteButton() {
}
```
+### Toast with an Action
+
+A toast with an `action` stays until the user closes it. Do not make it the only way to do something: if the toast offers Undo, the page offers a way back too.
+
+```typescript
+function ArchiveButton({ item }: { item: Item }) {
+ const toast = useToast();
+
+ const handleArchive = async () => {
+ await archiveItem(item.id);
+ toast(`${item.name} archived`, {
+ action: { label: "Undo", onClick: () => restoreItem(item.id) },
+ });
+ };
+
+ return ;
+}
+```
+
### Custom Duration
diff --git a/docs/components/app-shell.md b/docs/components/app-shell.md
index cef77a032..ab6a084d1 100644
--- a/docs/components/app-shell.md
+++ b/docs/components/app-shell.md
@@ -226,6 +226,22 @@ Supported locales: `en`, `ja`
Access the configured timezone in components using [`useTimeZone`](../api/use-time-zone.md).
+### toastDefaults
+
+- **Type:** `{ error?: ToastDefault; action?: ToastDefault }` where `ToastDefault` is `{ duration?: number; closeButton?: boolean }` with at least one field set (optional)
+- **Default:** `error` and `action` both `{ duration: Infinity, closeButton: true }`
+- **Description:** Options [`useToast`](../api/use-toast.md) applies to a toast when the call does not set them. `error` covers `toast.error(...)` and the error state of `toast.promise(...)`; `action` covers any toast with an `action`. With the defaults, these toasts stay until the user closes them and show a close button. A field set here replaces that field only; fields and kinds left out keep the default. An empty object such as `error: {}` is a type error; leave the kind out instead.
+
+```tsx
+// Errors close after 4 seconds without a close button, as before 1.21.0;
+// toasts with an action still stay.
+
+ {/* ... */}
+
+```
+
+Toasts with `dismissible: false` always keep sonner's defaults, and a `duration` or `closeButton` passed to the call always wins. See [useToast → Defaults](../api/use-toast.md#defaults).
+
### errorBoundary
- **Type:** `ErrorBoundaryComponent` (optional)
diff --git a/docs/migrations.md b/docs/migrations.md
index ba49b357a..ef857c27c 100644
--- a/docs/migrations.md
+++ b/docs/migrations.md
@@ -15,6 +15,7 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| Version | Change |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| 1.21.0 | [Error and action toasts stay until the user closes them](#1210-error-and-action-toasts-stay-until-the-user-closes-them) |
| 1.21.0 | [Testing helpers deprecated in favour of TestingProvider](#1210-testing-helpers-deprecated-in-favour-of-testingprovider) |
| 1.20.0 | [z-index tokens renamed; old names are aliases](#1200-z-index-tokens-renamed-old-names-are-aliases) |
| 1.18.0 | [Destructive colours now resolve to the danger roles](#1180-destructive-colours-now-resolve-to-the-danger-roles) |
@@ -30,6 +31,34 @@ Each entry states which versions are affected, what breaks, how to detect it, an
| 1.0.2 | [`Toaster` no longer accepts `richColors`](#102-toaster-no-longer-accepts-richcolors) |
| before 1.0 | [Pre-1.0 breaking changes](#before-10) |
+## 1.21.0: error and action toasts stay until the user closes them
+
+**Applies to:** apps that show toasts through `useToast`.
+
+Before 1.21.0, every toast closed after 4 seconds and had no close button, because AppShell passed no options and Sonner's defaults applied. From 1.21.0, `toast.error(...)`, the error state of `toast.promise(...)`, and any toast with an `action` get `duration: Infinity` and `closeButton: true`: they stay until the user closes them. Success, info, warning and plain toasts without an `action` are unchanged. Nothing errors; the change is only visible on screen.
+
+How to detect it: search the app for `toast.error(`, `toast.promise(` and toasts with `action:`. Look for places that show many errors in a row (for example, one per rejected edit): up to 3 toasts are visible, and with sticky errors they now stay until closed. Also check code that relied on an error toast closing by itself.
+
+What to change:
+
+- To keep the previous behavior, set both fields for the kind in the `toastDefaults` prop of `AppShell`. A field set there replaces that field only, so both fields are needed:
+
+ ```tsx
+
+ ```
+
+- To change one field, set only that field. `toastDefaults={{ error: { duration: 10_000 } }}` closes errors after 10 seconds and keeps the close button.
+- To change a single call, pass `duration` or `closeButton` to it. The call's options win over `toastDefaults`.
+- If a screen shows many errors in a row, give the call an `id` so that the new toast replaces the previous one: `toast.error(message, { id: "price-error" })`.
+
+An empty object for a kind, such as `error: {}`, is a type error. The prop is documented in [AppShell](./components/app-shell.md#toastdefaults), and the toast rules in [`useToast`](./api/use-toast.md).
+
## 1.21.0: testing helpers deprecated in favour of TestingProvider
**Applies to:** tests importing `AppShell` or `TestAppShellProps` from `@tailor-platform/app-shell/testing`.
diff --git a/docs/patterns/interaction-toast.md b/docs/patterns/interaction-toast.md
index dd922363d..9115ddd20 100644
--- a/docs/patterns/interaction-toast.md
+++ b/docs/patterns/interaction-toast.md
@@ -34,12 +34,16 @@ function InteractionToast() {
## Constraints
-- Toast renders as a top-right overlay; mobile (<1024) anchors to bottom-center
-- Stack max one visible at a time; replace prior toast on new emission
-- Success auto-dismisses after 3s; Error is sticky (no auto-dismiss)
+- Toasts render at the bottom right. At 600px and below they span the bottom of the viewport
+- Up to three stay visible; older ones collapse behind the newest and leave as new ones arrive
+- Success, info and plain toasts close by themselves after 4s
+- Error toasts, and any toast with an `action`, stay until the user closes them and show a close button. `useToast` sets this; a `duration` or `closeButton` passed to the call wins
+- An error that can fire again for the same operation (a retry, a repeated save, one per rejected edit) passes a stable `id`, so the new toast replaces the previous one instead of stacking another toast the user has to close
+- Never make a toast the only way to do something. If a toast offers Undo, the page offers a way back too. While a dialog or sheet is open, the keyboard reaches a toast only through sonner's hotkey (Alt+T)
## Anti-patterns
- Toast on every navigation — creates noise; reserve for mutation feedback
-- More than one toast stacking — replace, don't accumulate
+- One toast per item in a bulk operation — one toast that sums up the result
+- An Undo or Retry that exists only in the toast — the page needs the same way back
- Blocking the UI on a toast — toasts are non-modal by definition
diff --git a/packages/core/src/components/appshell/appshell.tsx b/packages/core/src/components/appshell/appshell.tsx
index 221a6c30d..228403518 100644
--- a/packages/core/src/components/appshell/appshell.tsx
+++ b/packages/core/src/components/appshell/appshell.tsx
@@ -16,6 +16,7 @@ import {
buildConfigurations,
type AppInfo,
type ContextData,
+ type ToastDefaults,
} from "@/contexts/appshell-context";
import { RouterContainer, type RouterContainerProps } from "@/routing/router";
import { ThemeProvider, type ColorTheme } from "@/contexts/theme-context";
@@ -28,6 +29,31 @@ import type { PageEntry } from "@/fs-routes/types";
import { Text } from "../text";
import { AppShellTestingContext } from "./testing-context";
+/**
+ * `toastDefaults={{ ... }}` written inline is a new object on every render. Keyed by its
+ * values, it keeps the configurations, and the `toast` that `useToast` returns, the same
+ * object while the values stay the same. Keyed by identity, every render would rebuild the
+ * config context, and an effect that depends on `toast` would run again.
+ */
+const useToastDefaultsByValue = (value: ToastDefaults | undefined): ToastDefaults | undefined => {
+ const isSet = value !== undefined;
+ const errorDuration = value?.error?.duration;
+ const errorCloseButton = value?.error?.closeButton;
+ const actionDuration = value?.action?.duration;
+ const actionCloseButton = value?.action?.closeButton;
+ return useMemo(
+ () =>
+ isSet
+ ? // A field left out stays `undefined`, which `useToast` reads as "keep the built-in one".
+ ({
+ error: { duration: errorDuration, closeButton: errorCloseButton },
+ action: { duration: actionDuration, closeButton: actionCloseButton },
+ } as ToastDefaults)
+ : undefined,
+ [isSet, errorDuration, errorCloseButton, actionDuration, actionCloseButton],
+ );
+};
+
/**
* Shared props for manual and file-based route configuration.
*
@@ -126,6 +152,22 @@ type SharedAppShellProps = React.PropsWithChildren<{
*/
timeZone?: string;
+ /**
+ * Defaults `useToast` applies per kind of toast when the call does not set them.
+ *
+ * Built-in: `toast.error(...)`, the error state of `toast.promise(...)`, and any toast
+ * with an `action` get `{ duration: Infinity, closeButton: true }`, so they stay until
+ * the user closes them. A field set here replaces that field only; fields and kinds left
+ * out keep the built-in default. An empty object for a kind is a type error.
+ *
+ * @example
+ * ```tsx
+ * // Errors close after 4 s without a close button, as before; toasts with an action still stay.
+ *
+ * ```
+ */
+ toastDefaults?: ToastDefaults;
+
/**
* Global error boundary component applied to all routes.
*
@@ -315,6 +357,8 @@ const AppShellRoot = (props: AppShellProps) => {
return propsModules;
}, [propsModules, rootComponent, rootGuards]);
+ const toastDefaults = useToastDefaultsByValue(props.toastDefaults);
+
// Memoize configurations to prevent unnecessary re-renders
// configurations will be null if modules is not provided
const configurations = useMemo(
@@ -327,6 +371,7 @@ const AppShellRoot = (props: AppShellProps) => {
errorBoundary: props.errorBoundary,
locale: props.locale,
timeZone: props.timeZone,
+ toastDefaults,
})
: null,
[
@@ -336,6 +381,7 @@ const AppShellRoot = (props: AppShellProps) => {
props.errorBoundary,
props.locale,
props.timeZone,
+ toastDefaults,
],
);
diff --git a/packages/core/src/contexts/appshell-context.tsx b/packages/core/src/contexts/appshell-context.tsx
index e8e9b0ce7..30ed9ff85 100644
--- a/packages/core/src/contexts/appshell-context.tsx
+++ b/packages/core/src/contexts/appshell-context.tsx
@@ -59,6 +59,32 @@ export type RouteParams = AppShellRegister extends { routeParams: infer T }
? T
: Record>;
+/** Per-toast options `useToast` applies when the call does not set them itself. */
+export type ToastDefault = {
+ /** Milliseconds before the toast closes on its own; `Infinity` keeps it until the user closes it. */
+ duration?: number;
+ /** Whether the toast shows a close button. */
+ closeButton?: boolean;
+};
+
+/**
+ * `T` with at least one of its fields set. An empty object is a type error, and the
+ * constraint follows `T` when fields are added to it.
+ */
+type AtLeastOne = { [K in keyof T]-?: Required> & Partial }[keyof T];
+
+/**
+ * Defaults `useToast` applies per kind of toast. The built-in default for both kinds is
+ * `{ duration: Infinity, closeButton: true }`. A field set here replaces that field only;
+ * fields and kinds left out keep the built-in default.
+ */
+export type ToastDefaults = {
+ /** `toast.error(...)` and the error state of `toast.promise(...)`. */
+ error?: AtLeastOne;
+ /** Any toast with an `action`. */
+ action?: AtLeastOne;
+};
+
export type RootConfiguration = {
modules: Modules;
settingsResources: Resource[];
@@ -69,6 +95,8 @@ export type RootConfiguration = {
resolvedLocale?: string;
/** IANA timezone (e.g. "America/Los_Angeles"). Used by date/time components. */
timeZone?: string;
+ /** Per-kind toast defaults for `useToast`. Omitted kinds keep the built-in defaults. */
+ toastDefaults?: ToastDefaults;
};
export type AppInfoEntry = {
@@ -90,6 +118,7 @@ export type ConfigurationOptions = {
errorBoundary?: ErrorBoundaryComponent;
locale?: string;
timeZone?: string;
+ toastDefaults?: ToastDefaults;
};
/**
@@ -107,6 +136,7 @@ export const buildConfigurations = (options: ConfigurationOptions): RootConfigur
locale: options.locale ? toLanguageSubtag(options.locale) : detectBrowserLocale(),
resolvedLocale: options.locale ?? detectBrowserFullLocale(),
timeZone: options.timeZone,
+ toastDefaults: options.toastDefaults,
});
/**
diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx
new file mode 100644
index 000000000..8eb5ca85b
--- /dev/null
+++ b/packages/core/src/hooks/use-toast.test.tsx
@@ -0,0 +1,426 @@
+import { act, cleanup, render, renderHook, waitFor } from "@testing-library/react";
+import { type ToastT, toast as sonnerToast } from "sonner";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ThemeProvider } from "@/contexts/theme-context";
+import {
+ AppShellConfigContext,
+ buildConfigurations,
+ type ToastDefaults,
+} from "@/contexts/appshell-context";
+import { Toaster } from "@/components/internals/sonner";
+import { AppShell } from "@/index";
+import { SidebarLayout } from "@/components/sidebar";
+import { defineModule } from "@/resource";
+import { AppShellTestingProvider } from "@/testing";
+import { useToast } from "./use-toast";
+
+const renderToaster = () =>
+ render(
+
+
+ ,
+ );
+
+const activeToast = (title: string) =>
+ sonnerToast.getToasts().find((t): t is ToastT => "title" in t && t.title === title);
+
+const closeButtonOf = (title: string) =>
+ Array.from(document.querySelectorAll("[data-sonner-toast]"))
+ .find((el) => el.textContent?.includes(title))
+ ?.querySelector("[data-close-button]");
+
+let toast: ReturnType;
+
+/** `useToast` under an AppShell whose `toastDefaults` prop is `toastDefaults`. */
+const useToastWith = (toastDefaults: ToastDefaults | undefined) => {
+ const configurations = buildConfigurations({ modules: [], toastDefaults });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+
+ {children}
+
+ );
+ return renderHook(() => useToast(), { wrapper }).result.current;
+};
+
+beforeEach(() => {
+ toast = renderHook(() => useToast()).result.current;
+});
+
+afterEach(() => {
+ sonnerToast.dismiss();
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("useToast", () => {
+ it("keeps the sonner API shape", () => {
+ expect(typeof toast).toBe("function");
+ for (const key of Object.keys(sonnerToast)) {
+ expect(toast).toHaveProperty(key);
+ }
+ });
+
+ it("gives error toasts a close button and no auto-dismiss", async () => {
+ renderToaster();
+ await act(async () => {
+ toast.error("Failed to save");
+ });
+ expect(activeToast("Failed to save")).toMatchObject({ duration: Infinity, closeButton: true });
+ await waitFor(() => {
+ expect(closeButtonOf("Failed to save")).not.toBeNull();
+ });
+ });
+
+ it("gives any toast with an action the same defaults", async () => {
+ renderToaster();
+ await act(async () => {
+ toast("Order archived", { action: { label: "Undo", onClick: () => {} } });
+ toast.success("Order approved", { action: { label: "View", onClick: () => {} } });
+ });
+ expect(activeToast("Order archived")).toMatchObject({ duration: Infinity, closeButton: true });
+ expect(activeToast("Order approved")).toMatchObject({ duration: Infinity, closeButton: true });
+ });
+
+ it("lets the caller's duration and closeButton win", async () => {
+ await act(async () => {
+ toast.error("Retrying", { duration: 1000 });
+ toast.error("Quiet", { closeButton: false });
+ toast.error("Forwarded", { duration: undefined, closeButton: undefined });
+ });
+ expect(activeToast("Retrying")).toMatchObject({ duration: 1000, closeButton: true });
+ expect(activeToast("Quiet")).toMatchObject({ duration: Infinity, closeButton: false });
+ expect(activeToast("Forwarded")).toMatchObject({ duration: Infinity, closeButton: true });
+ });
+
+ it("leaves toasts without an action on Sonner's defaults", async () => {
+ renderToaster();
+ await act(async () => {
+ toast.success("Saved");
+ toast("Plain");
+ toast.info("FYI", { description: "Details" });
+ });
+ for (const title of ["Saved", "Plain", "FYI"]) {
+ const t = activeToast(title);
+ expect(t).toBeDefined();
+ expect(t).not.toHaveProperty("duration");
+ expect(t).not.toHaveProperty("closeButton");
+ }
+ await waitFor(() => {
+ expect(closeButtonOf("Saved")).toBeNull();
+ });
+ });
+
+ it("resets the sticky defaults when a later call updates the toast by id", async () => {
+ vi.useFakeTimers();
+ renderToaster();
+ await act(async () => {
+ toast.success("Saved", { id: toast.error("Save failed") });
+ toast.success("Kept", { id: toast.error("Other failure"), duration: 8000 });
+ });
+ expect(activeToast("Saved")).toMatchObject({ type: "success" });
+ expect(activeToast("Saved")?.duration).toBeUndefined();
+ expect(activeToast("Saved")?.closeButton).toBeUndefined();
+ expect(activeToast("Kept")).toMatchObject({ type: "success", duration: 8000 });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(document.body.textContent).not.toContain("Saved");
+ expect(document.body.textContent).toContain("Kept");
+ });
+
+ it("leaves a toast with dismissible: false on Sonner's defaults", async () => {
+ vi.useFakeTimers();
+ renderToaster();
+ await act(async () => {
+ toast.error("Locked", { dismissible: false });
+ toast("Pinned", { dismissible: false, action: { label: "Undo", onClick: () => {} } });
+ toast.error("Kept open", { dismissible: false, duration: Infinity });
+ });
+ for (const title of ["Locked", "Pinned"]) {
+ const t = activeToast(title);
+ expect(t).toMatchObject({ dismissible: false });
+ expect(t).not.toHaveProperty("duration");
+ expect(t).not.toHaveProperty("closeButton");
+ }
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(50);
+ });
+ expect(closeButtonOf("Locked")).toBeNull();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(document.body.textContent).not.toContain("Locked");
+ expect(document.body.textContent).not.toContain("Pinned");
+ expect(document.body.textContent).toContain("Kept open");
+ });
+
+ it("leaves a non-dismissible error state of toast.promise on Sonner's defaults", async () => {
+ const ownState = toast.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving A",
+ error: { message: "A failed", dismissible: false },
+ });
+ // Sonner resets `dismissible` to true when the loading toast becomes the error toast, so a
+ // call-level `dismissible: false` does not reach the error state and the defaults apply.
+ const callLevel = toast.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving B",
+ error: "B failed",
+ dismissible: false,
+ });
+ await expect(ownState.unwrap()).rejects.toThrow();
+ await expect(callLevel.unwrap()).rejects.toThrow();
+ await waitFor(() => {
+ const a = activeToast("A failed");
+ expect(a).toMatchObject({ type: "error", dismissible: false });
+ expect(a).not.toHaveProperty("closeButton");
+ expect(a?.duration).toBeUndefined();
+ expect(activeToast("B failed")).toMatchObject({
+ type: "error",
+ dismissible: true,
+ duration: Infinity,
+ closeButton: true,
+ });
+ });
+ });
+
+ it("only the error toast outlives Sonner's 4 s timer", async () => {
+ vi.useFakeTimers();
+ renderToaster();
+ await act(async () => {
+ toast.success("Saved");
+ toast.error("Failed to save");
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(document.body.textContent).not.toContain("Saved");
+ expect(document.body.textContent).toContain("Failed to save");
+ });
+
+ it("gives the error state of toast.promise the same defaults", async () => {
+ const failing = toast.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving",
+ success: "Saved",
+ error: "Failed to save",
+ });
+ await expect(failing.unwrap()).rejects.toThrow("boom");
+ await waitFor(() => {
+ expect(activeToast("Failed to save")).toMatchObject({
+ type: "error",
+ duration: Infinity,
+ closeButton: true,
+ });
+ });
+ });
+
+ it("lets a promise call's own options win over the error defaults", async () => {
+ const fromFunction = toast.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving A",
+ error: (error: Error) => ({ message: `A: ${error.message}`, duration: 1500 }),
+ });
+ const fromCall = toast.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving B",
+ error: "B failed",
+ duration: 2500,
+ closeButton: false,
+ });
+ await expect(fromFunction.unwrap()).rejects.toThrow();
+ await expect(fromCall.unwrap()).rejects.toThrow();
+ await waitFor(() => {
+ expect(activeToast("A: boom")).toMatchObject({
+ type: "error",
+ duration: 1500,
+ closeButton: true,
+ });
+ expect(activeToast("B failed")).toMatchObject({
+ type: "error",
+ duration: 2500,
+ closeButton: false,
+ });
+ });
+ });
+
+ it("leaves the success state of toast.promise alone", async () => {
+ const ok = toast.promise(Promise.resolve(1), {
+ loading: "Saving",
+ success: "Saved",
+ error: "Failed",
+ });
+ await ok.unwrap();
+ await waitFor(() => {
+ const t = activeToast("Saved");
+ expect(t).toMatchObject({ type: "success" });
+ expect(t).not.toHaveProperty("closeButton");
+ });
+ });
+
+ it("keeps the success state of a toast.promise with an action until the user closes it", async () => {
+ vi.useFakeTimers();
+ renderToaster();
+ await act(async () => {
+ await toast
+ .promise(Promise.resolve(1), {
+ loading: "Saving",
+ success: "Saved with undo",
+ action: { label: "Undo", onClick: () => {} },
+ })
+ .unwrap();
+ });
+ expect(activeToast("Saved with undo")).toMatchObject({
+ type: "success",
+ duration: Infinity,
+ closeButton: true,
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(document.body.textContent).toContain("Saved with undo");
+ expect(closeButtonOf("Saved with undo")).toBeTruthy();
+ });
+
+ it("keeps the error default on a toast.promise with an action, and the caller still wins", async () => {
+ const t = useToastWith({ error: { duration: 7000 } });
+ const failing = t.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving",
+ error: "Failed with undo",
+ action: { label: "Undo", onClick: () => {} },
+ });
+ const own = toast.promise(Promise.resolve(1), {
+ loading: "Saving",
+ success: "Saved quickly",
+ action: { label: "Undo", onClick: () => {} },
+ duration: 3000,
+ });
+ await expect(failing.unwrap()).rejects.toThrow("boom");
+ await own.unwrap();
+ await waitFor(() => {
+ expect(activeToast("Failed with undo")).toMatchObject({ duration: 7000, closeButton: true });
+ expect(activeToast("Saved quickly")).toMatchObject({ duration: 3000, closeButton: true });
+ });
+ });
+});
+
+describe("useToast with ", () => {
+ it("passes toastDefaults through buildConfigurations unchanged", () => {
+ const toastDefaults = { error: { duration: 10_000 } };
+ expect(buildConfigurations({ modules: [], toastDefaults }).toastDefaults).toBe(toastDefaults);
+ expect(buildConfigurations({ modules: [] }).toastDefaults).toBeUndefined();
+ });
+
+ it("uses the built-in defaults when the prop is not set", async () => {
+ const t = useToastWith(undefined);
+ await act(async () => {
+ t.error("Failed");
+ });
+ expect(activeToast("Failed")).toMatchObject({ duration: Infinity, closeButton: true });
+ });
+
+ it("restores the previous behavior for one kind and keeps the other", async () => {
+ vi.useFakeTimers();
+ renderToaster();
+ const t = useToastWith({ error: { duration: 4000, closeButton: false } });
+ await act(async () => {
+ t.error("Failed");
+ t("Archived", { action: { label: "Undo", onClick: () => {} } });
+ });
+ expect(activeToast("Failed")).toMatchObject({ duration: 4000, closeButton: false });
+ expect(closeButtonOf("Failed")).toBeFalsy();
+ expect(activeToast("Archived")).toMatchObject({ duration: Infinity, closeButton: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000);
+ });
+ expect(document.body.textContent).not.toContain("Failed");
+ expect(document.body.textContent).toContain("Archived");
+ });
+
+ it("overrides only the configured fields, and the caller still wins", async () => {
+ const t = useToastWith({ error: { duration: 10_000 }, action: { closeButton: false } });
+ await act(async () => {
+ t.error("Slow");
+ t.error("Quick", { duration: 1000, closeButton: false });
+ t.success("Done", { action: { label: "View", onClick: () => {} } });
+ });
+ expect(activeToast("Slow")).toMatchObject({ duration: 10_000, closeButton: true });
+ expect(activeToast("Quick")).toMatchObject({ duration: 1000, closeButton: false });
+ expect(activeToast("Done")).toMatchObject({ duration: Infinity, closeButton: false });
+ });
+
+ it("applies the configured error default to the error state of toast.promise", async () => {
+ const t = useToastWith({ error: { duration: 7000 } });
+ const failing = t.promise(Promise.reject(new Error("boom")), {
+ loading: "Saving",
+ error: "Failed to save",
+ });
+ await expect(failing.unwrap()).rejects.toThrow("boom");
+ await waitFor(() => {
+ expect(activeToast("Failed to save")).toMatchObject({
+ type: "error",
+ duration: 7000,
+ closeButton: true,
+ });
+ });
+ });
+
+ it("rejects an empty default for a kind at the type level", () => {
+ const valid: ToastDefaults[] = [
+ { error: { duration: 5000 } },
+ { action: { closeButton: false } },
+ { error: { duration: 4000, closeButton: false } },
+ ];
+ // @ts-expect-error `{}` would mean "no change"; leave the kind out instead.
+ const emptyError: ToastDefaults = { error: {} };
+ // @ts-expect-error the same holds for `action`.
+ const emptyAction: ToastDefaults = { action: {} };
+ expect([...valid, emptyError, emptyAction]).toHaveLength(5);
+ });
+
+ it("keeps the toast object across AppShell renders with an inline toastDefaults", async () => {
+ const seen = new Set>();
+ const Page = () => {
+ seen.add(useToast());
+ return
Toast page
;
+ };
+ // Stable across renders, so only `toastDefaults` can change the configurations.
+ const modules = [
+ defineModule({ path: "toast", meta: { title: "Toast" }, component: Page, resources: [] }),
+ ];
+ const renderShell = (duration: number) => (
+
+
+
+
+
+ );
+
+ const { findByText, rerender } = render(renderShell(10_000));
+ await findByText("Toast page");
+ rerender(renderShell(10_000));
+ rerender(renderShell(10_000));
+ await findByText("Toast page");
+ expect(seen.size).toBe(1);
+
+ // A changed value still reaches `useToast`.
+ rerender(renderShell(7000));
+ await waitFor(() => expect(seen.size).toBe(2));
+ const latest = Array.from(seen).at(-1)!;
+ await act(async () => {
+ latest.error("Changed");
+ });
+ expect(activeToast("Changed")).toMatchObject({ duration: 7000, closeButton: true });
+ });
+
+ it("returns the same toast object while the config does not change", () => {
+ const configurations = buildConfigurations({
+ modules: [],
+ toastDefaults: { error: { duration: 4000 } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+
+ {children}
+
+ );
+ const { result, rerender } = renderHook(() => useToast(), { wrapper });
+ const first = result.current;
+ rerender();
+ expect(result.current).toBe(first);
+ });
+});
diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts
index df9765ef5..46ee6e1de 100644
--- a/packages/core/src/hooks/use-toast.ts
+++ b/packages/core/src/hooks/use-toast.ts
@@ -1,5 +1,135 @@
-import { toast } from "sonner";
+import { useMemo } from "react";
+import { type ExternalToast, toast as sonnerToast } from "sonner";
+import {
+ useAppShellConfig,
+ type ToastDefault,
+ type ToastDefaults,
+} from "@/contexts/appshell-context";
-export const useToast = (): typeof toast => {
- return toast;
+type Toast = typeof sonnerToast;
+// A mapped type over `typeof toast` keeps its methods and drops the call signature.
+type ToastMethods = Omit;
+type PromiseData = NonNullable>[1]>;
+type PromiseErrorResult = Exclude["error"], (...args: never[]) => unknown>;
+type PromiseErrorOptions = Extract;
+
+/**
+ * Sonner closes every toast after 4 s, whatever its type. A failed save that disappears
+ * before the user reads it, or an Undo that vanishes while the user reaches for it, is
+ * worse than no toast. So errors and toasts that carry an `action` stay until the user
+ * closes them, and they get a close button. Options the caller passes win, and an app
+ * changes either default field by field through ``.
+ * The values are written out here, not left to Sonner, so a Sonner upgrade cannot change them.
+ * Why: docs-src/patterns/interaction-toast.docs.outline.md (Constraints).
+ */
+const STAY_UNTIL_CLOSED: Required = { duration: Infinity, closeButton: true };
+
+/** A field the app sets replaces the built-in one; a field it leaves out keeps it. */
+const resolveDefault = (configured: ToastDefault | undefined): Required => ({
+ duration: configured?.duration ?? STAY_UNTIL_CLOSED.duration,
+ closeButton: configured?.closeButton ?? STAY_UNTIL_CLOSED.closeButton,
+});
+
+const isErrorOptions = (result: PromiseErrorResult): result is PromiseErrorOptions =>
+ typeof result === "object" && result !== null && "message" in result;
+
+const applyDefault = >(
+ data: D | undefined,
+ fallback: Required,
+): D | undefined => {
+ // A toast the user cannot dismiss gets no close button from Sonner (it draws one that does
+ // nothing) and must not stay open by default either, or nothing but `toast.dismiss(id)` ends
+ // it. It keeps Sonner's defaults; a caller that closes it in code passes `duration: Infinity`.
+ if (data?.dismissible === false) return data;
+ // Only `duration` and `closeButton` change, so the result keeps the caller's type.
+ return {
+ ...data,
+ duration: data?.duration ?? fallback.duration,
+ closeButton: data?.closeButton ?? fallback.closeButton,
+ } as D;
+};
+
+const createToast = (defaults: ToastDefaults): Toast => {
+ const errorDefault = resolveDefault(defaults.error);
+ const actionDefault = resolveDefault(defaults.action);
+
+ const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => {
+ if (data?.action) return applyDefault(data, actionDefault);
+ if (data?.id === undefined) return data;
+ // Sonner updates a toast by `id` by merging into the stored one, so the sticky defaults of
+ // an earlier error or action toast would survive into this one. An explicit `undefined`
+ // resets them; a `duration` or `closeButton` the caller passes stays.
+ return { ...data, duration: data.duration, closeButton: data.closeButton };
+ };
+
+ /**
+ * `toast.promise` describes its error state as a message, a `{ message, ...options }` object,
+ * or a function returning either. The top-level `duration` / `closeButton` of the call apply
+ * to every state, so they stand in for the defaults; the error state's own options win.
+ */
+ const withPromiseErrorDefaults = (data: PromiseData): PromiseData => {
+ const { error } = data;
+ if (error === undefined) return data;
+ const apply = (result: PromiseErrorResult): PromiseErrorOptions => {
+ const options = isErrorOptions(result) ? result : { message: result };
+ // Only the error state's own `dismissible` counts: Sonner resets `dismissible` to true when
+ // it turns the loading toast into the error toast, so a call-level `false` ends there.
+ if (options.dismissible === false) return options;
+ return {
+ ...options,
+ duration: options.duration ?? data.duration ?? errorDefault.duration,
+ closeButton: options.closeButton ?? data.closeButton ?? errorDefault.closeButton,
+ };
+ };
+ return {
+ ...data,
+ error:
+ typeof error === "function"
+ ? async (reason: unknown) => apply(await error(reason))
+ : apply(error),
+ };
+ };
+
+ /**
+ * Sonner copies a call-level `action` into the loading toast and merges each later state into
+ * it, so the success state shows the action too. The action default therefore goes on the
+ * call. The error state is resolved first, from the call as the caller wrote it, so it keeps
+ * the error default.
+ */
+ const withPromiseDefaults = (data: PromiseData): PromiseData => {
+ const withErrorDefaults = withPromiseErrorDefaults(data);
+ return data.action ? applyDefault(withErrorDefaults, actionDefault)! : withErrorDefaults;
+ };
+
+ const methods: ToastMethods = {
+ success: (message, data) => sonnerToast.success(message, withActionDefaults(data)),
+ info: (message, data) => sonnerToast.info(message, withActionDefaults(data)),
+ warning: (message, data) => sonnerToast.warning(message, withActionDefaults(data)),
+ message: (message, data) => sonnerToast.message(message, withActionDefaults(data)),
+ loading: (message, data) => sonnerToast.loading(message, withActionDefaults(data)),
+ error: (message, data) => sonnerToast.error(message, applyDefault(data, errorDefault)),
+ promise: (promise, data) => sonnerToast.promise(promise, data && withPromiseDefaults(data)),
+ // `custom` renders the caller's JSX alone: Sonner draws neither the action nor the close
+ // button for it, so a sticky default would leave nothing to close with. It passes through.
+ custom: sonnerToast.custom,
+ dismiss: sonnerToast.dismiss,
+ getHistory: sonnerToast.getHistory,
+ getToasts: sonnerToast.getToasts,
+ };
+
+ return Object.assign(
+ (message: Parameters[0], data?: ExternalToast) =>
+ sonnerToast(message, withActionDefaults(data)),
+ methods,
+ );
+};
+
+const builtInToast = createToast({});
+
+export const useToast = (): Toast => {
+ const { toastDefaults } = useAppShellConfig().configurations;
+ return useMemo(
+ () => (toastDefaults ? createToast(toastDefaults) : builtInToast),
+ [toastDefaults],
+ );
};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fa3476839..68e323563 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -53,6 +53,8 @@ export {
type AppInfo,
type AppInfoEntry,
type TimeZone,
+ type ToastDefault,
+ type ToastDefaults,
} from "./contexts/appshell-context";
export { useAppShellScrollContainer } from "./contexts/scroll-container-context";
export { useTheme, type ColorTheme, type ResolvedColorTheme } from "./contexts/theme-context";