# Loading, empty & error

Loading, empty, failed and loaded each look different and say so. Nobody should have to guess which one a blank area is.

API [Skeleton](/ui/storybook/?path=/docs/ui-primitives-skeleton--docs) [EmptyState](/ui/storybook/?path=/docs/ui-emptystate--docs) [LoadFailure](/ui/storybook/?path=/docs/ui-loadfailure--docs) [LoadMoreFooter](/ui/storybook/?path=/docs/ui-loadmorefooter--docs) [usePagedAppend](/ui/storybook/?path=/docs/ui-hooks-usepagedappend--docs) [Markdown](/ui/storybook/?path=/docs/ui-markdown-markdown--docs) [AttachmentLink](/ui/storybook/?path=/docs/ui-content-attachmentlink--docs)

**Every surface that loads has four states, and each one looks like itself: a skeleton while it loads, a sentence and a next step when it is empty, the error and a retry when it failed, and then the content.**

```tsx
import { NOTES } from "@orz/fixtures/notes.ts";
import { Button } from "@orz/ui/components/button";
import { EmptyState } from "@orz/ui/components/empty-state";
import { FrameBar } from "@orz/ui/components/frame";
import { List, ListItem } from "@orz/ui/components/list";
import { LoadFailure } from "@orz/ui/components/load-failure";
import { Skeleton } from "@orz/ui/components/skeleton";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@orz/ui/components/tabs";
import { NotebookIcon, PlusIcon } from "lucide-react";
import { useState } from "react";

const titleOf = (body: string) => /^# (.+)$/m.exec(body)?.[1] ?? "Untitled";

const SHOWN = NOTES.slice(0, 4);

export function ListStates() {
  const [state, setState] = useState("loading");
  const [retrying, setRetrying] = useState(false);
  return (
    <Tabs variant="framed" value={state} onValueChange={setState}>
      <FrameBar>
        <TabsList>
          <TabsTrigger value="loading">Loading</TabsTrigger>
          <TabsTrigger value="empty">Empty</TabsTrigger>
          <TabsTrigger value="failed">Failed</TabsTrigger>
          <TabsTrigger value="loaded">Loaded</TabsTrigger>
        </TabsList>
      </FrameBar>
      <TabsContent value="loading" className="min-h-56 p-2">
        <List purpose="listbox">
          <ul aria-label="Loading notes" className="grid gap-0.5">
            {SHOWN.map((note) => (
              <ListItem key={note.id} asChild>
                <li className="grid min-h-row gap-1.5 px-2.5 py-2">
                  <Skeleton className="h-4 w-32" />
                  <Skeleton className="h-3 w-20" />
                </li>
              </ListItem>
            ))}
          </ul>
        </List>
      </TabsContent>
      <TabsContent value="empty" className="min-h-56 px-6 py-10">
        <EmptyState
          icon={NotebookIcon}
          title="No notes yet"
          action={
            <Button variant="outline" size="sm">
              <PlusIcon />
              New note
            </Button>
          }
        >
          A note is markdown, kept in this tab. Start one with a # heading.
        </EmptyState>
      </TabsContent>
      <TabsContent value="failed" className="min-h-56 p-4.5">
        <LoadFailure
          message="Couldn't load your notes."
          detail="503 Service Unavailable"
          retrying={retrying}
          onRetry={() => {
            setRetrying(true);
            setTimeout(() => {
              setRetrying(false);
              setState("loaded");
            }, 800);
          }}
        />
      </TabsContent>
      <TabsContent value="loaded" className="min-h-56 p-2">
        <List purpose="listbox">
          <ul aria-label="Notes" className="grid gap-0.5">
            {SHOWN.map((note) => (
              <ListItem key={note.id} asChild>
                <li className="grid min-h-row gap-0.5 px-2.5 py-2">
                  <span className="font-medium text-ui">
                    {titleOf(note.body)}
                  </span>
                  <span className="text-muted-foreground text-ui-sm">
                    {note.folder}
                  </span>
                </li>
              </ListItem>
            ))}
          </ul>
        </List>
      </TabsContent>
    </Tabs>
  );
}
```

