# Feedback

Toast, inline message or dialog: where a result is said depends on whether people have to do something about it.

API [Toaster](/ui/storybook/?path=/docs/ui-primitives-toaster--docs) [LoadFailure](/ui/storybook/?path=/docs/ui-loadfailure--docs) [Dialog](/ui/storybook/?path=/docs/ui-primitives-dialog--docs) [Frame](/ui/storybook/?path=/docs/ui-primitives-frame--docs) [Input](/ui/storybook/?path=/docs/ui-primitives-input--docs) [Label](/ui/storybook/?path=/docs/ui-primitives-label--docs) [Button](/ui/storybook/?path=/docs/ui-primitives-button--docs) [CopyButton](/ui/storybook/?path=/docs/ui-primitives-copybutton--docs)

**Say a result where people will act on it. A toast for something done that needs nothing more, an inline message beside whatever needs fixing, and a dialog only when nothing may go on until it is answered.**

```tsx
import { PROFILE } from "@orz/fixtures/account.ts";
import { CI_RUN } from "@orz/fixtures/ci-run.ts";
import { INBOX_THREADS } from "@orz/fixtures/inbox.ts";
import { Button } from "@orz/ui/components/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@orz/ui/components/dropdown-menu";
import { FieldDescription, FieldError } from "@orz/ui/components/field";
import { Input } from "@orz/ui/components/input";
import { Label } from "@orz/ui/components/label";
import { List, ListItem } from "@orz/ui/components/list";
import { RefreshFailure } from "@orz/ui/components/load-failure";
import { ToolbarButton } from "@orz/ui/components/toolbar";
import { EllipsisIcon, ForwardIcon, LinkIcon } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

const [thread] = INBOX_THREADS;

const check = (email: string) =>
  /^\S+@\S+\.\S+$/.test(email)
    ? undefined
    : `Enter an email address, like ${PROFILE.email}.`;

export function FeedbackKinds() {
  const [email, setEmail] = useState("alice@example");
  const [error, setError] = useState<string>();
  const [retrying, setRetrying] = useState(false);
  const [stale, setStale] = useState(true);
  return (
    <div className="grid gap-8">
      <div className="flex max-w-md items-center gap-2">
        <span className="flex-1 truncate font-medium text-ui">
          {thread?.subject}
        </span>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <ToolbarButton aria-label="More actions" tooltip="More actions">
              <EllipsisIcon />
            </ToolbarButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-44">
            <DropdownMenuItem>
              <ForwardIcon />
              Forward
            </DropdownMenuItem>
            <DropdownMenuItem onSelect={() => toast("Link copied")}>
              <LinkIcon />
              Copy link
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
      <form
        className="grid max-w-md gap-2"
        noValidate
        onSubmit={(event) => {
          event.preventDefault();
          const problem = check(email);
          setError(problem);
          if (!problem) toast.success("Profile saved");
        }}
      >
        <Label htmlFor="fb-email">Email</Label>
        <div className="flex gap-2">
          <Input
            id="fb-email"
            type="email"
            autoComplete="email"
            value={email}
            onChange={(event) => {
              setEmail(event.target.value);
              if (error) setError(check(event.target.value));
            }}
            aria-invalid={error !== undefined}
            aria-describedby={error ? "fb-email-error" : "fb-email-hint"}
          />
          <Button type="submit">Save profile</Button>
        </div>
        {error ? (
          <FieldError id="fb-email-error">{error}</FieldError>
        ) : (
          <FieldDescription id="fb-email-hint">
            Like name@example.com.
          </FieldDescription>
        )}
      </form>
      <div className="grid gap-2">
        {stale && (
          <RefreshFailure
            what="the checks"
            detail="503 Service Unavailable"
            retrying={retrying}
            onRetry={() => {
              setRetrying(true);
              setTimeout(() => {
                setRetrying(false);
                setStale(false);
              }, 800);
            }}
          />
        )}
        <List purpose="collection">
          <ul className="text-ui">
            {CI_RUN.jobs.map((job) => (
              <ListItem key={job.id} asChild>
                <li className="flex min-h-row items-center justify-between gap-2 px-3 py-2">
                  <span>
                    {CI_RUN.workflow} / {job.name}
                  </span>
                  <span className="text-muted-foreground">{job.status}</span>
                </li>
              </ListItem>
            ))}
          </ul>
        </List>
      </div>
    </div>
  );
}
```

**Copy link**, from a Mail conversation's menu, succeeds and asks for nothing, so a toast says so and goes away. Press **Save profile**: the email from the Settings demo's profile form is missing its domain, which is said under the field and stays until the field is fixed. The pull request's checks failed to refresh, so the warning sits above the list it could not update, with the one control that can fix it.

## Do and don't

**Do**

Put a validation error under its field, mark the field `aria-invalid`, and point `aria-describedby` at the message.

**Don't**

Send a validation error as a toast: it disappears before the field is fixed, and never says which field.

**Do**

