# Toast

A stack of short notifications that any component below the provider posts to, and that leave on their own.

- Page: https://www.effectcn.com/components/toast
- Kind: Headless component with parts
- File: `src/ui/toast.ts`
- Built on: `Toast` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/toast.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/toast.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { ToastItem, ToastProvider } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the `view` closure of the kit's `ToastProvider` receives. */
export type ToastProviderParts = Component.Headless.Parts<typeof ToastProvider>

const positions = {
  "top-left": "inset-[1rem_auto_auto_1rem] [--toast-direction:1]",
  "top-center": "inset-[1rem_0_auto_0] mx-auto [--toast-direction:1]",
  "top-right": "inset-[1rem_1rem_auto_auto] [--toast-direction:1]",
  "bottom-left": "inset-[auto_auto_1rem_1rem] [--toast-direction:-1]",
  "bottom-center": "inset-[auto_0_1rem_0] mx-auto [--toast-direction:-1]",
  "bottom-right": "inset-[auto_1rem_1rem_auto] [--toast-direction:-1]"
} as const

export type ToastPosition = keyof typeof positions

type ClassOption = { readonly class?: string | undefined }

/**
 * The region that holds the stack. The kit makes it a popover in the top
 * layer, so these classes clear the browser's popover box and pin it to a
 * corner. With `topLayer: false` on the provider it is an ordinary element:
 * pass `class: "absolute"` to place it inside a `relative` ancestor.
 */
export const ToastViewport = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  options: ClassOption & { readonly position?: ToastPosition | undefined } = {}
) => {
  const position = options.position ?? "bottom-right"
  return toastProvider.viewport(
    h.div
      .class(cn(
        "group/toasts fixed m-0 h-[var(--toast-frontmost-height,0px)] w-[356px] max-w-[calc(100vw-2rem)] overflow-visible",
        "border-0 bg-transparent p-0 text-foreground outline-none [--toast-gap:10px] [--toast-peek:12px]",
        positions[position],
        options.class
      ))
      .attr("data-side", position.startsWith("top") ? "top" : "bottom")
  )
}

/**
 * One toast. Collapsed, the toasts sit behind the front one and peek out;
 * while the pointer or keyboard focus is on the stack they fan out, each
 * moved by the heights the kit measured.
 */
export const Toast = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider.root({
    element: h.div.class(cn(
      "absolute inset-x-0 bottom-0 z-[calc(100_-_var(--toast-index,0))] box-border origin-bottom rounded-md border",
      "h-[var(--toast-frontmost-height,auto)] bg-popover text-[13px] leading-snug text-foreground shadow-float",
      "group-data-[side=top]/toasts:top-0 group-data-[side=top]/toasts:bottom-auto group-data-[side=top]/toasts:origin-top",
      "translate-y-[calc(var(--toast-index,0)_*_var(--toast-peek)_*_var(--toast-direction))]",
      "scale-[calc(1_-_var(--toast-index,0)_*_0.05)]",
      "transition-[translate,scale,opacity,height] duration-200 ease-out",
      // Fills the gap between two toasts, so the pointer stays on the stack.
      "after:absolute after:inset-x-0 after:-inset-y-[var(--toast-gap)] after:-z-10 after:content-['']",
      "data-[expanded]:h-[var(--toast-height,auto)] data-[expanded]:scale-100",
      "data-[expanded]:translate-y-[calc((var(--toast-offset-y,0px)_+_var(--toast-index,0)_*_var(--toast-gap))_*_var(--toast-direction))]",
      "data-[starting-style]:translate-y-[calc(var(--toast-direction)_*_-24px)] data-[starting-style]:opacity-0",
      "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
      "data-[limited]:pointer-events-none data-[limited]:opacity-0",
      options.class
    )),
    toast
  })

/** The visible content of a toast, hidden while the toast sits behind the front one. */
export const ToastContent = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider.content({
    element: h.div.class(cn(
      "flex h-full items-start gap-2.5 overflow-hidden rounded-[inherit] bg-popover px-3.5 py-3",
      "transition-opacity duration-200 data-[behind]:not-data-[expanded]:opacity-0",
      options.class
    )),
    toast
  })

/** The column that holds the title and the description. */
export const ToastText = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("grid min-w-0 flex-1 gap-0.5", options.class))