Step through the tabs: the skeleton has the rows' shape, the empty list says what a note is and offers **New note**, and the failure names what failed. Press **Retry** there: it is disabled while the read runs, and the notes arrive.

## Do and don't

**Do**

Draw a `Skeleton` in the shape of the content that is coming, so the page does not jump when it arrives.

**Don't**

Cover the whole page with a spinner while one list loads: everything else on it was already usable.

**Do**

Say what would be here and how to get some: "No notes yet", a line on what a note is, and a **New note** button.

**Don't**

Leave "No data" in an empty box. It reads the same as a failed load or a filter that hides everything.

## The states

| State                                             | Show                                                                                        | Component                              |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------- |
| Loading, first time                               | Placeholders in the shape of the content                                                    | `Skeleton`                             |
| Loading, short (under about 500ms)                | Nothing new: the skeleton waits that long before it fades in, so a fast load does not flash | `DelayedSkeleton`                      |
| Loaded, nothing there                             | What would be here, why it is empty, and the action that fills it                           | `EmptyState`                           |
| Loaded, nothing matches a filter                  | That the filter hid everything, and a way to clear it                                       | `EmptyState`                           |
| Loaded, but not set up yet                        | What is missing, and the action that sets it up                                             | `EmptyState`                           |
| No permission to see it                           | What is held back, and how to get access when there is a way                                | `EmptyState`                           |
| Failed, nothing to show, in a line or a list      | The error, the server's own words in `detail`, and **Retry**                                | `LoadFailure`                          |
| Failed, nothing to show, filling a pane or a page | What failed as the title, the server's own words below it, and **Retry**                    | `LoadFailure` with `orientation`       |
| Refresh failed, older data still shown            | That the data is stale, the server's own words in `detail`, and **Retry**                   | `RefreshFailure`                       |
| Loading more of a list                            | A **Load more** button that turns into its own failure and retry                            | `LoadMoreFooter` with `usePagedAppend` |

```tsx
import { NOTES, type Note } from "@orz/fixtures/notes.ts";
import { Button } from "@orz/ui/components/button";
import { Frame } from "@orz/ui/components/frame";
import { Pane } from "@orz/ui/components/pane";
import { DelayedSkeleton, Skeleton } from "@orz/ui/components/skeleton";
import { useEffect, useRef, useState } from "react";

const titleOf = (note: Note) => /^# (.+)$/m.exec(note.body)?.[1] ?? "Untitled";
const openingOf = (note: Note) =>
  note.body.split("\n\n")[1]?.replace(/\s#[\w-]+/g, "") ?? "";

const OPENS = [
  { id: "retry-design", takes: 200 },
  { id: "job-states", takes: 2000 },
].flatMap(({ id, takes }) => {
  const note = NOTES.find((each) => each.id === id);
  return note ? [{ note, takes }] : [];
});

export function OpeningNotes() {
  const [shown, setShown] = useState(OPENS[0]?.note);
  const [loading, setLoading] = useState(false);
  // Stands in for the request: the note arrives `takes` ms after it was asked for.
  const request = useRef<number | undefined>(undefined);
  useEffect(() => () => window.clearTimeout(request.current), []);

  const open = (note: Note, takes: number) => {
    window.clearTimeout(request.current);
    setLoading(true);
    request.current = window.setTimeout(() => {
      setLoading(false);
      setShown(note);
    }, takes);
  };

  return (
    <div className="grid gap-3">
      <div className="flex flex-wrap gap-2">
        {OPENS.map(({ note, takes }) => (
          <Button
            key={note.id}
            variant="outline"
            onClick={() => open(note, takes)}
          >
            {titleOf(note)}, in {takes / 1000} s
          </Button>
        ))}
      </div>
      <Frame asChild>
        <Pane
          purpose="document"
          asChild
          className="grid min-h-32 content-start gap-2 p-4"
        >
          <article aria-busy={loading}>
            {loading ? (
              <DelayedSkeleton className="grid gap-2">
                <Skeleton className="h-7 w-40" />
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-5/6" />
              </DelayedSkeleton>
            ) : (
              shown && (
                <>
                  <h3 className="font-semibold text-heading-3">
                    {titleOf(shown)}
                  </h3>
                  <p className="text-ui">{openingOf(shown)}</p>
                </>
              )
            )}
          </article>
        </Pane>
      </Frame>
    </div>
  );
}
```