Toast "3 conversations archived" with an **Undo** action after a bulk change that can be reversed.

**Don't**

Open a dialog to say that something worked. A dialog stops everything; success should not.

## Which one

| What happened                                                  | Needs people to                | Use                                                                                                                 |
| -------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| An action finished as expected                                 | Nothing; maybe undo it         | `toast()`, `toast.success()`, with an `action` to undo                                                              |
| A control shows its own result where it was pressed            | Nothing                        | No toast: `CopyButton` turns into a check; `writeClipboard` toasts only a failure                                   |
| A copy came too late for the press that asked for it           | Press once more                | The copy offer: `offerCopy`, which `writeClipboard` and `copyToClipboard` raise themselves                          |
| Something finished in the background, out of view              | Know, maybe open it            | `toast()` with an action that opens it                                                                              |
| A field or a form is wrong                                     | Fix that field                 | An inline message under the field                                                                                   |
| A surface failed to load and has nothing to show               | Retry                          | `LoadFailure` in its place                                                                                          |
| A refresh failed but older data is still shown                 | Know the data is stale, retry  | `RefreshFailure` above the data                                                                                     |
| An action failed and the work is not saved                     | Decide what to do with it      | `toast.error()` with a retry, or inline if the place is on screen                                                   |
| A question waits in the flow of the page, or a run there ended | Answer it, or see how it ended | A `Frame` with an `intent`, its lid saying the status, see [Surfaces](/ui/guidelines/foundations/surfaces/index.md) |
| Nothing may continue until a question is answered              | Choose                         | `Dialog`, see [Overlays](/ui/guidelines/patterns/overlays/index.md)                                                 |

```tsx
import { CI_RUN } from "@orz/fixtures/ci-run.ts";
import { Button } from "@orz/ui/components/button";
import { List, ListItem } from "@orz/ui/components/list";
import { ArchiveIcon, RotateCwIcon } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

const failed = CI_RUN.jobs.filter((job) => job.status === "failed");

export function ToastKinds() {
  const [archived, setArchived] = useState(false);
  const [running, setRunning] = useState(false);
  const [details, setDetails] = useState(false);
  return (
    <div className="grid gap-4">
      <div className="flex flex-wrap gap-2">
        <Button
          variant="outline"
          disabled={archived}
          onClick={() => {
            setArchived(true);
            toast("Conversation archived", {
              action: { label: "Undo", onClick: () => setArchived(false) },
            });
          }}
        >
          <ArchiveIcon />
          Archive
        </Button>
        <Button
          variant="outline"
          disabled={running}
          onClick={() => {
            setRunning(true);
            setDetails(false);
            setTimeout(() => {
              setRunning(false);
              const [job] = failed;
              if (!job) return;
              toast.error(`${job.name} failed again in ${CI_RUN.workflow}`, {
                action: { label: "Details", onClick: () => setDetails(true) },
              });
            }, 1500);
          }}
        >
          <RotateCwIcon className={running ? "animate-spin" : undefined} />
          {running ? "Re-running…" : "Re-run failed jobs"}
        </Button>
      </div>
      {details && (
        <List purpose="collection">
          <ul className="text-ui">
            {CI_RUN.jobs.map((job) => (
              <ListItem key={job.id} asChild>
                <li className="flex min-h-row items-center justify-between gap-2 px-3 py-2">
                  <span>
                    {CI_RUN.workflow} / {job.name}
                  </span>
                  <span className="text-muted-foreground">{job.status}</span>
                </li>
              </ListItem>
            ))}
          </ul>
        </List>
      )}
    </div>
  );
}
```

Each button ends in a toast, in the demos' words. **Archive** can be undone from it. **Re-run failed jobs** finishes out of view, and its error toast opens the run.

```tsx
import { INBOX_THREADS } from "@orz/fixtures/inbox.ts";
import { List, ListItem } from "@orz/ui/components/list";
import { LoadFailure } from "@orz/ui/components/load-failure";
import { useState } from "react";

const THREADS = INBOX_THREADS.filter(
  ({ folder }) => folder === undefined,
).slice(0, 3);

export function ConversationsFailed() {
  const [loaded, setLoaded] = useState(false);
  const [retrying, setRetrying] = useState(false);
  if (!loaded) {
    return (
      <LoadFailure
        message="Couldn't load the conversations."
        detail="503 Service Unavailable"
        retrying={retrying}
        onRetry={() => {
          setRetrying(true);
          setTimeout(() => {
            setRetrying(false);
            setLoaded(true);
          }, 800);
        }}
      />
    );
  }
  return (
    <List purpose="listbox">
      <ul aria-label="Conversations" className="text-ui">
        {THREADS.map(({ id, subject }) => (
          <ListItem key={id} asChild>
            <li className="min-h-row truncate px-2 py-2">{subject}</li>
          </ListItem>
        ))}
      </ul>
    </List>
  );
}
```

Mail's list failed to load and has nothing to show, so `LoadFailure` takes its place until **Retry** brings the conversations.