export const ToastTitle = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider.title({ element: h.div.class(cn("font-medium", options.class)), toast }).children(toast.title)

export const ToastDescription = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider
    .description({ element: h.div.class(cn("text-muted-foreground", options.class)), toast })
    .children(toast.description)

/** A button for the consumer's own action. Chain `.on("click", message)` and the label. */
export const ToastAction = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider.action({
    element: h.button.class(cn(
      "inline-flex h-6.5 shrink-0 items-center self-center rounded-sm bg-primary px-2.5 text-xs font-medium",
      "text-primary-foreground transition-opacity duration-150 hover:opacity-85",
      options.class
    )),
    toast
  })

export const ToastClose = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  toast: ToastItem,
  options: ClassOption = {}
) =>
  toastProvider
    .close({
      element: h.button
        .class(cn(
          "-mt-0.5 -mr-1 inline-flex size-5.5 shrink-0 items-center justify-center rounded-sm text-muted-foreground",
          "transition-colors duration-150 hover:bg-accent hover:text-foreground",
          options.class
        ))
        .attr("aria-label", "Close"),
      toast
    })
    .children(
      h.el("svg")
        .attrs({
          class: "size-3.5",
          viewBox: "0 0 24 24",
          fill: "none",
          stroke: "currentColor",
          "stroke-width": "2",
          "stroke-linecap": "round",
          "aria-hidden": "true"
        })
        .children(h.el("path").attr("d", "M6 6l12 12M18 6 6 18"))
    )

const icons: Record<string, { readonly class: string; readonly path: string }> = {
  success: { class: "text-success", path: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20ZM8.5 12.5 11 15l4.5-5.5" },
  error: { class: "text-destructive", path: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20ZM15 9l-6 6M9 9l6 6" },
  warning: {
    class: "text-warning",
    path: "M10.3 3.9 2.4 17.5a2 2 0 0 0 1.7 3h15.8a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0ZM12 9v4M12 16.5h.01"
  },
  info: { class: "text-muted-foreground", path: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20ZM12 16v-4.5M12 8h.01" }
}

/** An icon for the toast's `type`: success, error, warning, info, or a spinner for loading. Nothing for any other. */
export const ToastIcon = <Msg>(h: Html.H<Msg>, toast: ToastItem, options: ClassOption = {}) => {
  if (toast.type === "loading") {
    return h.span
      .class(cn(
        "mt-px size-4 shrink-0 animate-spin rounded-full border-2 border-muted-foreground border-r-transparent",
        options.class
      ))
      .attr("aria-hidden", "true")
  }
  const icon = toast.type === undefined ? undefined : icons[toast.type]
  return icon === undefined ? undefined : h.el("svg")
    .attrs({
      class: cn("mt-px size-4 shrink-0", icon.class, options.class),
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      "aria-hidden": "true"
    })
    .children(h.el("path").attr("d", icon.path))
}

/**
 * The whole stack with the usual toast: icon, title, description and a close
 * button. Draw it once inside the provider's `view` closure, next to the app:
 * `ToastProvider(h, { view: (toastProvider) => h.div(App(h, {}), Toaster(h, toastProvider)) })`.
 * For a toast with other content, compose the parts above yourself.
 */
export const Toaster = <Msg>(
  h: Html.H<Msg>,
  toastProvider: ToastProviderParts,
  options: ClassOption & { readonly position?: ToastPosition | undefined } = {}
) =>
  ToastViewport(h, toastProvider, options).children(
    toastProvider.toasts.map((toast) =>
      Toast(h, toastProvider, toast).children(
        ToastContent(h, toastProvider, toast).children(
          ToastIcon(h, toast),
          ToastText(h).children(
            ToastTitle(h, toastProvider, toast),
            toast.description !== undefined && ToastDescription(h, toastProvider, toast)
          ),
          toast.type !== "loading" && ToastClose(h, toastProvider, toast)
        )
      )
    )
  )
```

```ts
import { ToastViewport, Toast, ToastContent, ToastText, ToastTitle, ToastDescription, ToastAction, ToastClose, ToastIcon, Toaster } from "#ui/toast"
```

## Usage

A component below the provider sends RequestedAdd from its update. The toast closes after 5 seconds.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const ToastBasicTriggerMessage = UiSchema.TaggedEnum({ PressedAddToCalendar: {} })

// A sender sits below the provider and posts to it from `update`.
const ToastBasicTrigger = Html.component({
  name: "ToastBasicTrigger",
  model: Schema.Struct({ scheduled: Schema.Number }),
  message: ToastBasicTriggerMessage
}).make({
  init: () => ({ scheduled: 0 }),
  update: {
    PressedAddToCalendar: ($) =>
      $.evolve({ scheduled: (scheduled) => scheduled + 1 }).send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: {
          id: `event-${$.model.scheduled}`,
          title: "Event has been created",
          description: "Sunday, December 3 at 9:00 AM"
        }
      })
  },
  view: (h) =>
    Button(h, { variant: "outline", onPress: ToastBasicTriggerMessage.PressedAddToCalendar() }).children(
      "Add to calendar"
    )
})

export const ToastBasic = Html.component({
  name: "ToastBasic",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ToastProvider(h, {
      view: (toastProvider) => h.div(ToastBasicTrigger(h, {}), Toaster(h, toastProvider))
    })
})
```

## Examples

### Types

The toast's type shows as data-type on every part, here for the icon. The error is a high-priority alert.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const ToastTypesTriggersMessage = UiSchema.TaggedEnum({
  PressedType: { type: Schema.String }
})

const toasts: Record<string, { readonly title: string; readonly description: string }> = {
  success: { title: "Changes saved", description: "Your profile is up to date." },
  info: { title: "New version available", description: "Reload the page to update." },
  warning: { title: "Storage almost full", description: "You have used 92% of your quota." },
  error: { title: "Couldn't send message", description: "Check your connection and try again." }
}

const ToastTypesTriggers = Html.component({
  name: "ToastTypesTriggers",
  model: Schema.Struct({}),
  message: ToastTypesTriggersMessage
}).make({
  init: () => ({}),
  update: {
    // `type` is any string, and shows as data-type on every part. An error is
    // worth interrupting for, so it is announced at once.
    PressedType: ($, { type }) =>
      $.send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: { id: type, type, priority: type === "error" ? "high" : "low", ...toasts[type] }
      })
  },
  view: (h) =>
    h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
      Object.keys(toasts).map((type) =>
        Button(h, { variant: "outline", onPress: ToastTypesTriggersMessage.PressedType({ type }) }).children(
          type[0]!.toUpperCase() + type.slice(1)
        )
      )
    )
})

