From ddc120aa0cc994911a59ea424b3ebc014f3f2c72 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Sun, 8 Nov 2026 12:32:23 +0900 Subject: [PATCH 01/10] fix(toast): keep error and action toasts until the user closes them `useToast` now wraps sonner's `toast` and gives `toast.error`, the error state of `toast.promise`, and any toast with an `action` the defaults `duration: Infinity` and `closeButton: true`. Options passed by the caller win. `toast.custom` passes through, because sonner draws neither the action nor the close button for it. The toast docs described a position, count and durations that the `` never set (top right, one at a time, success 3 s, error sticky). They now describe sonner's real defaults (bottom right, up to 3, 4 s) plus the two defaults this change adds, and tell consumers not to make a toast the only way to do something. Part of tailor-inc/platform-planning#2349 Co-Authored-By: Claude Fable 5.1 --- .changeset/sticky-error-toasts.md | 15 ++ docs-manifest.json | 12 +- docs-src/hooks/use-toast.docs.outline.md | 45 ++++- .../interaction-toast.docs.outline.md | 11 +- docs/api/use-toast.md | 45 ++++- docs/patterns/interaction-toast.md | 11 +- packages/core/src/hooks/use-toast.test.tsx | 163 ++++++++++++++++++ packages/core/src/hooks/use-toast.ts | 76 +++++++- 8 files changed, 360 insertions(+), 18 deletions(-) create mode 100644 .changeset/sticky-error-toasts.md create mode 100644 packages/core/src/hooks/use-toast.test.tsx diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md new file mode 100644 index 000000000..f2dad62e1 --- /dev/null +++ b/.changeset/sticky-error-toasts.md @@ -0,0 +1,15 @@ +--- +"@tailor-platform/app-shell": patch +--- + +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. + +A `duration` or `closeButton` passed to the call still wins: + +```ts +toast.error("Retrying in 5s", { duration: 5000 }); // closes after 5 seconds +``` + +`toast.custom`, 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 2cf95ac98..1c11d356a 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1008,9 +1008,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "45b23abe90e466b2", + "outline": "c1802da0be69c18a", "snapshot": null, - "outputMd": "f68bdab855730f48", + "outputMd": "4191e757cf7c58cb", "examples": "7089e7331b95df31" } }, @@ -1739,9 +1739,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "6b730cf39dcfa154", + "outline": "36e4faca6e84a9cb", "snapshot": null, - "outputMd": "30983a761bc61593", + "outputMd": "158878508bc367ce", "examples": null } }, @@ -1844,7 +1844,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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "30983a761bc61593", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "158878508bc367ce", "packages/core/skills/app-shell-patterns/references/patterns/form-composer.md": "ed187ac3a0773d3d", "packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "be00d1109761b7f1", "packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c", @@ -1853,7 +1853,7 @@ "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": "4191e757cf7c58cb", "packages/core/skills/app-shell-patterns/references/patterns/list-dense-scan.md": "59c93617dc135033", "packages/core/skills/app-shell-patterns/references/pages/document-detail.md": "930db027a28bbe24", "packages/core/skills/app-shell-patterns/references/migrations.md": "e0286979718e2769", diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index c6a37315a..63a2692e3 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,29 @@ 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 error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. + +These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. + ## Parameters ### ExternalToast @@ -84,6 +107,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 +116,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 ```typescript diff --git a/docs-src/patterns/interaction-toast.docs.outline.md b/docs-src/patterns/interaction-toast.docs.outline.md index 3c88d0944..5aa4373bc 100644 --- a/docs-src/patterns/interaction-toast.docs.outline.md +++ b/docs-src/patterns/interaction-toast.docs.outline.md @@ -40,12 +40,15 @@ 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 +- 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 7bdcfe5eb..12f89ca19 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,29 @@ 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 error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. + +These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. + ## Parameters ### ExternalToast @@ -84,6 +107,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 +116,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 ```typescript diff --git a/docs/patterns/interaction-toast.md b/docs/patterns/interaction-toast.md index dd922363d..7d7cc780c 100644 --- a/docs/patterns/interaction-toast.md +++ b/docs/patterns/interaction-toast.md @@ -34,12 +34,15 @@ 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 +- 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/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx new file mode 100644 index 000000000..b6b4c71c0 --- /dev/null +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -0,0 +1,163 @@ +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 { Toaster } from "@/components/internals/sonner"; +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; + +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("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"); + }); + }); +}); diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index df9765ef5..6ca5ad3c5 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -1,5 +1,77 @@ -import { toast } from "sonner"; +import { type ExternalToast, toast as sonnerToast } from "sonner"; -export const useToast = (): typeof toast => { +type Toast = typeof sonnerToast; +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. + * Why: docs-src/patterns/interaction-toast.docs.outline.md (Constraints). + */ +const stayUntilClosed = (data?: ExternalToast): ExternalToast => ({ + ...data, + duration: data?.duration ?? Infinity, + closeButton: data?.closeButton ?? true, +}); + +const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => + data?.action ? stayUntilClosed(data) : data; + +const isErrorOptions = (result: PromiseErrorResult): result is PromiseErrorOptions => + typeof result === "object" && result !== null && "message" in result; + +/** + * `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 }; + return { + ...options, + duration: options.duration ?? data.duration ?? Infinity, + closeButton: options.closeButton ?? data.closeButton ?? true, + }; + }; + return { + ...data, + error: + typeof error === "function" + ? async (reason: unknown) => apply(await error(reason)) + : apply(error), + }; +}; + +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, stayUntilClosed(data)), + promise: (promise, data) => sonnerToast.promise(promise, data && withPromiseErrorDefaults(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, +}; + +const toast: Toast = Object.assign( + (message: Parameters[0], data?: ExternalToast) => + sonnerToast(message, withActionDefaults(data)), + methods, +); + +export const useToast = (): Toast => { return toast; }; From 228389d617e1c77e4302775b23eb3ae9a39d09ce Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Sun, 8 Nov 2026 16:37:04 +0900 Subject: [PATCH 02/10] fix(toast): reset sticky defaults when a toast is updated by id Sonner merges an update by `id` into the stored toast, so the `duration: Infinity` and `closeButton: true` that `useToast` gives an error or action toast survived into a later `toast.success("Saved", { id })`, which then never closed. A call without an `action` that updates by `id` now passes an explicit `undefined` for both unless the caller sets them. Co-Authored-By: Claude Fable 5.1 --- .changeset/sticky-error-toasts.md | 2 +- docs-manifest.json | 6 +++--- docs-src/hooks/use-toast.docs.outline.md | 2 ++ docs/api/use-toast.md | 2 ++ packages/core/src/hooks/use-toast.test.tsx | 18 ++++++++++++++++++ packages/core/src/hooks/use-toast.ts | 10 ++++++++-- 6 files changed, 34 insertions(+), 6 deletions(-) diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md index f2dad62e1..619404f9e 100644 --- a/.changeset/sticky-error-toasts.md +++ b/.changeset/sticky-error-toasts.md @@ -10,6 +10,6 @@ A `duration` or `closeButton` passed to the call still wins: toast.error("Retrying in 5s", { duration: 5000 }); // closes after 5 seconds ``` -`toast.custom`, 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. +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`, 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 1c11d356a..04c0c5a22 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1739,9 +1739,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "36e4faca6e84a9cb", + "outline": "16c98cfd7a812782", "snapshot": null, - "outputMd": "158878508bc367ce", + "outputMd": "79a26c46ef5aa965", "examples": null } }, @@ -1844,7 +1844,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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "158878508bc367ce", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "79a26c46ef5aa965", "packages/core/skills/app-shell-patterns/references/patterns/form-composer.md": "ed187ac3a0773d3d", "packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "be00d1109761b7f1", "packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c", diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index 63a2692e3..9100d3b95 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -46,6 +46,8 @@ For `toast.promise`, a `duration` or `closeButton` on the call applies to the er An error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. +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. + These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. ## Parameters diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index 12f89ca19..acc185ab6 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -46,6 +46,8 @@ For `toast.promise`, a `duration` or `closeButton` on the call applies to the er An error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. +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. + These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. ## Parameters diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index b6b4c71c0..2e3bd229f 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -90,6 +90,24 @@ describe("useToast", () => { }); }); + 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("only the error toast outlives Sonner's 4 s timer", async () => { vi.useFakeTimers(); renderToaster(); diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index 6ca5ad3c5..98890a67b 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -19,8 +19,14 @@ const stayUntilClosed = (data?: ExternalToast): ExternalToast => ({ closeButton: data?.closeButton ?? true, }); -const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => - data?.action ? stayUntilClosed(data) : data; +const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => { + if (data?.action) return stayUntilClosed(data); + 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 }; +}; const isErrorOptions = (result: PromiseErrorResult): result is PromiseErrorOptions => typeof result === "object" && result !== null && "message" in result; From 729f5201e508115d4f6eb19a59267ee6f2dac521 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Mon, 9 Nov 2026 16:37:13 +0900 Subject: [PATCH 03/10] fix(toast): leave non-dismissible toasts on Sonner's defaults With `dismissible: false`, Sonner draws a close button that does nothing and ignores swipe and Escape, so a sticky default would leave `toast.dismiss(id)` as the only way to end the toast. Such toasts now keep Sonner's defaults (no close button, 4 s), as before. For `toast.promise`, only the error state's own `dismissible` counts, because Sonner resets the flag when the loading toast becomes the error toast. Co-Authored-By: Claude Fable 5.1 --- .changeset/sticky-error-toasts.md | 2 +- docs-manifest.json | 6 +-- docs-src/hooks/use-toast.docs.outline.md | 2 +- docs/api/use-toast.md | 2 +- packages/core/src/hooks/use-toast.test.tsx | 54 ++++++++++++++++++++++ packages/core/src/hooks/use-toast.ts | 19 ++++++-- 6 files changed, 74 insertions(+), 11 deletions(-) diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md index 619404f9e..a6140c329 100644 --- a/.changeset/sticky-error-toasts.md +++ b/.changeset/sticky-error-toasts.md @@ -10,6 +10,6 @@ A `duration` or `closeButton` passed to the call still wins: 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`, 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. +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 026079774..37e86b253 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1739,9 +1739,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "16c98cfd7a812782", + "outline": "5f91ce781349ee1c", "snapshot": null, - "outputMd": "79a26c46ef5aa965", + "outputMd": "0928302d47bcf194", "examples": null } }, @@ -1844,7 +1844,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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "79a26c46ef5aa965", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "0928302d47bcf194", "packages/core/skills/app-shell-patterns/references/patterns/form-composer.md": "ed187ac3a0773d3d", "packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "be00d1109761b7f1", "packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c", diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index 9100d3b95..2558a8df4 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -44,7 +44,7 @@ toast.error("Failed to save", { closeButton: false }); // stays; swipe, or Escap 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 error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. +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`. 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. diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index acc185ab6..bf48cccee 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -44,7 +44,7 @@ toast.error("Failed to save", { closeButton: false }); // stays; swipe, or Escap 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 error toast with `dismissible: false` now stays until the caller calls `toast.dismiss(id)`; give it a `duration` if it should close on its own. +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`. 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. diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index 2e3bd229f..f19480da2 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -108,6 +108,60 @@ describe("useToast", () => { 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(); diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index 98890a67b..0b7ee078f 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -13,11 +13,17 @@ type PromiseErrorOptions = Extract; * closes them, and they get a close button. Options the caller passes win. * Why: docs-src/patterns/interaction-toast.docs.outline.md (Constraints). */ -const stayUntilClosed = (data?: ExternalToast): ExternalToast => ({ - ...data, - duration: data?.duration ?? Infinity, - closeButton: data?.closeButton ?? true, -}); +const stayUntilClosed = (data?: ExternalToast): ExternalToast | 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; + return { + ...data, + duration: data?.duration ?? Infinity, + closeButton: data?.closeButton ?? true, + }; +}; const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => { if (data?.action) return stayUntilClosed(data); @@ -41,6 +47,9 @@ const withPromiseErrorDefaults = (data: PromiseData): PromiseData => { 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 ?? Infinity, From 8c486c4ea0493ec8da857ada68571422a1712ce6 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Wed, 11 Nov 2026 21:13:17 +0900 Subject: [PATCH 04/10] feat(toast): add toastDefaults to AppShell `useToast` now reads its per-kind defaults from the AppShell configuration. The built-in defaults are unchanged (`error` and `action` toasts stay until the user closes them, with a close button). An app replaces a kind as a whole with ``, which falls back to sonner's own defaults for that kind, or sets its own `duration` / `closeButton`. Co-Authored-By: Claude Fable 5.1 --- .changeset/sticky-error-toasts.md | 9 +- docs-manifest.json | 18 +-- docs-src/components/app-shell.docs.outline.md | 15 ++ docs-src/hooks/use-toast.docs.outline.md | 10 ++ docs/api/use-toast.md | 10 ++ docs/components/app-shell.md | 15 ++ .../core/src/components/appshell/appshell.tsx | 20 +++ .../core/src/contexts/appshell-context.tsx | 23 +++ packages/core/src/hooks/use-toast.test.tsx | 90 +++++++++++ packages/core/src/hooks/use-toast.ts | 153 ++++++++++-------- packages/core/src/index.ts | 2 + 11 files changed, 291 insertions(+), 74 deletions(-) diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md index a6140c329..914eaf029 100644 --- a/.changeset/sticky-error-toasts.md +++ b/.changeset/sticky-error-toasts.md @@ -1,9 +1,16 @@ --- -"@tailor-platform/app-shell": patch +"@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 kind set there replaces its built-in default as a whole; a kind left out keeps it: + +```tsx +// Back to Sonner's defaults (4 seconds, no close button) for both kinds + +``` + A `duration` or `closeButton` passed to the call still wins: ```ts diff --git a/docs-manifest.json b/docs-manifest.json index 37e86b253..04c03935b 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -115,10 +115,10 @@ "claims": [], "symbols": ["AppShell", "AppShellProps"], "hashes": { - "typeSurface": "51313066e142afc2", - "outline": "feea161ef91395db", + "typeSurface": "5214717584b72041", + "outline": "65915c80077a66c4", "snapshot": null, - "outputMd": "e6447700166b7952", + "outputMd": "fe53248b2e3fb3f8", "examples": null } }, @@ -635,7 +635,7 @@ "hashes": { "typeSurface": "b1614970f950ceb6", "outline": "b265fed115996728", - "snapshot": "db7d26786cde5cfc", + "snapshot": "a0c8071024eb2e72", "outputMd": "e862d97903e8f596", "examples": "934c52d4e8761404" } @@ -1264,7 +1264,7 @@ "hashes": { "typeSurface": "e760949efcbe4c38", "outline": "464d91acc48f7c9d", - "snapshot": "429bdb8c86bb2ad6", + "snapshot": "41f7a2d2d8035a74", "outputMd": "1f81ebd562c50371", "examples": "b0eebb8c5e2219dc" } @@ -1739,9 +1739,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "5f91ce781349ee1c", + "outline": "580b876ad8e38e64", "snapshot": null, - "outputMd": "0928302d47bcf194", + "outputMd": "457f341ceaca5e3a", "examples": null } }, @@ -1776,7 +1776,7 @@ "packages/core/skills/app-shell-patterns/references/components/activity-card.md": "1a2bb081c3e34482", "packages/core/skills/app-shell-patterns/references/components/ai-chat.md": "82313d5b6fe140d2", "packages/core/skills/app-shell-patterns/references/components/alert.md": "db2c4388ca783a75", - "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "e6447700166b7952", + "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "fe53248b2e3fb3f8", "packages/core/skills/app-shell-patterns/references/components/appearance-switcher.md": "b55f1d538651d467", "packages/core/skills/app-shell-patterns/references/components/attachment.md": "35bebce540d6ac28", "packages/core/skills/app-shell-patterns/references/components/autocomplete.md": "bd6ae01bf39d1ad6", @@ -1844,7 +1844,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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "0928302d47bcf194", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "457f341ceaca5e3a", "packages/core/skills/app-shell-patterns/references/patterns/form-composer.md": "ed187ac3a0773d3d", "packages/core/skills/app-shell-patterns/references/patterns/form-modal.md": "be00d1109761b7f1", "packages/core/skills/app-shell-patterns/references/patterns/form-sectioned.md": "d31cd3ae6ad0790c", diff --git a/docs-src/components/app-shell.docs.outline.md b/docs-src/components/app-shell.docs.outline.md index 4d1102c0a..e6af19c03 100644 --- a/docs-src/components/app-shell.docs.outline.md +++ b/docs-src/components/app-shell.docs.outline.md @@ -228,6 +228,21 @@ 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 }` (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 kind set here replaces its built-in default as a whole; a kind left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 seconds, no close button). + +```tsx +// Errors close on their own again; 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/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index 2558a8df4..70228c909 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -48,6 +48,16 @@ A toast with `dismissible: false` keeps sonner's defaults (no close button, clos 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 kind set there replaces its built-in default as a whole; a kind left out keeps it: + +```tsx +// Errors close on their own again; toasts with an action still stay. + + +// Errors stay for 10 seconds without a close button; the action default is unchanged. + +``` + These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. ## Parameters diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index bf48cccee..7f723d027 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -48,6 +48,16 @@ A toast with `dismissible: false` keeps sonner's defaults (no close button, clos 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 kind set there replaces its built-in default as a whole; a kind left out keeps it: + +```tsx +// Errors close on their own again; toasts with an action still stay. + + +// Errors stay for 10 seconds without a close button; the action default is unchanged. + +``` + These defaults live in `useToast`. A `toast` imported from `sonner` directly does not get them. ## Parameters diff --git a/docs/components/app-shell.md b/docs/components/app-shell.md index 99b9a3000..8a7708082 100644 --- a/docs/components/app-shell.md +++ b/docs/components/app-shell.md @@ -226,6 +226,21 @@ 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 }` (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 kind set here replaces its built-in default as a whole; a kind left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 seconds, no close button). + +```tsx +// Errors close on their own again; 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/packages/core/src/components/appshell/appshell.tsx b/packages/core/src/components/appshell/appshell.tsx index 612fc2afe..f615a1e62 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"; @@ -125,6 +126,23 @@ 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 kind set here replaces its built-in default as a whole; a kind + * left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 s, no + * close button). + * + * @example + * ```tsx + * // Errors close on their own again; toasts with an action still stay. + * + * ``` + */ + toastDefaults?: ToastDefaults; + /** * Global error boundary component applied to all routes. * @@ -334,6 +352,7 @@ export const AppShellInternal = (props: AppShellInternalProps) => { errorBoundary: props.errorBoundary, locale: props.locale, timeZone: props.timeZone, + toastDefaults: props.toastDefaults, }) : null, [ @@ -343,6 +362,7 @@ export const AppShellInternal = (props: AppShellInternalProps) => { props.errorBoundary, props.locale, props.timeZone, + props.toastDefaults, ], ); diff --git a/packages/core/src/contexts/appshell-context.tsx b/packages/core/src/contexts/appshell-context.tsx index e8e9b0ce7..cf718ba2a 100644 --- a/packages/core/src/contexts/appshell-context.tsx +++ b/packages/core/src/contexts/appshell-context.tsx @@ -59,6 +59,25 @@ 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; +}; + +/** + * Defaults `useToast` applies per kind of toast. A kind that is set here replaces the + * built-in default for that kind as a whole; a kind that is omitted keeps the built-in one. + */ +export type ToastDefaults = { + /** `toast.error(...)` and the error state of `toast.promise(...)`. */ + error?: ToastDefault; + /** Any toast with an `action`. */ + action?: ToastDefault; +}; + export type RootConfiguration = { modules: Modules; settingsResources: Resource[]; @@ -69,6 +88,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 +111,7 @@ export type ConfigurationOptions = { errorBoundary?: ErrorBoundaryComponent; locale?: string; timeZone?: string; + toastDefaults?: ToastDefaults; }; /** @@ -107,6 +129,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 index f19480da2..e6e21251d 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -2,6 +2,11 @@ import { act, cleanup, render, renderHook, waitFor } from "@testing-library/reac 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 { useToast } from "./use-toast"; @@ -22,6 +27,17 @@ const closeButtonOf = (title: string) => 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; }); @@ -233,3 +249,77 @@ describe("useToast", () => { }); }); }); + +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("replaces one kind with sonner's defaults and keeps the other", async () => { + vi.useFakeTimers(); + renderToaster(); + const t = useToastWith({ error: {} }); + await act(async () => { + t.error("Failed"); + t("Archived", { action: { label: "Undo", onClick: () => {} } }); + }); + expect(activeToast("Failed")?.duration).toBeUndefined(); + expect(activeToast("Failed")?.closeButton).toBeUndefined(); + 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("applies a configured default as a whole, and the caller still wins", async () => { + const t = useToastWith({ error: { duration: 10_000 }, action: { closeButton: true } }); + await act(async () => { + t.error("Slow"); + t.error("Quick", { duration: 1000, closeButton: true }); + t.success("Done", { action: { label: "View", onClick: () => {} } }); + }); + expect(activeToast("Slow")).toMatchObject({ duration: 10_000 }); + expect(activeToast("Slow")?.closeButton).toBeUndefined(); + expect(activeToast("Quick")).toMatchObject({ duration: 1000, closeButton: true }); + expect(activeToast("Done")).toMatchObject({ closeButton: true }); + expect(activeToast("Done")?.duration).toBeUndefined(); + }); + + 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 }); + expect(activeToast("Failed to save")?.closeButton).toBeUndefined(); + }); + }); + + it("returns the same toast object while the config does not change", () => { + const configurations = buildConfigurations({ modules: [], toastDefaults: { error: {} } }); + 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 0b7ee078f..2460db0d0 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -1,6 +1,13 @@ +import { useMemo } from "react"; import { type ExternalToast, toast as sonnerToast } from "sonner"; +import { + useAppShellConfig, + type ToastDefault, + type ToastDefaults, +} from "@/contexts/appshell-context"; 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>; @@ -10,83 +17,101 @@ 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. + * closes them, and they get a close button. Options the caller passes win, and an app + * replaces either default through ``. * Why: docs-src/patterns/interaction-toast.docs.outline.md (Constraints). */ -const stayUntilClosed = (data?: ExternalToast): ExternalToast | 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; - return { - ...data, - duration: data?.duration ?? Infinity, - closeButton: data?.closeButton ?? true, - }; -}; - -const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => { - if (data?.action) return stayUntilClosed(data); - 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 }; -}; +const STAY_UNTIL_CLOSED: ToastDefault = { duration: Infinity, closeButton: true }; const isErrorOptions = (result: PromiseErrorResult): result is PromiseErrorOptions => typeof result === "object" && result !== null && "message" in result; -/** - * `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; +const createToast = (defaults: ToastDefaults): Toast => { + const errorDefault = defaults.error ?? STAY_UNTIL_CLOSED; + const actionDefault = defaults.action ?? STAY_UNTIL_CLOSED; + + const applyDefault = ( + data: ExternalToast | undefined, + fallback: ToastDefault, + ): ExternalToast | 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; + return { + ...data, + duration: data?.duration ?? fallback.duration, + closeButton: data?.closeButton ?? fallback.closeButton, + }; + }; + + 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 { - ...options, - duration: options.duration ?? data.duration ?? Infinity, - closeButton: options.closeButton ?? data.closeButton ?? true, + ...data, + error: + typeof error === "function" + ? async (reason: unknown) => apply(await error(reason)) + : apply(error), }; }; - return { - ...data, - error: - typeof error === "function" - ? async (reason: unknown) => apply(await error(reason)) - : apply(error), + + 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 && withPromiseErrorDefaults(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, }; -}; -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, stayUntilClosed(data)), - promise: (promise, data) => sonnerToast.promise(promise, data && withPromiseErrorDefaults(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 toast: Toast = Object.assign( - (message: Parameters[0], data?: ExternalToast) => - sonnerToast(message, withActionDefaults(data)), - methods, -); +const builtInToast = createToast({}); export const useToast = (): Toast => { - return 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 ed65dfd63..41325686f 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"; From 1f2a06eff0eff89bedba97a53bffe37a8b69d5cf Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Wed, 11 Nov 2026 21:16:11 +0900 Subject: [PATCH 05/10] refactor(toast): hoist applyDefault to module scope unicorn/consistent-function-scoping: it captures nothing from createToast. Co-Authored-By: Claude Fable 5.1 --- packages/core/src/hooks/use-toast.ts | 30 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index 2460db0d0..d981e9d96 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -26,25 +26,25 @@ const STAY_UNTIL_CLOSED: ToastDefault = { duration: Infinity, closeButton: true const isErrorOptions = (result: PromiseErrorResult): result is PromiseErrorOptions => typeof result === "object" && result !== null && "message" in result; +const applyDefault = ( + data: ExternalToast | undefined, + fallback: ToastDefault, +): ExternalToast | 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; + return { + ...data, + duration: data?.duration ?? fallback.duration, + closeButton: data?.closeButton ?? fallback.closeButton, + }; +}; + const createToast = (defaults: ToastDefaults): Toast => { const errorDefault = defaults.error ?? STAY_UNTIL_CLOSED; const actionDefault = defaults.action ?? STAY_UNTIL_CLOSED; - const applyDefault = ( - data: ExternalToast | undefined, - fallback: ToastDefault, - ): ExternalToast | 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; - return { - ...data, - duration: data?.duration ?? fallback.duration, - closeButton: data?.closeButton ?? fallback.closeButton, - }; - }; - const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => { if (data?.action) return applyDefault(data, actionDefault); if (data?.id === undefined) return data; From 2cbc0994a5c2695c260ab242bf5777363c510787 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Tue, 17 Nov 2026 19:08:12 +0900 Subject: [PATCH 06/10] feat(toast): override toastDefaults field by field and reject empty kinds Following the review on #687: - The built-in default `{ duration: Infinity, closeButton: true }` is written out in AppShell instead of relying on Sonner's defaults. - A field set in `toastDefaults` replaces that field only; fields and kinds left out keep the built-in default. - An empty object for a kind (`error: {}`, `action: {}`) is a type error, through a generic `AtLeastOne` utility. - docs/migrations.md gets a 1.21.0 entry with the steps to keep the previous behavior. Co-Authored-By: Claude Opus 5.5 --- .changeset/sticky-error-toasts.md | 12 +- docs-manifest.json | 26 ++-- docs-src/components/app-shell.docs.outline.md | 9 +- docs-src/guides/migrations.docs.outline.md | 29 ++++ docs-src/hooks/use-toast.docs.outline.md | 9 +- docs/api/use-toast.md | 9 +- docs/components/app-shell.md | 9 +- docs/migrations.md | 29 ++++ .../core/src/components/appshell/appshell.tsx | 9 +- .../core/src/contexts/appshell-context.tsx | 23 +++- packages/core/src/hooks/use-toast.test.tsx | 126 ++++++++++++++---- packages/core/src/hooks/use-toast.ts | 20 ++- 12 files changed, 235 insertions(+), 75 deletions(-) diff --git a/.changeset/sticky-error-toasts.md b/.changeset/sticky-error-toasts.md index 914eaf029..e561feb73 100644 --- a/.changeset/sticky-error-toasts.md +++ b/.changeset/sticky-error-toasts.md @@ -4,11 +4,17 @@ 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 kind set there replaces its built-in default as a whole; a kind left out keeps 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 -// Back to Sonner's defaults (4 seconds, no close button) for both kinds - +// The previous behavior (4 seconds, no close button) for both kinds + ``` A `duration` or `closeButton` passed to the call still wins: diff --git a/docs-manifest.json b/docs-manifest.json index 7e3593c1e..b664419fa 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": "c1802da0be69c18a", "snapshot": null, - "outputMd": "f68bdab855730f48", + "outputMd": "4191e757cf7c58cb", "examples": "7089e7331b95df31" } }, @@ -1130,9 +1130,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "80dfe11d696ce694", + "outline": "ccbd73be4f8a9661", "snapshot": null, - "outputMd": "af237de157fd8691", + "outputMd": "0849a2d0325ff396", "examples": null } }, @@ -1790,9 +1790,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "6b730cf39dcfa154", + "outline": "431796ac9e8f8ca2", "snapshot": null, - "outputMd": "30983a761bc61593", + "outputMd": "d068aa70c3ad34e8", "examples": null } }, @@ -1828,7 +1828,7 @@ "packages/core/skills/app-shell-patterns/references/components/activity-card.md": "1a2bb081c3e34482", "packages/core/skills/app-shell-patterns/references/components/ai-chat.md": "82313d5b6fe140d2", "packages/core/skills/app-shell-patterns/references/components/alert.md": "db2c4388ca783a75", - "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": "35bebce540d6ac28", "packages/core/skills/app-shell-patterns/references/components/autocomplete.md": "bd6ae01bf39d1ad6", @@ -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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "30983a761bc61593", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "d068aa70c3ad34e8", "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,10 +1906,10 @@ "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": "4191e757cf7c58cb", "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/references/migrations.md": "2b1c0ad9006a3c55", + "packages/core/skills/app-shell-patterns/references/migrations.md": "d383043ac07bfe02", "packages/core/skills/app-shell-patterns/SKILL.md": "5e3664f725b4d546" } } diff --git a/docs-src/components/app-shell.docs.outline.md b/docs-src/components/app-shell.docs.outline.md index 4d1a1e9e9..cd7ebb8c4 100644 --- a/docs-src/components/app-shell.docs.outline.md +++ b/docs-src/components/app-shell.docs.outline.md @@ -230,13 +230,14 @@ Access the configured timezone in components using [`useTimeZone`](../api/use-ti ### toastDefaults -- **Type:** `{ error?: ToastDefault; action?: ToastDefault }` where `ToastDefault` is `{ duration?: number; closeButton?: boolean }` (optional) +- **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 kind set here replaces its built-in default as a whole; a kind left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 seconds, no close button). +- **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 on their own again; toasts with an action still stay. - +// Errors close after 4 seconds without a close button, as before 1.21.0; +// toasts with an action still stay. + {/* ... */} ``` diff --git a/docs-src/guides/migrations.docs.outline.md b/docs-src/guides/migrations.docs.outline.md index 3750f3ffa..331e7d410 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 70228c909..d12711f6b 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -48,13 +48,14 @@ A toast with `dismissible: false` keeps sonner's defaults (no close button, clos 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 kind set there replaces its built-in default as a whole; a kind left out keeps it: +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 on their own again; toasts with an action still stay. - +// Errors close after 4 seconds without a close button, as before 1.21.0; +// toasts with an action still stay. + -// Errors stay for 10 seconds without a close button; the action default is unchanged. +// Errors close after 10 seconds and keep the close button; the action default is unchanged. ``` diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index 7f723d027..7cb1949bd 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -48,13 +48,14 @@ A toast with `dismissible: false` keeps sonner's defaults (no close button, clos 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 kind set there replaces its built-in default as a whole; a kind left out keeps it: +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 on their own again; toasts with an action still stay. - +// Errors close after 4 seconds without a close button, as before 1.21.0; +// toasts with an action still stay. + -// Errors stay for 10 seconds without a close button; the action default is unchanged. +// Errors close after 10 seconds and keep the close button; the action default is unchanged. ``` diff --git a/docs/components/app-shell.md b/docs/components/app-shell.md index 4f79013d6..ab6a084d1 100644 --- a/docs/components/app-shell.md +++ b/docs/components/app-shell.md @@ -228,13 +228,14 @@ Access the configured timezone in components using [`useTimeZone`](../api/use-ti ### toastDefaults -- **Type:** `{ error?: ToastDefault; action?: ToastDefault }` where `ToastDefault` is `{ duration?: number; closeButton?: boolean }` (optional) +- **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 kind set here replaces its built-in default as a whole; a kind left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 seconds, no close button). +- **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 on their own again; toasts with an action still stay. - +// Errors close after 4 seconds without a close button, as before 1.21.0; +// toasts with an action still stay. + {/* ... */} ``` diff --git a/docs/migrations.md b/docs/migrations.md index 2a379d76a..abc97859e 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/packages/core/src/components/appshell/appshell.tsx b/packages/core/src/components/appshell/appshell.tsx index 38e76c922..1ff2c2af7 100644 --- a/packages/core/src/components/appshell/appshell.tsx +++ b/packages/core/src/components/appshell/appshell.tsx @@ -132,14 +132,13 @@ type SharedAppShellProps = React.PropsWithChildren<{ * * 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 kind set here replaces its built-in default as a whole; a kind - * left out keeps it. Pass `{}` for a kind to fall back to sonner's own defaults (4 s, no - * close button). + * 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 on their own again; toasts with an action still stay. - * + * // Errors close after 4 s without a close button, as before; toasts with an action still stay. + * * ``` */ toastDefaults?: ToastDefaults; diff --git a/packages/core/src/contexts/appshell-context.tsx b/packages/core/src/contexts/appshell-context.tsx index cf718ba2a..2633d469c 100644 --- a/packages/core/src/contexts/appshell-context.tsx +++ b/packages/core/src/contexts/appshell-context.tsx @@ -68,14 +68,23 @@ export type ToastDefault = { }; /** - * Defaults `useToast` applies per kind of toast. A kind that is set here replaces the - * built-in default for that kind as a whole; a kind that is omitted keeps the built-in one. + * `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?: ToastDefault; + error?: AtLeastOne; /** Any toast with an `action`. */ - action?: ToastDefault; + action?: AtLeastOne; }; export type RootConfiguration = { @@ -235,5 +244,9 @@ export interface TimeZone { export const useTimeZone = (): TimeZone => { const { configurations } = useContext(AppShellConfigContext); const timeZone = configurations.timeZone ?? getLocalTimeZone(); - return { value: timeZone, today: () => today(timeZone), now: () => now(timeZone) }; + return { + value: timeZone, + today: () => today(timeZone), + now: () => now(timeZone), + }; }; diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index e6e21251d..f9fe91ba5 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -61,7 +61,10 @@ describe("useToast", () => { await act(async () => { toast.error("Failed to save"); }); - expect(activeToast("Failed to save")).toMatchObject({ duration: Infinity, closeButton: true }); + expect(activeToast("Failed to save")).toMatchObject({ + duration: Infinity, + closeButton: true, + }); await waitFor(() => { expect(closeButtonOf("Failed to save")).not.toBeNull(); }); @@ -71,10 +74,18 @@ describe("useToast", () => { renderToaster(); await act(async () => { toast("Order archived", { action: { label: "Undo", onClick: () => {} } }); - toast.success("Order approved", { action: { label: "View", 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, }); - 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 () => { @@ -83,9 +94,18 @@ describe("useToast", () => { 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 }); + 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 () => { @@ -111,12 +131,18 @@ describe("useToast", () => { renderToaster(); await act(async () => { toast.success("Saved", { id: toast.error("Save failed") }); - toast.success("Kept", { id: toast.error("Other failure"), duration: 8000 }); + 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 }); + expect(activeToast("Kept")).toMatchObject({ + type: "success", + duration: 8000, + }); await act(async () => { await vi.advanceTimersByTimeAsync(5000); }); @@ -129,7 +155,10 @@ describe("useToast", () => { renderToaster(); await act(async () => { toast.error("Locked", { dismissible: false }); - toast("Pinned", { dismissible: false, action: { label: "Undo", onClick: () => {} } }); + toast("Pinned", { + dismissible: false, + action: { label: "Undo", onClick: () => {} }, + }); toast.error("Kept open", { dismissible: false, duration: Infinity }); }); for (const title of ["Locked", "Pinned"]) { @@ -211,7 +240,10 @@ describe("useToast", () => { 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 }), + error: (error: Error) => ({ + message: `A: ${error.message}`, + duration: 1500, + }), }); const fromCall = toast.promise(Promise.reject(new Error("boom")), { loading: "Saving B", @@ -262,20 +294,29 @@ describe("useToast with ", () => { await act(async () => { t.error("Failed"); }); - expect(activeToast("Failed")).toMatchObject({ duration: Infinity, closeButton: true }); + expect(activeToast("Failed")).toMatchObject({ + duration: Infinity, + closeButton: true, + }); }); - it("replaces one kind with sonner's defaults and keeps the other", async () => { + it("restores the previous behavior for one kind and keeps the other", async () => { vi.useFakeTimers(); renderToaster(); - const t = useToastWith({ error: {} }); + const t = useToastWith({ error: { duration: 4000, closeButton: false } }); await act(async () => { t.error("Failed"); t("Archived", { action: { label: "Undo", onClick: () => {} } }); }); - expect(activeToast("Failed")?.duration).toBeUndefined(); - expect(activeToast("Failed")?.closeButton).toBeUndefined(); - expect(activeToast("Archived")).toMatchObject({ duration: Infinity, closeButton: true }); + 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); }); @@ -283,18 +324,28 @@ describe("useToast with ", () => { expect(document.body.textContent).toContain("Archived"); }); - it("applies a configured default as a whole, and the caller still wins", async () => { - const t = useToastWith({ error: { duration: 10_000 }, action: { closeButton: true } }); + 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: true }); + t.error("Quick", { duration: 1000, closeButton: false }); t.success("Done", { action: { label: "View", onClick: () => {} } }); }); - expect(activeToast("Slow")).toMatchObject({ duration: 10_000 }); - expect(activeToast("Slow")?.closeButton).toBeUndefined(); - expect(activeToast("Quick")).toMatchObject({ duration: 1000, closeButton: true }); - expect(activeToast("Done")).toMatchObject({ closeButton: true }); - expect(activeToast("Done")?.duration).toBeUndefined(); + 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 () => { @@ -305,13 +356,32 @@ describe("useToast with ", () => { }); await expect(failing.unwrap()).rejects.toThrow("boom"); await waitFor(() => { - expect(activeToast("Failed to save")).toMatchObject({ type: "error", duration: 7000 }); - expect(activeToast("Failed to save")?.closeButton).toBeUndefined(); + 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("returns the same toast object while the config does not change", () => { - const configurations = buildConfigurations({ modules: [], toastDefaults: { error: {} } }); + const configurations = buildConfigurations({ + modules: [], + toastDefaults: { error: { duration: 4000 } }, + }); const wrapper = ({ children }: { children: React.ReactNode }) => ( {children} diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index d981e9d96..58c15a85a 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -18,17 +18,27 @@ type PromiseErrorOptions = Extract; * 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 - * replaces either default through ``. + * 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: ToastDefault = { duration: Infinity, closeButton: true }; +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: ExternalToast | undefined, - fallback: ToastDefault, + fallback: Required, ): ExternalToast | 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 @@ -42,8 +52,8 @@ const applyDefault = ( }; const createToast = (defaults: ToastDefaults): Toast => { - const errorDefault = defaults.error ?? STAY_UNTIL_CLOSED; - const actionDefault = defaults.action ?? STAY_UNTIL_CLOSED; + const errorDefault = resolveDefault(defaults.error); + const actionDefault = resolveDefault(defaults.action); const withActionDefaults = (data?: ExternalToast): ExternalToast | undefined => { if (data?.action) return applyDefault(data, actionDefault); From 62eb652753b6e49dbe19b150ab514ba2a879c125 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Wed, 18 Nov 2026 09:03:51 +0900 Subject: [PATCH 07/10] style(toast): drop formatting-only changes from the previous commit The previous commit was formatted with a print width that is not the repository's, which rewrapped unrelated lines in use-toast.test.tsx and appshell-context.tsx. This restores them. No behavior change. Co-Authored-By: Claude Opus 5.5 --- .../core/src/contexts/appshell-context.tsx | 10 +-- packages/core/src/hooks/use-toast.test.tsx | 89 ++++--------------- packages/core/src/hooks/use-toast.ts | 5 +- 3 files changed, 21 insertions(+), 83 deletions(-) diff --git a/packages/core/src/contexts/appshell-context.tsx b/packages/core/src/contexts/appshell-context.tsx index 2633d469c..30ed9ff85 100644 --- a/packages/core/src/contexts/appshell-context.tsx +++ b/packages/core/src/contexts/appshell-context.tsx @@ -71,9 +71,7 @@ export type ToastDefault = { * `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]; +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 @@ -244,9 +242,5 @@ export interface TimeZone { export const useTimeZone = (): TimeZone => { const { configurations } = useContext(AppShellConfigContext); const timeZone = configurations.timeZone ?? getLocalTimeZone(); - return { - value: timeZone, - today: () => today(timeZone), - now: () => now(timeZone), - }; + return { value: timeZone, today: () => today(timeZone), now: () => now(timeZone) }; }; diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index f9fe91ba5..a40df1112 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -61,10 +61,7 @@ describe("useToast", () => { await act(async () => { toast.error("Failed to save"); }); - expect(activeToast("Failed to save")).toMatchObject({ - duration: Infinity, - closeButton: true, - }); + expect(activeToast("Failed to save")).toMatchObject({ duration: Infinity, closeButton: true }); await waitFor(() => { expect(closeButtonOf("Failed to save")).not.toBeNull(); }); @@ -74,18 +71,10 @@ describe("useToast", () => { 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, + 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 () => { @@ -94,18 +83,9 @@ describe("useToast", () => { 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, - }); + 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 () => { @@ -131,18 +111,12 @@ describe("useToast", () => { renderToaster(); await act(async () => { toast.success("Saved", { id: toast.error("Save failed") }); - toast.success("Kept", { - id: toast.error("Other failure"), - duration: 8000, - }); + 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, - }); + expect(activeToast("Kept")).toMatchObject({ type: "success", duration: 8000 }); await act(async () => { await vi.advanceTimersByTimeAsync(5000); }); @@ -155,10 +129,7 @@ describe("useToast", () => { renderToaster(); await act(async () => { toast.error("Locked", { dismissible: false }); - toast("Pinned", { - dismissible: false, - action: { label: "Undo", onClick: () => {} }, - }); + toast("Pinned", { dismissible: false, action: { label: "Undo", onClick: () => {} } }); toast.error("Kept open", { dismissible: false, duration: Infinity }); }); for (const title of ["Locked", "Pinned"]) { @@ -240,10 +211,7 @@ describe("useToast", () => { 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, - }), + error: (error: Error) => ({ message: `A: ${error.message}`, duration: 1500 }), }); const fromCall = toast.promise(Promise.reject(new Error("boom")), { loading: "Saving B", @@ -294,10 +262,7 @@ describe("useToast with ", () => { await act(async () => { t.error("Failed"); }); - expect(activeToast("Failed")).toMatchObject({ - duration: Infinity, - closeButton: true, - }); + expect(activeToast("Failed")).toMatchObject({ duration: Infinity, closeButton: true }); }); it("restores the previous behavior for one kind and keeps the other", async () => { @@ -308,15 +273,9 @@ describe("useToast with ", () => { t.error("Failed"); t("Archived", { action: { label: "Undo", onClick: () => {} } }); }); - expect(activeToast("Failed")).toMatchObject({ - duration: 4000, - closeButton: false, - }); + expect(activeToast("Failed")).toMatchObject({ duration: 4000, closeButton: false }); expect(closeButtonOf("Failed")).toBeFalsy(); - expect(activeToast("Archived")).toMatchObject({ - duration: Infinity, - closeButton: true, - }); + expect(activeToast("Archived")).toMatchObject({ duration: Infinity, closeButton: true }); await act(async () => { await vi.advanceTimersByTimeAsync(5000); }); @@ -325,27 +284,15 @@ describe("useToast with ", () => { }); it("overrides only the configured fields, and the caller still wins", async () => { - const t = useToastWith({ - error: { duration: 10_000 }, - action: { closeButton: false }, - }); + 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, - }); + 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 () => { diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index 58c15a85a..2567832ba 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -22,10 +22,7 @@ type PromiseErrorOptions = Extract; * 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, -}; +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 => ({ From 894bc9bd3a931125b8921d7c756b33536c8648ff Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Wed, 18 Nov 2026 09:16:43 +0900 Subject: [PATCH 08/10] fix(toast): keep toastDefaults stable when it is written inline `toastDefaults={{ ... }}` written inline is a new object on every render. The configurations memo depended on its identity, so every AppShell render rebuilt the config context and `useToast` returned a new `toast`. An effect with `toast` in its dependencies then ran again and could stack duplicate sticky error toasts. AppShell now keys `toastDefaults` by its values. A test renders the real AppShell, re-renders it with an inline object, and checks that `toast` keeps its identity until a value changes. Co-Authored-By: Claude Opus 5.5 --- .../core/src/components/appshell/appshell.tsx | 31 ++++++++++++++- packages/core/src/hooks/use-toast.test.tsx | 39 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/packages/core/src/components/appshell/appshell.tsx b/packages/core/src/components/appshell/appshell.tsx index 1ff2c2af7..228403518 100644 --- a/packages/core/src/components/appshell/appshell.tsx +++ b/packages/core/src/components/appshell/appshell.tsx @@ -29,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. * @@ -332,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( @@ -344,7 +371,7 @@ const AppShellRoot = (props: AppShellProps) => { errorBoundary: props.errorBoundary, locale: props.locale, timeZone: props.timeZone, - toastDefaults: props.toastDefaults, + toastDefaults, }) : null, [ @@ -354,7 +381,7 @@ const AppShellRoot = (props: AppShellProps) => { props.errorBoundary, props.locale, props.timeZone, - props.toastDefaults, + toastDefaults, ], ); diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index a40df1112..0be01b31c 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -8,6 +8,10 @@ import { 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 = () => @@ -324,6 +328,41 @@ describe("useToast with ", () => { 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: [], From f4df18888e47f33bc82d8238ade3526144239d59 Mon Sep 17 00:00:00 2001 From: Hiroki Uemura Date: Wed, 18 Nov 2026 09:29:21 +0900 Subject: [PATCH 09/10] fix(toast): keep the success state of toast.promise with an action Sonner copies a call-level `action` into the loading toast and merges the success state into it, so the success toast shows the action but closed after 4 s. `useToast` now gives such a call the action defaults. The error state is resolved first from the call as written, so it keeps the error default. Co-Authored-By: Claude Opus 5.5 --- docs-manifest.json | 6 +-- docs-src/hooks/use-toast.docs.outline.md | 2 +- docs/api/use-toast.md | 2 +- packages/core/src/hooks/use-toast.test.tsx | 45 ++++++++++++++++++++++ packages/core/src/hooks/use-toast.ts | 23 ++++++++--- 5 files changed, 67 insertions(+), 11 deletions(-) diff --git a/docs-manifest.json b/docs-manifest.json index 3db066a72..e48fa5e71 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1790,9 +1790,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "431796ac9e8f8ca2", + "outline": "a1d2e217a3007c59", "snapshot": null, - "outputMd": "d068aa70c3ad34e8", + "outputMd": "5ebd7d3580fa23a8", "examples": null } }, @@ -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": "c338022de386d5e4", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "30c15545ab3c4954", - "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "d068aa70c3ad34e8", + "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "5ebd7d3580fa23a8", "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", diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index d12711f6b..e3f6ed2b5 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -42,7 +42,7 @@ 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. +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`. diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index 7cb1949bd..a425a8ebf 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -42,7 +42,7 @@ 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. +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`. diff --git a/packages/core/src/hooks/use-toast.test.tsx b/packages/core/src/hooks/use-toast.test.tsx index 0be01b31c..8eb5ca85b 100644 --- a/packages/core/src/hooks/use-toast.test.tsx +++ b/packages/core/src/hooks/use-toast.test.tsx @@ -252,6 +252,51 @@ describe("useToast", () => { 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 ", () => { diff --git a/packages/core/src/hooks/use-toast.ts b/packages/core/src/hooks/use-toast.ts index 2567832ba..46ee6e1de 100644 --- a/packages/core/src/hooks/use-toast.ts +++ b/packages/core/src/hooks/use-toast.ts @@ -33,19 +33,20 @@ const resolveDefault = (configured: ToastDefault | undefined): Required typeof result === "object" && result !== null && "message" in result; -const applyDefault = ( - data: ExternalToast | undefined, +const applyDefault = >( + data: D | undefined, fallback: Required, -): ExternalToast | undefined => { +): 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 => { @@ -89,6 +90,17 @@ const createToast = (defaults: ToastDefaults): Toast => { }; }; + /** + * 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)), @@ -96,8 +108,7 @@ const createToast = (defaults: ToastDefaults): Toast => { 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 && withPromiseErrorDefaults(data)), + 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, From 56c3cb3e41a111232119c613a0deb384cf9a223f Mon Sep 17 00:00:00 2001 From: interacsean Date: Thu, 19 Nov 2026 10:39:11 +1100 Subject: [PATCH 10/10] docs(toast): give repeatable errors a stable id Sticky error toasts now stack when the same operation fails again. State in the useToast and interaction-toast docs that such calls pass a stable id so the new toast replaces the previous one. Co-Authored-By: Claude Opus 5.5 --- docs-manifest.json | 12 ++++++------ docs-src/hooks/use-toast.docs.outline.md | 2 ++ docs-src/patterns/interaction-toast.docs.outline.md | 1 + docs/api/use-toast.md | 2 ++ docs/patterns/interaction-toast.md | 1 + 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs-manifest.json b/docs-manifest.json index 2cbbb0690..d7047c862 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -1028,9 +1028,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "c1802da0be69c18a", + "outline": "4ede6f17c870d838", "snapshot": null, - "outputMd": "4191e757cf7c58cb", + "outputMd": "fbdc96bd3d3d0140", "examples": "7089e7331b95df31" } }, @@ -1790,9 +1790,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "7c84727d4caa7d34", + "outline": "0fc65140da8f7dff", "snapshot": null, - "outputMd": "b85f0c9258628e9d", + "outputMd": "90d80eef666e4cb4", "examples": "0dce35625d5e56cf" } }, @@ -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": "b85f0c9258628e9d", + "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,7 +1906,7 @@ "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": "4191e757cf7c58cb", + "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", diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index 527637c60..721ad8d5a 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -46,6 +46,8 @@ For `toast.promise`, a `duration` or `closeButton` on the call applies to the er 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: diff --git a/docs-src/patterns/interaction-toast.docs.outline.md b/docs-src/patterns/interaction-toast.docs.outline.md index 5aa4373bc..0b344fb41 100644 --- a/docs-src/patterns/interaction-toast.docs.outline.md +++ b/docs-src/patterns/interaction-toast.docs.outline.md @@ -44,6 +44,7 @@ dont: - 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 diff --git a/docs/api/use-toast.md b/docs/api/use-toast.md index 72448d592..0b569677a 100644 --- a/docs/api/use-toast.md +++ b/docs/api/use-toast.md @@ -46,6 +46,8 @@ For `toast.promise`, a `duration` or `closeButton` on the call applies to the er 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: diff --git a/docs/patterns/interaction-toast.md b/docs/patterns/interaction-toast.md index 7d7cc780c..9115ddd20 100644 --- a/docs/patterns/interaction-toast.md +++ b/docs/patterns/interaction-toast.md @@ -38,6 +38,7 @@ function InteractionToast() { - 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