The first note answers in 0.2 s, before its skeleton would show: the pane is blank that long, then holds the note. The second takes 2 s: its skeleton fades in after 500ms and holds the note's place until it arrives. The wait is `DelayedSkeleton`'s own: the `Skeleton`s inside it are laid out as the note will be, and nothing times them.

When one skeleton gives way to another for the same wait, as a route's does to the page's own once the page has mounted, wrap the place in a `DelayedSkeletonProvider`. The page's skeleton then carries on the route's wait: it fades in once, and one already shown stays shown, rather than blinking out and waiting all over again.

An empty state that comes from a filter is not the same as an empty list. "No notes yet" invites writing one; "No notes match" invites clearing the filter.

```tsx
import { NOTES } from "@orz/fixtures/notes.ts";
import { Button } from "@orz/ui/components/button";
import { EmptyState } from "@orz/ui/components/empty-state";
import { List, ListItem } from "@orz/ui/components/list";
import { Toggle } from "@orz/ui/components/toggle";
import { NotebookIcon } from "lucide-react";
import { useState } from "react";

const TAGS = ["ci", "design", "fetch", "release"];

const titleOf = (body: string) => /^# (.+)$/m.exec(body)?.[1] ?? "Untitled";
const hasTag = (body: string, tag: string) =>
  new RegExp(`(^|\\s)#${tag}\\b`).test(body);

export function FilteredNotes() {
  const [chosen, setChosen] = useState<ReadonlySet<string>>(new Set(["ci"]));
  const shown = NOTES.filter((note) =>
    [...chosen].every((tag) => hasTag(note.body, tag)),
  );
  const toggle = (tag: string) =>
    setChosen((was) => {
      const next = new Set(was);
      if (!next.delete(tag)) next.add(tag);
      return next;
    });
  return (
    <div className="grid gap-3">
      <fieldset aria-label="Tags" className="flex flex-wrap gap-1">
        {TAGS.map((tag) => (
          <Toggle
            key={tag}
            pressed={chosen.has(tag)}
            onPressedChange={() => toggle(tag)}
          >
            #{tag}
          </Toggle>
        ))}
      </fieldset>
      <List purpose="listbox" className="min-h-44 p-2">
        {shown.length === 0 ? (
          <EmptyState
            icon={NotebookIcon}
            title="No notes match"
            action={
              <Button
                variant="outline"
                size="sm"
                onClick={() => setChosen(new Set())}
              >
                Clear filter
              </Button>
            }
            className="px-4 py-6"
          >
            Try fewer tags.
          </EmptyState>
        ) : (
          <ul aria-label="Notes" className="grid gap-0.5">
            {shown.map((note) => (
              <ListItem key={note.id} asChild>
                <li className="grid min-h-row gap-0.5 px-2.5 py-2">
                  <span className="font-medium text-ui">
                    {titleOf(note.body)}
                  </span>
                  <span className="text-muted-foreground text-ui-sm">
                    {note.folder}
                  </span>
                </li>
              </ListItem>
            ))}
          </ul>
        )}
      </List>
    </div>
  );
}
```

Add **#release** to **#ci**: no note has both, and the list says so with **Clear filter** rather than "No notes yet".

## Filling the space or sharing it

An `EmptyState` that is the only thing in its pane, list or page stands vertical, centred in the space. One that shares its space with other content, such as a section of a settings page, a sidebar group or a card among other cards, lies on one row with `orientation="horizontal"`, so it takes no more height than the content it stands in for.

An icon and a title are a whole empty state. Add the description only when the title leaves the reader asking why, and the action only when there is a next step.

```tsx
import { Button } from "@orz/ui/components/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  ModuleGrid,
} from "@orz/ui/components/card";
import { EmptyState } from "@orz/ui/components/empty-state";
import { LoadFailure } from "@orz/ui/components/load-failure";
import { KeyRoundIcon, LockIcon, PlusIcon, WebhookIcon } from "lucide-react";
import { useState } from "react";