export const ToastTypes = Html.component({
  name: "ToastTypes",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ToastProvider(h, {
      view: (toastProvider) => h.div(ToastTypesTriggers(h, {}), Toaster(h, toastProvider))
    })
})
```

### With an action

Composed from the parts instead of Toaster: Undo restores the file and closes the toast.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toast, ToastAction as ToastActionButton, ToastContent, ToastText, ToastTitle, ToastViewport } from "#ui/toast"

const ToastActionFilesMessage = UiSchema.TaggedEnum({ PressedDelete: { file: Schema.String } })

const ToastActionFilesEvents = UiSchema.TaggedEnum({ Deleted: { file: Schema.String } })

const ToastActionFiles = Html.component({
  name: "ToastActionFiles",
  props: Schema.Struct({ files: Schema.Array(Schema.String) }),
  model: Schema.Struct({}),
  message: ToastActionFilesMessage,
  events: ToastActionFilesEvents
}).make({
  init: () => ({}),
  update: {
    PressedDelete: ($, { file }) =>
      $.send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: { id: file, title: `Moved ${file} to the bin`, timeout: 8000 }
      }).emit(ToastActionFilesEvents.Deleted({ file }))
  },
  view: (h) =>
    h.props.files.length === 0
      ? h.p.class("text-xs text-muted-foreground").children("Nothing left to delete.")
      : h.ul.class("grid w-72 gap-1.5").children(
        h.props.files.map((file) =>
          h.li.key(file).class("flex items-center justify-between gap-3 rounded-md border py-1 pr-1 pl-3 text-[13px]")
            .children(
              file,
              Button(h, { variant: "ghost", size: "sm", onPress: ToastActionFilesMessage.PressedDelete({ file }) })
                .children("Delete")
            )
        )
      )
})

const ToastActionMessage = UiSchema.TaggedEnum({
  DeletedFile: { file: Schema.String },
  ClickedUndo: { file: Schema.String }
})

const files = ["invoice.pdf", "notes.md", "photo.png"]

export const ToastAction = Html.component({
  name: "ToastAction",
  model: Schema.Struct({ deleted: Schema.Array(Schema.String) }),
  message: ToastActionMessage
}).make({
  init: () => ({ deleted: [] }),
  update: {
    DeletedFile: ($, { file }) => $.evolve({ deleted: (deleted) => [...deleted, file] }),
    ClickedUndo: ($, { file }) => $.evolve({ deleted: (deleted) => deleted.filter((other) => other !== file) })
  },
  view: (h, model) =>
    ToastProvider(h, {
      view: (toastProvider) =>
        h.div(
          ToastActionFiles(h, {
            props: { files: files.filter((file) => !model.deleted.includes(file)) },
            onEmit: { Deleted: ({ file }) => ToastActionMessage.DeletedFile({ file }) }
          }),
          ToastViewport(h, toastProvider).children(
            toastProvider.toasts.map((toast) =>
              Toast(h, toastProvider, toast).children(
                ToastContent(h, toastProvider, toast, { class: "items-center" }).children(
                  ToastText(h).children(ToastTitle(h, toastProvider, toast)),
                  // Stacking `close` on the action closes the toast, and the
                  // consumer's own handler runs after the provider's.
                  toastProvider
                    .close({ element: ToastActionButton(h, toastProvider, toast), toast })
                    .on("click", ToastActionMessage.ClickedUndo({ file: toast.id }))
                    .children("Undo")
                )
              )
            )
          )
        )
    })
})
```

