The states round a screen's data
Loading, failed, first run, filtered, not found, no access, sending
This recipe draws ListPage arrangement="filtered"; the others (agent/layout-chooser.md) take the same slots. Your page fits another? Change the one prop:
plain(fields: few):filtersa few, in the header line;collectionrows or a feed.views-column(views: saved):viewsthe saved views, a column beside the list.centred(fields: few; Trail draws it asplain):collectionrows read as items.
Copy the file below whole (src/screens/states.tsx) beside frame.tsx (docs/screen-frame.md). Each state is named in the table below; your screens import its part (import { LoadFailed, FirstRun } from './states'). The default export, a studies list, wires them to one load: rows load, the first run shows its starter cards, a filter leaving nothing says so. The sample answers with no study (so you see the first run) after a moment, fetching nothing: put your fetch in loadStudies, your send in deliver, your request in requestAccess. failFirst (on the screen and useOutbox) is a sample switch only: set, the first load or a message's first send fails, showing the failed state and Retry; remove it, and a real failure shows the same. The states are the parts' own looks, light and dark, phone and desktop: add no class.
Which one
| When | The state | What it shows | |---|---|---| | Rows loading (a table, a list) | loading-rows | a table's header over grey rows (SkeletonContainer round it: a fast answer never flashes them); Item rows as LoadingList, stacked Skeleton rows | | Cards or a dashboard's tiles loading | loading-cards | CardGrid loading: placeholder cards in the cards' places; a tile's number a Skeleton in a SkeletonContainer | | The data did not load | failed | LoadFailed: a red Alert in the data's place, its Retry re-running the request | | Nothing made yet (a first visit, a new workspace) | first-run | FirstRun: an icon, a title, a line, then starter cards, each with its action | | A search or filter leaves nothing, though records exist | filtered | Filtered: words and Clear filters, no icon or starter cards | | An address leads nowhere (an old link, a deleted record) | not-found | NotFoundScreen: a page in the frame, its icon, heading and way back | | The record exists but is not the person's | access | NoAccessScreen: who to ask, and Request access, spinning while it goes | | The person's message on its way, or refused | sending / failed-send | OwnMessage and useOutbox: ChatMessage's status line, Retry on a refused one | | One action running (a save, a send) | none here | Button loading: its spinner over its words | | The app is offline or read-only | none here | one Banner first in the panel's header (Banner's page) | | An empty card or section in a filled page | none here | CardList empty or an Empty variant="outline" row: words only |
The page-wide states (failed, first run, not found, no access) lead with an icon, as about two real empty states in three do; a filtered result and an empty section are words only. No record at all: the first run; records the filters hide: filtered, never the one for the other.
Show the code498 lines
// src/screens/states.tsx: the states round a screen’s data
import { useEffect, useState } from 'react';
import { AppFramePanel } from '@/components/goop/patterns/app-frame';
import { ListPage } from '@/components/goop/patterns/list-page';
import { PageBody, pageRoles } from '@/components/goop/patterns/page-body';
import { Alert, AlertAction, AlertDescription, AlertIcon, AlertTitle } from '@/components/ui/goop/alert';
import { Button, ButtonIcon, ButtonLabel } from '@/components/ui/goop/button';
import {
Card,
CardAction,
CardDescription,
CardHeader,
CardMedia,
CardText,
CardTitle,
} from '@/components/ui/goop/card';
import { CardGrid, CardGridItem } from '@/components/ui/goop/card-grid';
import { ChatMessage } from '@/components/ui/goop/chat-message';
import { CommandShortcut } from '@/components/ui/goop/command';
import {
Empty,
EmptyContent,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from '@/components/ui/goop/empty';
import { IconTile, IconTileIcon } from '@/components/ui/goop/icon-tile';
import { PageHeader, PageHeaderTitle } from '@/components/ui/goop/page-header';
import { SearchInput } from '@/components/ui/goop/search-input';
import { SegmentedControl, SegmentedControlItem } from '@/components/ui/goop/segmented-control';
import {
Select,
SelectContent,
SelectIcon,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/goop/select';
import { Skeleton, SkeletonContainer, SkeletonMedia } from '@/components/ui/goop/skeleton';
import { StatusMark } from '@/components/ui/goop/status-mark';
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/goop/table';
import { TableCell, TableCellLabel, TableCellPerson } from '@/components/ui/goop/table-cell';
import { Glyph } from '@/lib/goop/trail/glyph';
import { ScreenFrame, ScreenTopBar } from './frame';
import { go } from './router';
// ---- the sample data and requests: swap them for yours
type Status = 'todo' | 'in-progress' | 'done';
const STATUS_WORDS: Record<Status, string> = { todo: 'Planned', 'in-progress': 'Running', done: 'Done' };
const STATUSES = Object.keys(STATUS_WORDS) as Status[];
interface Study {
id: string;
title: string;
status: Status;
owner: string;
}
const ME = 'Teodora Valk';
/** The first run's starter cards: the ways to start a first study. */
const STARTERS = [
{
id: 'interviews',
title: 'Customer interviews',
words: 'Talk to eight people about one job they do.',
icon: 'users',
},
{
id: 'usability',
title: 'Usability test',
words: 'Watch people try one task on your product.',
icon: 'device-desktop',
},
{ id: 'diary', title: 'Diary study', words: 'Collect short notes from people over two weeks.', icon: 'calendar' },
] as const;
type Starter = (typeof STARTERS)[number];
const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));
/** The sample request: no study yet; `fail` (the sample switch's) makes it fail. Your fetch takes its place. */
async function loadStudies(fail: boolean): Promise<Study[]> {
await wait(600);
if (fail) throw new Error('The studies did not load.');
return [];
}
/** The sample send: `fail` (the sample switch's) refuses it. Your send takes its place. */
async function deliver(_text: string, fail: boolean): Promise<void> {
await wait(400);
if (fail) throw new Error('Not sent.');
}
/** The sample access request: it asks the owner and answers. Your request takes its place. */
async function requestAccess(_owner: string): Promise<void> {
await wait(600);
}
// ---- loading-rows, a list's: the Skeleton's rows, stacked, the first rounded (an inbox, a feed of Item rows)
export function LoadingList({ rows = 4 }: { rows?: number }) {
return (
<>
{Array.from({ length: rows }, (_, row) => row).map((row) => (
<Skeleton key={row} variant="row" shape={row === 0 ? 'rounded-top' : 'square'}>
<SkeletonMedia>
<Glyph icon="circle-dashed" box={{ w: 16, h: 16 }} />
</SkeletonMedia>
</Skeleton>
))}
</>
);
}
// ---- failed: said where the data would stand, with Retry, which runs the request again
export function LoadFailed({ what, onRetry }: { what: string; onRetry: () => void }) {
return (
<Alert variant="destructive">
<AlertIcon />
<AlertTitle>{`The ${what} did not load`}</AlertTitle>
<AlertDescription>Check your connection, then try again. Nothing you saved is lost.</AlertDescription>
<AlertAction>
<Button size="sm" onClick={onRetry}>
Retry
</Button>
</AlertAction>
</Alert>
);
}
// ---- first-run: nothing made yet; an icon, a title, a line, then the ways to start, each card with its action
export function FirstRun({ onStart }: { onStart: (starter: Starter) => void }) {
return (
<>
<Empty variant="outline">
<EmptyMedia>
<IconTile>
<IconTileIcon icon="file-text" />
</IconTile>
</EmptyMedia>
<EmptyHeader>
<EmptyTitle asChild>
<h2>No studies yet</h2>
</EmptyTitle>
<EmptyDescription>
A study holds its sessions, notes and findings. Start one from a card below.
</EmptyDescription>
</EmptyHeader>
</Empty>
<CardGrid aria-label="Ways to start">
{STARTERS.map((starter) => (
<CardGridItem key={starter.id}>
<Card variant="outline">
<CardHeader>
<CardMedia>
<IconTile variant="surface">
<IconTileIcon icon={starter.icon} />
</IconTile>
</CardMedia>
<CardTitle asChild>
<h3>{starter.title}</h3>
</CardTitle>
<CardDescription>{starter.words}</CardDescription>
<CardAction>
<Button
variant="outline"
size="sm"
aria-label={`Start ${starter.title.toLowerCase()}`}
onClick={() => onStart(starter)}
>
Start
</Button>
</CardAction>
</CardHeader>
</Card>
</CardGridItem>
))}
</CardGrid>
</>
);
}
// ---- filtered: the records are there, the filters hide them all; words and the one way out, no starter cards
export function Filtered({ onClear }: { onClear: () => void }) {
return (
<Empty variant="outline">
<EmptyHeader>
<EmptyTitle>No study matches these filters</EmptyTitle>
<EmptyDescription>Try other words, or clear the filters to see every study.</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button variant="ghost" size="lg" onClick={onClear}>
<ButtonIcon icon="x" />
<ButtonLabel>Clear filters</ButtonLabel>
</Button>
</EmptyContent>
</Empty>
);
}
// ---- not-found: an address that leads nowhere; a page in the frame with the way back (App.tsx's last route)
export function NotFoundScreen() {
return (
<ScreenFrame>
<AppFramePanel header={<ScreenTopBar title="Not found" />}>
<PageBody variant="column">
<Empty variant="outline">
<EmptyMedia>
<IconTile>
<IconTileIcon icon="map-2" />
</IconTile>
</EmptyMedia>
<EmptyHeader>
<EmptyTitle asChild>
<h1>This page isn’t here</h1>
</EmptyTitle>
<EmptyDescription>The link may be old, or what it pointed to was deleted.</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button variant="ghost" size="lg" onClick={() => go('/')}>
Back to the overview
</Button>
</EmptyContent>
</Empty>
</PageBody>
</AppFramePanel>
</ScreenFrame>
);
}
// ---- access: the record is there and not the person's to see; whom to ask, and the request sent from here
export function NoAccessScreen({ owner = 'Dagny Holm' }: { owner?: string }) {
const [asked, setAsked] = useState<'no' | 'asking' | 'asked'>('no');
const ask = async () => {
setAsked('asking');
await requestAccess(owner);
setAsked('asked');
};
return (
<ScreenFrame>
<AppFramePanel header={<ScreenTopBar title="No access" />}>
<PageBody variant="column">
<Empty variant="outline">
<EmptyMedia>
<IconTile>
<IconTileIcon icon="lock" />
</IconTile>
</EmptyMedia>
<EmptyHeader>
<EmptyTitle asChild>
<h1>You don’t have access to this study</h1>
</EmptyTitle>
<EmptyDescription>
{asked === 'asked' ? `We asked ${owner} to add you.` : `${owner} owns it: ask them to add you.`}
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button loading={asked === 'asking'} disabled={asked === 'asked'} onClick={ask}>
{asked === 'asked' ? 'Access requested' : 'Request access'}
</Button>
</EmptyContent>
</Empty>
</PageBody>
</AppFramePanel>
</ScreenFrame>
);
}
// ---- sending / failed-send: the person's own messages as they go, a refused one with Retry
export interface Outgoing {
id: string;
text: string;
time: string;
status: 'sending' | 'sent' | 'failed';
tries: number;
}
let made = 0;
/**
* The person's messages: `send` posts one, `retry` sends a refused one again. `failFirst` is the sample switch (remove
* it in your app): each message's first send is refused, to show the failed line and its Retry.
*/
export function useOutbox({ failFirst = false }: { failFirst?: boolean } = {}) {
const [messages, setMessages] = useState<Outgoing[]>([]);
const post = async (message: Outgoing) => {
const status = await deliver(message.text, failFirst && message.tries === 0).then(
() => 'sent' as const,
() => 'failed' as const,
);
setMessages((all) => all.map((each) => (each.id === message.id ? { ...each, status } : each)));
};
const send = (text: string) => {
made += 1;
const time = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
const message: Outgoing = { id: `message-${made}`, text, time, status: 'sending', tries: 0 };
setMessages((all) => [...all, message]);
void post(message);
};
const retry = (id: string) => {
const refused = messages.find((each) => each.id === id);
if (!refused) return;
const again: Outgoing = { ...refused, status: 'sending', tries: refused.tries + 1 };
setMessages((all) => all.map((each) => (each.id === id ? again : each)));
void post(again);
};
return { messages, send, retry };
}
/** One of the person's messages in a thread: the status line under it while it goes, Retry once it is refused. */
export function OwnMessage({ message, onRetry }: { message: Outgoing; onRetry: () => void }) {
return (
<ChatMessage from="self" author="You" time={message.time} status={message.status} onRetry={onRetry}>
{message.text}
</ChatMessage>
);
}
// ---- the sample screen: one list that loads, fails, starts and filters through the states above
const ANY = 'any';
const counted = (n: number) => `${n} ${n === 1 ? 'study' : 'studies'}`;
/** loading-rows: the table with its header kept; `studies` null while they load, grey blocks in its rows. */
function StudyTable({ studies }: { studies: Study[] | null }) {
return (
<Table
aria-label="Studies"
gutter="page"
columns={['minmax(160px, 1fr)', '128px', { track: '176px', hide: 'narrow' }]}
>
<TableHeader>
<TableRow>
<TableHead>
<TableCellLabel>Study</TableCellLabel>
</TableHead>
<TableHead>
<TableCellLabel>Status</TableCellLabel>
</TableHead>
<TableHead>
<TableCellLabel>Owner</TableCellLabel>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{studies === null
? [1, 2, 3, 4].map((row) => (
<TableRow key={row}>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
</TableRow>
))
: studies.map((study) => (
<TableRow key={study.id}>
<TableCell>
<TableCellLabel primary>{study.title}</TableCellLabel>
</TableCell>
<TableCell>
<StatusMark status={study.status} label={STATUS_WORDS[study.status]} />
</TableCell>
<TableCell>
<TableCellPerson name={study.owner} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
/** `failFirst` is the sample switch (remove it in your app): the first load fails, to show `failed` and its Retry. */
export default function StudiesScreen({ failFirst = false }: { failFirst?: boolean }) {
const [attempt, setAttempt] = useState(0);
const [load, setLoad] = useState<'loading' | 'failed' | 'ready'>('loading');
const [studies, setStudies] = useState<Study[]>([]);
const [view, setView] = useState<'table' | 'cards'>('table');
const [query, setQuery] = useState('');
const [status, setStatus] = useState<string>(ANY);
useEffect(() => {
let live = true;
loadStudies(failFirst && attempt === 0).then(
(answer) => {
if (!live) return;
setStudies(answer);
setLoad('ready');
},
() => {
if (live) setLoad('failed');
},
);
return () => {
live = false;
};
}, [attempt, failFirst]);
const retry = () => {
setLoad('loading');
setAttempt((n) => n + 1);
};
const start = (starter: Starter) =>
setStudies((all) => [
...all,
{ id: `${starter.id}-${all.length + 1}`, title: starter.title, status: 'todo', owner: ME },
]);
const clear = () => {
setQuery('');
setStatus(ANY);
};
// what the search leaves: each status option counts its own share of it
const found = studies.filter((study) => study.title.toLowerCase().includes(query.trim().toLowerCase()));
const shown = found.filter((study) => status === ANY || study.status === status);
const countOf = (value: string) => (value === ANY ? found : found.filter((study) => study.status === value)).length;
const statusWords = (value: string) => (value === ANY ? 'All' : STATUS_WORDS[value as Status]);
const loading = load === 'loading';
const records =
view === 'table' ? (
<SkeletonContainer loading={loading} skeleton={<StudyTable studies={null} />}>
<StudyTable studies={shown} />
</SkeletonContainer>
) : (
// loading-cards: the grid's own placeholder cards where the cards will stand
<CardGrid aria-label="Studies" loading={loading} className={pageRoles.inset}>
{shown.map((study) => (
<CardGridItem key={study.id}>
<Card>
<CardText>
<CardTitle>{study.title}</CardTitle>
<CardDescription>{`${STATUS_WORDS[study.status]} · ${study.owner}`}</CardDescription>
</CardText>
</Card>
</CardGridItem>
))}
</CardGrid>
);
// the one state the collection shows: failed, then first run (no record at all), then filtered, then the records
const state =
load === 'failed' ? (
<LoadFailed what="studies" onRetry={retry} />
) : load === 'ready' && studies.length === 0 ? (
<FirstRun onStart={start} />
) : load === 'ready' && shown.length === 0 ? (
<Filtered onClear={clear} />
) : null;
return (
<ScreenFrame>
<ListPage
arrangement="filtered"
header={<ScreenTopBar title="Studies" />}
heading={
<PageHeader>
<PageHeaderTitle asChild>
<h1>Studies</h1>
</PageHeaderTitle>
</PageHeader>
}
views={
<SegmentedControl aria-label="View" value={view} onValueChange={(next) => setView(next as 'table' | 'cards')}>
<SegmentedControlItem value="table">Table</SegmentedControlItem>
<SegmentedControlItem value="cards">Cards</SegmentedControlItem>
</SegmentedControl>
}
filters={
<>
<SearchInput
label="Search studies"
placeholder="Search studies"
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
/>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger aria-label={`Status: ${statusWords(status)}, ${counted(countOf(status))}`}>
<SelectValue>{`Status: ${statusWords(status)} ${countOf(status)}`}</SelectValue>
<SelectIcon />
</SelectTrigger>
<SelectContent aria-label="Status" search={false}>
{[ANY, ...STATUSES].map((value) => (
<SelectItem
key={value}
value={value}
aria-label={`${statusWords(value)}, ${counted(countOf(value))}`}
>
{statusWords(value)}
<CommandShortcut>{countOf(value)}</CommandShortcut>
</SelectItem>
))}
</SelectContent>
</Select>
</>
}
collection={
state === null ? (
records
) : (
<div className={`flex flex-col ${pageRoles.inset} ${pageRoles.block}`}>{state}</div>
)
}
/>
</ScreenFrame>
);
}