A message that stays has to be removable by fixing its cause, not by a close button; one that leaves by itself must not carry the only copy of something people need to read.

A control that shows its own result needs no toast as well.

```tsx
import { TASKS } from "@orz/fixtures/tasks.ts";
import { CopyButton } from "@orz/ui/components/copy-button";
import { LinkIcon } from "lucide-react";

const task = TASKS.find((each) => each.id === 6);

export function CopyInPlace() {
  return (
    <div className="flex max-w-md items-center gap-2 text-ui">
      <span className="text-muted-foreground tabular-nums">T-{task?.id}</span>
      <span className="flex-1 truncate font-medium">{task?.title}</span>
      <CopyButton
        text={`https://app.example/tasks/${task?.id}`}
        icon={<LinkIcon />}
        copiedLabel="Link copied"
      >
        Copy link
      </CopyButton>
    </div>
  );
}
```

Press **Copy link**: a `CopyButton` turns its icon into a check for a moment, and says "Link copied" to a screen reader. The eyes are already on the button, and a toast in the corner would only pull them away. Its failure still toasts, since the button cannot say why it failed.

- Copy from a button on screen with `CopyButton`: a code block's **Copy**, a new token's **Copy token**, an install line's icon. Alone, the icon is named by `aria-label`, which its tooltip shows; give it words where the icon would not say what is copied.
- Copy from a menu or a shortcut with `copyToClipboard`, which toasts the success: nothing on screen changes, and the menu is gone. A `CopyButton` that a toolbar moves into its `⋯` menu toasts there for the same reason.
- A control of another kind that answers itself copies with `writeClipboard` from `@orz/ui/lib/clipboard`, which toasts only a failure. A component that reports the copy to its caller, as `HexView`'s `onCopy` does, copies with `writeClipboardQuietly`, which says nothing.
- Copy in the press itself. Text still on its way, such as bytes being read, goes to any of these as a promise, handed over inside the press. A page served over plain http from another machine has no Clipboard API, and the browser's copy command these fall back to works only for a moment after the press, about a second in WebKit.
- A copy whose text came too late for its press is offered instead of failing: a toast, "Ready to copy", whose **Copy** button makes the copy in a press of its own. `writeClipboard` and `copyToClipboard` offer it themselves. A component that reports the copy calls `offerCopy` when `writeClipboardQuietly` answers `"needs-press"`, and reports the offer's outcome; one closed unpressed was the reader's choice and reports nothing.

## Writing the message

- Say what happened in the past tense, naming the thing: "Profile saved", "Couldn't load the conversations". Do not open with "Success!" or "Error:"; the icon already says which.
- An error says what failed and, when it is known, the server's own words: `LoadFailure` and `RefreshFailure` take them as `detail`, which stays out of the sentence.
- A message for one item names the item; a message for several counts them.

## On each platform

### Desktop & pointer

- Toasts stack in a corner, out of the way of the work. Hovering one pauses its timer, so it can be read and its action taken.
- A toast shows over every overlay and takes the pointer there too: pressing it, or its action, closes nothing beneath it.
- A toast's action is reachable from the keyboard. Alt+T moves the focus to the toasts, from inside an open Dialog, Sheet, Popover or menu as well, and Tab past them, Escape or the action itself takes it back where it was. Still, anything that matters is also reachable where it happened, since a toast may be gone before focus reaches it.

### Touch

- A toast covers part of a small screen. Keep it to one line, and swipe it away to dismiss.
- An inline error must stay visible above the on-screen keyboard: put it directly under the field, not at the top of the form.

## In the demos

- [Releases](/ui/demos/releases/index.md): Each change says what happened to which release in a toast, Promoting web v5.11.1 to staging or Rolled back 2 releases, with Undo in it.
- [Settings](/ui/demos/settings/index.md): Save the profile or revoke a token for a toast that names what happened. A wrong email is said under its field instead, where it can be fixed.
- [Admin](/ui/demos/admin/index.md): Each change names what happened in a toast, Changed bob's role to Member or Revoked the invitation to peggy\@example.com. A wrong address in Invite people… is said under the field instead.
- [Tasks](/ui/demos/tasks/index.md): Close, reopen, create or delete a task, and a toast names the task it was done to. New task with no title says so under the field.
- [Mail](/ui/demos/mail/index.md): Archive, delete, mark or send a message, and a toast says so, with Undo. Press Refresh: the first check fails, and says so above the list it kept, with Retry.
- [Pull request](/ui/demos/pull-request/index.md): Press Re-run failed jobs and move to Files changed: the run ends in a toast, and its Details leads back to the log.
- [Config editor](/ui/demos/config-editor/index.md): Save a file for a toast that names it. A syntax error is said under the editor, where it can be fixed, and pressing it moves the caret to the error.
- [Binary inspector](/ui/demos/binary-inspector/index.md): Paste more bytes than fit, or text that is not hex: a toast says what was pasted and what was refused. Revert ends in one that names the file.