### Loading, then done

A loading toast stays until a RequestedUpdate with the same id gives it its result.

```ts
import { Command, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Effect, Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const ToastPromiseUploadMessage = UiSchema.TaggedEnum({
  PressedUpload: { fails: Schema.Boolean },
  SucceededUploadReport: { id: Schema.String },
  FailedUploadReport: { id: Schema.String }
})

const UploadReport = Command.make(
  "UploadReport",
  { args: { id: Schema.String, fails: Schema.Boolean } },
  ({ fails, id }) =>
    Effect.sleep("2 seconds").pipe(
      Effect.as(
        fails
          ? ToastPromiseUploadMessage.FailedUploadReport({ id })
          : ToastPromiseUploadMessage.SucceededUploadReport({ id })
      )
    )
)

const ToastPromiseUpload = Html.component({
  name: "ToastPromiseUpload",
  model: Schema.Struct({ uploads: Schema.Number }),
  message: ToastPromiseUploadMessage
}).make({
  init: () => ({ uploads: 0 }),
  update: {
    // A loading toast never times out. The update below gives it a type
    // that does, and its timer starts then.
    PressedUpload: ($, { fails }) => {
      const id = `upload-${$.model.uploads}`
      return $.evolve({ uploads: (uploads) => uploads + 1 })
        .send(ToastProvider, {
          _tag: "RequestedAdd",
          toast: { id, type: "loading", title: "Uploading report.pdf…" }
        })
        .run(UploadReport.make({ id, fails }))
    },
    SucceededUploadReport: ($, { id }) =>
      $.send(ToastProvider, {
        _tag: "RequestedUpdate",
        id,
        type: "success",
        title: "Report uploaded",
        description: "report.pdf is in Documents."
      }),
    FailedUploadReport: ($, { id }) =>
      $.send(ToastProvider, {
        _tag: "RequestedUpdate",
        id,
        type: "error",
        title: "Upload failed",
        description: "The server didn't answer in time."
      })
  },
  view: (h) =>
    h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
      Button(h, { variant: "outline", onPress: ToastPromiseUploadMessage.PressedUpload({ fails: false }) }).children(
        "Upload"
      ),
      Button(h, { variant: "outline", onPress: ToastPromiseUploadMessage.PressedUpload({ fails: true }) }).children(
        "Upload and fail"
      )
    )
})

export const ToastPromise = Html.component({
  name: "ToastPromise",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ToastProvider(h, {
      view: (toastProvider) => h.div(ToastPromiseUpload(h, {}), Toaster(h, toastProvider))
    })
})
```

### Positions

