Toast unstable
A stack of short notifications that the app posts to and that leave on their own after a timeout.
ToastProvider is headless: it keeps the toast list in its own Model, owns
the timers, the stacking variables, the data attributes and the ARIA, and
the consumer draws the markup. The list is the provider's and not a prop,
because a closing toast stays on screen with its content until its exit
transition ends, after the app has stopped caring about it.
Any update below the provider adds, updates and closes toasts by
sending requests to it with $.send(ToastProvider, message):
{ _tag: "RequestedAdd", toast }showstoast. The sender picks itsid, so it can update or close it later. A toast with anidthat already shows is replaced, and its timer starts again.{ _tag: "RequestedUpdate", id, ...changes }changes the fields it names on a toast that shows. A toast that has closed stays closed.{ _tag: "RequestedClose", id }closes a toast.
When the user closes a toast, with the close part, Escape, a swipe or its
timeout, the provider emits Dismissed with its id.
A toast that is loading, then done, is a RequestedAdd with
type: "loading" when the work starts, and a RequestedUpdate with the
same id when its result arrives. A loading toast never times out.
Anatomy
| Part | Element |
|---|---|
viewport |
<div>, the landmark region that holds the toasts |
root |
<div>, one toast |
content |
<div> inside the root, for the visible content |
title |
any element, the toast's label |
description |
any element, the toast's description |
action |
<button> for the consumer's own action |
close |
<button> that closes the toast |
viewport takes the consumer's builder. Every other part takes
{ element, toast }, with a toast from the parts' toasts, and returns
the builder for the consumer to chain on and fill:
toastProvider.title({ element: h.strong, toast }).children(toast.title). root sets
the element's key to the toast's id, so a toast keeps its element as
the list changes. The viewport adds, after the consumer's children, a
visually hidden assertive live region that announces high-priority
toasts.
Data attributes
Each present with an empty value or absent, except data-type, which
holds the toast's type, and data-swipe-direction, which holds the
direction a swipe dismissed the toast in:
viewport:data-expandedroot:data-expanded,data-limited,data-type,data-starting-style,data-ending-style,data-swiping,data-swipe-directioncontent:data-expanded,data-behindtitle,description,action,close:data-type
The stack is expanded while the pointer is on the viewport or keyboard
focus is in it. Tapping a toast also expands the stack when at least two
non-closing toasts fit within limit. Touching outside the viewport or
dropping below two ends tap expansion; hover or keyboard focus can
still hold the stack open. Tapping a button, link, form control or
element marked data-swipe-ignore doesn't expand it, nor does tapping a
toast whose root is marked.
data-behind marks the content of every toast but the front one.
data-limited marks a toast past the provider's limit, which is also
inert.
root sets --toast-index, the toast's place from the front,
--toast-offset-y, the height of the toasts in front of it, and
--toast-height, its own height, once measured. viewport sets
--toast-frontmost-height. They are added after the consumer's inline
style.
Swiping
With swipeDirections on the provider, a toast follows a drag from a
finger, a pen or the primary mouse button, locked to the axis it first
moves 6px along. Released in an allowed direction, it dismisses once it
has moved swipeDistance px (40 by default), or 10px while still moving
at swipeVelocity px/ms (0.5 by default). Any other release, or a
cancelled drag, puts it back. Buttons, links, form controls and anything
with data-swipe-ignore, the root included, never start a drag. A drag
pauses the timers, as hovering does.
While dragging, the root has data-swiping, inline transition: none,
and --toast-swipe-movement-x or --toast-swipe-movement-y in px, for
example translate: var(--toast-swipe-movement-x, 0px) var(--toast-swipe-movement-y, 0px). A dismissing swipe keeps the
movement and sets data-swipe-direction, so the exit can continue that
way. The root's touch-action leaves the browser the pan along the axis
no direction uses.
Keyboard
F6 enters the viewport while it holds a toast. F6 again returns focus to the page. Shift+Tab or Escape does the same when the viewport itself has focus. Tab moves through toast roots and buttons; Escape closes the focused toast.
When a focused toast closes, focus moves to the next toast, or the previous toast if none follows. Tab and Shift+Tab skip closing toasts in the direction of travel. With no toast to move to, focus returns to its previous position on the page. If that position is unavailable, focus leaves the viewport so the stack can collapse.
Timers
A toast closes after its timeout, or the provider's, 5000 ms by
default. 0 and type: "loading" turn it off. Every timer pauses
while the stack is expanded, the window doesn't have focus or the page is
hidden, and starts again from the full timeout when it resumes. A toast
added while paused waits for the resume.
Layering
The viewport is a manual popover, shown while the provider is drawn, so
it sits in the top layer above the page. When a Dialog shows, the
viewport shows itself again to stay in front of it, so its toasts can be
pressed while a modal is open. z-index on the viewport has no effect.
The browser gives a popover its own box: position: fixed, inset: 0,
margin: auto, a border, padding, overflow: auto and the Canvas
colors. The viewport keeps that box, so its CSS places it, for example
inset: auto 1rem 1rem auto; margin: 0; border: 0; padding: 0; background: none; overflow: visible.
With topLayer: false on the provider, the viewport is no popover: it is
an ordinary element where the view draws it, so an ancestor's overflow,
position: relative and stacking context apply to it, and its CSS
places it inside that ancestor, for example
.card { position: relative } .toasts { position: absolute; inset: auto 0.5rem 0.5rem auto }.
It has no box from the browser, isn't kept above dialogs, and z-index
on it works as on any other element. A Dialog with modal: true hides
it from screen readers along with the rest of the page, and its layer
takes the presses meant for it.
Limits
Toasts anchored to another element aren't supported. For feedback beside
a control, such as "Copied", open that control's Tooltip from the
Model. Code outside the component tree, such as an Effect service, posts
toasts with the Toaster service instead.
Example A save button that shows a toast
import { UiSchema } from "effect/ui"import { Html, HtmlServer } from "effect/ui/html"import { ToastProvider } from "effect/ui/kit"import { Effect, Schema } from "effect"
const EditorMessage = UiSchema.TaggedEnum({ ClickedSave: {} })
// Any component below the provider can send to it.const Editor = Html.component({ name: "Editor", model: Schema.Null, message: EditorMessage}).make({ init: () => null, update: { ClickedSave: ($) => $.send(ToastProvider, { _tag: "RequestedAdd", toast: { id: "saved", title: "Saved", type: "success" } }) }, view: (h) => h.button.on("click", EditorMessage.ClickedSave()).children("Save")})
const App = Html.component({ name: "App", model: Schema.Null, message: Schema.Never}).make({ init: () => null, update: ($) => $.model, view: (h) => ToastProvider(h, { view: (toastProvider) => h.div( Editor(h, {}), toastProvider.viewport(h.div.class("toasts")).children( toastProvider.toasts.map((toast) => toastProvider.root({ element: h.div.class("toast"), toast }).children( toastProvider.title({ element: h.strong, toast }).children(toast.title), toastProvider.close({ element: h.button, toast }).children("Dismiss") ) ) ) ) })})
// The viewport is a polite live region, there before any toast.const { html } = await Effect.runPromise(HtmlServer.renderToHtml(App, {}))if (!/<div class="toasts"[^>]* aria-live="polite"/.test(html)) throw new Error("the viewport isn't a live region")Components
ToastProvider
unstableKeeps the app's toasts, and draws them with the consumer's markup where it
places the viewport. Call it once near the root with a view closure that
holds the app's body and the toasts, drawn with toastProvider.toasts and the parts.
Details
The provider shares state with the components in its closure, so any
update below it can $.send(ToastProvider, ...) a RequestedAdd,
RequestedUpdate or RequestedClose. A component that sends to it needs it
above: rendered outside the closure, it doesn't compile. The component
that renders the provider reaches it the same way, from a component
inside the closure.
The parts also return toasts, newest first, closing toasts included,
and expanded. Draw every toast in toasts, limited and closing
ones too: a toast leaves the list once its root's exit transition ends.
A message an action button sends goes to the component whose closure
draws it, and the toast's id says which toast it was.
Every provider update re-runs the closure, so put the app's body in it as one normal component, which skips the re-render when its props are equal.
The provider's attributes win over the ones the consumer set on the
builder it passes in: the ARIA and data attributes, ids, tabindex,
inert and type. That includes the ones a state leaves absent.
aria-label on the viewport is the consumer's, "Notifications" when
it sets none. The CSS variables are added after the consumer's inline
style. A handler the consumer adds to a part runs after the provider's
own.
History restore saves nothing of it: after Back, forward or a reload it
starts from init.
Signature
declare const ToastProvider: Headless<{ readonly limit?: number; readonly swipeDirections?: readonly Array<"left" | "right" | "up" | "down">; readonly swipeDistance?: number; readonly swipeVelocity?: number; readonly timeout?: number; readonly topLayer?: boolean;}, { readonly _tag: "Dismissed"; readonly id: string;}, { action: <B extends PartTarget<"button">>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<"button", [toast: ToastItem], never>, "~R">; close: <B extends PartTarget<"button">>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<"button", [toast: ToastItem], never>, "~R">; content: <B extends PartTarget<"div">>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<"div", [toast: ToastItem], never>, "~R">; description: <B extends PartTarget<string>>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<string, [toast: ToastItem], never>, "~R">; expanded: boolean; root: <B extends PartTarget<"div"> & { readonly key: (key: string) => PartTarget<"div">; }>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<"div", [toast: ToastItem], never>, "~R">; title: <B extends PartTarget<string>>(__namedParameters: { readonly element: B; readonly toast: ToastItem; }) => ReturnType<B["attr"]> & Pick<Part<string, [toast: ToastItem], never>, "~R">; toasts: readonly Array<ToastItem>; viewport: Part<"div", [], never>;}, never, { readonly _tag: "RequestedClose"; readonly id: string;} | { readonly _tag: "RequestedAdd"; readonly toast: { readonly description?: string; readonly id: string; readonly priority?: "low" | "high"; readonly timeout?: number; readonly title?: string; readonly type?: string; };} | { readonly _tag: "RequestedUpdate"; readonly description?: string; readonly id: string; readonly priority?: "low" | "high"; readonly timeout?: number; readonly title?: string; readonly type?: string;}, Shared<"ToastProvider">, {}, never, never, { readonly focused: boolean; readonly hovering: boolean; readonly swiping: readonly Array<string>; readonly tapped: boolean; readonly toasts: readonly Array<{ readonly description?: string; readonly height: number; readonly id: string; readonly priority?: "low" | "high"; readonly timeout?: number; readonly title?: string; readonly transition: "ending" | "starting" | "shown"; readonly type?: string; }>; readonly visible: boolean; readonly windowFocused: boolean;}, { readonly _tag: "RequestedClose"; readonly id: string;} | { readonly _tag: "ClickedClose"; readonly id: string;} | { readonly _tag: "PressedEscape"; readonly id: string;} | { readonly _tag: "StartedSwipe"; readonly id: string;} | { readonly _tag: "RequestedAdd"; readonly toast: { readonly description?: string; readonly id: string; readonly priority?: "low" | "high"; readonly timeout?: number; readonly title?: string; readonly type?: string; };} | { readonly _tag: "EnteredViewport";} | { readonly _tag: "LeftViewport";} | { readonly _tag: "FocusedViewport";} | { readonly _tag: "BlurredViewport";} | { readonly _tag: "TappedViewport";} | { readonly _tag: "TouchedOutside";} | { readonly _tag: "ChangedLimit";} | { readonly _tag: "FocusedWindow";} | { readonly _tag: "BlurredWindow";} | { readonly _tag: "ChangedVisibility"; readonly visible: boolean;} | { readonly _tag: "MeasuredToast"; readonly height: number; readonly id: string;} | { readonly _tag: "FinishedExit"; readonly id: string;} | { readonly _tag: "EndedSwipe"; readonly dismissed: boolean; readonly id: string;} | { readonly _tag: "CompletedWaitBeforeDismissal"; readonly id: string;} | { readonly _tag: "RequestedUpdate"; readonly description?: string; readonly id: string; readonly priority?: "low" | "high"; readonly timeout?: number; readonly title?: string; readonly type?: string;}, QueryEntries<{}, {}>>Models
The content of a toast, as a sender posts it in RequestedAdd.
Signature
type ToastData = typeof ToastData.TypeA toast as the parts' toasts list it: its content, with where it is in
its life.
Details
transitionStatus:"starting"until the toast is measured after it first renders,"ending"from when it closes until its exit transition ends, andundefinedin between.limited: the toast is past the provider'slimit.
Signature
interface ToastItem extends ToastData { readonly limited: boolean; readonly transitionStatus: "ending" | "starting" | undefined;}What a ToastProvider emits.
Signature
type ToastProviderEvents = typeof ToastProviderEvents.TypeThe props of a ToastProvider.
Signature
type ToastProviderProps = typeof ToastProviderProps.TypeSchemas
The content of a toast, as a sender posts it in RequestedAdd.
Details
id: required, and picked by the sender, so a laterRequestedUpdateorRequestedClosecan name the toast. Build it from domain data, such assave-${note.id}.titleanddescription: the text the consumer draws, and the toast's accessible name and description.type: any string, shown asdata-typeon the parts, for the consumer's styles and icons."loading"never times out.timeout: milliseconds before the toast closes on its own, the provider'stimeoutby default.0keeps it until it's closed.priority:"high"announces the toast at once, in an assertive live region, and makes the root analertdialog."low", the default, waits for the screen reader to be idle.
Signature
declare const ToastData: Struct<{ readonly description: optional<String>; readonly id: String; readonly priority: optional<Literals<readonly ["low", "high"]>>; readonly timeout: optional<Number>; readonly title: optional<String>; readonly type: optional<String>;}>ToastProviderEvents
unstableDismissed reports that the user closed the toast id, with its close
part, Escape or a swipe, or that its timeout ran out. A RequestedClose sent to the
provider emits nothing. Handling it is optional.
Signature
declare const ToastProviderEvents: TaggedEnum<{ Dismissed: TaggedStruct<"Dismissed", { readonly id: String; }>;}>ToastProviderProps
unstableThe props of a ToastProvider.
Details
timeout: milliseconds before a toast without its owntimeoutcloses, 5000 by default.0keeps toasts until they're closed.limit: how many toasts show at once, 3 by default. The older ones stay in the list, markedlimitedandinert, until newer ones close.topLayer:falsedraws the viewport in place, as an ordinary element where the view puts it, instead of as a popover in the top layer, as the module's Layering describes.truewhen left out.swipeDirections: the directions a swipe dismisses a toast in, as the module's Swiping describes. Left out or empty, toasts don't swipe.swipeDistance: dismissal distance in px, 40 by default.swipeVelocity: release speed threshold in px/ms (default 0.5). Dismisses belowswipeDistanceafter at least 10px of movement.
Signature
declare const ToastProviderProps: Struct<{ readonly limit: optional<Number>; readonly swipeDirections: optional<$Array<Literals<readonly ["up", "down", "left", "right"]>>>; readonly swipeDistance: optional<Number>; readonly swipeVelocity: optional<Number>; readonly timeout: optional<Number>; readonly topLayer: optional<Boolean>;}>