diff --git a/.changeset/toast-component.md b/.changeset/toast-component.md new file mode 100644 index 00000000000..151b15e6251 --- /dev/null +++ b/.changeset/toast-component.md @@ -0,0 +1,5 @@ +--- +"@hashintel/ds-components": patch +--- + +Add `Toast` and `Toaster`, toast notifications with two APIs: wrap the app in a `Toaster`, then either render a `Toast` declaratively (with `Toast.Title`, `Toast.Body`, `Toast.Actions`) or call the `toaster` functions (`create`, `promise`, `update`, `close`) from anywhere, in Banner's tones and variants. diff --git a/libs/@hashintel/ds-components/src/components/Banner/banner.tsx b/libs/@hashintel/ds-components/src/components/Banner/banner.tsx index cc338f253d1..54be5f4a073 100644 --- a/libs/@hashintel/ds-components/src/components/Banner/banner.tsx +++ b/libs/@hashintel/ds-components/src/components/Banner/banner.tsx @@ -2,6 +2,7 @@ import { Children, isValidElement } from "react"; import { cx } from "@hashintel/ds-helpers/css"; +import { defaultToneIcon } from "../../util/default-tone-icon"; import { Button, type ButtonProps } from "../Button/button"; import { Icon, type IconName } from "../Icon/icon"; import { styles } from "./banner.recipe"; @@ -10,15 +11,6 @@ import type { Tone } from "../../util/form-shared"; type BannerVariant = "solid" | "soft" | "outline"; -/** The default leading icon shown when `icon` is `true`, keyed by tone. */ -const defaultToneIcon: Record = { - neutral: "info", - brand: "info", - warning: "warning", - error: "diamondExclamation", - success: "circleCheck", -}; - export type BannerRootProps = { className?: string; children: React.ReactNode; diff --git a/libs/@hashintel/ds-components/src/components/Toast/toast.docs.mdx b/libs/@hashintel/ds-components/src/components/Toast/toast.docs.mdx new file mode 100644 index 00000000000..875bf62e1a6 --- /dev/null +++ b/libs/@hashintel/ds-components/src/components/Toast/toast.docs.mdx @@ -0,0 +1,773 @@ +import { Meta } from "@storybook/addon-docs/blocks"; +import { useRef, useState } from "react"; + +import { DoList, DontList } from "../../../docs/blocks/do-dont-list"; +import { PropsTable } from "../../../docs/blocks/props-table"; +import { ReferenceLinks } from "../../../docs/blocks/reference-links"; +import { Stage } from "../../../docs/blocks/stage"; +import { Button } from "../Button/button"; +import { + Toast, + ToastAction, + ToastActions, + ToastBody, + ToastTitle, +} from "./toast"; +import { Toaster, ToasterToastPropsDoc } from "./toaster"; +import { toaster } from "./toaster-api"; + + + +export const meta = { + title: "Toast", + description: + "A transient notification that confirms an action or reports a background event.", + alternativeNames: ["Snackbar", "Notification", "Toaster"], + links: { + source: + "https://github.com/hashintel/hash/blob/main/libs/@hashintel/ds-components/src/components/Toast/toast.tsx", + stories: + "https://tokens.hash.design/?path=/story/components-toast--default", + }, + referenceLinks: { + apg: "https://www.w3.org/WAI/ARIA/apg/patterns/alert/", + ark: "https://ark-ui.com/docs/components/toast", + }, + related: ["Banner", "Dialog"], +}; + +# Toast + +A transient notification that confirms an action or reports a background event. + + + +export const heroCode = `import { useState } from "react"; + +import { Button, Toast, Toaster } from "@hashintel/ds-components"; + +// Somewhere near the application root: +// …the app… + +export const PublishButton = () => { + const [published, setPublished] = useState(false); + + return ( + <> + + {published ? ( + { + if (status === "exit") { + setPublished(false); + } + }} + > + + Version 3 is now live. + + ) : null} + + ); +};`; + +export const HeroDemo = () => { + const [published, setPublished] = useState(false); + return ( + + + {published ? ( + { + if (status === "exit") { + setPublished(false); + } + }} + > + + Version 3 is now live. + + ) : null} + + ); +}; + + + + + +## Installation + +1. Install the package. + +```sh +npm install @hashintel/ds-components +``` + +2. Mount a `Toaster` once, wrapping the part of the application (usually all + of it) that shows toasts. + +```tsx +import { Toaster } from "@hashintel/ds-components"; + +export const App = () => {/* …the application… */}; +``` + +3. Render a `Toast` to show it, and remove it when `onStatusChange` reports + `exit` — the same mount-to-open contract as `Dialog`. The other statuses + (`enter`, plus `behind`/`front` as newer toasts stack in front of it and + leave again) are informational. + +### When to use + + + +### When not to use + + + +## Anatomy + +```tsx + + + The file exceeds the 10 MB limit. + Retry} /> + +``` + +Children are free-form: compose `Toast.Title`, `Toast.Body`, and +`Toast.Actions` in that order for the standard layout, or pass any custom +node — paired with `withPadding={false}` for edge-to-edge content. The +function form of `children` receives `close` for custom content that +dismisses its own toast. A close button renders automatically unless +`shouldCloseOn="none"`. The toast itself renders nothing where it is +mounted — it appears in the `Toaster`'s stacking region for its `position`. + +## Examples + +### Tones and variants + +`tone` and `variant` reuse Banner's visual system: `solid` fills with the +saturated tone color, `soft` tints the surface, and `outline` draws a border +on a page-colored card. Each tone also sets `Toast.Title`'s default icon. + +export const tonesCode = ` + + Describe what happened in a sentence. +`; + +export const TonesDemo = () => { + const [queued, setQueued] = useState([]); + const fire = (tone, variant) => + setQueued((previous) => [...previous, { key: Date.now(), tone, variant }]); + return ( + + {["soft", "outline", "solid"].map((variant) => + ["neutral", "brand", "success", "warning", "error"].map((tone) => ( + + )), + )} + {queued.map(({ key, tone, variant }) => ( + { + if (status === "exit") { + setQueued((previous) => previous.filter((toast) => toast.key !== key)); + } + }} + > + + Describe what happened in a sentence. + + ))} + + ); +}; + + + + + +### Title row + +`Toast.Title` lays out the leading icon and the heading on one row. The icon +defaults to the tone's: pass `icon={false}` for none, `icon={{ iconName }}` +for another design-system icon, or `icon={{ custom }}` for arbitrary content. +`loading` swaps the icon for a spinner. Pass `children` instead to replace +the structured layout entirely. + +export const titleCode = ` + + 3 of 24 files processed. +`; + +export const TitleDemo = () => { + const [visible, setVisible] = useState(false); + return ( + + + {visible ? ( + + + 3 of 24 files processed. + + ) : null} + + ); +}; + + + + + +### Actions + +`Toast.Actions` renders the buttons for responding to the toast — under the +body, or sharing the title's line (when they fit) in a toast without a body. +Fill it with `Toast.Action`s: `Button`s defaulting to the compact action +treatment, lifted onto a white background on the `soft` and `solid` fills. +Keep the toast around while it has actions — pass `duration={Infinity}` so it +can't vanish before the user decides. + +An action leaves the toast open unless `closeToast` is set, which dismisses +the toast when the action is activated — an action that resolves it, like +"Undo" or "Retry". A promise returned from the action's `onClick` defers the +dismissal until it resolves: the button shows its loading state and the toast +can't time out meanwhile, and a rejection keeps the toast open with a fresh +timer (update the toast to report the failure). Calling +`event.preventDefault()` in `onClick` cancels the dismissal. + +export const actionsCode = ` + + The file exceeds the 10 MB limit. + + {/* A returned promise defers the close until the retry finishes. */} + retryImport()}> + Retry + + Details + + } + /> +`; + +export const ActionsDemo = () => { + const [visible, setVisible] = useState(false); + return ( + + + {visible ? ( + { + if (status === "exit") { + setVisible(false); + } + }} + > + + The file exceeds the 10 MB limit. + + + new Promise((resolve) => setTimeout(resolve, 1500)) + } + > + Retry + + Details + + } + /> + + ) : null} + + ); +}; + + + + + +### Custom content + +Any node passed as `children` replaces the standard sections — pair it with +`withPadding={false}` for an edge-to-edge layout. The function form receives +`close`, which dismisses the toast with its exit animation, so fully custom +content can close itself. + +export const customContentCode = ` + {({ close }) => ( +
+ Fully custom children +

