# Toast

A 3D toaster whose slice of bread is a real Toast: the lever runs your work, and the slice pops with its result. Built with [ui-sdk](https://ui-sdk.dev).

A React component for projects built on shadcn/ui. The [interactive page](https://alexandrejoly.me/lab/literal-ui/toast) shows each example live.

```tsx
import {
  Toast,
  ToastDial,
  ToastLever,
  ToastRegion,
  ToastStage,
  ToastStop,
} from "@/components/ui/toast/toast";
import { ToastAudio } from "@/components/ui/toast/toast-sound";
import { createToaster } from "@ui-sdk/react/toast";

const toaster = createToaster();

export const ToastDemo = () => (
  <Toast
    className="w-full max-w-3xl"
    onToast={() => "Toast is ready"}
    toaster={toaster}
  >
    <ToastStage>
      <ToastRegion />
      <ToastDial />
      <ToastStop />
      <ToastLever />
    </ToastStage>
    <ToastAudio />
  </Toast>
);
```

## Installation

With the shadcn CLI:

```bash
pnpm dlx shadcn@latest add @alexandrejoly/toast
```

## Usage

```tsx
import { createToaster } from "@ui-sdk/react/toast";

import {
  Toast,
  ToastDial,
  ToastLever,
  ToastRegion,
  ToastStage,
  ToastStop,
} from "@/components/ui/literal-ui/toast/toast";
import { ToastAudio } from "@/components/ui/literal-ui/toast/toast-sound";

const toaster = createToaster();
```

```tsx
<Toast onToast={() => "Toast is ready"} toaster={toaster}>
  <ToastStage>
    <ToastRegion />
    <ToastDial />
    <ToastStop />
    <ToastLever />
  </ToastStage>
  <ToastAudio />
</Toast>
```

## Examples

### Async work

`onToast` can await real work. The lever stays down until it settles: a resolved title pops as a success, and a rejection pops its message as an error, every second save here. Stop aborts `signal`.

```tsx
import {
  Toast,
  ToastDial,
  ToastLever,
  ToastRegion,
  ToastStage,
  ToastStop,
} from "@/components/ui/toast/toast";
import { ToastAudio } from "@/components/ui/toast/toast-sound";
import { createToaster } from "@ui-sdk/react/toast";
import { useRef } from "react";

const save = (signal: AbortSignal, fails: boolean) =>
  new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => {
      if (fails) {
        reject(new Error("Couldn't save changes"));
      } else {
        resolve();
      }
    }, 2500);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    });
  });

const toaster = createToaster();

export const ToastAsync = () => {
  const attempts = useRef(0);

  return (
    <Toast
      className="w-full"
      onToast={async ({ signal }) => {
        attempts.current += 1;
        await save(signal, attempts.current % 2 === 0);
        return "Changes saved";
      }}
      toaster={toaster}
    >
      <ToastStage>
        <ToastRegion />
        <ToastDial />
        <ToastStop />
        <ToastLever />
      </ToastStage>
      <ToastAudio />
    </Toast>
  );
};
```

### Controlled

Set `toasting` to start a cycle from your own code. Here the form pushes the lever down, and the slice pops with your message three seconds later. The lever, the dial and Stop still work by hand, and `onToastingChange` reports each start and each end.

```tsx
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Toast,
  ToastDial,
  ToastLever,
  ToastRegion,
  ToastStage,
  ToastStop,
} from "@/components/ui/toast/toast";
import { ToastAudio } from "@/components/ui/toast/toast-sound";
import { createToaster } from "@ui-sdk/react/toast";
import { useState } from "react";

const wait = (ms: number, signal: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    });
  });

const toaster = createToaster();

export const ToastControlled = () => {
  const [message, setMessage] = useState("");
  const [toasting, setToasting] = useState(false);

  return (
    <div className="flex w-full flex-col gap-6">
      <Toast
        className="w-full"
        onToast={async ({ signal }) => {
          await wait(3000, signal);
          return message || "Toast is ready";
        }}
        onToastingChange={setToasting}
        toaster={toaster}
        toasting={toasting}
      >
        <ToastStage>
          <ToastRegion />
          <ToastDial />
          <ToastStop />
          <ToastLever />
        </ToastStage>
        <ToastAudio />
      </Toast>
      <form
        className="flex gap-2"
        onSubmit={(event) => {
          event.preventDefault();
          setToasting(true);
        }}
      >
        <Input
          aria-label="Message"
          maxLength={20}
          onChange={(event) => setMessage(event.target.value)}
          placeholder="Good morning"
          required
          value={message}
        />
        <Button type="submit">Toast</Button>
      </form>
    </div>
  );
};
```

## API reference

### Toast

Holds the cycle, the slice and the browning level. The slice is a toast in your `toaster`.

Takes every prop of `div`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `toaster` | `Toaster` | — | From `createToaster()`. Give it to this toaster alone: every toast it holds shows in the slot. |
| `onToast` | `(cycle: ToastCycle) => ToastOutcome \| void \| Promise<ToastOutcome \| void>` | — | Runs once the catch holds the lever. Return a title for a success, or toast options such as `{ type: "error", title }`. A throw shows its message as an error. Return nothing to keep what you set with `toaster.update(id, …)`. |
| `canToast` | `() => boolean` | — | Asked as the lever reaches the catch. Return `false` and the lever springs back up. |
| `defaultLevel` | `1 \| 2 \| 3 \| 4 \| 5` | `3` | The dial's browning level: how long a cycle lasts and how much it browns the slice. |
| `level` | `1 \| 2 \| 3 \| 4 \| 5` | — | The browning level, controlled. |
| `onLevelChange` | `(level: ToastLevel) => void` | — | Runs when the dial turns to a new level. |
| `defaultToasting` | `boolean` | `false` | Starts a cycle on mount, as if the lever had been pushed down. |
| `toasting` | `boolean` | — | Whether a cycle runs, controlled. Set it to `true` to push the lever down and start a cycle, and to `false` to stop it, as Stop does. |
| `onToastingChange` | `(toasting: boolean) => void` | — | Runs when a cycle starts, by hand or from `toasting`, and when it ends, by a pop or by Stop. |
| `idleTitle` | `string` | `"Plain bread, ready to toast"` | The title of a fresh slice, for screen readers. |
| `toastingTitle` | `string` | `"Toasting…"` | The slice's title while a cycle runs. |

### ToastCycle

What `onToast` receives.

| Field | Type | Description |
| --- | --- | --- |
| `id` | `string` | The slice's toast id in your toaster. |
| `level` | `1 \| 2 \| 3 \| 4 \| 5` | The dial's level for this cycle. |
| `browning` | `number` | How toasted the slice will be once the cycle ends, from 0 to 1. Browning adds up from one cycle to the next. |
| `burnt` | `boolean` | Whether that browning reads as burnt. |
| `signal` | `AbortSignal` | Aborted when Stop ends the cycle. The slice then goes back to what it said. |

### ToastStage

The toaster in 3D, with the controls laid over its parts. It shows a still picture until the scene loads, and keeps it without WebGL 2, with the slice's title written on it.

Takes every prop of `div`.

### ToastRegion

The front slot, where the slice stands. Pull the slice up to take it out, and a fresh one drops in.

Takes every prop of [UI SDK ToastRegion](https://ui-sdk.dev/docs/react/components/toast).

### ToastDial

The browning dial. Drag up or down, or use the arrow keys.

Takes every prop of [UI SDK Slider](https://ui-sdk.dev/docs/react/components/slider).

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` | `string` | `"Browning"` | Names the dial. |

### ToastLever

The lever. Drag it down to the catch, or press Enter, Space or the Down arrow.

Takes every prop of [UI SDK Slider](https://ui-sdk.dev/docs/react/components/slider).

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` | `string` | `"Lever"` | Names the lever. |

### ToastStop

Ends the cycle early. The slice keeps its browning and its previous title.

Takes every prop of [UI SDK Button](https://ui-sdk.dev/docs/react/components/button).

### ToastAudio

Plays the toaster's recorded sounds. It renders nothing, and loads nothing until the page is pressed. Import it from `toast-sound`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `muted` | `boolean` | `false` | Silences this toaster alone. |

### ToastAudioProvider

Mutes every `ToastAudio` inside it, for a sound preference that covers the whole app or one part of it. It renders nothing of its own.

| Prop | Type | Description |
| --- | --- | --- |
| `muted` | `boolean` | Silences the toasters below. Turned off during a press, their sounds unlock at once. |

### useToastEvents

Follows what the toaster does as it happens, as `ToastAudio` does: the lever, the dial, Stop, each pop and each slice.

| Returns | Type | Description |
| --- | --- | --- |
| `subscribe` | `(listener: (event: ToastEvent) => void) => () => void` | Calls `listener` with each event. Returns the unsubscribe. |

[Back to Literal UI](https://alexandrejoly.me/lab/literal-ui.md)