export function SettingsSections() {
  const [retrying, setRetrying] = useState(false);
  return (
    <ModuleGrid>
      <Card>
        <CardHeader>
          <CardTitle>Deploy keys</CardTitle>
        </CardHeader>
        <CardContent>
          <EmptyState
            orientation="horizontal"
            icon={LockIcon}
            title="Only maintainers see deploy keys"
            action={
              <Button variant="outline" size="sm">
                Request access
              </Button>
            }
          />
        </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <CardTitle>Tokens</CardTitle>
        </CardHeader>
        <CardContent>
          <EmptyState
            orientation="horizontal"
            icon={KeyRoundIcon}
            title="No tokens yet"
            action={
              <Button variant="outline" size="sm">
                <PlusIcon />
                New token
              </Button>
            }
          >
            A token lets a script act as you.
          </EmptyState>
        </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <CardTitle>Webhooks</CardTitle>
        </CardHeader>
        <CardContent>
          <LoadFailure
            orientation="horizontal"
            icon={WebhookIcon}
            message="Couldn't load webhooks"
            detail="503 Service Unavailable"
            onRetry={() => {
              setRetrying(true);
              setTimeout(() => setRetrying(false), 1000);
            }}
            retrying={retrying}
          />
        </CardContent>
      </Card>
    </ModuleGrid>
  );
}
```

The failed section is a `LoadFailure` with `orientation="horizontal"`: it keeps the same row as the empty ones and says what failed in its title. The red is not what tells it apart from the empty sections: the title and **Retry** do that.

```tsx
import {
  INBOX_PEOPLE,
  INBOX_THREADS,
  type InboxThread,
} from "@orz/fixtures/inbox.ts";
import { Frame } from "@orz/ui/components/frame";
import { List, ListItem } from "@orz/ui/components/list";
import { RefreshFailure } from "@orz/ui/components/load-failure";
import { LoadMoreFooter } from "@orz/ui/components/load-more";
import { Pane } from "@orz/ui/components/pane";
import { Separator } from "@orz/ui/components/separator";
import { ToolbarButton } from "@orz/ui/components/toolbar";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@orz/ui/components/tooltip";
import { usePagedAppend } from "@orz/ui/hooks/use-paged-append";
import { RefreshCwIcon } from "lucide-react";
import { useRef, useState } from "react";