The viewport is placed by its classes, so the position option moves the stack to any corner.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const Position = Schema.Literals([
  "top-left",
  "top-center",
  "top-right",
  "bottom-left",
  "bottom-center",
  "bottom-right"
])

const ToastPositionsTriggerMessage = UiSchema.TaggedEnum({ PressedShow: {} })

const ToastPositionsTrigger = Html.component({
  name: "ToastPositionsTrigger",
  props: Schema.Struct({ position: Position }),
  model: Schema.Struct({ shown: Schema.Number }),
  message: ToastPositionsTriggerMessage
}).make({
  init: () => ({ shown: 0 }),
  update: {
    PressedShow: ($) =>
      $.evolve({ shown: (shown) => shown + 1 }).send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: {
          id: `copied-${$.model.shown}`,
          title: "Copied to clipboard",
          description: `Shown at ${$.props.position}.`
        }
      })
  },
  view: (h) => Button(h, { onPress: ToastPositionsTriggerMessage.PressedShow() }).children("Show toast")
})

const ToastPositionsMessage = UiSchema.TaggedEnum({ PressedPosition: { position: Position } })

export const ToastPositions = Html.component({
  name: "ToastPositions",
  model: Schema.Struct({ position: Position }),
  message: ToastPositionsMessage
}).make({
  init: () => ({ position: "top-center" }),
  update: {
    PressedPosition: ($, { position }) => $.evolve({ position })
  },
  view: (h, model) =>
    ToastProvider(h, {
      view: (toastProvider) =>
        h.div.class("flex flex-col items-center gap-4").children(
          h.div.class("grid grid-cols-3 gap-1").attrs({ role: "group", "aria-label": "Position" }).children(
            Position.literals.map((position) =>
              Button(h, {
                variant: position === model.position ? "secondary" : "ghost",
                size: "sm",
                onPress: ToastPositionsMessage.PressedPosition({ position })
              })
                .attr("aria-pressed", String(position === model.position))
                .children(position)
            )
          ),
          ToastPositionsTrigger(h, { props: { position: model.position } }),
          Toaster(h, toastProvider, { position: model.position })
        )
    })
})
```

### Stacked

Toasts that never time out, four at a time. The stack expands under the pointer or keyboard focus.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const ToastStackedTriggersMessage = UiSchema.TaggedEnum({ PressedAdd: {}, PressedClear: {} })

const subjects = ["Design review", "Lunch with Ada", "Release notes", "Standup", "Invoice #204"]

const ToastStackedTriggers = Html.component({
  name: "ToastStackedTriggers",
  model: Schema.Struct({ added: Schema.Number }),
  message: ToastStackedTriggersMessage
}).make({
  init: () => ({ added: 0 }),
  update: {
    PressedAdd: ($) =>
      $.evolve({ added: (added) => added + 1 }).send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: {
          id: `reminder-${$.model.added}`,
          title: subjects[$.model.added % subjects.length]!,
          description: `Reminder ${$.model.added + 1}`
        }
      }),
    // One send per toast. Closing one that has already gone does nothing.
    PressedClear: ($) =>
      Array.from({ length: $.model.added }, (_, index) => `reminder-${index}`).reduce(
        (step, id) => step.send(ToastProvider, { _tag: "RequestedClose", id }),
        $.send(ToastProvider, { _tag: "RequestedClose", id: "reminder-0" }).evolve({ added: 0 })
      )
  },
  view: (h) =>
    h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
      Button(h, { onPress: ToastStackedTriggersMessage.PressedAdd() }).children("Add reminder"),
      Button(h, { variant: "outline", onPress: ToastStackedTriggersMessage.PressedClear() }).children("Clear all")
    )
})

export const ToastStacked = Html.component({
  name: "ToastStacked",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ToastProvider(h, {
      props: { limit: 4, timeout: 0 },
      view: (toastProvider) =>
        h.div.class("flex flex-col items-center gap-4").children(
          ToastStackedTriggers(h, {}),
          h.p.class("text-xs text-muted-foreground tabular-nums").children(
            `${toastProvider.toasts.filter((toast) => toast.transitionStatus !== "ending").length} open, ${
              toastProvider.toasts.filter((toast) => toast.limited).length
            } past the limit of 4. ${toastProvider.expanded ? "Expanded." : "Hover the stack to expand it."}`
          ),
          Toaster(h, toastProvider)
        )
    })
})
```

