From d231ffeb866f88f7a798428732ddca6c6d3508c6 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Sun, 29 Nov 2026 23:45:07 +0100 Subject: [PATCH 1/7] feat(toast): stack toasts like a deck and restyle the toast Toasts stack with the newest in front and fan out on hover or focus. `expand` keeps the full list. The description takes the muted colour under a title and the tone icon grows to 20px, aligned with the title. Co-Authored-By: Claude Opus 5.5 --- .changeset/toast-stack.md | 8 ++ .../skills/verify-codeui/features/feedback.md | 1 + .../verify-codeui/journeys/toast-stack.mjs | 37 ++++++++ apps/docs/content/docs/design/motion.mdx | 2 +- packages/kit/DESIGN.md | 2 +- packages/kit/src/components/Toast/Toaster.tsx | 20 ++++- packages/kit/src/components/Toast/stack.ts | 55 ++++++++++++ .../storybook/src/stories/Toaster.stories.tsx | 34 ++++++++ .../styles/css/components/Toast/Toast.css | 84 +++++++++++++++++-- packages/styles/scripts/appearance.mjs | 2 + 10 files changed, 236 insertions(+), 9 deletions(-) create mode 100644 .changeset/toast-stack.md create mode 100644 .claude/skills/verify-codeui/journeys/toast-stack.mjs create mode 100644 packages/kit/src/components/Toast/stack.ts diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md new file mode 100644 index 00000000..a0ade958 --- /dev/null +++ b/.changeset/toast-stack.md @@ -0,0 +1,8 @@ +--- +"@codeui/solid": minor +"@codeui/styles": minor +--- + +Toaster: toasts stack like a deck by default. The newest sits in front and up to two older ones peek behind it, narrower and without content. Hovering or focusing the stack fans the toasts out to full height; leaving collapses it. Toasts in a stack take the region's full width. Pass `expand` to list every toast in full as before. + +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. diff --git a/.claude/skills/verify-codeui/features/feedback.md b/.claude/skills/verify-codeui/features/feedback.md index ba3b38ba..b6082e3f 100644 --- a/.claude/skills/verify-codeui/features/feedback.md +++ b/.claude/skills/verify-codeui/features/feedback.md @@ -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 is lowest and two peek above with hidden content. Hover and Tab both fan the stack out with no overlap. 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-stack.mjs b/.claude/skills/verify-codeui/journeys/toast-stack.mjs new file mode 100644 index 00000000..8414557b --- /dev/null +++ b/.claude/skills/verify-codeui/journeys/toast-stack.mjs @@ -0,0 +1,37 @@ +const rects = page => page.$$eval('[data-cui-stack] > [data-cui="toast"]', els => + els.map(el => { + const r = el.getBoundingClientRect(); + const visible = getComputedStyle(el.querySelector('[data-cui="toast-title"]')).opacity; + return { index: el.getAttribute("data-cui-stack-index"), top: Math.round(r.top), bottom: Math.round(r.bottom), width: Math.round(r.width), contentOpacity: visible }; + })); +export default async ({ page, step, check, focus }) => { + await page.waitForSelector('[data-cui-stack] > [data-cui="toast"]'); + 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 () => { + const front = page.locator('[data-cui-stack-index="0"]'); + await 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 check("focus expands the stack", async () => { + const r = await rects(page); + return { pass: r.every(x => x.contentOpacity === "1"), r, focus: await focus() }; + }); +}; 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/packages/kit/DESIGN.md b/packages/kit/DESIGN.md index 39d834b6..cb7dfc17 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: the newest in front, up to two older ones peeking 12px behind it at 95% and 90% scale with their content hidden. Hover or focus fans them out with `translate`, `scale` and `clip-path` over 400ms ease-out; `expand` lists them in full instead. 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/src/components/Toast/Toaster.tsx b/packages/kit/src/components/Toast/Toaster.tsx index 49c84d3e..6f750d96 100644 --- a/packages/kit/src/components/Toast/Toaster.tsx +++ b/packages/kit/src/components/Toast/Toaster.tsx @@ -2,6 +2,7 @@ import { toaster as engine, useToastContext } from "@kobalte/core/toast"; import { type Accessor, createContext, + createEffect, createMemo, createSignal, getOwner, @@ -18,6 +19,7 @@ import { ToneIcon } from "../../icons/ToneIcon"; import * as T from "../../parts/toast"; import { mergeClasses } from "../../utils/css"; import { Spinner } from "../Spinner/Spinner"; +import { stackToasts } from "./stack"; /** Scoped to the controller that returned it. Two controllers can return the same id. */ export type ToastId = number; @@ -320,6 +322,11 @@ export type ToasterProps = Omit< position?: T.ToastPosition; /** The close button's accessible name, in the app's language. */ closeLabel: string; + /** + * Lists every toast in full. By default the toasts stack like a deck, + * newest in front, and fan out while the pointer or focus is on them. + */ + expand?: boolean; /** Classes for the region and list. Per-toast classes go in the toast options. */ classes?: Pick; }; @@ -329,7 +336,12 @@ export type ToasterProps = Omit< * providers: toast content renders here and can read their context. */ export function Toaster(props: ToasterProps) { - const others = omit(props, "toaster", "closeLabel", "classes", "class"); + const others = omit(props, "toaster", "closeLabel", "classes", "class", "expand"); + let list: HTMLElement | undefined; + createEffect( + () => props.expand, + expand => (expand || !list ? undefined : stackToasts(list)), + ); return ( props.closeLabel }}> - + ); diff --git a/packages/kit/src/components/Toast/stack.ts b/packages/kit/src/components/Toast/stack.ts new file mode 100644 index 00000000..cd113d5c --- /dev/null +++ b/packages/kit/src/components/Toast/stack.ts @@ -0,0 +1,55 @@ +const toastSelector = '[data-cui="toast"]'; + +function layout(list: HTMLElement) { + const gap = Number.parseFloat(getComputedStyle(list).rowGap) || 0; + const open = [...list.children].filter( + (child): child is HTMLElement => + child instanceof HTMLElement && + child.matches(toastSelector) && + !child.hasAttribute("data-closed"), + ); + // Kobalte renders the oldest toast first; the newest sits at the front. + open.reverse(); + let offset = 0; + open.forEach((toast, index) => { + toast.setAttribute("data-cui-stack-index", String(index)); + toast.style.setProperty("--cui-toast-index", String(index)); + toast.style.setProperty("--cui-toast-offset", `${offset}px`); + toast.style.setProperty("--cui-toast-height", `${toast.offsetHeight}px`); + offset += toast.offsetHeight + gap; + }); + list.style.setProperty("--cui-toast-front-height", `${open[0]?.offsetHeight ?? 0}px`); + list.style.setProperty("--cui-toast-stack-height", `${Math.max(0, offset - gap)}px`); +} + +/** + * Stacks the toasts of a list like a deck: the newest in front, older ones + * peeking behind it. Hovering or focusing the list fans them out. Heights + * are measured here; the movement is CSS on `[data-cui-stack]`. + */ +export function stackToasts(list: HTMLElement): () => void { + const resize = new ResizeObserver(() => layout(list)); + const observeToasts = () => { + resize.disconnect(); + for (const child of list.children) { + if (child.matches(toastSelector)) resize.observe(child); + } + }; + const mutations = new MutationObserver(records => { + if (records.some(record => record.type === "childList" && record.target === list)) + observeToasts(); + layout(list); + }); + mutations.observe(list, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["data-closed"], + }); + observeToasts(); + layout(list); + return () => { + mutations.disconnect(); + resize.disconnect(); + }; +} diff --git a/packages/storybook/src/stories/Toaster.stories.tsx b/packages/storybook/src/stories/Toaster.stories.tsx index 7c7b6522..996e8f38 100644 --- a/packages/storybook/src/stories/Toaster.stories.tsx +++ b/packages/storybook/src/stories/Toaster.stories.tsx @@ -18,6 +18,7 @@ function Frame(props: { label: string; height: string; position?: ToastPosition; + expand?: boolean; toasts?: ToastOptions[]; children?: (toaster: ToastController) => JSX.Element; }) { @@ -32,6 +33,7 @@ function Frame(props: { toaster={toaster} position={props.position} limit={5} + expand={props.expand} closeLabel="Dismiss" aria-label={`${props.label} notifications`} /> @@ -52,6 +54,7 @@ export const Tones: Story = { ({ tone, @@ -63,6 +66,37 @@ export const Tones: Story = { ), }; +/** The default: newest in front, older ones peek behind. Hover or focus to fan out. */ +export const Stacked: Story = { + render: () => ( + dismiss() }, + }, + { + tone: "info", + title: "100xDeveloper in #welcome", + description: + "Hi! My own skills are code-review, which reviews a branch, a PR or work in progress since a fixed point, on two axes.", + action: { label: "Open Inbox", onClick: ({ dismiss }) => dismiss() }, + }, + { + tone: "success", + title: "Snippet exported", + description: "Saved to your downloads.", + }, + ]} + /> + ), +}; + export const WithAction: Story = { render: () => ( .cui-toast { + --cui-toast-cut: max(0px, var(--cui-toast-height) - var(--cui-toast-front-height)); + position: absolute; + inset-inline: 0; + bottom: 0; + z-index: calc(10 - var(--cui-toast-index, 0)); + width: 100%; + transform-origin: top center; + translate: 0 calc(var(--cui-toast-height) - var(--cui-toast-front-height) - var(--cui-toast-index, 0) * var(--cui-toast-peek)); + scale: calc(1 - var(--cui-toast-index, 0) * 0.05); + clip-path: inset(calc(-1 * var(--cui-toast-shadow-room)) calc(-1 * var(--cui-toast-shadow-room)) var(--cui-toast-cut) calc(-1 * var(--cui-toast-shadow-room))); + transition-property: translate, scale, clip-path, opacity; + transition-duration: var(--cui-motion-duration-rise); + transition-timing-function: var(--cui-motion-ease-out); + } + [data-position^=top] [data-cui-stack] > .cui-toast { + top: 0; + bottom: auto; + transform-origin: bottom center; + translate: 0 calc(var(--cui-toast-front-height) - var(--cui-toast-height) + var(--cui-toast-index, 0) * var(--cui-toast-peek)); + clip-path: inset(var(--cui-toast-cut) calc(-1 * var(--cui-toast-shadow-room)) calc(-1 * var(--cui-toast-shadow-room))); + } + [data-cui-stack] > .cui-toast:is([data-cui-stack-index="0"], :not([data-cui-stack-index])) { + translate: 0 0; + clip-path: inset(calc(-1 * var(--cui-toast-shadow-room))); + } + [data-cui-stack] > .cui-toast:not([data-cui-stack-index="0"]) > * { + opacity: 0; + transition: opacity var(--cui-motion-duration-panel) var(--cui-motion-ease-out); + } + [data-cui-stack] > .cui-toast:not([data-cui-stack-index="0"], [data-cui-stack-index="1"], [data-cui-stack-index="2"]) { + opacity: 0; + pointer-events: none; + } + [data-cui-stack]:is(:hover, :focus-within) > .cui-toast { + translate: 0 calc(-1 * var(--cui-toast-offset, 0px)); + scale: 1; + clip-path: inset(calc(-1 * var(--cui-toast-shadow-room))); + opacity: 1; + pointer-events: auto; + & > * { + opacity: 1; + } + } + [data-position^=top] [data-cui-stack]:is(:hover, :focus-within) > .cui-toast { + translate: 0 var(--cui-toast-offset, 0px); + } :where(.cui-toast) { &:is(:not([data-tone]), [data-tone="neutral"]) { --cui-toast-accent: var(--cui-component-toast-root-tone-neutral-accent); @@ -161,23 +220,35 @@ } .cui-toast-icon { grid-column: 1; - grid-row: 1 / span 2; + grid-row: 1; + align-self: start; display: inline-flex; - margin-inline-end: var(--cui-space-2); + height: calc(var(--cui-font-size-sm) * var(--cui-font-line-height-snug)); + align-items: center; + margin-inline-end: var(--cui-space-3); color: var(--cui-toast-accent); } .cui-toast-icon > svg { - width: var(--cui-font-size-md); - height: var(--cui-font-size-md); + width: var(--cui-space-5); + height: var(--cui-space-5); + } + :not(:has(> .cui-toast-title)) > .cui-toast-icon { + grid-row: 1 / span 2; + align-self: center; } .cui-toast-title { grid-column: 2; + color: var(--cui-text-toast); font-weight: var(--cui-font-weight-semibold); } .cui-toast-description { grid-column: 2; min-width: 0; } + .cui-toast-title + .cui-toast-description { + margin-top: var(--cui-space-0-5); + color: var(--cui-text-muted); + } :not(:has(> .cui-toast-title)) > .cui-toast-description { grid-row: 1 / span 2; align-self: center; @@ -257,6 +328,9 @@ .cui-toast[data-swipe=end] { animation-name: cui-toast-fade-out; } + [data-cui-stack] > .cui-toast { + transition-property: opacity; + } } @media (hover: hover) { .cui-toast-action:hover { diff --git a/packages/styles/scripts/appearance.mjs b/packages/styles/scripts/appearance.mjs index c11e373a..3035c910 100644 --- a/packages/styles/scripts/appearance.mjs +++ b/packages/styles/scripts/appearance.mjs @@ -14,6 +14,8 @@ const adapterAttributes = new Set([ "data-closed", "data-contained", "data-cui-replaced", + "data-cui-stack", + "data-cui-stack-index", "data-disabled", "data-dragging", "data-expanded", From ceca8149676d0abdcb7bb92a86df333e6627558d Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Mon, 30 Nov 2026 14:48:32 +0100 Subject: [PATCH 2/7] feat(toast): own Sonner-style toast engine behind Toaster Replaces Kobalte's toast region behind createToaster and Toaster with our own engine: transitions for enter and leave, a deck stack that fans out on hover or focus, timers that pause while expanded or hidden, a limit that hides older toasts instead of queueing, and swipe toward the region's edge. The styled Kobalte parts are unchanged. Co-Authored-By: Claude Opus 5.5 --- .changeset/toast-stack.md | 4 +- .../skills/verify-codeui/features/feedback.md | 2 +- .../verify-codeui/journeys/toast-rise.mjs | 6 +- .../verify-codeui/journeys/toast-stack.mjs | 56 +- .../content/docs/(kit)/components/toast.mdx | 8 +- packages/docs-demos/src/props/toast.ts | 23 +- packages/kit/DESIGN.md | 2 +- .../kit/src/components/Toast/ToastItem.tsx | 252 +++++++++ packages/kit/src/components/Toast/Toaster.tsx | 491 ++++++------------ .../kit/src/components/Toast/controller.tsx | 188 +++++++ packages/kit/src/components/Toast/stack.ts | 55 -- packages/kit/src/components/Toast/swipe.ts | 96 ++++ packages/kit/test/toaster.test.tsx | 48 +- .../storybook/src/stories/Toaster.stories.tsx | 23 +- .../styles/css/components/Toast/Toast.css | 111 ++-- packages/styles/scripts/appearance.mjs | 7 +- 16 files changed, 903 insertions(+), 469 deletions(-) create mode 100644 packages/kit/src/components/Toast/ToastItem.tsx create mode 100644 packages/kit/src/components/Toast/controller.tsx delete mode 100644 packages/kit/src/components/Toast/stack.ts create mode 100644 packages/kit/src/components/Toast/swipe.ts diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md index a0ade958..61b96e19 100644 --- a/.changeset/toast-stack.md +++ b/.changeset/toast-stack.md @@ -3,6 +3,8 @@ "@codeui/styles": minor --- -Toaster: toasts stack like a deck by default. The newest sits in front and up to two older ones peek behind it, narrower and without content. Hovering or focusing the stack fans the toasts out to full height; leaving collapses it. Toasts in a stack take the region's full width. Pass `expand` to list every toast in full as before. +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: `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. diff --git a/.claude/skills/verify-codeui/features/feedback.md b/.claude/skills/verify-codeui/features/feedback.md index b6082e3f..26cde492 100644 --- a/.claude/skills/verify-codeui/features/feedback.md +++ b/.claude/skills/verify-codeui/features/feedback.md @@ -28,7 +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 is lowest and two peek above with hidden content. Hover and Tab both fan the stack out with no overlap. Stories that need every toast in full pass `expand` (Tones). +- **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..8cc4624c 100644 --- a/.claude/skills/verify-codeui/journeys/toast-rise.mjs +++ b/.claude/skills/verify-codeui/journeys/toast-rise.mjs @@ -11,9 +11,9 @@ export default async ({ page, step, check, theme }) => { 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 index 8414557b..ca81d4a9 100644 --- a/.claude/skills/verify-codeui/journeys/toast-stack.mjs +++ b/.claude/skills/verify-codeui/journeys/toast-stack.mjs @@ -1,37 +1,65 @@ -const rects = page => page.$$eval('[data-cui-stack] > [data-cui="toast"]', els => - els.map(el => { - const r = el.getBoundingClientRect(); - const visible = getComputedStyle(el.querySelector('[data-cui="toast-title"]')).opacity; - return { index: el.getAttribute("data-cui-stack-index"), top: Math.round(r.top), bottom: Math.round(r.bottom), width: Math.round(r.width), contentOpacity: visible }; - })); +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"]'); + 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; + 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 () => { - const front = page.locator('[data-cui-stack-index="0"]'); - await front.hover(); + 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)); + 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 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 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..3662eb26 100644 --- a/apps/docs/content/docs/(kit)/components/toast.mdx +++ b/apps/docs/content/docs/(kit)/components/toast.mdx @@ -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/packages/docs-demos/src/props/toast.ts b/packages/docs-demos/src/props/toast.ts index d19a9b37..46f2fbd8 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" | "aria-label" | "class" | "classes" >; /** The options createToaster takes. */ @@ -30,17 +27,13 @@ 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." }, "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." }, diff --git a/packages/kit/DESIGN.md b/packages/kit/DESIGN.md index cb7dfc17..4d6bdcb6 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. Several toasts stack like a deck: the newest in front, up to two older ones peeking 12px behind it at 95% and 90% scale with their content hidden. Hover or focus fans them out with `translate`, `scale` and `clip-path` over 400ms ease-out; `expand` lists them in full instead. 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. 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/src/components/Toast/ToastItem.tsx b/packages/kit/src/components/Toast/ToastItem.tsx new file mode 100644 index 00000000..1351c9dc --- /dev/null +++ b/packages/kit/src/components/Toast/ToastItem.tsx @@ -0,0 +1,252 @@ +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 } 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; + 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 ?? "inverted"; + 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 ( +
= props.limit() ? "" : undefined} + data-expanded={props.expanded() ? "" : undefined} + data-swiping={swipe.swiping() ? "" : undefined} + data-swipe-out={swipe.swipedOut()} + class={mergeClasses(toastStyles.root(), classes()?.root, options().class)} + style={style()} + onKeyDown={event => { + if (event.key === "Escape") entry.context.dismiss(); + }} + {...swipe.handlers} + > + + + + +
+ {render(title())} +
+
+
+ {render(options().description)} +
+ + {action => ( + + )} + + + + +
+ ); +} diff --git a/packages/kit/src/components/Toast/Toaster.tsx b/packages/kit/src/components/Toast/Toaster.tsx index 6f750d96..38b50989 100644 --- a/packages/kit/src/components/Toast/Toaster.tsx +++ b/packages/kit/src/components/Toast/Toaster.tsx @@ -1,360 +1,175 @@ -import { toaster as engine, useToastContext } from "@kobalte/core/toast"; -import { - type Accessor, - createContext, - createEffect, - createMemo, - createSignal, - getOwner, - onCleanup, - onSettled, - type Setter, - Show, - useContext, - omit, -} from "solid-js"; -import { type JSX, isServer } from "@solidjs/web"; - -import { ToneIcon } from "../../icons/ToneIcon"; -import * as T from "../../parts/toast"; +import { createMemo, createSignal, For, onSettled, omit } from "solid-js"; +import type { JSX } from "@solidjs/web"; +import * as styles from "../../components/Toast/Toast.css"; +import { type ToastClasses, type ToastPosition, toastParts, toastStyles } from "../../parts/toast"; import { mergeClasses } from "../../utils/css"; -import { Spinner } from "../Spinner/Spinner"; -import { stackToasts } from "./stack"; - -/** Scoped to the controller that returned it. Two controllers can return the same id. */ -export type ToastId = number; -export type ToastContext = { id: ToastId; dismiss: () => void }; -export type ToastContent = JSX.Element | ((context: ToastContext) => JSX.Element); -export type ToastAction = { - label: JSX.Element; - /** The toast stays open. Call `context.dismiss()` to close it. */ - onClick: (context: ToastContext) => void; -}; - -export type ToastOptions = { - title?: ToastContent; - description: ToastContent; - tone?: T.ToastTone; - /** Replaces the tone icon. `null` hides it. Neutral has no tone icon. */ - icon?: ToastContent; - action?: ToastAction; - /** Shows the close button. Defaults to true. */ - 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"; - class?: string; - classes?: T.ToastClasses; - style?: JSX.CSSProperties; -}; - -export type ToastPromiseOptions = { - loading: ToastOptions; - success: ToastOptions | ((data: D) => ToastOptions); - error: ToastOptions | ((error: unknown) => ToastOptions); -}; - -export interface ToastController { - /** Ties the controller to its ``. */ - readonly regionId: string; - show(options: ToastOptions): ToastId; - /** Merges into the open toast. A new duration restarts its timer. */ - update(id: ToastId, options: Partial): void; - /** Closes with the exit animation. */ - dismiss(id: ToastId): void; - /** Dismisses every toast of this controller. */ - clear(): void; - /** - * Shows `loading` until the promise settles, then `success` or `error` in - * the same toast. Loading stays open and shows a spinner unless its options - * say otherwise. - */ - promise( - promise: Promise | (() => Promise), - options: ToastPromiseOptions, - ): ToastId; -} - -export type CreateToasterOptions = { - /** Default milliseconds before a toast closes. Defaults to 5000. */ - duration?: number; -}; - -type Entry = { - options: Accessor; - setOptions: Setter; - /** Changes when the close timer must restart. Remounts the toast. */ - timer: Accessor; - setTimer: Setter; - engineId: number; - close?: () => void; -}; - -let regionCount = 0; - -/** - * 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 function createToaster(options: CreateToasterOptions = {}): ToastController { - const regionId = `cui-toaster-${++regionCount}`; - const entries = new Map(); - let lastId = 0; - - const durationOf = (toast: ToastOptions) => toast.duration ?? options.duration ?? 5000; - - const dismiss = (id: ToastId) => { - const entry = entries.get(id); - if (!entry) return; - if (entry.close) return entry.close(); - entries.delete(id); - engine.dismiss(entry.engineId); - }; - - const show = (toast: ToastOptions): ToastId => { - const id = ++lastId; - if (isServer) return id; - const [options, setOptions] = createSignal(toast); - const [timer, setTimer] = createSignal(0); - const entry: Entry = { options, setOptions, timer, setTimer, engineId: 0 }; - const context: ToastContext = { id, dismiss: () => dismiss(id) }; - entries.set(id, entry); - entry.engineId = engine.show( - props => ( - - {key => ( - 1} - onClosed={() => entries.delete(id)} - /> - )} - - ), - { region: regionId }, - ); - return id; - }; - - const replace = (id: ToastId, next: ToastOptions) => { - const entry = entries.get(id); - if (!entry) return; - const restart = durationOf(next) !== durationOf(entry.options()); - entry.setOptions(next); - if (restart) entry.setTimer(timer => timer + 1); - }; - - const controller: ToastController = { - regionId, - show, - dismiss, - update: (id, patch) => { - const entry = entries.get(id); - if (entry) replace(id, { ...entry.options(), ...patch }); - }, - clear: () => [...entries.keys()].forEach(dismiss), - promise( - input: Promise | (() => Promise), - { loading, success, error }: ToastPromiseOptions, - ) { - const id = show({ duration: Infinity, icon: () => , ...loading }); - new Promise(resolve => - resolve(typeof input === "function" ? input() : input), - ).then( - data => - replace(id, { - tone: "success", - ...(typeof success === "function" ? success(data) : success), - }), - reason => - replace(id, { - tone: "danger", - ...(typeof error === "function" ? error(reason) : error), - }), - ); - return id; - }, - }; - - if (getOwner()) onCleanup(controller.clear); - return controller; -} - -const ToasterContext = createContext<{ closeLabel: () => string }>(); - -function ReadyToast(props: { - toastId: number; - entry: Entry; - context: ToastContext; - duration: number; - replaced: boolean; - onClosed: () => void; -}) { - const toaster = useContext(ToasterContext); - const options = props.entry.options; - const classes = () => options().classes; - const title = createMemo(() => options().title); - const description = createMemo(() => options().description); - 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 render = (content: ToastContent) => - typeof content === "function" ? content(props.context) : content; - - let element: HTMLElement | undefined; - const [pageScheme, setPageScheme] = createSignal<"light" | "dark">(); - onSettled(() => { - const read = () => { - const parent = element?.parentElement; - if (!parent) return; - const scheme = [ - getComputedStyle(parent).colorScheme, - parent.closest("[data-cui-theme]")?.getAttribute("data-cui-theme"), - ].find(value => value === "light" || value === "dark"); - setPageScheme(scheme 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); - }; - }); - const theme = () => { - const theme = options().theme ?? "inverted"; - if (theme === "page") return undefined; - if (theme !== "inverted") return theme; - const page = pageScheme(); - return page && (page === "dark" ? "light" : "dark"); - }; - onCleanup(() => { - if (element?.hasAttribute("data-closed")) props.onClosed(); - }); - - return ( - - - - {render(icon())} - - - {render(title())} - - - {render(description())} - - - {action => ( - action().onClick(props.context)} - > - {action().label} - - )} - - - - - - ); -} - -/** Lets `dismiss` close the mounted toast through the engine, so it plays its exit. */ -function CloseHandle(props: { entry: Entry }) { - const close = useToastContext().close; - props.entry.close = close; - onCleanup(() => { - if (props.entry.close === close) props.entry.close = undefined; - }); - return null; -} - -export type ToasterProps = Omit< - T.RegionProps, - "regionId" | "duration" | "children" | "position" -> & { +import { type ToastController, type ToastId, toastStore } from "./controller"; +import type { SwipeSide } from "./swipe"; +import { ToastItem, type ToastPlace } from "./ToastItem"; + +export { createToaster } from "./controller"; +export type { + CreateToasterOptions, + ToastAction, + ToastContent, + ToastContext, + ToastController, + ToastId, + ToastOptions, + ToastPromiseOptions, +} from "./controller"; + +export type ToasterProps = Omit, "children"> & { toaster: ToastController; /** Defaults to bottom center. */ - position?: T.ToastPosition; + 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; /** - * Lists every toast in full. By default the toasts stack like a deck, + * 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[]; /** Classes for the region and list. Per-toast classes go in the toast options. */ - classes?: Pick; + classes?: Pick; }; +function swipeSides(position: ToastPosition): SwipeSide[] { + const [y, x] = position.split("-") as ["top" | "bottom", "left" | "center" | "right"]; + return x === "center" ? [y] : [y, x]; +} + +function createDocumentHidden() { + const [hidden, setHidden] = createSignal(false); + onSettled(() => { + const read = () => setHidden(document.hidden); + read(); + document.addEventListener("visibilitychange", read); + return () => document.removeEventListener("visibilitychange", read); + }); + return hidden; +} + /** * 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 function Toaster(props: ToasterProps) { - const others = omit(props, "toaster", "closeLabel", "classes", "class", "expand"); - let list: HTMLElement | undefined; - createEffect( - () => props.expand, - expand => (expand || !list ? undefined : stackToasts(list)), + const store = toastStore(props.toaster); + const others = omit( + props, + "toaster", + "position", + "closeLabel", + "limit", + "expand", + "hotkey", + "classes", + "class", + "aria-label", ); + const [heights, setHeights] = createSignal>(new Map()); + const [hovered, setHovered] = createSignal(false); + const [focused, setFocused] = createSignal(false); + const [interacting, setInteracting] = createSignal(false); + const [gap, setGap] = createSignal(0); + const documentHidden = createDocumentHidden(); + let list: HTMLDivElement | undefined; + + const position = () => props.position ?? "bottom-center"; + const limit = () => props.limit ?? 3; + const expanded = () => Boolean(props.expand) || hovered() || focused() || interacting(); + const paused = () => hovered() || focused() || interacting() || documentHidden(); + + const layout = createMemo(() => { + const places = new Map(); + let offset = 0; + let front = 0; + store + .toasts() + .filter(toast => !toast.closing()) + .forEach((toast, index) => { + const height = heights().get(toast.id) ?? 0; + if (index === 0) front = height; + places.set(toast.id, { index, offset, height }); + if (index < limit()) offset += height + gap(); + }); + return { places, front, total: Math.max(0, offset - gap()) }; + }); + + const setHeight = (id: ToastId, height: number | undefined) => + setHeights(current => { + if (current.get(id) === height) return current; + const next = new Map(current); + if (height === undefined) next.delete(id); + else next.set(id, height); + return next; + }); + + onSettled(() => { + if (list) setGap(Number.parseFloat(getComputedStyle(list).rowGap) || 0); + const hotkey = props.hotkey ?? ["altKey", "KeyT"]; + const onKeyDown = (event: KeyboardEvent) => { + const pressed = hotkey.every( + key => event[key as keyof KeyboardEvent] === true || event.code === key, + ); + if (pressed) list?.focus({ preventScroll: true }); + }; + document.addEventListener("keydown", onKeyDown); + return () => document.removeEventListener("keydown", onKeyDown); + }); + return ( - props.closeLabel }}> - +
setHovered(true)} + onPointerLeave={() => setHovered(false)} + onFocusIn={() => setFocused(true)} + onFocusOut={event => { + if (!list?.contains(event.relatedTarget as Node | null)) setFocused(false); + }} > - - - + + {toast => ( + layout().places.get(toast.id)} + count={() => store.toasts().length} + limit={limit} + expanded={expanded} + paused={paused} + swipeSides={() => swipeSides(position())} + closeLabel={() => props.closeLabel} + onHeight={height => setHeight(toast.id, height)} + onInteract={setInteracting} + /> + )} + +
+ ); } diff --git a/packages/kit/src/components/Toast/controller.tsx b/packages/kit/src/components/Toast/controller.tsx new file mode 100644 index 00000000..9f8ae331 --- /dev/null +++ b/packages/kit/src/components/Toast/controller.tsx @@ -0,0 +1,188 @@ +import { type Accessor, createSignal, getOwner, onCleanup, type Setter } from "solid-js"; +import { type JSX, isServer } from "@solidjs/web"; +import type * as T from "../../parts/toast"; +import { Spinner } from "../Spinner/Spinner"; + +/** Scoped to the controller that returned it. Two controllers can return the same id. */ +export type ToastId = number; +export type ToastContext = { id: ToastId; dismiss: () => void }; +export type ToastContent = JSX.Element | ((context: ToastContext) => JSX.Element); +export type ToastAction = { + label: JSX.Element; + /** The toast stays open. Call `context.dismiss()` to close it. */ + onClick: (context: ToastContext) => void; +}; + +export type ToastOptions = { + title?: ToastContent; + description: ToastContent; + tone?: T.ToastTone; + /** Replaces the tone icon. `null` hides it. Neutral has no tone icon. */ + icon?: ToastContent; + action?: ToastAction; + /** Shows the close button. Defaults to true. */ + 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"; + class?: string; + classes?: T.ToastClasses; + style?: JSX.CSSProperties; +}; + +export type ToastPromiseOptions = { + loading: ToastOptions; + success: ToastOptions | ((data: D) => ToastOptions); + error: ToastOptions | ((error: unknown) => ToastOptions); +}; + +export interface ToastController { + /** Ties the controller to its ``. */ + readonly regionId: string; + show(options: ToastOptions): ToastId; + /** Merges into the open toast. A new duration restarts its timer. */ + update(id: ToastId, options: Partial): void; + /** Closes with the exit animation. */ + dismiss(id: ToastId): void; + /** Dismisses every toast of this controller. */ + clear(): void; + /** + * Shows `loading` until the promise settles, then `success` or `error` in + * the same toast. Loading stays open and shows a spinner unless its options + * say otherwise. + */ + promise( + promise: Promise | (() => Promise), + options: ToastPromiseOptions, + ): ToastId; +} + +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; +}; + +const stores = new WeakMap(); + +export function toastStore(controller: ToastController): ToastStore { + const store = stores.get(controller); + if (!store) throw new Error("Toaster needs a controller from createToaster()."); + return store; +} + +let regionCount = 0; + +/** + * 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 function createToaster(options: CreateToasterOptions = {}): ToastController { + const regionId = `cui-toaster-${++regionCount}`; + const open = new Map(); + const [toasts, setToasts] = createSignal([]); + let lastId = 0; + + const durationOf = (toast: ToastOptions) => toast.duration ?? options.duration ?? 5000; + const remove = (id: ToastId) => setToasts(list => list.filter(toast => toast.id !== id)); + + const dismiss = (id: ToastId) => { + const entry = open.get(id); + if (!entry) return; + open.delete(id); + if (entry.rendered) entry.setClosing(true); + else remove(id); + }; + + const show = (toast: ToastOptions): ToastId => { + const id = ++lastId; + if (isServer) return id; + const [current, setOptions] = createSignal(toast); + const [timer, setTimer] = createSignal(0); + const [closing, setClosing] = createSignal(false); + const entry: ToastEntry = { + id, + context: { id, dismiss: () => dismiss(id) }, + options: current, + setOptions, + duration: () => durationOf(current()), + timer, + setTimer, + closing, + setClosing, + rendered: false, + }; + open.set(id, entry); + setToasts(list => [entry, ...list]); + return id; + }; + + const replace = (id: ToastId, next: ToastOptions) => { + const entry = open.get(id); + if (!entry) return; + const restart = durationOf(next) !== durationOf(entry.options()); + entry.setOptions(next); + if (restart) entry.setTimer(timer => timer + 1); + }; + + const controller: ToastController = { + regionId, + show, + dismiss, + update: (id, patch) => { + const entry = open.get(id); + if (entry) replace(id, { ...entry.options(), ...patch }); + }, + clear: () => [...open.keys()].forEach(dismiss), + promise( + input: Promise | (() => Promise), + { loading, success, error }: ToastPromiseOptions, + ) { + const id = show({ duration: Infinity, icon: () => , ...loading }); + new Promise(resolve => + resolve(typeof input === "function" ? input() : input), + ).then( + data => + replace(id, { + tone: "success", + ...(typeof success === "function" ? success(data) : success), + }), + reason => + replace(id, { + tone: "danger", + ...(typeof error === "function" ? error(reason) : error), + }), + ); + return id; + }, + }; + + stores.set(controller, { toasts, remove }); + if (getOwner()) onCleanup(controller.clear); + return controller; +} diff --git a/packages/kit/src/components/Toast/stack.ts b/packages/kit/src/components/Toast/stack.ts deleted file mode 100644 index cd113d5c..00000000 --- a/packages/kit/src/components/Toast/stack.ts +++ /dev/null @@ -1,55 +0,0 @@ -const toastSelector = '[data-cui="toast"]'; - -function layout(list: HTMLElement) { - const gap = Number.parseFloat(getComputedStyle(list).rowGap) || 0; - const open = [...list.children].filter( - (child): child is HTMLElement => - child instanceof HTMLElement && - child.matches(toastSelector) && - !child.hasAttribute("data-closed"), - ); - // Kobalte renders the oldest toast first; the newest sits at the front. - open.reverse(); - let offset = 0; - open.forEach((toast, index) => { - toast.setAttribute("data-cui-stack-index", String(index)); - toast.style.setProperty("--cui-toast-index", String(index)); - toast.style.setProperty("--cui-toast-offset", `${offset}px`); - toast.style.setProperty("--cui-toast-height", `${toast.offsetHeight}px`); - offset += toast.offsetHeight + gap; - }); - list.style.setProperty("--cui-toast-front-height", `${open[0]?.offsetHeight ?? 0}px`); - list.style.setProperty("--cui-toast-stack-height", `${Math.max(0, offset - gap)}px`); -} - -/** - * Stacks the toasts of a list like a deck: the newest in front, older ones - * peeking behind it. Hovering or focusing the list fans them out. Heights - * are measured here; the movement is CSS on `[data-cui-stack]`. - */ -export function stackToasts(list: HTMLElement): () => void { - const resize = new ResizeObserver(() => layout(list)); - const observeToasts = () => { - resize.disconnect(); - for (const child of list.children) { - if (child.matches(toastSelector)) resize.observe(child); - } - }; - const mutations = new MutationObserver(records => { - if (records.some(record => record.type === "childList" && record.target === list)) - observeToasts(); - layout(list); - }); - mutations.observe(list, { - childList: true, - subtree: true, - attributes: true, - attributeFilter: ["data-closed"], - }); - observeToasts(); - layout(list); - return () => { - mutations.disconnect(); - resize.disconnect(); - }; -} diff --git a/packages/kit/src/components/Toast/swipe.ts b/packages/kit/src/components/Toast/swipe.ts new file mode 100644 index 00000000..b95d48bd --- /dev/null +++ b/packages/kit/src/components/Toast/swipe.ts @@ -0,0 +1,96 @@ +import { type Accessor, createSignal } from "solid-js"; + +export type SwipeSide = "top" | "bottom" | "left" | "right"; + +const SWIPE_THRESHOLD = 45; +const SWIPE_VELOCITY = 0.11; + +/** Follows Sonner's swipe: lock an axis, damp the wrong way, dismiss past 45px or a flick. */ +const dampen = (delta: number) => delta * (1 / (1.5 + Math.abs(delta) / 20)); + +export function createSwipe(options: { + sides: Accessor; + onDismiss: (side: SwipeSide) => void; + onInteract: (interacting: boolean) => void; +}) { + const [swiping, setSwiping] = createSignal(false); + const [swipedOut, setSwipedOut] = createSignal(); + let start: { x: number; y: number; time: number } | undefined; + let axis: "x" | "y" | undefined; + let amount = { x: 0, y: 0 }; + + const apply = (element: HTMLElement) => { + element.style.setProperty("--cui-toast-swipe-x", `${amount.x}px`); + element.style.setProperty("--cui-toast-swipe-y", `${amount.y}px`); + }; + + const follow = (delta: number, forward: SwipeSide, backward: SwipeSide) => { + const sides = options.sides(); + if (sides.includes(delta > 0 ? forward : backward)) return delta; + return sides.includes(forward) || sides.includes(backward) ? dampen(delta) : 0; + }; + + const onPointerDown = (event: PointerEvent) => { + if (event.button !== 0 || swipedOut()) return; + if ((event.target as Element).closest("button, a, input, textarea, select")) return; + (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId); + start = { x: event.clientX, y: event.clientY, time: Date.now() }; + axis = undefined; + options.onInteract(true); + }; + + const onPointerMove = (event: PointerEvent) => { + if (!start) return; + const x = event.clientX - start.x; + const y = event.clientY - start.y; + if (!axis && (Math.abs(x) > 1 || Math.abs(y) > 1)) axis = Math.abs(x) > Math.abs(y) ? "x" : "y"; + if (!axis) return; + amount = + axis === "x" + ? { x: follow(x, "right", "left"), y: 0 } + : { x: 0, y: follow(y, "bottom", "top") }; + if (amount.x !== 0 || amount.y !== 0) setSwiping(true); + apply(event.currentTarget as HTMLElement); + }; + + const onPointerUp = (event: PointerEvent) => { + if (!start) return; + const element = event.currentTarget as HTMLElement; + const distance = axis === "x" ? amount.x : amount.y; + const velocity = Math.abs(distance) / Math.max(1, Date.now() - start.time); + const side: SwipeSide | undefined = axis + ? axis === "x" + ? distance > 0 + ? "right" + : "left" + : distance > 0 + ? "bottom" + : "top" + : undefined; + start = undefined; + options.onInteract(false); + setSwiping(false); + if ( + side && + options.sides().includes(side) && + (Math.abs(distance) >= SWIPE_THRESHOLD || velocity > SWIPE_VELOCITY) + ) { + setSwipedOut(side); + options.onDismiss(side); + return; + } + amount = { x: 0, y: 0 }; + apply(element); + }; + + return { + swiping, + swipedOut, + handlers: { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel: onPointerUp, + }, + }; +} diff --git a/packages/kit/test/toaster.test.tsx b/packages/kit/test/toaster.test.tsx index 25573752..a303fd58 100644 --- a/packages/kit/test/toaster.test.tsx +++ b/packages/kit/test/toaster.test.tsx @@ -1,4 +1,3 @@ -import { toaster as engine } from "@kobalte/core/toast"; import { createContext, createRoot, useContext } from "solid-js"; import { cleanup, @@ -17,7 +16,6 @@ import { toastParts } from "../src/parts/toast"; import { expectDismissed, tick } from "./helpers"; afterEach(() => { - engine.clear(); cleanup(); vi.useRealTimers(); }); @@ -161,7 +159,9 @@ describe("createToaster", () => { notifications.show({ description: "Closeable" }); notifications.show({ description: "Stuck", closeable: false }); await waitFor(() => expect(screen.getAllByRole("status")).toHaveLength(2)); - const [closeable, stuck] = screen.getAllByRole("status"); + const [closeable, stuck] = ["Closeable", "Stuck"].map( + text => screen.getByText(text).closest("[role=status]")!, + ); expect(within(closeable).getByRole("button", { name: "Close" })).toBeInTheDocument(); expect(within(stuck).queryByRole("button")).toBeNull(); fireEvent.click(within(closeable).getByRole("button", { name: "Close" })); @@ -240,6 +240,48 @@ describe("createToaster", () => { }); }); +describe("stack", () => { + it("shows the newest toasts and hides older ones past the limit", async () => { + const notifications = createToaster(); + render(() => ); + ["One", "Two", "Three"].forEach(description => notifications.show({ description })); + await waitFor(() => expect(screen.getAllByRole("status")).toHaveLength(3)); + const toast = (text: string) => screen.getByText(text).closest("[role=status]")!; + expect(toast("Three")).toHaveAttribute("data-front"); + expect(toast("Two")).not.toHaveAttribute("data-hidden"); + expect(toast("One")).toHaveAttribute("data-hidden"); + }); + + it("fans out while the pointer or focus is on the toasts", async () => { + const notifications = createToaster(); + mount(notifications); + notifications.show({ description: "First" }); + notifications.show({ description: "Second" }); + await waitFor(() => expect(screen.getAllByRole("status")).toHaveLength(2)); + const [toast] = screen.getAllByRole("status"); + const list = toast.parentElement!; + expect(list).not.toHaveAttribute("data-expanded"); + fireEvent.pointerMove(toast); + await tick(); + expect(list).toHaveAttribute("data-expanded"); + expect(toast).toHaveAttribute("data-expanded"); + fireEvent.pointerLeave(list); + await tick(); + expect(list).not.toHaveAttribute("data-expanded"); + toast.focus(); + await tick(); + expect(list).toHaveAttribute("data-expanded"); + }); + + it("stays fanned out with expand", async () => { + const notifications = createToaster(); + render(() => ); + notifications.show({ description: "Open" }); + const toast = await screen.findByRole("status"); + expect(toast.parentElement).toHaveAttribute("data-expanded"); + }); +}); + describe("toast timing", () => { beforeEach(() => vi.useFakeTimers()); diff --git a/packages/storybook/src/stories/Toaster.stories.tsx b/packages/storybook/src/stories/Toaster.stories.tsx index 996e8f38..a42052c8 100644 --- a/packages/storybook/src/stories/Toaster.stories.tsx +++ b/packages/storybook/src/stories/Toaster.stories.tsx @@ -93,7 +93,28 @@ export const Stacked: Story = { description: "Saved to your downloads.", }, ]} - /> + > + {toaster => { + let count = 0; + return ( +
+ +
+ ); + }} + ), }; diff --git a/packages/styles/css/components/Toast/Toast.css b/packages/styles/css/components/Toast/Toast.css index 3673c96b..6affcf12 100644 --- a/packages/styles/css/components/Toast/Toast.css +++ b/packages/styles/css/components/Toast/Toast.css @@ -22,6 +22,16 @@ opacity: 0; } } +@keyframes cui-toast-swipe-out-stacked { + from { + transform: var(--cui-toast-y) translate(var(--cui-toast-swipe-x, 0px), var(--cui-toast-swipe-y, 0px)); + opacity: 1; + } + to { + transform: var(--cui-toast-y) var(--cui-toast-swipe-to); + opacity: 0; + } +} @keyframes cui-toast-swipe-out { from { transform: translateX(var(--cui-toast-swipe-end-x)); @@ -139,29 +149,39 @@ } } .cui-toast-list[data-cui-stack] { + --cui-toast-lift: -1; --cui-toast-peek: var(--cui-space-3); - --cui-toast-shadow-room: var(--cui-space-8); + --cui-toast-room: calc(-1 * var(--cui-space-8)); position: relative; - isolation: isolate; width: 100%; - height: var(--cui-toast-front-height, auto); + height: var(--cui-toast-front-height); + gap: var(--cui-space-3); pointer-events: auto; } - .cui-toast-list[data-cui-stack]:is(:hover, :focus-within) { - height: var(--cui-toast-stack-height, auto); + [data-position^=top] .cui-toast-list[data-cui-stack] { + --cui-toast-lift: 1; + } + .cui-toast-list[data-cui-stack][data-expanded] { + height: var(--cui-toast-stack-height); + } + .cui-toast-list[data-cui-stack][data-empty] { + pointer-events: none; } [data-cui-stack] > .cui-toast { + --cui-toast-y: translateY(calc(var(--cui-toast-lift) * -100%)); --cui-toast-cut: max(0px, var(--cui-toast-height) - var(--cui-toast-front-height)); position: absolute; inset-inline: 0; bottom: 0; - z-index: calc(10 - var(--cui-toast-index, 0)); + z-index: var(--cui-toast-z); width: 100%; + opacity: 0; + transform: var(--cui-toast-y); transform-origin: top center; - translate: 0 calc(var(--cui-toast-height) - var(--cui-toast-front-height) - var(--cui-toast-index, 0) * var(--cui-toast-peek)); - scale: calc(1 - var(--cui-toast-index, 0) * 0.05); - clip-path: inset(calc(-1 * var(--cui-toast-shadow-room)) calc(-1 * var(--cui-toast-shadow-room)) var(--cui-toast-cut) calc(-1 * var(--cui-toast-shadow-room))); - transition-property: translate, scale, clip-path, opacity; + clip-path: inset(var(--cui-toast-room)); + touch-action: none; + animation: none; + transition-property: transform, opacity, clip-path; transition-duration: var(--cui-motion-duration-rise); transition-timing-function: var(--cui-motion-ease-out); } @@ -169,33 +189,60 @@ top: 0; bottom: auto; transform-origin: bottom center; - translate: 0 calc(var(--cui-toast-front-height) - var(--cui-toast-height) + var(--cui-toast-index, 0) * var(--cui-toast-peek)); - clip-path: inset(var(--cui-toast-cut) calc(-1 * var(--cui-toast-shadow-room)) calc(-1 * var(--cui-toast-shadow-room))); } - [data-cui-stack] > .cui-toast:is([data-cui-stack-index="0"], :not([data-cui-stack-index])) { - translate: 0 0; - clip-path: inset(calc(-1 * var(--cui-toast-shadow-room))); + [data-cui-stack] > .cui-toast > * { + transition: opacity var(--cui-motion-duration-rise) var(--cui-motion-ease-out); + } + [data-cui-stack] > .cui-toast[data-mounted] { + --cui-toast-y: translateY(0); + opacity: 1; + } + [data-cui-stack] > .cui-toast[data-mounted]:not([data-expanded], [data-front]) { + --cui-toast-y: translateY(calc(var(--cui-toast-lift) * (var(--cui-toast-index) * var(--cui-toast-peek) - var(--cui-toast-height) + var(--cui-toast-front-height)))) scale(calc(1 - var(--cui-toast-index) * 0.05)); + clip-path: inset(var(--cui-toast-room) var(--cui-toast-room) var(--cui-toast-cut) var(--cui-toast-room)); + } + [data-position^=top] [data-cui-stack] > .cui-toast[data-mounted]:not([data-expanded], [data-front]) { + clip-path: inset(var(--cui-toast-cut) var(--cui-toast-room) var(--cui-toast-room) var(--cui-toast-room)); } - [data-cui-stack] > .cui-toast:not([data-cui-stack-index="0"]) > * { + [data-cui-stack] > .cui-toast:not([data-expanded], [data-front]) > * { opacity: 0; - transition: opacity var(--cui-motion-duration-panel) var(--cui-motion-ease-out); } - [data-cui-stack] > .cui-toast:not([data-cui-stack-index="0"], [data-cui-stack-index="1"], [data-cui-stack-index="2"]) { + [data-cui-stack] > .cui-toast[data-mounted][data-expanded] { + --cui-toast-y: translateY(calc(var(--cui-toast-lift) * var(--cui-toast-offset))); + } + [data-cui-stack] > .cui-toast[data-hidden] { opacity: 0; pointer-events: none; } - [data-cui-stack]:is(:hover, :focus-within) > .cui-toast { - translate: 0 calc(-1 * var(--cui-toast-offset, 0px)); - scale: 1; - clip-path: inset(calc(-1 * var(--cui-toast-shadow-room))); - opacity: 1; - pointer-events: auto; - & > * { - opacity: 1; - } + [data-cui-stack] > .cui-toast[data-closed] { + opacity: 0; + pointer-events: none; + transition-duration: var(--cui-motion-duration-panel); + } + [data-cui-stack] > .cui-toast[data-closed][data-front]:not([data-swipe-out]) { + --cui-toast-y: translateY(calc(var(--cui-toast-lift) * -100%)); + } + [data-cui-stack] > .cui-toast[data-closed][data-expanded]:not([data-front], [data-swipe-out]) { + --cui-toast-y: translateY(calc(var(--cui-toast-lift) * var(--cui-toast-offset) + var(--cui-toast-lift) * -100%)); } - [data-position^=top] [data-cui-stack]:is(:hover, :focus-within) > .cui-toast { - translate: 0 var(--cui-toast-offset, 0px); + [data-cui-stack] > .cui-toast[data-swiping] { + transform: var(--cui-toast-y) translate(var(--cui-toast-swipe-x, 0px), var(--cui-toast-swipe-y, 0px)); + transition: none; + } + [data-cui-stack] > .cui-toast[data-swipe-out] { + animation: cui-toast-swipe-out-stacked var(--cui-motion-duration-panel) var(--cui-motion-ease-out) forwards; + } + [data-cui-stack] > .cui-toast[data-swipe-out=left] { + --cui-toast-swipe-to: translate(calc(var(--cui-toast-swipe-x, 0px) - 100%), 0); + } + [data-cui-stack] > .cui-toast[data-swipe-out=right] { + --cui-toast-swipe-to: translate(calc(var(--cui-toast-swipe-x, 0px) + 100%), 0); + } + [data-cui-stack] > .cui-toast[data-swipe-out=top] { + --cui-toast-swipe-to: translate(0, calc(var(--cui-toast-swipe-y, 0px) - 100%)); + } + [data-cui-stack] > .cui-toast[data-swipe-out=bottom] { + --cui-toast-swipe-to: translate(0, calc(var(--cui-toast-swipe-y, 0px) + 100%)); } :where(.cui-toast) { &:is(:not([data-tone]), [data-tone="neutral"]) { @@ -328,9 +375,13 @@ .cui-toast[data-swipe=end] { animation-name: cui-toast-fade-out; } - [data-cui-stack] > .cui-toast { + [data-cui-stack] > .cui-toast, + [data-cui-stack] > .cui-toast[data-closed] { transition-property: opacity; } + [data-cui-stack] > .cui-toast[data-swipe-out] { + animation-name: cui-toast-fade-out; + } } @media (hover: hover) { .cui-toast-action:hover { diff --git a/packages/styles/scripts/appearance.mjs b/packages/styles/scripts/appearance.mjs index 3035c910..01766855 100644 --- a/packages/styles/scripts/appearance.mjs +++ b/packages/styles/scripts/appearance.mjs @@ -15,7 +15,12 @@ const adapterAttributes = new Set([ "data-contained", "data-cui-replaced", "data-cui-stack", - "data-cui-stack-index", + "data-empty", + "data-front", + "data-hidden", + "data-mounted", + "data-swipe-out", + "data-swiping", "data-disabled", "data-dragging", "data-expanded", From c7b122ada25a563c97b32dec996fa94a00386e32 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Mon, 30 Nov 2026 14:57:30 +0100 Subject: [PATCH 3/7] fix(toast): cap the stack width on the list, not only the region An app style that stretches the region (the docs demo frame sets `w-full` on direct child sections from the utilities layer) made the stacked toasts span the viewport. The list now caps itself at 480px and aligns to the region's side. Co-Authored-By: Claude Opus 5.5 --- packages/styles/css/components/Toast/Toast.css | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/styles/css/components/Toast/Toast.css b/packages/styles/css/components/Toast/Toast.css index 6affcf12..88c2130c 100644 --- a/packages/styles/css/components/Toast/Toast.css +++ b/packages/styles/css/components/Toast/Toast.css @@ -154,6 +154,7 @@ --cui-toast-room: calc(-1 * var(--cui-space-8)); position: relative; width: 100%; + max-width: 480px; height: var(--cui-toast-front-height); gap: var(--cui-space-3); pointer-events: auto; @@ -161,6 +162,12 @@ [data-position^=top] .cui-toast-list[data-cui-stack] { --cui-toast-lift: 1; } + :where(.cui-toast-region):is(:not([data-position]), [data-position="bottom-center"], [data-position="top-center"]) .cui-toast-list[data-cui-stack] { + margin-inline: auto; + } + [data-position$=right] .cui-toast-list[data-cui-stack] { + margin-inline-start: auto; + } .cui-toast-list[data-cui-stack][data-expanded] { height: var(--cui-toast-stack-height); } From b1f3bc796833762a2400dcfc835a197216f62947 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Mon, 30 Nov 2026 15:05:06 +0100 Subject: [PATCH 4/7] feat(toast): narrow toasts to 360px Co-Authored-By: Claude Opus 5.5 --- .changeset/toast-stack.md | 2 +- packages/styles/css/components/Toast/Toast.css | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md index 61b96e19..ddd4e93d 100644 --- a/.changeset/toast-stack.md +++ b/.changeset/toast-stack.md @@ -7,4 +7,4 @@ Toaster: a new engine with Sonner's motion replaces Kobalte's toast region behin Breaking: `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. +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 are 360px wide, down from 480px, and the stack keeps that width even when an app stretches the region. diff --git a/packages/styles/css/components/Toast/Toast.css b/packages/styles/css/components/Toast/Toast.css index 88c2130c..7fac5588 100644 --- a/packages/styles/css/components/Toast/Toast.css +++ b/packages/styles/css/components/Toast/Toast.css @@ -46,7 +46,7 @@ position: fixed; z-index: 50; box-sizing: border-box; - width: min(100%, calc(480px + 2 * var(--cui-space-4))); + width: min(100%, calc(360px + 2 * var(--cui-space-4))); padding: var(--cui-space-4); outline: none; pointer-events: none; @@ -154,7 +154,7 @@ --cui-toast-room: calc(-1 * var(--cui-space-8)); position: relative; width: 100%; - max-width: 480px; + max-width: 360px; height: var(--cui-toast-front-height); gap: var(--cui-space-3); pointer-events: auto; From d1d933f363ccbf55133f6945b95b5428f105c35d Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Mon, 30 Nov 2026 15:14:18 +0100 Subject: [PATCH 5/7] fix(toast): separate stacked cards and use the floating-surface shadow Co-Authored-By: Claude Opus 5.5 --- .changeset/toast-stack.md | 2 +- packages/kit/DESIGN.md | 2 +- packages/styles/css/components/Toast/Toast.css | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md index ddd4e93d..df86528c 100644 --- a/.changeset/toast-stack.md +++ b/.changeset/toast-stack.md @@ -7,4 +7,4 @@ Toaster: a new engine with Sonner's motion replaces Kobalte's toast region behin Breaking: `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 are 360px wide, down from 480px, and the stack keeps that width even when an app stretches the region. +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/packages/kit/DESIGN.md b/packages/kit/DESIGN.md index 4d6bdcb6..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. 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. 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'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/styles/css/components/Toast/Toast.css b/packages/styles/css/components/Toast/Toast.css index 7fac5588..404b85b0 100644 --- a/packages/styles/css/components/Toast/Toast.css +++ b/packages/styles/css/components/Toast/Toast.css @@ -110,7 +110,7 @@ border-radius: var(--cui-radius-card); background-color: var(--cui-surface-toast); color: var(--cui-text-toast); - box-shadow: var(--cui-shadow-menu); + box-shadow: var(--cui-shadow-dialog); font-family: var(--cui-font-family-sans); font-size: var(--cui-font-size-sm); line-height: var(--cui-font-line-height-snug); @@ -188,7 +188,7 @@ clip-path: inset(var(--cui-toast-room)); touch-action: none; animation: none; - transition-property: transform, opacity, clip-path; + transition-property: transform, opacity, clip-path, filter; transition-duration: var(--cui-motion-duration-rise); transition-timing-function: var(--cui-motion-ease-out); } @@ -207,6 +207,10 @@ [data-cui-stack] > .cui-toast[data-mounted]:not([data-expanded], [data-front]) { --cui-toast-y: translateY(calc(var(--cui-toast-lift) * (var(--cui-toast-index) * var(--cui-toast-peek) - var(--cui-toast-height) + var(--cui-toast-front-height)))) scale(calc(1 - var(--cui-toast-index) * 0.05)); clip-path: inset(var(--cui-toast-room) var(--cui-toast-room) var(--cui-toast-cut) var(--cui-toast-room)); + filter: brightness(calc(1 - var(--cui-toast-index) * 0.08)); + } + [data-cui-stack] > .cui-toast[data-cui-theme=dark][data-mounted]:not([data-expanded], [data-front]) { + filter: brightness(calc(1 + var(--cui-toast-index) * 0.3)); } [data-position^=top] [data-cui-stack] > .cui-toast[data-mounted]:not([data-expanded], [data-front]) { clip-path: inset(var(--cui-toast-cut) var(--cui-toast-room) var(--cui-toast-room) var(--cui-toast-room)); From 37129434a9f94caa41996aba0477c2aad12d38a3 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Mon, 30 Nov 2026 15:21:28 +0100 Subject: [PATCH 6/7] feat(toast): follow the page theme by default, invert on request Toasts now render in the theme around the Toaster. `theme="inverted"` on the Toaster, or on one toast, keeps the light-on-dark card. Adds `ToastTheme` and an Inverted story. Co-Authored-By: Claude Opus 5.5 --- .changeset/toast-stack.md | 2 +- .../skills/verify-codeui/features/feedback.md | 2 +- .../verify-codeui/journeys/toast-rise.mjs | 8 ++--- .../content/docs/(kit)/components/toast.mdx | 2 +- packages/docs-demos/src/props/toast.ts | 5 +-- .../kit/src/components/Toast/ToastItem.tsx | 5 +-- packages/kit/src/components/Toast/Toaster.tsx | 7 ++++- .../kit/src/components/Toast/controller.tsx | 14 +++++---- packages/kit/src/ready/toast.ts | 1 + packages/kit/test/toaster.test.tsx | 31 ++++++++++++++----- .../storybook/src/stories/Toaster.stories.tsx | 17 ++++++++++ 11 files changed, 68 insertions(+), 26 deletions(-) diff --git a/.changeset/toast-stack.md b/.changeset/toast-stack.md index df86528c..868d03ac 100644 --- a/.changeset/toast-stack.md +++ b/.changeset/toast-stack.md @@ -5,6 +5,6 @@ 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: `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. +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 26cde492..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) diff --git a/.claude/skills/verify-codeui/journeys/toast-rise.mjs b/.claude/skills/verify-codeui/journeys/toast-rise.mjs index 8cc4624c..92f4ce87 100644 --- a/.claude/skills/verify-codeui/journeys/toast-rise.mjs +++ b/.claude/skills/verify-codeui/journeys/toast-rise.mjs @@ -1,11 +1,11 @@ -// 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(() => { diff --git a/apps/docs/content/docs/(kit)/components/toast.mdx b/apps/docs/content/docs/(kit)/components/toast.mdx index 3662eb26..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 diff --git a/packages/docs-demos/src/props/toast.ts b/packages/docs-demos/src/props/toast.ts index 46f2fbd8..c960af25 100644 --- a/packages/docs-demos/src/props/toast.ts +++ b/packages/docs-demos/src/props/toast.ts @@ -5,7 +5,7 @@ import type { PropNotes } from "./notes"; /** The props of Toaster. */ export type Toaster = Pick< ToasterProps, - "toaster" | "closeLabel" | "position" | "limit" | "expand" | "hotkey" | "aria-label" | "class" | "classes" + "toaster" | "closeLabel" | "position" | "limit" | "expand" | "hotkey" | "theme" | "aria-label" | "class" | "classes" >; /** The options createToaster takes. */ @@ -31,6 +31,7 @@ export const notes = { 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." }, + 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." }, @@ -46,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/src/components/Toast/ToastItem.tsx b/packages/kit/src/components/Toast/ToastItem.tsx index 1351c9dc..d9febed8 100644 --- a/packages/kit/src/components/Toast/ToastItem.tsx +++ b/packages/kit/src/components/Toast/ToastItem.tsx @@ -13,7 +13,7 @@ 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 } from "./controller"; +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. */ @@ -31,6 +31,7 @@ export type ToastItemProps = { paused: Accessor; swipeSides: Accessor; closeLabel: Accessor; + theme: Accessor; onHeight: (height: number | undefined) => void; onInteract: (interacting: boolean) => void; }; @@ -131,7 +132,7 @@ export function ToastItem(props: ToastItemProps) { ? (options().tone ?? "neutral") !== "neutral" : icon() != null && icon() !== false; const theme = () => { - const theme = options().theme ?? "inverted"; + const theme = options().theme ?? props.theme(); if (theme === "page") return undefined; if (theme !== "inverted") return theme; const page = pageScheme(); diff --git a/packages/kit/src/components/Toast/Toaster.tsx b/packages/kit/src/components/Toast/Toaster.tsx index 38b50989..0b4df51c 100644 --- a/packages/kit/src/components/Toast/Toaster.tsx +++ b/packages/kit/src/components/Toast/Toaster.tsx @@ -3,7 +3,7 @@ import type { JSX } from "@solidjs/web"; import * as styles from "../../components/Toast/Toast.css"; import { type ToastClasses, type ToastPosition, toastParts, toastStyles } from "../../parts/toast"; import { mergeClasses } from "../../utils/css"; -import { type ToastController, type ToastId, toastStore } from "./controller"; +import { type ToastController, type ToastId, type ToastTheme, toastStore } from "./controller"; import type { SwipeSide } from "./swipe"; import { ToastItem, type ToastPlace } from "./ToastItem"; @@ -17,6 +17,7 @@ export type { ToastId, ToastOptions, ToastPromiseOptions, + ToastTheme, } from "./controller"; export type ToasterProps = Omit, "children"> & { @@ -34,6 +35,8 @@ export type ToasterProps = Omit, "children"> & { 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; }; @@ -69,6 +72,7 @@ export function Toaster(props: ToasterProps) { "limit", "expand", "hotkey", + "theme", "classes", "class", "aria-label", @@ -164,6 +168,7 @@ export function Toaster(props: ToasterProps) { paused={paused} swipeSides={() => swipeSides(position())} closeLabel={() => props.closeLabel} + theme={() => props.theme ?? "page"} onHeight={height => setHeight(toast.id, height)} onInteract={setInteracting} /> diff --git a/packages/kit/src/components/Toast/controller.tsx b/packages/kit/src/components/Toast/controller.tsx index 9f8ae331..17f54f44 100644 --- a/packages/kit/src/components/Toast/controller.tsx +++ b/packages/kit/src/components/Toast/controller.tsx @@ -13,6 +13,12 @@ export type ToastAction = { 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; @@ -24,12 +30,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; diff --git a/packages/kit/src/ready/toast.ts b/packages/kit/src/ready/toast.ts index a11decf0..365ff660 100644 --- a/packages/kit/src/ready/toast.ts +++ b/packages/kit/src/ready/toast.ts @@ -10,4 +10,5 @@ export type { ToastId, ToastOptions, ToastPromiseOptions, + ToastTheme, } from "../components/Toast/Toaster"; diff --git a/packages/kit/test/toaster.test.tsx b/packages/kit/test/toaster.test.tsx index a303fd58..50793eea 100644 --- a/packages/kit/test/toaster.test.tsx +++ b/packages/kit/test/toaster.test.tsx @@ -206,25 +206,40 @@ describe("createToaster", () => { expect(await screen.findByRole("status")).toHaveAttribute("data-cui-theme", "light"); }); - it("inverts the page theme by default and follows the page with theme page", async () => { + it("follows the page by default and inverts with theme inverted", async () => { const notifications = createToaster(); render(() => (
)); - notifications.show({ description: "Copied" }); - const copied = await screen.findByRole("status"); - expect(copied).toHaveAttribute("data-cui-theme", "light"); + notifications.show({ description: "Saved" }); + const saved = (await screen.findByText("Saved")).closest("[role=status]")!; + expect(saved).not.toHaveAttribute("data-cui-theme"); + notifications.show({ description: "Copied", theme: "inverted" }); + const copied = (await screen.findByText("Copied")).closest("[role=status]")!; + await waitFor(() => expect(copied).toHaveAttribute("data-cui-theme", "light")); // The page switches theme while the toast is open. copied .closest("[data-cui-theme=dark]:not([role=status])")! .setAttribute("data-cui-theme", "light"); await waitFor(() => expect(copied).toHaveAttribute("data-cui-theme", "dark")); - notifications.clear(); - notifications.show({ description: "Saved", theme: "page" }); - const saved = await screen.findByText("Saved"); - expect(saved.closest("[role=status]")).not.toHaveAttribute("data-cui-theme"); + }); + + it("inverts every toast with the Toaster theme, unless a toast overrides it", async () => { + const notifications = createToaster(); + render(() => ( +
+ +
+ )); + notifications.show({ description: "Inverted" }); + notifications.show({ description: "Own", theme: "page" }); + const inverted = (await screen.findByText("Inverted")).closest("[role=status]")!; + await waitFor(() => expect(inverted).toHaveAttribute("data-cui-theme", "light")); + expect(screen.getByText("Own").closest("[role=status]")).not.toHaveAttribute( + "data-cui-theme", + ); }); it("renders content inside the providers around its Toaster", async () => { diff --git a/packages/storybook/src/stories/Toaster.stories.tsx b/packages/storybook/src/stories/Toaster.stories.tsx index a42052c8..10bc5f5a 100644 --- a/packages/storybook/src/stories/Toaster.stories.tsx +++ b/packages/storybook/src/stories/Toaster.stories.tsx @@ -19,6 +19,7 @@ function Frame(props: { height: string; position?: ToastPosition; expand?: boolean; + theme?: ToastOptions["theme"]; toasts?: ToastOptions[]; children?: (toaster: ToastController) => JSX.Element; }) { @@ -34,6 +35,7 @@ function Frame(props: { position={props.position} limit={5} expand={props.expand} + theme={props.theme} closeLabel="Dismiss" aria-label={`${props.label} notifications`} /> @@ -118,6 +120,21 @@ export const Stacked: Story = { ), }; +/** `theme="inverted"` on the Toaster: light toasts on a dark page, dark toasts on a light one. */ +export const Inverted: Story = { + render: () => ( + + ), +}; + export const WithAction: Story = { render: () => ( Date: Mon, 30 Nov 2026 15:29:23 +0100 Subject: [PATCH 7/7] chore(toast): update the public API snapshot and docs manifest for ToastTheme Co-Authored-By: Claude Opus 5.5 --- apps/docs/export-manifest.json | 6 ++- packages/kit/api/kit.api.md | 87 +++++++++++++++++++++++++--------- 2 files changed, 69 insertions(+), 24 deletions(-) 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/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