const INBOX = INBOX_THREADS.filter(
  (thread) => (thread.folder ?? "inbox") === "inbox",
);
const PAGE = 3;

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export function InboxList() {
  const [refreshing, setRefreshing] = useState(false);
  const [stale, setStale] = useState(false);
  const refreshes = useRef(0);
  const paged = usePagedAppend<InboxThread[]>("inbox");
  const loads = useRef(0);
  const focusRequested = useRef(false);
  const threads = [INBOX.slice(0, PAGE), ...paged.pages].flat();

  const refresh = async () => {
    setRefreshing(true);
    await wait(600);
    refreshes.current += 1;
    setStale(refreshes.current === 1);
    setRefreshing(false);
  };
  const loadMore = () => {
    focusRequested.current = true;
    const from = threads.length;
    paged.append(async () => {
      await wait(600);
      loads.current += 1;
      if (loads.current === 2) throw new Error("the connection dropped");
      return INBOX.slice(from, from + PAGE);
    });
  };

  return (
    <TooltipProvider>
      <Frame asChild>
        <Pane purpose="panel" className="min-w-0">
          <Pane
            purpose="toolbar"
            edge="bottom"
            className="flex items-center gap-1 px-1.5 py-1.5"
          >
            <Tooltip>
              <TooltipTrigger asChild>
                <ToolbarButton
                  aria-label="Refresh"
                  disabled={refreshing}
                  onClick={refresh}
                >
                  <RefreshCwIcon
                    className={
                      refreshing ? "motion-safe:animate-spin" : undefined
                    }
                  />
                </ToolbarButton>
              </TooltipTrigger>
              <TooltipContent>Refresh</TooltipContent>
            </Tooltip>
            <span className="flex-1 font-medium text-ui">Inbox</span>
            <span className="px-2 text-muted-foreground text-ui-sm tabular-nums">
              {threads.length} of {INBOX.length}
            </span>
          </Pane>
          {stale && (
            <>
              <RefreshFailure
                what="the inbox"
                detail="503 Service Unavailable"
                retrying={refreshing}
                onRetry={refresh}
                className="px-3 py-2"
              />
              <Separator />
            </>
          )}
          <List purpose="listbox">
            <ul aria-label="Conversations">
              {threads.map((thread) => (
                <ListItem key={thread.id} asChild>
                  <li className="grid min-h-row gap-0.5 px-3 py-2.5">
                    <span className="truncate font-medium text-ui">
                      {INBOX_PEOPLE[thread.messages[0]?.from ?? ""]}
                    </span>
                    <span className="truncate text-muted-foreground text-ui">
                      {thread.subject}
                    </span>
                  </li>
                </ListItem>
              ))}
            </ul>
          </List>
          {threads.length < INBOX.length && (
            <>
              <Separator />
              <div className="p-3">
                <LoadMoreFooter
                  pending={paged.pending}
                  error={paged.error}
                  onLoadMore={loadMore}
                  focusRequested={focusRequested}
                />
              </div>
            </>
          )}
        </Pane>
      </Frame>
    </TooltipProvider>
  );
}
```

Press **Refresh**: the first one fails, and the conversations already shown stay under the warning. Press **Load more** twice: the second page fails in place of the button, and its **Retry** loads only that page.

## Files a document names

**A file that a document links or embeds looks one way while the app looks it up, another when there is no such file, and another once it was deleted, so the reader knows before clicking whether it will open.**

```tsx
import { SLOW_LOOKUP } from "@orz/fixtures/lookup.ts";
import { ATTACHMENT_RENDERERS } from "@orz/fixtures/renderers.ts";
import { Button } from "@orz/ui/components/button";
import { Frame } from "@orz/ui/components/frame";
import { Pane } from "@orz/ui/components/pane";
import { ContentRenderers } from "@orz/ui-content";
import { AttachmentViewerProvider } from "@orz/ui-content/attachment";
import {
  attachmentLinks,
  imagePairs,
  Markdown,
  markdownEmbeds,
} from "@orz/ui-markdown";
import { useState } from "react";

const PLUGINS = [
  imagePairs(SLOW_LOOKUP),
  markdownEmbeds(SLOW_LOOKUP),
  attachmentLinks(SLOW_LOOKUP),
];

const NOTE = `Read [the appendix](files/appendix.md) before tagging; [the old plan](files/missing/plan.md) it replaced is gone. The new mark: ![mark](files/sprite.png)

![](files/appendix.md)

![v1](files/settings-before.svg) → ![v2](files/settings-after.svg)

The first logo, ![logo](files/deleted/logo.svg), is not coming back.
`;