### In place

With topLayer: false the viewport is an ordinary element, clipped by the card it is drawn in.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToastProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Toaster } from "#ui/toast"

const ToastInPlaceTriggerMessage = UiSchema.TaggedEnum({ PressedInvite: {} })

const people = ["Ada", "Grace", "Linus", "Margaret"]

const ToastInPlaceTrigger = Html.component({
  name: "ToastInPlaceTrigger",
  model: Schema.Struct({ invited: Schema.Number }),
  message: ToastInPlaceTriggerMessage
}).make({
  init: () => ({ invited: 0 }),
  update: {
    PressedInvite: ($) =>
      $.evolve({ invited: (invited) => invited + 1 }).send(ToastProvider, {
        _tag: "RequestedAdd",
        toast: {
          id: `invite-${$.model.invited}`,
          type: "success",
          title: `Invitation sent to ${people[$.model.invited % people.length]}`
        }
      })
  },
  view: (h) => Button(h, { size: "sm", onPress: ToastInPlaceTriggerMessage.PressedInvite() }).children("Invite someone")
})

export const ToastInPlace = Html.component({
  name: "ToastInPlace",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    // With topLayer: false the viewport is no popover, so the card's
    // `relative` and `overflow-hidden` apply to it.
    ToastProvider(h, {
      props: { topLayer: false, timeout: 4000 },
      view: (toastProvider) =>
        h.section
          .class("relative flex h-60 w-full max-w-md flex-col items-start gap-1.5 overflow-hidden rounded-lg border bg-card p-4")
          .children(
            h.h3.class("text-sm font-semibold").children("Team"),
            h.p.class("mb-2 text-[13px] text-muted-foreground").children("Toasts stay inside this card."),
            ToastInPlaceTrigger(h, {}),
            Toaster(h, toastProvider, { class: "absolute inset-[auto_0.75rem_0.75rem_auto] w-[min(300px,calc(100%-1.5rem))]" })
          )
    })
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `viewport` | <div>: the landmark region that holds the toasts. A manual popover in the top layer. |
| `root` | <div>: one toast. Takes { element, toast }, as every part below, and keys the element by the toast's id. |
| `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. |
| `toasts` | The toasts to draw, newest first, closing and limited ones included. |
| `expanded` | Whether the pointer is on the viewport or keyboard focus is in it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `timeout` | `number` | Milliseconds before a toast without its own timeout closes. 5000 by default, 0 keeps toasts until they are closed. |
| `limit` | `number` | How many toasts show at once, 3 by default. Older ones stay in the list, limited and inert. |
| `topLayer` | `boolean` | false draws the viewport in place instead of as a popover in the top layer. |
| `toast.id` | `string` | Picked by the sender, so a later RequestedUpdate or RequestedClose can name the toast. |
| `toast.title / description` | `string` | The text the consumer draws, and the toast's accessible name and description. |
| `toast.type` | `string` | Any string, shown as data-type. "loading" never times out. |
| `toast.timeout` | `number` | This toast's own timeout in milliseconds. |
| `toast.priority` | `"low" \| "high"` | "high" announces the toast at once, as an alert. |

### Events

| Event | Description |
| --- | --- |
| `Dismissed` | The user closed the toast id with its close part or Escape, or its timeout ran out. |
| `$.send RequestedAdd` | { toast }: shows a toast, or replaces the one that shows with the same id. |
| `$.send RequestedUpdate` | { id, ...changes }: changes the fields it names on a toast that shows. |
| `$.send RequestedClose` | { id }: closes a toast, without a Dismissed. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-expanded` | On viewport, root and content while the stack is expanded. |
| `data-type` | On root, title, description, action and close: the toast's type. |
| `data-starting-style` | On root until the toast is first measured. |
| `data-ending-style` | On root while the toast plays its exit. |
| `data-limited` | On root: the toast is past the provider's limit. |
| `data-behind` | On content: every toast but the front one. |
| `--toast-index` | On root: the toast's place from the front. |
| `--toast-offset-y` | On root: the height of the toasts in front of it. |
| `--toast-height` | On root: its own measured height. |
| `--toast-frontmost-height` | On viewport: the front toast's height. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