The toast only provides the card.

+ +
+ )} +
`; + +export const CustomContentDemo = () => { + const [visible, setVisible] = useState(false); + return ( + + + {visible ? ( + { + if (status === "exit") { + setVisible(false); + } + }} + > + {({ close }) => ( +
+ Fully custom children + The toast only provides the card. + +
+ )} +
+ ) : null} +
+ ); +}; + + + + + +### Updating in place + +Toasts rendered with the same `id` update the same toast — re-render with new +content to show progress without stacking a second card. + +export const updateCode = `const [saved, setSaved] = useState(false); + + + +`; + +export const UpdateDemo = () => { + const [phase, setPhase] = useState("idle"); + const start = () => { + setPhase("saving"); + setTimeout(() => { + setPhase("saved"); + }, 2000); + }; + return ( + + + {phase === "idle" ? null : ( + + + + )} + + ); +}; + + + + + +### Duration and dismissal + +By default a toast's lifetime depends on its `tone`: `success` dismisses +after 2 seconds and the other tones after 5. Pass `duration` (in +milliseconds, or `Infinity`) to override it. Hovering or focusing a stack +pauses every timer in it, as does leaving the page — switching tabs or apps. +`shouldCloseOn="none"` drops the close button and Escape, leaving dismissal +to `duration`, unmounting, or a `closeToast` action. + +export const durationCode = ` + + Stays for 30 seconds. + + + + No close button; gone after 4 seconds. +`; + +export const DurationDemo = () => { + const [queued, setQueued] = useState([]); + const fire = (extras) => + setQueued((previous) => [...previous, { key: Date.now(), ...extras }]); + return ( + + + + {queued.map(({ key, label, ...extras }) => ( + { + if (status === "exit") { + setQueued((previous) => previous.filter((toast) => toast.key !== key)); + } + }} + > + {label} + + ))} + + ); +}; + + + + + +### Position + +`position` picks the viewport edge or corner the toast stacks at; toasts +sharing a position share a stacking region. `left`/`right` values map onto +the nearest corner (`-start` the top one, `-end` the bottom one). The +centered `top` and `bottom` placements render slightly wider by default. + +export const positionCode = ` + Placed top. +`; + +export const PositionDemo = () => { + const [queued, setQueued] = useState([]); + const fire = (position) => + setQueued((previous) => [...previous, { key: Date.now(), position }]); + return ( + + {["top-start", "top", "top-end", "bottom-start", "bottom", "bottom-end"].map( + (position) => ( + + ), + )} + {queued.map(({ key, position }) => ( + { + if (status === "exit") { + setQueued((previous) => previous.filter((toast) => toast.key !== key)); + } + }} + > + Placed {position}. + + ))} + + ); +}; + + + + + +### Deep stacks + +A collapsed stack shows its front three toasts; hovering or focusing it +expands the full column, which scrolls when it outgrows the viewport. At most +100 toasts are mounted per stacking region — any more wait in a queue and +appear as older ones leave. + +export const stackingCode = `{toasts.map((toast) => ( + + + +))}`; + +export const StackingDemo = () => { + const [queued, setQueued] = useState([]); + const nextKeyRef = useRef(0); + const fire = (count) => { + const batch = []; + for (let i = 0; i < count; i++) { + nextKeyRef.current += 1; + batch.push(nextKeyRef.current); + } + setQueued((previous) => [...previous, ...batch]); + }; + return ( + + + + {queued.map((key) => ( + { + if (status === "exit") { + setQueued((previous) => previous.filter((toastKey) => toastKey !== key)); + } + }} + > + + Hover the stack to expand it. + + ))} + + ); +}; + + + + + +### The toaster functions + +For call sites without a natural place to render a `Toast` — API handlers, +stores, effects — the `toaster` functions show one imperatively from anywhere +below (or outside) the mounted `Toaster`. Each takes the flat props form +(every `Toast` prop except `withPadding` and `children`, with the content as +`title`/`body`/`actions`) or a `Toast` element for full control. +`toaster.create` returns the toast's id; `toaster.promise` shows a persistent +pending toast and replaces it with the `success` or `error` toast (toned +accordingly by default) when the promise settles; `toaster.update` merges new +props into a showing toast; `toaster.close` dismisses one — including +declaratively rendered toasts — by id. + +export const functionalCode = `import { toaster, Toast } from "@hashintel/ds-components"; + +const id = toaster.create({ + tone: "success", + title: "Entity type published", + body: "Version 3 is now live.", +}); + +toaster.create( + + + Full control over the composition. + , +); + +toaster.promise(saveDraft(), { + loading: { title: "Saving draft…" }, + success: { title: "Draft saved" }, + error: { title: "Could not save draft" }, +}); + +toaster.update(id, { body: "Version 4 is now live." }); +toaster.close(id);`; + +export const FunctionalDemo = () => ( + + + + +); + + + + + +## Content + +- Lead with the outcome in the title, in a few words: "Entity type + published", "Import failed". +- Use `Toast.Body` for the one detail worth adding — what changed, or what to + do about a failure. +- Name action buttons with a verb ("Undo", "Retry", "View"), never "OK" — a + toast needs no acknowledgement. + +## Accessibility + +Toasts follow the +[WAI-ARIA alert pattern](https://www.w3.org/WAI/ARIA/apg/patterns/alert/). + +### What Toast provides + +- Each stacking region is a labelled `role="region"` landmark with + `aria-live="polite"`, so new toasts are announced without interrupting what + the screen reader is currently saying. +- Each toast is a `role="status"` element labelled by its title and described + by its body. +- The hotkey Alt+T moves focus into a region; toasts + are focusable, and Escape dismisses the focused one (unless + `shouldCloseOn="none"`). +- Timers pause while the pointer or focus is inside a region and while the + page is idle — the tab hidden or the window unfocused — so a toast can't + vanish mid-read. + +### What you must do + +- Remove the `Toast` element when `onStatusChange` reports `exit`; + otherwise the next render of a stale element re-creates the toast. +- Keep toasts supplementary: anything the user must read or act on belongs in + persistent UI, since a toast may never be noticed. +- Don't rely on color alone to distinguish outcomes — the title should carry + the meaning ("Import failed", not just a red tint). + +## API reference + +### Toast + + + +### Toast.Title + +Either the structured title row (`title`, `icon`, `loading`, `actions`) +or fully custom `children` — the two are mutually exclusive. + + + +### Toast.Body + + + +### Toast.Actions + + + +### Toast.Action + +An action button for the `Toast.Actions` row, taking the same props as +`Button`. + + + +### Toaster + + + +### toaster + +The imperative counterpart to rendering `Toast` elements; it requires a +mounted `Toaster` and its toasts clean up after themselves. + +- `toaster.create(props | element)` — shows a toast and returns its id; an + input carrying the id of a showing toast replaces it in place. +- `toaster.promise(promise, { loading, success, error })` — shows the + persistent `loading` toast (spinner in the title's icon slot), then replaces + it with `success` or `error` — toned accordingly by default — when the + promise settles. Returns the input promise. +- `toaster.update(id, props)` — merges new props into a showing toast. +- `toaster.close(id)` — dismisses a showing toast, including declaratively + rendered ones, by id. + +The props form accepts: + + diff --git a/libs/@hashintel/ds-components/src/components/Toast/toast.recipe.ts b/libs/@hashintel/ds-components/src/components/Toast/toast.recipe.ts new file mode 100644 index 00000000000..640cfba33ce --- /dev/null +++ b/libs/@hashintel/ds-components/src/components/Toast/toast.recipe.ts @@ -0,0 +1,385 @@ +import { sva } from "@hashintel/ds-helpers/css"; + +export const toastTones = [ + "neutral", + "brand", + "error", + "warning", + "success", +] as const; + +export const toastVariants = ["solid", "soft", "outline"] as const; + +export type ToastVariant = (typeof toastVariants)[number]; + +/** + * The tone × variant system mirrors Banner's (same tones, same + * solid/soft/outline treatments, `--toast-*` custom properties in place of + * `--banner-*`). Placement, stacking, and per-toast motion are driven by the + * CSS custom properties zag's toast machine sets inline (`--x`, `--y`, + * `--scale`, `--opacity`, `--height`, `--z-index`); the root styles only + * consume them and define how changes to them transition. + */ +export const styles = sva({ + slots: [ + "shell", + "group", + "root", + "content", + "titleRow", + "icon", + "defaultIcon", + "title", + "body", + "actions", + "closeTrigger", + ], + base: { + // The region's scroll shell (see `ToasterRegion`): full-viewport and + // pointer-transparent — zag re-enables pointer events per toast inline, + // `auto` while visible and `none` while exiting — with its `transform` + // making it the containing block zag's fixed group positions and scrolls + // within. + shell: { + position: "fixed", + inset: "0", + // zag's MAX_Z_INDEX, which the group inside sets inline. + zIndex: "[2147483647]", + pointerEvents: "none", + transform: "[translateZ(0)]", + display: "flex", + flexDirection: "column", + overflowY: "auto", + scrollbarWidth: "[none]", + overscrollBehavior: "contain", + // Bottom stacks grow upward, so reverse the column: scrollable overflow + // then extends block-start-ward and the resting scroll sits at the + // bottom, on the front toast. + "&[data-side=bottom]": { + flexDirection: "column-reverse", + }, + // While a stack is expanded, a spacer provides the scroll extent of the + // measured toast column plus the region's 1rem viewport offsets. + "&:has([data-part=root][data-stack])::after": { + content: '""', + flexShrink: "0", + width: "[1px]", + height: "[calc(var(--column-height, 0px) + 2rem)]", + }, + }, + group: {}, + root: { + display: "flex", + alignItems: "flex-start", + gap: "[8px]", + // Read through a custom property so a consumer `className` can set a + // custom width deterministically (a plain `width` override would tie + // with this one on specificity and fall to stylesheet order). + width: "[var(--toast-width, var(--toast-width-default, 356px))]", + maxWidth: "[calc(100vw - 32px)]", + // The centered edge placements read better slightly wider than the + // corner stacks. + "&:is([data-placement=top], [data-placement=bottom])": { + "--toast-width-default": "[450px]", + }, + borderRadius: "xl", + borderWidth: "1px", + borderStyle: "solid", + boxShadow: + "[0 0 0 1px rgba(0, 0, 0, 0.03), 0 4px 12px -4px rgba(0, 0, 0, 0.12), 0 12px 28px -8px rgba(0, 0, 0, 0.14)]", + textStyle: "sm", + overflowWrap: "anywhere", + "--toast-text-color": "var(--colors-fg-body)", + translate: "[var(--x) var(--y)]", + scale: "[var(--scale, 1)]", + opacity: "[var(--opacity)]", + zIndex: "[var(--z-index)]", + willChange: "[translate, opacity, scale]", + transition: + "[translate 400ms cubic-bezier(0.21, 1.02, 0.73, 1), scale 400ms cubic-bezier(0.21, 1.02, 0.73, 1), opacity 400ms cubic-bezier(0.21, 1.02, 0.73, 1)]", + // The exit fades out within the store's 200ms `removeDelay` (see + // `createToaster`), so the toast is fully transparent when zag unmounts + // it and the longer translate/scale tail is never visibly clipped. + "&[data-state=closed]": { + transition: + "[translate 400ms cubic-bezier(0.06, 0.71, 0.55, 1), scale 400ms cubic-bezier(0.06, 0.71, 0.55, 1), opacity 200ms cubic-bezier(0.06, 0.71, 0.55, 1)]", + }, + // While overlapped behind the frontmost toast, clamp to the frontmost + // toast's measured height so the collapsed deck reads as even cards, and + // hide the content so only clean card edges peek out; it fades back in + // when hovering expands the stack. Height stays unclamped everywhere + // else — zag measures it rounded to whole pixels, and applying that to + // the visible toast nudges its height on hover. The zag-rendered ghost + // divs must stay hit-testable. + "&[data-sibling][data-overlap]": { + height: "[var(--height)]", + }, + "& > *:not([data-ghost])": { + transition: "[opacity 200ms ease]", + }, + "&[data-sibling][data-overlap] > *:not([data-ghost])": { + opacity: "0", + }, + // Beyond the collapsed deck of three (`data-deck-hidden`, set from the + // stack index): fully hidden — `visibility` also drops hit-testing and + // tab order — until the stack expands or the toast advances into the + // deck. Pinned just behind the third card (overriding the per-index + // lift and scale) so deep stacks neither leave phantom scroll extent in + // the shell nor fade in from far away. Hiding delays `visibility` so + // the card fades out first; revealing flips it instantly and fades in + // through the base transition. + "&[data-deck-hidden][data-overlap]": { + opacity: "0", + visibility: "hidden", + translate: "[var(--x) calc(var(--lift-amount) * 3)]", + scale: "[0.85]", + transition: + "[translate 400ms cubic-bezier(0.21, 1.02, 0.73, 1), scale 400ms cubic-bezier(0.21, 1.02, 0.73, 1), opacity 400ms cubic-bezier(0.21, 1.02, 0.73, 1), visibility 0s linear 400ms]", + _motionReduce: { + transition: "[opacity 150ms ease, visibility 0s linear 150ms]", + }, + }, + _motionReduce: { + transition: "[opacity 150ms ease]", + }, + }, + content: { + flex: "1", + alignSelf: "center", + minWidth: "0", + // Gap between the stacked title row / body / custom children. + "& > * + *": { marginTop: "[1px]" }, + // Without a body, the title and actions share a line when they fit (the + // title grows, pushing the actions to the trailing edge) and the actions + // wrap beneath it when they don't. + "&:not(:has([data-part=description]))": { + display: "flex", + flexWrap: "wrap", + alignItems: "center", + columnGap: "[16px]", + rowGap: "[4px]", + "& > :first-child": { flexGrow: "1" }, + "& > * + *": { marginTop: "0" }, + "& > [data-toast-actions]": { paddingTop: "0" }, + }, + }, + titleRow: { + display: "flex", + alignItems: "flex-start", + gap: "[6px]", + }, + icon: { + flexShrink: "0", + display: "flex", + alignItems: "center", + minHeight: "[1.6em]", + color: "var(--toast-icon-color, var(--toast-text-color))", + }, + defaultIcon: {}, + title: { + margin: "0", + fontWeight: "semibold", + color: "var(--toast-text-color)", + alignSelf: "center", + }, + body: { + color: "var(--toast-text-color)", + }, + actions: { + display: "flex", + flexWrap: "wrap", + alignItems: "center", + gap: "[8px]", + paddingTop: "[12px]", + }, + closeTrigger: { + flexShrink: "0", + display: "inline-flex", + alignItems: "center", + justifyContent: "center", + width: "[24px]", + height: "[24px]", + marginTop: "[-4px]", + marginRight: "[-4px]", + // Single-line toasts center the trigger on their one line instead of + // nudging it into the top corner (measured by ToastContent). + "&[data-single-line]": { + alignSelf: "center", + marginTop: "0", + }, + borderRadius: "full", + cursor: "pointer", + color: "var(--toast-dismiss-color, var(--toast-text-color))", + transition: "[background 0.15s ease, color 0.15s ease]", + _hover: { + color: + "[var(--toast-dismiss-hover-color, color-mix(in oklab, var(--toast-dismiss-color, var(--toast-text-color)) 70%, black))]", + backgroundColor: "var(--toast-dismiss-hover-bg, transparent)", + }, + _focusVisible: { + outlineWidth: "2px", + outlineStyle: "solid", + outlineOffset: "[-2px]", + }, + }, + }, + variants: { + // Tones pick the palette; `--toast-tone-icon-color` overrides the icon + // tint the soft/outline variants apply (the warning and error link colors + // read too light for their glyphs). Only the tone axis writes it, and only + // the variant axis writes `--toast-icon-color`, so the two never race. + tone: { + neutral: { + root: { colorPalette: "neutral" }, + defaultIcon: { transform: "[translateY(-0.7px)]" }, + }, + brand: { + root: { colorPalette: "blue" }, + defaultIcon: { transform: "[translateY(-0.7px)]" }, + }, + error: { + root: { + colorPalette: "red", + "--toast-tone-icon-color": "var(--colors-color-palette-fg-body)", + }, + // The diamond glyph reads smaller than the other tone icons, so enlarge + // it to 18px (mirroring Banner). + defaultIcon: { + width: "[18px !important]", + height: "[18px !important]", + }, + }, + warning: { + root: { + colorPalette: "orange", + "--toast-tone-icon-color": "var(--colors-color-palette-fg-body)", + }, + }, + success: { + root: { colorPalette: "green" }, + defaultIcon: { transform: "[translateY(-0.7px)]" }, + }, + }, + variant: { + solid: { + root: { + backgroundColor: "var(--toast-solid)", + borderColor: "var(--toast-solid)", + "--toast-text-color": "var(--colors-fg-on-solid)", + "--toast-dismiss-hover-color": "var(--colors-fg-on-solid)", + "--toast-dismiss-hover-bg": "var(--colors-white-a20)", + // Restyle default (subtle) `Toast.Action`s to read on the fill. + "& [data-toast-actions] .toast-action-button": { + backgroundColor: "white", + borderColor: "[transparent]", + color: "fg.body", + "&:not([aria-disabled=true]):hover": { + backgroundColor: "neutral.s30", + color: "fg.body", + borderColor: "[transparent]", + }, + "&:focus-visible": { + outlineColor: "var(--toast-text-color)", + outlineOffset: "[2px]", + }, + }, + }, + closeTrigger: { + _focusVisible: { + outlineColor: "var(--toast-text-color)", + }, + }, + }, + soft: { + root: { + backgroundColor: "colorPalette.bgSolid.surface.active", + borderColor: "colorPalette.bd.subtle", + "--toast-icon-color": + "var(--toast-tone-icon-color, var(--colors-color-palette-fg-link))", + "--toast-dismiss-hover-bg": "var(--colors-neutral-a30)", + // Default (subtle) `Toast.Action`s blend into the tinted surface, so + // lift them onto a white background. + "& [data-toast-actions] .toast-action-button": { + backgroundColor: "white", + color: "fg.body", + "&:not([aria-disabled=true]):hover": { + backgroundColor: "neutral.s20", + color: "fg.body", + }, + }, + }, + }, + outline: { + root: { + backgroundColor: "colorPalette.bgSolid.min", + borderColor: "colorPalette.bd.solid", + "--toast-icon-color": + "var(--toast-tone-icon-color, var(--colors-color-palette-fg-link))", + "--toast-dismiss-color": "var(--colors-fg-max)", + "--toast-dismiss-hover-bg": "var(--colors-neutral-a40)", + }, + }, + }, + withPadding: { + true: { + root: { padding: "[12px]" }, + }, + false: { + // The close trigger's negative margins exist to optically inset it + // within the padding; without padding they push it over the edge. + closeTrigger: { + marginTop: "0", + marginRight: "0", + }, + }, + }, + }, + compoundVariants: [ + { + tone: "neutral", + variant: "solid", + css: { + root: { "--toast-solid": "var(--colors-neutral-s120)" }, + }, + }, + { + tone: "brand", + variant: "solid", + css: { root: { "--toast-solid": "var(--colors-blue-s110)" } }, + }, + { + tone: "error", + variant: "solid", + css: { root: { "--toast-solid": "var(--colors-red-s110)" } }, + }, + { + tone: "success", + variant: "solid", + css: { root: { "--toast-solid": "var(--colors-green-s110)" } }, + }, + { + tone: "warning", + variant: "solid", + css: { + root: { + "--toast-solid": "var(--colors-yellow-s100)", + "--toast-text-color": "var(--colors-yellow-fg-on-solid)", + "--toast-dismiss-hover-color": "var(--colors-yellow-fg-on-solid)", + "--toast-dismiss-hover-bg": "[rgba(0, 0, 0, 0.05)]", + }, + }, + }, + { + tone: "neutral", + variant: "soft", + css: { + root: { "--toast-dismiss-hover-color": "var(--colors-fg-max)" }, + }, + }, + ], + defaultVariants: { + tone: "neutral", + variant: "soft", + withPadding: true, + }, +}); diff --git a/libs/@hashintel/ds-components/src/components/Toast/toast.stories.tsx b/libs/@hashintel/ds-components/src/components/Toast/toast.stories.tsx new file mode 100644 index 00000000000..3c634582d2d --- /dev/null +++ b/libs/@hashintel/ds-components/src/components/Toast/toast.stories.tsx @@ -0,0 +1,561 @@ +import { useCallback, useRef, useState } from "react"; + +import { css } from "@hashintel/ds-helpers/css"; + +import { PortalContainerContext } from "../../util/portal-container-context"; +import { Button } from "../Button/button"; +import { Toast, type ToastProps } from "./toast"; +import { toastTones, toastVariants } from "./toast.recipe"; +import { Toaster } from "./toaster"; + +import type { Position } from "../Tooltip/base-tooltip"; +import type { Meta, StoryObj } from "@storybook/react-vite"; + +const meta = { + title: "Components/Toast", + component: Toast, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +const demoActions = ( + <> + View + Undo + +); + +const manyActions = ( + <> + Retry + Skip + View log + Details + Dismiss + +); + +type KitchenSinkToastProps = Omit, "children"> & { + title?: string; + body?: string; + actions?: React.ReactNode; +}; + +/** The full toast — icon, title, body, and an action row. */ +const KitchenSinkToast = ({ + title = "Entity type published", + body = "Version 3 of the Person type is now live.", + tone = "neutral", + actions = demoActions, + ...toastProps +}: KitchenSinkToastProps) => ( + + + {body} + + +); + +/* ------------------------------------------------------------------ */ +/* Default: every composition, rendered directly into the page layout */ +/* ------------------------------------------------------------------ */ + +/** + * Neutralizes the toast region's viewport-anchored chrome so a cell's toast + * renders in the page flow: the region portals into this cell (via + * `PortalContainerContext`) and the inline `position: fixed` / `absolute` + * placement styles zag writes are overridden. The ghost divs exist for + * pointer-exit tracking in real regions and would cover the page here. + */ +const inlineToastRegion = css({ + "& [data-scope=toast][data-part=shell]": { + position: "[static !important]", + transform: "[none !important]", + overflow: "[visible !important]", + }, + "& [data-scope=toast][data-part=shell]::after": { + display: "[none !important]", + }, + "& [data-scope=toast][data-part=group]": { + position: "[static !important]", + alignItems: "[flex-start !important]", + }, + "& [data-scope=toast][data-part=root]": { + position: "[static !important]", + }, + "& [data-scope=toast] [data-ghost]": { + display: "[none !important]", + }, +}); + +/** A self-contained inline Toaster: one gallery cell per toast. */ +const InlineToast = ({ children }: { children: React.ReactNode }) => { + const containerRef = useRef(null); + const [container, setContainer] = useState(null); + const attachContainer = useCallback((node: HTMLDivElement | null) => { + containerRef.current = node; + setContainer(node); + }, []); + + return ( +
+ {container ? ( + + {children} + + ) : null} +
+ ); +}; + +const gallery = css({ + display: "flex", + flexDirection: "column", + gap: "[32px]", +}); + +const sectionHeading = css({ + textStyle: "sm", + fontWeight: "semibold", + color: "fg.body", + marginBottom: "[12px]", +}); + +const cellRow = css({ + display: "flex", + flexWrap: "wrap", + alignItems: "flex-start", + gap: "[16px]", +}); + +const variantColumn = css({ + display: "flex", + flexDirection: "column", + gap: "[12px]", + flex: "[0 1 360px]", + minWidth: "0", +}); + +const exampleLabel = css({ + textStyle: "sm", + fontWeight: "medium", + color: "fg.muted", + marginBottom: "1.5", + textTransform: "capitalize", +}); + +const Example = ({ + name, + children, +}: { + name: string; + children: React.ReactNode; +}) => ( +
+
{name}
+ {children} +
+); + +// Edge-to-edge custom content for the `withPadding={false}` example. +const customStripe = css({ + height: "[56px]", + borderTopRadius: "[calc(token(radii.xl) - 1px)]", + background: + "[linear-gradient(135deg, var(--colors-blue-s90), var(--colors-purple-s90))]", +}); + +const customBody = css({ + display: "flex", + flexDirection: "column", + gap: "[2px]", + padding: "[12px]", +}); + +const customTitle = css({ + fontWeight: "semibold", + color: "fg.heading", +}); + +const customDescription = css({ + color: "fg.muted", +}); + +const titlePart = ( + +); +const bodyPart = ( + Version 3 of the Person type is now live. +); +const actionsPart = ; + +/** + * Every composition, rendered directly into the page: the title/body/actions + * combinations, the full toast for each tone × variant, and `withPadding` + * disabled. All toasts are persistent, so the story is stable for visual + * snapshots. + */ +export const Default: Story = { + render: () => ( +
+
+
Content combinations
+
+ + + + + + + {titlePart} + + + + + + + + {bodyPart} + + + + {titlePart} + {bodyPart} + + + + + {titlePart} + {actionsPart} + + + + + {bodyPart} + {actionsPart} + + + + + {titlePart} + {bodyPart} + {actionsPart} + + +
+
+ +
+
Tone × variant
+
+ {toastVariants.map((variant) => ( +
+
{variant}
+ {toastTones.map((tone) => ( + + + + ))} +
+ ))} +
+
+ +
+
Without padding
+
+ + + {({ close }) => ( +
+
+
+
Fresh coat of paint
+
+ Fully custom children — the toast only provides the card. +
+ +
+
+ )} + + +
+
+ +
+
Custom width
+
+ + + + + + +
+
+ +
+
Overflowing
+
+ + + + + The property + ORGANIZATION_MEMBERSHIP_ROLE_ASSIGNMENT_CONSTRAINT_VIOLATION + exceeded the allowed nesting depth. + + + + + + + + + + +
+
+
+ ), +}; + +/* ------------------------------------------------------------------ */ +/* Interactive: buttons that create a toast */ +/* ------------------------------------------------------------------ */ + +const positions = [ + "top-start", + "top", + "top-end", + "bottom-start", + "bottom", + "bottom-end", +] as const satisfies readonly Position[]; + +const buttonColumn = css({ + display: "flex", + flexDirection: "column", + alignItems: "flex-start", + gap: "2", +}); + +const buttonRow = css({ + display: "flex", + flexWrap: "wrap", + alignItems: "center", + gap: "2", +}); + +const rowLabel = css({ + textStyle: "sm", + fontWeight: "medium", + color: "fg.muted", + width: "[72px]", +}); + +type QueuedToast = { + key: number; + title: string; + body: string; + actions?: React.ReactNode; + options: Partial>; +}; + +const InteractiveDemo = () => { + const [queued, setQueued] = useState([]); + const nextKeyRef = useRef(0); + + const fire = (toast: Omit) => { + nextKeyRef.current += 1; + // Captured eagerly: the updater runs later, when batched fires would all + // read the same final ref value. + const key = nextKeyRef.current; + setQueued((previous) => [...previous, { ...toast, key }]); + }; + + const removeToast = (key: number) => { + setQueued((previous) => previous.filter((toast) => toast.key !== key)); + }; + + return ( +
+
+ Position + {positions.map((position) => ( + + ))} +
+
+ Closes on + + +
+
+ Actions + + +
+
+ Duration + + +
+ {queued.map( + ({ key, title: toastTitle, body: toastBody, actions, options }) => ( + { + if (status === "exit") { + removeToast(key); + } + }} + /> + ), + )} +
+ ); +}; + +/** + * The lifecycle options, each fired from a button into the real + * viewport-anchored regions: placement, dismissal affordances, and duration. + */ +export const Interactive: Story = { + render: () => ( + + + + ), +}; diff --git a/libs/@hashintel/ds-components/src/components/Toast/toast.tsx b/libs/@hashintel/ds-components/src/components/Toast/toast.tsx new file mode 100644 index 00000000000..2a6fdfc52b2 --- /dev/null +++ b/libs/@hashintel/ds-components/src/components/Toast/toast.tsx @@ -0,0 +1,505 @@ +import { Toast as ArkToast, useToastContext } from "@ark-ui/react/toast"; +import { + useCallback, + useContext, + useEffect, + useId, + useRef, + useState, +} from "react"; + +import { cx } from "@hashintel/ds-helpers/css"; + +import { defaultToneIcon } from "../../util/default-tone-icon"; +import { Button, type ButtonProps } from "../Button/button"; +import { Icon, type IconName } from "../Icon/icon"; +import { LoadingSpinner } from "../Loading/loading-spinner"; +import { styles, type ToastVariant } from "./toast.recipe"; +import { + ToastInstanceContext, + ToastToneContext, + useToasterContext, +} from "./toaster-context"; + +import type { Tone } from "../../util/form-shared"; +import type { Position } from "../Tooltip/base-tooltip"; +import type { ToastPlacement } from "@ark-ui/react/toast"; +import type { ExclusifyUnion } from "type-fest"; + +export type ToastShouldCloseOn = "closeButton" | "none"; + +/** + * A lifecycle status reported through `onStatusChange`: `enter` when the toast + * becomes visible, `behind` when a newer toast pushes it behind the front of + * its stack, `front` when it returns to the front, and `exit` once it has + * fully left. + */ +export type ToastStatus = "enter" | "exit" | "behind" | "front"; + +export type ToastStatusChangeDetails = { + /** The status the toast moved to. */ + status: ToastStatus; +}; + +/** What the function form of `children` receives. */ +export type ToastRenderDetails = { + /** Dismisses the toast, playing its exit animation. */ + close: () => void; +}; + +export type ToastTitleProps = ExclusifyUnion< + | { + /** The toast's heading. */ + title?: React.ReactNode; + /** + * The leading icon: `true` for the tone's default icon, `false` for + * none, a named design-system icon, or arbitrary custom content. + * Ignored while `loading` is set. + */ + icon?: boolean | { iconName: IconName } | { custom: React.ReactNode }; + /** Whether to show a spinner in the icon slot. */ + loading?: boolean; + className?: string; + } + | { + /** Custom title-row content, replacing the structured title layout. */ + children?: React.ReactNode; + className?: string; + } +>; + +export type ToastBodyProps = { + /** The toast's main message. */ + children: React.ReactNode; + className?: string; +}; + +export type ToastActionsProps = { + /** The action buttons for responding to the toast. */ + actions?: React.ReactNode; +}; + +const renderIcon = ( + icon: boolean | { iconName: IconName } | { custom: React.ReactNode }, + tone: Tone, + classes: ReturnType, +): React.ReactNode => { + if (!icon) { + return null; + } + if (icon === true) { + return ( + + ); + } + if ("iconName" in icon) { + return ; + } + return icon.custom; +}; + +// The parts are exported (beyond the `Toast.*` members) so react-docgen picks +// up their props for the published docs tables. +export const ToastTitle = (props: ToastTitleProps) => { + const { title, icon = true, loading, className, children } = props; + // The tone lives on the `Toast` root; the toaster provides it where the + // content renders so `icon`'s tone default can resolve here. + const tone = useContext(ToastToneContext); + const classes = styles({ tone }); + + if (children !== undefined) { + return ( + + {children} + + ); + } + + const iconNode = loading ? ( + + ) : ( + renderIcon(icon, tone, classes) + ); + + return ( +
+ {iconNode && ( + + )} + {title} +
+ ); +}; + +export const ToastBody = ({ children, className }: ToastBodyProps) => { + const classes = styles(); + return ( + + {children} + + ); +}; + +export type ToastActionProps = ButtonProps & { + /** + * Whether activating the action also dismisses the toast. A promise + * returned from `onClick` defers the dismissal until it resolves — the + * button shows its loading state and the toast cannot time out meanwhile — + * and a rejection keeps the toast open with its timer restarted. + * `event.preventDefault()` in `onClick` cancels the dismissal. + */ + closeToast?: boolean; + /** + * Called when the action is activated. With `closeToast`, a returned + * promise defers the dismissal until it resolves. + */ + onClick?: ( + event: React.MouseEvent, + ) => void | Promise; +}; + +type ToastActionButtonProps = Omit; + +const isThenable = (value: unknown): value is PromiseLike => + typeof value === "object" && + value !== null && + typeof (value as { then?: unknown }).then === "function"; + +const ToastActionButton = ({ + variant, + className, + ...props +}: ToastActionButtonProps) => ( +