export function FileReferences() {
  // Each reload mounts the note afresh, and every lookup starts over.
  const [run, setRun] = useState(0);
  return (
    <div className="grid gap-3">
      <div className="flex">
        <Button variant="outline" onClick={() => setRun((n) => n + 1)}>
          Reload
        </Button>
      </div>
      <ContentRenderers renderers={ATTACHMENT_RENDERERS}>
        <AttachmentViewerProvider>
          <Frame asChild>
            <Pane purpose="document" asChild className="min-h-32 p-4">
              <article>
                <Markdown key={run} plugins={PLUGINS}>
                  {NOTE}
                </Markdown>
              </article>
            </Pane>
          </Frame>
        </AttachmentViewerProvider>
      </ContentRenderers>
    </div>
  );
}
```

Press **Reload** and the note asks for its files again. The links are chips at once; the picture, the card's lines and the comparison's sides show their placeholders a moment later. Then the answers arrive: the files that exist draw, the old plan is not found, and the first logo says it was deleted.

| The app's lookup | A link                                           | A picture                                      | An embedded file                                      |
| ---------------- | ------------------------------------------------ | ---------------------------------------------- | ----------------------------------------------------- |
| Still running    | The chip it will be, a plain link to the address | Nothing at first, then `PendingAttachmentMark` | The card, named by the address, over `ContentLoading` |
| Found            | `AttachmentLink`, which opens the viewer         | The picture                                    | The card, its size and its contents                   |
| No such file     | `MissingAttachmentMark`                          | `MissingAttachmentMark`                        | `MissingAttachmentMark`                               |
| Deleted          | `DeletedAttachmentMark`                          | `DeletedAttachmentMark`                        | `DeletedAttachmentMark`                               |

A file found to be one no renderer draws in a document, such as a PDF behind an address whose name reads like a picture or a text file, is an `AttachmentLink` wherever it was embedded, never a broken picture.

A link is the same chip whether the lookup has answered or not; only what a click does changes, so nothing on the line moves when the answer comes. A picture and a card's body wait as **Loading, short** says above: a lookup that answers quickly never shows a placeholder. Looking a file up, fetching the renderer that draws it and reading its text are one wait to the reader, so a card draws the same lines for all three, and they fade in once, however the wait passes from one to the next.

An app tells the plugins what it knows through `useSource`, beside the `resolve` that reads the address:

- While the lookup runs, return `undefined`.
- Return `null` only when the app knows there is no such file. A file the reader may not see, or one in another place the app does not look, is not a missing file.
- When the lookup fails, or there is nothing more to know, return the source `useSource` was handed: the file is drawn as its address says, and an address that works keeps working.
- Give a text file its `size`. A card does not load text of unknown size until the reader asks.

## Retrying

A failure does not recover by itself, so its way out is a control, not a promise to try again later. **Retry** reruns only the read that failed, and is disabled while it runs. When an overlay opened from a failed surface closes, send focus to its **Retry** through `retryRef`: the overlay's own trigger may be gone. `LoadFailure` wires both in every orientation, so a failure that fills a pane is a `LoadFailure` too, not an `EmptyState` with a **Retry** of its own.

A renderer whose code does not arrive (the reader went offline, or a new release replaced the chunk an open page asked for) is one such failure: a `LoadFailure` takes its place, and under it the text stays readable as written, or the file stays a download link, so the content is never lost behind the failure.

## On each platform

### Desktop & pointer

- Keep what loaded already in place while the next page or a refresh loads; replace only what changed.
- A failure on one line (`LoadFailure`, `RefreshFailure`, the **Load more** footer's) puts the raw error in its `title`, so hovering it shows the detail.

### Touch

- Hover shows nothing on a phone, so an error message names what failed in words, not only in a tooltip.
- Prefer a **Load more** button at the end of a list to loading on scroll alone: a thumb flicking past the end should not start requests it did not ask for, and a failure needs a place to sit.

## In the demos

- [Releases](/ui/demos/releases/index.md): Pick a place in the sidebar for skeleton rows in the list's own columns. Search for what no release has for No releases match with Clear filters, and in Services billing's status page fails with Retry.
- [Gallery](/ui/demos/gallery/index.md): Filter for a name no component has: the sheet says No components match and offers Clear filter, rather than leaving an empty page.
- [Admin](/ui/demos/admin/index.md): Usage and billing's invoices fail on their first load, with Retry. Pick Field notes in the workspace menu for a new workspace's set-up list and empty audit log, and Design guild for billing held back by its owner.
- [Tasks](/ui/demos/tasks/index.md): Filter until nothing is left: No tasks match, with Clear filters. Scroll to the end, and Load more fetches the next page and says how many remain.
- [Mail](/ui/demos/mail/index.md): Open an empty folder for what it holds and how mail gets there, search for a word no mail has for the filter's own empty state, and scroll to the end for Load more.
- [Notes](/ui/demos/notes/index.md): Filter for a word no note has: No notes match, with Clear filter. Delete every note, and the empty notebook says what a note is, with New note.
- [Pull request](/ui/demos/pull-request/index.md): Reload the page: each log, diff and the comment box shows a skeleton in its shape until it is drawn, so nothing jumps.
- [Repository](/ui/demos/repository/index.md): Open scripts/ for an empty folder, docs/old-guide.md for a file deleted from disk, and filter for a word no path holds.
- [Binary inspector](/ui/demos/binary-inspector/index.md): Pick another sample: skeleton rows hold its place while it loads. Should the fetch fail, the error takes that place, with Retry.
