diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md
new file mode 100644
index 00000000..868d03ac
--- /dev/null
+++ b/.changeset/toast-stack.md
@@ -0,0 +1,10 @@
+---
+"@codeui/solid": minor
+"@codeui/styles": minor
+---
+
+Toaster: a new engine with Sonner's motion replaces Kobalte's toast region behind `createToaster` and `Toaster`. Toasts stack like a deck: the newest in front, two older ones peeking behind it, smaller and without content. Hovering or focusing the stack fans the toasts out, and every timer pauses until the pointer and focus leave, or while the page is hidden. Toasts enter and leave with transitions, so a new toast pushes the stack back smoothly instead of crossing over it. `limit` now hides older toasts instead of queueing newer ones. Swipe a toast toward the region's edge to dismiss it. `expand` keeps the toasts fanned out. The toasts render newest first.
+
+Breaking: toasts follow the page theme by default; pass `theme="inverted"` to `Toaster`, or to one toast, for the old light-on-dark card. `Toaster` no longer takes Kobalte's `swipeDirection`, `pauseOnInteraction`, `pauseOnPageIdle` or `translations`. The styled parts in `@codeui/solid/toast/parts` still wrap Kobalte and are unchanged.
+
+Toast: the description takes the muted text colour under a title, with 2px between them, so the two read apart. The tone icon grows to 20px and lines up with the title instead of centring on the whole card. The toast gains 4px of padding on its leading side. Toasts take the floating-surface shadow, `--cui-shadow-dialog`, and the cards behind the front one fade a step toward the page, so the stack reads as separate cards on any page. Toasts are 360px wide, down from 480px, and the stack keeps that width even when an app stretches the region.
diff --git a/.claude/skills/verify-codeui/features/feedback.md b/.claude/skills/verify-codeui/features/feedback.md
index ba3b38ba..301b26d6 100644
--- a/.claude/skills/verify-codeui/features/feedback.md
+++ b/.claude/skills/verify-codeui/features/feedback.md
@@ -10,7 +10,7 @@ Tooltip shows a short label next to its trigger on hover and should also show on
- `tooltip-variants` renders primary, secondary, disabled and custom JSX content.
- `tooltip-motion` pops on hover; keyboard focus opens it with `data-motion="none"`, and the focused child (not the wrapper) carries `aria-describedby`.
- `tooltip-empty` never opens when `content` is `undefined`, `null` or `""`, on hover or focus, and the focused trigger gets no `aria-describedby`.
-- `toast-rise` (Toaster) renders in the inverted theme (`data-cui-theme` opposite the page) and sits 80px above the bottom of its region's container.
+- `toast-rise` (Toaster) follows the page theme (no `data-cui-theme` of its own) and sits 80px above the bottom of its region's container. `designsystem-toaster--inverted` shows `theme="inverted"`.
## How to get to it (user POV)
@@ -28,6 +28,7 @@ Preconditions:
- **Motion and description.** `drive.mjs designsystem-tooltip--tooltip-story --journey .claude/skills/verify-codeui/journeys/tooltip-motion.mjs`.
- **Empty content.** `drive.mjs designsystem-tooltip--empty-content --journey .claude/skills/verify-codeui/journeys/tooltip-empty.mjs`.
- **Toast.** `drive.mjs designsystem-toaster--with-action --journey .claude/skills/verify-codeui/journeys/toast-rise.mjs`.
+- **Toast stack.** `drive.mjs designsystem-toaster--stacked --journey .claude/skills/verify-codeui/journeys/toast-stack.mjs`. Collapsed: the front toast (`data-front`) is lowest and two peek above with hidden content. Hover and Tab both fan the stack out with no overlap, and Escape closes the focused toast. The story's Add notification button adds live toasts. The harness turns transitions off, so record a video with `reducedMotion: "no-preference"` to judge motion. Stories that need every toast in full pass `expand` (Tones).
- **Dismiss.** After hover, press Escape; expect count 0.
- **Theme.** Screenshot the open tooltip in both themes (`step('hovered')`).
diff --git a/.claude/skills/verify-codeui/journeys/toast-rise.mjs b/.claude/skills/verify-codeui/journeys/toast-rise.mjs
index aa1e0c93..92f4ce87 100644
--- a/.claude/skills/verify-codeui/journeys/toast-rise.mjs
+++ b/.claude/skills/verify-codeui/journeys/toast-rise.mjs
@@ -1,19 +1,19 @@
-// Toaster: the toast uses the inverted theme and sits 80px from the bottom of its frame.
+// Toaster: the toast follows the page theme and sits 80px from the bottom of its frame.
export default async ({ page, step, check, theme }) => {
const toast = page.getByRole("status").first();
await step("toasts shown", () => toast.waitFor());
- await check("inverted theme", async () => {
+ await check("follows the page theme", async () => {
const value = await toast.getAttribute("data-cui-theme");
- const bg = await toast.evaluate(el => getComputedStyle(el).backgroundColor);
- return { pass: value === (theme === "dark" ? "light" : "dark"), value, bg };
+ const scheme = await toast.evaluate(el => getComputedStyle(el).colorScheme);
+ return { pass: value === null && scheme.includes(theme), value, scheme };
});
await check("80px from the bottom of the frame, radius 16, explicit line height", async () => {
const m = await page.evaluate(() => {
const region = document.querySelector("[data-cui=toast-region]");
const frame = region.parentElement.getBoundingClientRect();
- const toasts = [...document.querySelectorAll("[role=status]")];
- const last = toasts.at(-1).getBoundingClientRect();
- const c = getComputedStyle(toasts.at(-1));
+ const front = document.querySelector("[role=status][data-front]");
+ const last = front.getBoundingClientRect();
+ const c = getComputedStyle(front);
return { gap: Math.round(frame.bottom - last.bottom), radius: c.borderRadius, fontSize: c.fontSize, lineHeight: c.lineHeight };
});
return { pass: m.gap === 80 && m.radius === "16px" && m.lineHeight !== "normal", ...m };
diff --git a/.claude/skills/verify-codeui/journeys/toast-stack.mjs b/.claude/skills/verify-codeui/journeys/toast-stack.mjs
new file mode 100644
index 00000000..ca81d4a9
--- /dev/null
+++ b/.claude/skills/verify-codeui/journeys/toast-stack.mjs
@@ -0,0 +1,65 @@
+const rects = page =>
+ page.$$eval('[data-cui-stack] > [data-cui="toast"]:not([data-closed])', els =>
+ els.map(el => {
+ const r = el.getBoundingClientRect();
+ const title = el.querySelector('[data-cui="toast-title"]');
+ return {
+ index: el.style.getPropertyValue("--cui-toast-index"),
+ top: Math.round(r.top),
+ bottom: Math.round(r.bottom),
+ width: Math.round(r.width),
+ contentOpacity: title ? getComputedStyle(title).opacity : null,
+ };
+ }),
+ );
+
+export default async ({ page, step, check, focus }) => {
+ await page.waitForSelector('[data-cui-stack] > [data-cui="toast"][data-mounted]');
+ await page.mouse.move(5, 5);
+ await step("collapsed", async () => {});
+ await check("collapsed: front is lowest, two peek above", async () => {
+ const r = await rects(page);
+ const by = i => r.find(x => x.index === String(i));
+ const pass =
+ r.length === 3 &&
+ by(0).contentOpacity === "1" &&
+ by(1).contentOpacity === "0" &&
+ by(1).top < by(0).top &&
+ by(2).top < by(1).top &&
+ by(0).top - by(2).top < 40;
+ return { pass, r };
+ });
+ await step("hover fans out", async () => {
+ await page.locator('[data-cui="toast"][data-front]').hover();
+ });
+ await check("expanded: no overlap, all readable", async () => {
+ const r = (await rects(page)).sort((a, b) => a.top - b.top);
+ const pass = r.every(
+ (x, i) => x.contentOpacity === "1" && (i === 0 || r[i - 1].bottom <= x.top),
+ );
+ return { pass, r };
+ });
+ await step("pointer leaves", async () => {
+ await page.mouse.move(5, 5);
+ });
+ await check("collapsed again", async () => {
+ const r = await rects(page);
+ return { pass: r.filter(x => x.contentOpacity === "0").length === 2, r };
+ });
+ await step("Tab reaches a toast", async () => {
+ await page.keyboard.press("Tab");
+ await page.keyboard.press("Tab");
+ });
+ await check("focus expands the stack", async () => {
+ const r = await rects(page);
+ return { pass: r.every(x => x.contentOpacity === "1"), r, focus: await focus() };
+ });
+ await step("Escape closes the focused toast", async () => {
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(400);
+ });
+ await check("two toasts remain", async () => {
+ const r = await rects(page);
+ return { pass: r.length === 2, r };
+ });
+};
diff --git a/apps/docs/content/docs/(kit)/components/toast.mdx b/apps/docs/content/docs/(kit)/components/toast.mdx
index f6164dde..d58b73d4 100644
--- a/apps/docs/content/docs/(kit)/components/toast.mdx
+++ b/apps/docs/content/docs/(kit)/components/toast.mdx
@@ -63,7 +63,7 @@ A `Toaster` has one `position`. The default is `bottom-center`. Toasts rise from
`title` and `description` take JSX or a callback. The callback receives the toast context, `{ id, dismiss }`, so the content can close its own toast. The content renders inside `Toaster`, so it reads the context of the providers around `Toaster`, such as the locale.
-`icon` replaces the tone icon. `icon: null` hides it. `theme` picks the toast's theme. The default, `inverted`, renders the opposite of the theme around the `Toaster`, as CodeImage does: a light card on a dark page, and a dark card on a light page. It follows the page when the theme changes while the toast is open. `page` uses the page theme. `light` and `dark` force one.
+`icon` replaces the tone icon. `icon: null` hides it. `theme` picks the toast's theme. The default, `page`, follows the theme around the `Toaster`. `inverted` renders its opposite, as CodeImage does: a light card on a dark page, and a dark card on a light page, and it flips when the page theme changes while the toast is open. `light` and `dark` force one. Set `theme` on `Toaster` to give all its toasts one theme; a toast's own `theme` overrides it.
### Action
@@ -103,9 +103,9 @@ Every timer of a `Toaster` pauses while the pointer is over its toasts or focus
All three do nothing when the id is not open. A `ToastId` is a number scoped to its controller. Two controllers can return the same id.
-### Queue
+### Stack
-A `Toaster` shows three toasts at once. Set `limit` to change that. A later toast waits until a visible one closes, and its timer starts when it appears.
+A `Toaster` stacks its toasts like a deck: the newest in front, two older ones peeking behind it. Hovering or focusing the stack fans the toasts out, and every timer pauses until the pointer and focus leave. Timers also pause while the page is hidden. Set `limit` to show more or fewer toasts; older ones stay open but hidden. Set `expand` to keep the toasts fanned out. Swipe a toast toward the region's edge to dismiss it, and press alt+T to move focus to the toasts.
### Two toasters on one page
@@ -121,10 +121,6 @@ Each controller has its own toasts, ids, and default duration. `clear()` on one
-Inherited from Kobalte's [toast region](https://kobalte.dev/docs/core/components/toast):
-
-
-
### `createToaster`
`createToaster(options)` returns a `ToastController`. Created inside a component, the controller dismisses its toasts when that component's owner is disposed.
diff --git a/apps/docs/content/docs/design/motion.mdx b/apps/docs/content/docs/design/motion.mdx
index 78e7acf7..3947aab6 100644
--- a/apps/docs/content/docs/design/motion.mdx
+++ b/apps/docs/content/docs/design/motion.mdx
@@ -32,7 +32,7 @@ Naming the movements gives designers, developers and agents a shared vocabulary.
| **Expand** | Accordion | Height and opacity 200ms, reversible mid-way |
| **Morph** | The content after a value changes | The changed property, 150–200ms |
| **Collapse to origin** | Closing something that lives on elsewhere | Shrinks into where it can be found again, 200ms |
-| **Rise** | Corner card, toast | From the edge 400ms; leaves in 200ms |
+| **Rise** | Corner card, toast | From the edge 400ms; leaves in 200ms. Several toasts stack as a deck and fan out on hover or focus in 400ms |
| **Reveal** | A surface growing in place | `clip-path`, 260ms |
| **Slide** | Phone sheet, side sheet | From its edge in 260ms on the drawer curve; out in 200ms ease-out; turns around if reopened mid-exit; follows the finger when dragged |
| **Ring** | Selection ring | From `scale(0.92)` with a fade, 200ms |
diff --git a/apps/docs/export-manifest.json b/apps/docs/export-manifest.json
index 10993080..539cdb5e 100644
--- a/apps/docs/export-manifest.json
+++ b/apps/docs/export-manifest.json
@@ -278,7 +278,8 @@
"TooltipDefaults": "components/tooltip#defaults-for-a-whole-app",
"TooltipProvider": "components/tooltip#defaults-for-a-whole-app",
"HoverCardGroup": "components/hover-card#hovercardgroup",
- "HoverCardGroupProps": "components/hover-card#hovercardgroup"
+ "HoverCardGroupProps": "components/hover-card#hovercardgroup",
+ "ToastTheme": "components/toast#toaster"
},
"@codeui/solid/accordion/parts": {
"AccordionClasses": "components/accordion#anatomy",
@@ -985,7 +986,8 @@
"ToasterProps": "components/toast#toaster",
"ToastId": "components/toast#createtoaster",
"ToastOptions": "components/toast#createtoaster",
- "ToastPromiseOptions": "components/toast#createtoaster"
+ "ToastPromiseOptions": "components/toast#createtoaster",
+ "ToastTheme": "components/toast#toaster"
},
"@codeui/solid/checkbox": {
"Checkbox": "components/checkbox#checkbox",
diff --git a/packages/docs-demos/src/props/toast.ts b/packages/docs-demos/src/props/toast.ts
index d19a9b37..c960af25 100644
--- a/packages/docs-demos/src/props/toast.ts
+++ b/packages/docs-demos/src/props/toast.ts
@@ -2,13 +2,10 @@ import type { CreateToasterOptions, ToasterProps, ToastOptions } from "@codeui/s
import type { RegionProps, RootProps } from "@codeui/solid/toast/parts";
import type { PropNotes } from "./notes";
-/** Props that Toaster adds on top of the styled toast region. */
-export type Toaster = Pick;
-
-/** Kobalte toast region options that Toaster passes through. */
-export type ToasterInherited = Pick<
+/** The props of Toaster. */
+export type Toaster = Pick<
ToasterProps,
- "limit" | "hotkey" | "swipeDirection" | "pauseOnInteraction" | "pauseOnPageIdle" | "aria-label" | "translations"
+ "toaster" | "closeLabel" | "position" | "limit" | "expand" | "hotkey" | "theme" | "aria-label" | "class" | "classes"
>;
/** The options createToaster takes. */
@@ -30,17 +27,14 @@ export const notes = {
Toaster: {
toaster: { description: "The controller whose toasts this region shows." },
closeLabel: { description: "Accessible name of each toast's close button, in the app's language." },
- position: { default: '"bottom-center"', description: "Viewport edge and alignment of the region." },
- class: { description: "Class merged after the kit styles on the region." },
- classes: { description: "Classes for the region and list parts. Per-toast classes go in the toast options." },
- },
- ToasterInherited: {
- limit: { default: "3", description: "Most toasts shown at once. Later toasts wait in the queue." },
+ position: { default: '"bottom-center"', description: "Viewport edge and alignment of the region. Toasts swipe away toward this edge." },
+ limit: { default: "3", description: "Toasts shown in the stack. Older toasts stay open but hidden behind them." },
+ expand: { default: "false", description: "Keeps every toast fanned out instead of stacking them." },
hotkey: { default: '["altKey", "KeyT"]', description: "Keys that move focus to the toast list." },
- swipeDirection: { default: '"right"', description: "Direction of the swipe that dismisses a toast." },
- pauseOnInteraction: { default: "true", description: "Pauses every timer while the pointer is over the list or focus is inside it." },
- pauseOnPageIdle: { default: "true", description: "Pauses every timer while the window is not focused." },
+ theme: { default: '"page"', description: "Theme of every toast. `inverted` renders the opposite of the page theme." },
"aria-label": { default: '"Notifications (alt+T)"', description: "Accessible name of the region." },
+ class: { description: "Class merged after the kit styles on the region." },
+ classes: { description: "Classes for the region and list parts. Per-toast classes go in the toast options." },
},
CreateToaster: {
duration: { default: "5000", description: "Milliseconds before a toast closes, when the toast sets no duration." },
@@ -53,7 +47,7 @@ export const notes = {
action: { description: "An inline text button. Its `onClick` receives the toast context. The toast stays open." },
closeable: { default: "true", description: "Shows the close button." },
duration: { default: "createToaster duration", description: "Milliseconds before the toast closes. `Infinity` keeps it open." },
- theme: { description: "Renders the toast in this theme, whatever the page theme." },
+ theme: { default: "Toaster theme", description: "Overrides the Toaster theme for this toast." },
class: { description: "Class merged after the kit styles on the toast root." },
classes: { description: "Classes for the parts of this toast, keyed by part name." },
},
diff --git a/packages/kit/DESIGN.md b/packages/kit/DESIGN.md
index 39d834b6..ab1a9aab 100644
--- a/packages/kit/DESIGN.md
+++ b/packages/kit/DESIGN.md
@@ -290,7 +290,7 @@ Rules for every movement:
- Hover styles only under `@media (hover: hover) and (pointer: fine)`.
- **No materials.** Unlike Apple's design language, Inkstone has no translucency or `backdrop-filter` on the interface. Matte is a trait.
-The kit's popover, hover card, menu, list popovers and tooltip follow Pop, and its toast follows Rise. Pop uses CSS keyframes. The kit keeps each closing surface mounted until its exit finishes. The rest of the kit's motion is slower than these rules today: buttons press in 200ms `ease`, and the focus ring transitions with `ease-in`. **Proposed:** move them to Press and a 120ms colour change.
+The kit's popover, hover card, menu, list popovers and tooltip follow Pop, and its toast follows Rise. Several toasts stack like a deck, after Sonner: the newest in front, up to two older ones peeking 12px behind it at 95% and 90% scale with their content hidden, each a step closer to the page colour (`filter: brightness()`) so the cards read apart. A toast is a floating surface: `--cui-shadow-dialog`, with its inner ring in dark mode. A toast enters with a transition from its edge, so the stack moves back while it rises. Hover or focus fans them out with `transform` and `clip-path` over 400ms ease-out; a toast leaves toward its edge in 200ms; `expand` keeps them fanned out. Pop uses CSS keyframes. The kit keeps each closing surface mounted until its exit finishes. The rest of the kit's motion is slower than these rules today: buttons press in 200ms `ease`, and the focus ring transitions with `ease-in`. **Proposed:** move them to Press and a 120ms colour change.
The kit sheet follows Slide with transitions, and its scrim fades with it. It stays mounted until its exit ends, and the page under it takes clicks during that exit. Opened or closed from the keyboard, it does not move.
diff --git a/packages/kit/api/kit.api.md b/packages/kit/api/kit.api.md
index 8992740e..dc7e2359 100644
--- a/packages/kit/api/kit.api.md
+++ b/packages/kit/api/kit.api.md
@@ -5152,8 +5152,45 @@ export {};
## components/Toast/Toaster.d.ts
```ts
+import type { JSX } from "@solidjs/web";
+import { type ToastClasses, type ToastPosition } from "../../parts/toast.js";
+import { type ToastController, type ToastTheme } from "./controller.js";
+export { createToaster } from "./controller.js";
+export type { CreateToasterOptions, ToastAction, ToastContent, ToastContext, ToastController, ToastId, ToastOptions, ToastPromiseOptions, ToastTheme, } from "./controller.js";
+export type ToasterProps = Omit, "children"> & {
+ toaster: ToastController;
+ /** Defaults to bottom center. */
+ position?: ToastPosition;
+ /** The close button's accessible name, in the app's language. */
+ closeLabel: string;
+ /** How many toasts show in the stack. Older ones wait hidden. Defaults to 3. */
+ limit?: number;
+ /**
+ * Keeps every toast fanned out. By default the toasts stack like a deck,
+ * newest in front, and fan out while the pointer or focus is on them.
+ */
+ expand?: boolean;
+ /** Keys that move focus to the toasts, as `KeyboardEvent` codes or modifier names. Defaults to alt+T. */
+ hotkey?: string[];
+ /** The theme of its toasts. A toast's own `theme` overrides it. Defaults to `page`. */
+ theme?: ToastTheme;
+ /** Classes for the region and list. Per-toast classes go in the toast options. */
+ classes?: Pick;
+};
+/**
+ * The region that shows one controller's toasts. Place it inside the app's
+ * providers: toast content renders here and can read their context.
+ * Motion follows Sonner (emilkowalski/sonner, src/index.tsx and styles.css).
+ */
+export declare function Toaster(props: ToasterProps): JSX.Element;
+```
+
+## components/Toast/controller.d.ts
+
+```ts
+import { type Accessor, type Setter } from "solid-js";
import { type JSX } from "@solidjs/web";
-import * as T from "../../parts/toast.js";
+import type * as T from "../../parts/toast.js";
/** Scoped to the controller that returned it. Two controllers can return the same id. */
export type ToastId = number;
export type ToastContext = {
@@ -5166,6 +5203,11 @@ export type ToastAction = {
/** The toast stays open. Call `context.dismiss()` to close it. */
onClick: (context: ToastContext) => void;
};
+/**
+ * `page` follows the theme around the toaster. `inverted` uses its opposite,
+ * as CodeImage does: a light card on a dark page. `light` and `dark` force one.
+ */
+export type ToastTheme = "light" | "dark" | "inverted" | "page";
export type ToastOptions = {
title?: ToastContent;
description: ToastContent;
@@ -5177,12 +5219,8 @@ export type ToastOptions = {
closeable?: boolean;
/** Milliseconds before the toast closes. `Infinity` keeps it open. */
duration?: number;
- /**
- * The toast's theme. `inverted` (the default) uses the opposite of the
- * theme around the toaster, as CodeImage does: a light card on a dark
- * page. `page` follows the page. `light` and `dark` force one.
- */
- theme?: "light" | "dark" | "inverted" | "page";
+ /** Overrides the `Toaster` theme for this toast. */
+ theme?: ToastTheme;
class?: string;
classes?: T.ToastClasses;
style?: JSX.CSSProperties;
@@ -5213,26 +5251,31 @@ export type CreateToasterOptions = {
/** Default milliseconds before a toast closes. Defaults to 5000. */
duration?: number;
};
+export type ToastEntry = {
+ id: ToastId;
+ context: ToastContext;
+ options: Accessor;
+ setOptions: Setter;
+ duration: Accessor;
+ /** Changes when the close timer must restart. */
+ timer: Accessor;
+ setTimer: Setter;
+ closing: Accessor;
+ setClosing: Setter;
+ /** Set while a `` renders the toast, so dismiss can wait for its exit. */
+ rendered: boolean;
+};
+export type ToastStore = {
+ toasts: Accessor;
+ remove(id: ToastId): void;
+};
+export declare function toastStore(controller: ToastController): ToastStore;
/**
* Creates a toast controller for one ``. Each controller has its own
* toasts, so create one per app or per region. On the server it shows nothing.
* Created inside a component, it clears its toasts when that owner is disposed.
*/
export declare function createToaster(options?: CreateToasterOptions): ToastController;
-export type ToasterProps = Omit & {
- toaster: ToastController;
- /** Defaults to bottom center. */
- position?: T.ToastPosition;
- /** The close button's accessible name, in the app's language. */
- closeLabel: string;
- /** Classes for the region and list. Per-toast classes go in the toast options. */
- classes?: Pick;
-};
-/**
- * The region that shows one controller's toasts. Place it inside the app's
- * providers: toast content renders here and can read their context.
- */
-export declare function Toaster(props: ToasterProps): JSX.Element;
```
## components/Tooltip/Tooltip.css.d.ts
@@ -6704,7 +6747,7 @@ export * from "../components/Text/Text.js";
```ts
export { Toaster, createToaster } from "../components/Toast/Toaster.js";
-export type { CreateToasterOptions, ToastAction, ToastContent, ToastContext, ToastController, ToasterProps, ToastId, ToastOptions, ToastPromiseOptions, } from "../components/Toast/Toaster.js";
+export type { CreateToasterOptions, ToastAction, ToastContent, ToastContext, ToastController, ToasterProps, ToastId, ToastOptions, ToastPromiseOptions, ToastTheme, } from "../components/Toast/Toaster.js";
```
## ready/tooltip.d.ts
diff --git a/packages/kit/src/components/Toast/ToastItem.tsx b/packages/kit/src/components/Toast/ToastItem.tsx
new file mode 100644
index 00000000..d9febed8
--- /dev/null
+++ b/packages/kit/src/components/Toast/ToastItem.tsx
@@ -0,0 +1,253 @@
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ createUniqueId,
+ onCleanup,
+ onSettled,
+ Show,
+} from "solid-js";
+import type { JSX } from "@solidjs/web";
+import { CloseIcon } from "../../icons/CloseIcon";
+import { ToneIcon } from "../../icons/ToneIcon";
+import { toastParts, toastStyles } from "../../parts/toast";
+import { mergeClasses } from "../../utils/css";
+import type { ToastContent, ToastEntry, ToastStore, ToastTheme } from "./controller";
+import { createSwipe, type SwipeSide } from "./swipe";
+
+/** Sonner unmounts 200ms after a toast starts to leave; Inkstone's leave is 200ms too. */
+const TIME_BEFORE_UNMOUNT = 200;
+
+export type ToastPlace = { index: number; offset: number; height: number };
+
+export type ToastItemProps = {
+ entry: ToastEntry;
+ store: ToastStore;
+ place: Accessor;
+ count: Accessor;
+ limit: Accessor;
+ expanded: Accessor;
+ paused: Accessor;
+ swipeSides: Accessor;
+ closeLabel: Accessor;
+ theme: Accessor;
+ onHeight: (height: number | undefined) => void;
+ onInteract: (interacting: boolean) => void;
+};
+
+function createPageScheme(element: () => HTMLElement | undefined) {
+ const [scheme, setScheme] = createSignal<"light" | "dark">();
+ onSettled(() => {
+ const read = () => {
+ const parent = element()?.parentElement;
+ if (!parent) return;
+ const value = [
+ getComputedStyle(parent).colorScheme,
+ parent.closest("[data-cui-theme]")?.getAttribute("data-cui-theme"),
+ ].find(value => value === "light" || value === "dark");
+ setScheme(value as "light" | "dark" | undefined);
+ };
+ read();
+ // Follow a theme switch while the toast is open: the app flips
+ // `data-cui-theme`, a class or the system preference.
+ const observer = new MutationObserver(read);
+ const scopes = new Set([
+ document.documentElement,
+ document.body,
+ element()?.parentElement?.closest("[data-cui-theme]"),
+ ]);
+ for (const scope of scopes) {
+ if (scope)
+ observer.observe(scope, {
+ attributes: true,
+ attributeFilter: ["data-cui-theme", "class", "style"],
+ });
+ }
+ const media = window.matchMedia?.("(prefers-color-scheme: dark)");
+ media?.addEventListener?.("change", read);
+ return () => {
+ observer.disconnect();
+ media?.removeEventListener?.("change", read);
+ };
+ });
+ return scheme;
+}
+
+function createCloseTimer(props: ToastItemProps) {
+ let remaining = props.entry.duration();
+ let lastTimer = -1;
+ createEffect(
+ () => ({
+ paused: props.paused(),
+ timer: props.entry.timer(),
+ closing: props.entry.closing(),
+ }),
+ ({ paused, timer, closing }) => {
+ if (timer !== lastTimer) {
+ lastTimer = timer;
+ remaining = props.entry.duration();
+ }
+ if (paused || closing || !Number.isFinite(remaining)) return;
+ const startedAt = Date.now();
+ const id = window.setTimeout(props.entry.context.dismiss, remaining);
+ return () => {
+ window.clearTimeout(id);
+ remaining -= Date.now() - startedAt;
+ };
+ },
+ );
+}
+
+export function ToastItem(props: ToastItemProps) {
+ const entry = props.entry;
+ const options = entry.options;
+ const classes = () => options().classes;
+ const titleId = createUniqueId();
+ const descriptionId = createUniqueId();
+ const [element, setElement] = createSignal();
+ const [mounted, setMounted] = createSignal(false);
+ const pageScheme = createPageScheme(element);
+
+ const place = createMemo(
+ previous =>
+ (entry.closing() && previous) || props.place() || previous || { index: 0, offset: 0, height: 0 },
+ );
+ const swipe = createSwipe({
+ sides: props.swipeSides,
+ onDismiss: entry.context.dismiss,
+ onInteract: props.onInteract,
+ });
+ createCloseTimer(props);
+
+ const render = (content: ToastContent) =>
+ typeof content === "function" ? content(entry.context) : content;
+ const title = createMemo(() => options().title);
+ const icon = createMemo(() => {
+ const { icon, tone } = options();
+ return icon === undefined ? () => : icon;
+ });
+ const hasIcon = () =>
+ options().icon === undefined
+ ? (options().tone ?? "neutral") !== "neutral"
+ : icon() != null && icon() !== false;
+ const theme = () => {
+ const theme = options().theme ?? props.theme();
+ if (theme === "page") return undefined;
+ if (theme !== "inverted") return theme;
+ const page = pageScheme();
+ return page && (page === "dark" ? "light" : "dark");
+ };
+
+ entry.rendered = true;
+ onSettled(() => {
+ const root = element();
+ if (!root) return;
+ props.onHeight(root.offsetHeight);
+ const resize = new ResizeObserver(() => {
+ if (!entry.closing()) props.onHeight(root.offsetHeight);
+ });
+ resize.observe(root);
+ const frame = requestAnimationFrame(() => setMounted(true));
+ return () => {
+ cancelAnimationFrame(frame);
+ resize.disconnect();
+ };
+ });
+ createEffect(entry.closing, closing => {
+ if (!closing) return;
+ props.onHeight(undefined);
+ const id = window.setTimeout(() => props.store.remove(entry.id), TIME_BEFORE_UNMOUNT);
+ return () => window.clearTimeout(id);
+ });
+ onCleanup(() => {
+ entry.rendered = false;
+ props.onHeight(undefined);
+ if (entry.closing()) props.store.remove(entry.id);
+ });
+
+ const style = (): JSX.CSSProperties => ({
+ "--cui-toast-index": String(place().index),
+ "--cui-toast-offset": `${place().offset}px`,
+ "--cui-toast-height": `${place().height}px`,
+ "--cui-toast-z": String(props.count() - place().index),
+ ...options().style,
+ });
+
+ return (
+