gallery
A tab bar app (a rail on wide windows) whose home screen opens eight areas: Language, Styling and themes, Data, Navigation, Kit core, Overlays, Inputs and media, Navigation parts. Each area is a screen of small demos you can use. It runs with no network (its data is in memory), keeps its images in public/, and has a light/dark switch.
Run it
cargo run -p duolith-cli -- dev examples/gallery # live, reloads on save
cargo run -p duolith-cli -- build examples/gallery # static output in examples/gallery/dist
The folder on the web: examples/gallery.
Features it shows
| Feature | Where | Screenshot |
|---|---|---|
<screen> with a title | every page; gallery pages/index.duo | gallery-home.png |
<view> | gallery pages/styling.duo | gallery-styling.png |
<text> | gallery pages/styling.duo (Type) | gallery-styling-type.png |
<image> (alt, decorative, placeholder, lazy) | gallery pages/language.duo (Elements) | gallery-language-elements.png |
<input> | gallery pages/language.duo (Two-way binding) | gallery-language-binding.png |
<textarea> | gallery pages/language.duo (Two-way binding) | gallery-language-binding.png |
<list> with each, as, key and index | gallery pages/language.duo (Keyed list) | gallery-language-list.png |
<scroll> | gallery pages/language.duo (Elements) | gallery-language-elements.png |
<form> | gallery pages/language.duo (A form) | gallery-language-form.png |
<toggle> | gallery pages/language.duo (Two-way binding); components pages/index.duo | gallery-language-binding.png |
<checkbox> | gallery pages/language.duo (Two-way binding) | gallery-language-binding.png |
<slider> | gallery pages/language.duo (Two-way binding) | gallery-language-binding.png |
<progress> (determinate and indeterminate) | gallery pages/language.duo (Elements) | gallery-language-elements.png |
<icon> | gallery pages/language.duo (Elements) | gallery-language-elements.png |
<overlay> (kind, anchor, open) | gallery pages/overlays.duo (The overlay element) | gallery-overlays-element.png |
<show> and <otherwise> | gallery pages/language.duo; control-flow | gallery-language.png |
Components with props() | gallery components/Panel.duo, components/Rating.duo | gallery-language-components.png |
bindable() props and bind: on a component | gallery components/Rating.duo | gallery-language-components.png |
<slot>, named slots | gallery components/Panel.duo; components components/Card.duo | gallery-language-components.png |
Scoped <style> blocks | gallery pages/styling.duo (A page style block) | gallery-styling-dark.png |
class:name={condition} | gallery pages/language.duo (Conditional classes) | gallery-language-effects.png |
derived() | gallery pages/language.duo (Derived values) | gallery-language-list.png |
effect(), onDispose(), untracked() | gallery pages/language.duo (effect, onDispose and untracked) | gallery-language-effects.png |
bind:value, bind:checked | gallery pages/language.duo (Two-way binding) | gallery-language-binding.png |
on:press | gallery pages/language.duo (Events) | gallery-language-events.png |
on:longpress | gallery pages/language.duo (Events); control-flow | gallery-language-events.png, control-flow-longpress.png |
on:key | gallery pages/language.duo (Events), components/Rating.duo | gallery-language-events.png |
on:focus, on:blur | gallery pages/language.duo (Events) | gallery-language-events.png |
on:change | gallery pages/language.duo (Events) | gallery-language-events.png |
on:submit | gallery pages/language.duo (A form) | gallery-language-form.png |
on:load, on:error on <image> | gallery pages/language.duo (Elements) | gallery-language-elements.png |
on:dismiss on <overlay> | gallery pages/overlays.duo (The overlay element) | gallery-overlays-element.png |
label, id | gallery pages/language.duo (A form, Accessibility attributes) | gallery-language-accessibility.png |
described-by | gallery pages/language.duo (A form) | gallery-language-form.png |
labelled-by, controls | gallery pages/language.duo (Accessibility attributes) | gallery-language-accessibility.png |
role, selected, tab-stop | gallery components/Rating.duo | gallery-language-components.png |
value-now, value-min, value-max, value-text | gallery pages/language.duo (Accessibility attributes) | gallery-language-accessibility.png |
href | gallery pages/navigation/index.duo | gallery-navigation.png |
current | gallery pages/navigation/item/[id].duo (hand-built section links, styled from [aria-current]) | gallery-navigation-item.png |
| Layout utilities (row, grow, items, justify, gap, grid) | gallery pages/styling.duo (Layout); styling pages/layout.duo | gallery-styling.png, styling-layout.png |
| Spacing utilities | styling pages/spacing.duo; gallery pages/styling.duo | styling-spacing.png |
| Sizing utilities | gallery pages/styling.duo (Sizing) | gallery-styling-sizing.png |
| Position utilities | gallery pages/styling.duo (Position) | gallery-styling-sizing.png |
| Colour utilities | gallery pages/styling.duo (Colour); styling pages/color.duo | gallery-styling-colour.png, styling-color.png |
| Type utilities | gallery pages/styling.duo (Type) | gallery-styling-type.png |
| Borders and radius | styling pages/borders.duo; gallery pages/styling.duo | styling-borders.png |
| Shadows and opacity | gallery pages/styling.duo (Shadows and opacity) | gallery-styling-shadows.png |
pressed:, hover:, focus:, disabled: | gallery pages/styling.duo (State prefixes); styling pages/states.duo | gallery-styling-prefixes.png, styling-states.png |
md:, lg: | gallery pages/_layout.duo (rail), pages/styling.duo | gallery-home-wide.png, gallery-styling-dark-wide.png |
dark: | gallery pages/styling.duo (Window and scheme prefixes) | gallery-styling-dark.png |
A light/dark switch, colorScheme | gallery pages/index.duo, pages/appearance.duo | gallery-appearance-dark.png |
File routes and [param] routes | gallery pages/navigation/item/[id].duo | gallery-navigation-item.png |
[...rest] routes | gallery pages/navigation/docs/[...topic].duo | gallery-navigation-rest.png |
route() (params and query) | gallery pages/navigation/item/[id].duo | gallery-navigation-item.png |
navigate(), with replace | gallery pages/navigation/index.duo | gallery-navigation-item.png |
back(), canGoBack(), backTitle() | gallery pages/navigation/item/[id].duo | gallery-navigation-item.png |
| Transitions (push slides, replace and tabs crossfade) | gallery pages/navigation/index.duo | gallery-navigation-transition.png |
Layouts (_layout.duo), nested | gallery pages/_layout.duo; navigation pages/profile/_layout.duo | gallery-home.png, navigation-settings.png |
guard() | gallery pages/navigation/vault.duo | gallery-navigation-guarded.png, gallery-navigation-vault.png |
Shared state, state(x, { shared }) | gallery pages/navigation/index.duo, pages/_layout.duo | gallery-navigation-shared.png |
_not-found.duo | gallery pages/_not-found.duo | gallery-navigation-not-found.png |
| Screen titles | gallery pages/navigation/item/[id].duo | gallery-navigation-item.png |
public/ files | gallery public/images/; inputs-and-media public/photos/ | gallery-inputs-and-media-images.png |
state.load() | gallery pages/data.duo (state.load) | gallery-data.png |
| A load keyed by state | gallery pages/data.duo | gallery-data-keyed.png |
action() with an optimistic change, rolled back | gallery pages/data.duo | gallery-data-rollback.png |
describeError() | gallery pages/data.duo (Optimistic action) | gallery-data-rollback.png |
Offline queue, network | gallery pages/data.duo (Offline queue); data pages/offline.duo | gallery-data-offline.png, data-offline-queued.png |
pagedList() | gallery pages/data.duo; data pages/catalogue.duo | gallery-data-paging.png, data-catalogue-more.png |
listView(), byText, byNumber, containsText | gallery pages/data.duo, pages/search.duo | gallery-data-paging.png, gallery-search-query.png |
filterItems(), sortItems() | gallery pages/data.duo | gallery-data-functions.png |
form(), field(), required, minLength, maxLength, email, matches, custom | gallery pages/data.duo (Form validation) | gallery-data-validation.png |
environment() | gallery pages/data.duo (Settings per build) | gallery-data-functions.png |
| Button, IconButton | gallery pages/kit-core.duo; kit pages/buttons.duo | gallery-kit-core.png, kit-buttons.png |
| ListRow, Section | gallery pages/kit-core.duo; kit pages/lists.duo | gallery-kit-core.png, kit-lists.png |
| Card, Avatar, Badge, Divider | gallery pages/kit-core.duo | gallery-kit-core-cards.png |
| TextField, TextArea | gallery pages/kit-core.duo; kit pages/inputs.duo | gallery-kit-core-fields.png, kit-inputs.png |
| ToggleRow, Checkbox, RadioGroup | gallery pages/kit-core.duo; kit pages/selection.duo | gallery-kit-core-selection.png, kit-selection.png |
| SegmentedControl, Slider | gallery pages/kit-core.duo | gallery-kit-core-controls.png |
| Spinner, ProgressBar | gallery pages/kit-core.duo | gallery-kit-core-controls.png |
| EmptyState, ErrorState | gallery pages/kit-core.duo; kit pages/feedback.duo | gallery-kit-core-feedback.png, kit-feedback.png |
| Sheet with detents | gallery pages/overlays.duo | gallery-overlays-sheet.png |
| Dialog | gallery pages/overlays.duo | gallery-overlays-dialog.png |
| AlertDialog | gallery pages/overlays.duo | gallery-overlays-alert.png |
| Menu | gallery pages/overlays.duo | gallery-overlays-menu.png |
| Popover | gallery pages/overlays.duo | gallery-overlays-popover.png |
| Tooltip | overlays pages/index.duo; gallery pages/overlays.duo | overlays-tooltip.png |
Toast, toast(), visibleToasts(), dismissToast() | gallery pages/overlays.duo | gallery-overlays-toast.png |
| Select | gallery pages/overlays.duo | gallery-overlays-select.png |
| DatePicker | gallery pages/inputs-and-media.duo | gallery-inputs-and-media.png |
| TimePicker, Stepper | gallery pages/inputs-and-media.duo; inputs-and-media pages/pickers.duo | inputs-and-media-pickers.png |
| SearchField, ChipGroup, Chip | gallery pages/inputs-and-media.duo | gallery-inputs-and-media-chips.png |
| Tabs | gallery pages/inputs-and-media.duo | gallery-inputs-and-media-tabs.png |
| Image (placeholder, fade, fallback) | gallery pages/inputs-and-media.duo; inputs-and-media pages/media.duo | gallery-inputs-and-media-images.png, inputs-and-media-media-fallback.png |
| ImageViewer and zoom | gallery pages/inputs-and-media.duo | gallery-inputs-and-media-viewer.png |
| Skeleton | gallery pages/inputs-and-media.duo | gallery-inputs-and-media-skeleton.png |
| TabBar, TabBarItem (badge, rail on wide windows) | gallery pages/_layout.duo, pages/navigation-parts.duo | gallery-navigation-parts.png, gallery-home-wide.png |
| NavHeader (large title, up, trailing actions) | gallery pages/index.duo, components/AreaScreen.duo | gallery-home.png, gallery-navigation-parts.png |
| Toolbar | gallery pages/navigation-parts.duo | gallery-navigation-parts-toolbar.png |
| Breadcrumbs | gallery pages/navigation/docs/[...topic].duo | gallery-navigation-rest.png |
| Link | gallery pages/navigation-parts.duo | gallery-navigation-parts.png |
Kit parts' props typed (ChipGroup's values for several choices) | gallery pages/inputs-and-media.duo (Chips) | gallery-inputs-and-media-chips.png |
| Keyed lists move only the rows that changed order, in TypeScript, measured against Rust built to WebAssembly (decision 0077) | gallery pages/language.duo (Keyed list, Reverse) | pnpm bench --budgets |
Source
components/AreaScreen.duo
---
// The frame every area screen shares: a header with a way back to the gallery, an
// introduction, and the demos in a grid that is one column on a phone and more on a
// wide window.
import { props } from "@duolith/client";
import { NavHeader } from "@duolith/kit";
let { title, intro } = props<{ title: string; intro: string }>();
---
<NavHeader title={title} up="/" upTitle="Gallery" />
<view class="page gap-5 p-4 pb-12 md:p-8">
<text class="text-body text-muted">{intro}</text>
<view class="demos">
<slot />
</view>
</view>
<style>
.page {
width: 100%;
max-width: 1120px;
margin: 0 auto;
}
.demos {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
align-items: start;
gap: var(--space-4);
}
</style>components/Demo.duo
---
// One live demo on an area screen: a title, a line on what to try, and the demo itself.
import { props } from "@duolith/client";
let { title, note } = props<{ title: string; note?: string }>();
---
<view class="demo gap-4 p-4 rounded-xl bg-surface border">
<view class="gap-1">
<text role="heading" class="text-label font-semibold text-ink">{title}</text>
<show when={note}>
<text class="text-caption text-muted">{note}</text>
</show>
</view>
<slot />
</view>
<style>
.demo {
min-width: 0;
box-shadow: var(--shadow-sm);
}
</style>components/Panel.duo
---
// A panel with named slots: a header piece, the children, and a footer piece.
import { props } from "@duolith/client";
let { tone = "plain" } = props<{ tone?: "plain" | "accent" }>();
---
<view class="rounded-lg border overflow-hidden" class:accent={tone === "accent"}>
<view class="row items-center gap-2 px-3 py-2 bg-raised">
<slot name="header" />
</view>
<view class="gap-2 p-3">
<slot />
</view>
<view class="row justify-end gap-2 px-3 py-2 border-t">
<slot name="footer" />
</view>
</view>
<style>
.accent {
border-color: var(--color-primary);
}
</style>components/Rating.duo
---
// A star rating: a component with a bindable prop, a radio group of stars with one Tab
// stop, and the arrow keys through on:key.
import { bindable, props } from "@duolith/client";
let { label, value = bindable(3) } = props<{ label: string; value?: number }>();
const stars = [1, 2, 3, 4, 5];
function move(key: string) {
if (key === "ArrowRight" || key === "ArrowUp") value = Math.min(5, value + 1);
if (key === "ArrowLeft" || key === "ArrowDown") value = Math.max(1, value - 1);
if (key === "Home") value = 1;
if (key === "End") value = 5;
}
---
<view
role="radio-group"
label={label}
class="row items-center gap-1"
on:key={(event) => move(event.key)}
>
<list each={stars} as="star" key={star} class="row gap-1">
<view
role="radio"
label={`${star} of 5`}
selected={star === value}
tab-stop={star === value}
class="star items-center justify-center rounded-md"
class:lit={star <= value}
on:press={() => (value = star)}
>
<icon name="star" />
</view>
</list>
</view>
<style>
.star {
width: 36px;
height: 36px;
color: var(--color-border);
cursor: pointer;
}
.lit {
color: var(--color-primary);
}
/* Keyboard focus: browsers only, as a phone gives only fields the focus. */
@supports selector(:focus-visible) {
.star:focus-visible {
outline: 2px solid var(--color-primary);
}
}
@supports (outline-offset: 1px) {
.star:focus-visible {
outline-offset: 1px;
}
}
</style>pages/_layout.duo
---
// The gallery's chrome: a tab bar at the bottom of a phone, a rail at the side of a wide
// window. Every area screen belongs to the Gallery tab.
import { route, state } from "@duolith/client";
import { TabBar, TabBarItem } from "@duolith/kit";
// Features added since the gallery was last searched; the Search screen clears it.
let unseen = state(3, { shared: "gallery-unseen" });
function isInGallery(): boolean {
const path = route().path;
return !path.startsWith("/search") && !path.startsWith("/appearance");
}
---
<view class="lg:row">
<slot />
<TabBar rail>
<TabBarItem label="Gallery" icon="home" href="/" current={isInGallery()} />
<TabBarItem label="Search" icon="search" href="/search" badge={unseen} />
<TabBarItem label="Appearance" icon="sun" href="/appearance" />
</TabBar>
</view>pages/_not-found.duo
---
// Shown, inside the layout, for any path no page serves.
import { route } from "@duolith/client";
import { EmptyState } from "@duolith/kit";
let { path } = route();
---
<screen title="Not found" class="items-center justify-center p-6">
<EmptyState icon="alert" title="Nothing here" message={`No screen is at ${path}.`} />
<view href="/" class="px-4 py-2 rounded-md bg-primary pressed:opacity-75">
<text class="text-label text-on-primary">Back to the gallery</text>
</view>
</screen>pages/appearance.duo
---
// Appearance: light, dark or the device's setting, with colorScheme from @duolith/client
// (decision 0043). The choice is kept on this device.
import { colorScheme, effect, state, type ColorSchemeChoice } from "@duolith/client";
import { Avatar, Badge, Button, Card, ListRow, NavHeader, Section, SegmentedControl, ToggleRow } from "@duolith/kit";
const schemes: { value: ColorSchemeChoice; label: string; icon: string }[] = [
{ value: "system", label: "System", icon: "settings" },
{ value: "light", label: "Light", icon: "sun" },
{ value: "dark", label: "Dark", icon: "moon" },
];
// The control gives back any string; only a known choice reaches colorScheme.
let scheme = state<string>(colorScheme.choice);
effect(() => {
const chosen = schemes.find((each) => each.value === scheme);
if (chosen) colorScheme.choose(chosen.value);
});
let preview = state(true);
---
<screen title="Appearance">
<NavHeader title="Appearance" large />
<view class="page gap-5 p-4 pb-12">
<SegmentedControl label="Appearance" options={schemes} bind:value={scheme} />
<text class="text-caption text-muted">
Showing {colorScheme.isDark ? "dark" : "light"} values.
{scheme === "system" ? "Following this device's setting." : "Kept on this device until you choose System."}
</text>
<Card title="Preview" subtitle="Every part takes its colours from the theme's tokens.">
<view class="row items-center gap-3">
<Avatar name="Ada Lovelace" status="online" />
<view class="grow gap-1">
<text class="text-label text-ink">Ada Lovelace</text>
<text class="text-caption text-muted">Online now</text>
</view>
<Badge label="Pro" tone="primary" />
</view>
<ToggleRow label="Show the preview row" bind:checked={preview} />
<show when={preview}>
<view class="row gap-2">
<Button label="Primary" />
<Button label="Secondary" variant="secondary" />
</view>
</show>
</Card>
<Section
title="Themes"
footer="A project theme is theme.yaml, checked and built in; examples/theming shows one. Whole themes are chosen when the app is built, not while it runs."
>
<ListRow title="Theme" value="Default" icon="eye" />
<ListRow title="Dark values" value={colorScheme.isDark ? "In use" : "Ready"} icon="moon" />
</Section>
</view>
</screen>
<style>
.page {
width: 100%;
max-width: 720px;
margin: 0 auto;
}
</style>pages/data.duo
---
// The data layer with an in-memory server, so the gallery needs no network: state.load and
// one keyed by state, an optimistic action that rolls back, queued writes while offline,
// load-more paging, a list view, form validation, the network and build settings.
// examples/data shows the same against a real HTTP server, with api() and a live stream.
import { action, byNumber, byText, containsText, custom, derived, describeError, email, environment } from "@duolith/client";
import { field, filterItems, form, listView, matches, maxLength, minLength, network, pagedList, required } from "@duolith/client";
import { effect, sortItems, state } from "@duolith/client";
import { Badge, Button, ListRow, SegmentedControl, Skeleton, TextField, ToggleRow } from "@duolith/kit";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
type Post = { id: number; title: string; likes: number };
type Plant = { id: number; name: string; family: string; height: number };
// The pretend server: answers after a short wait, kept in memory.
const wait = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const posts: Post[] = [
{ id: 1, title: "First light over the harbour", likes: 12 },
{ id: 2, title: "New desk, same bugs", likes: 4 },
{ id: 3, title: "Likes are closed on this one", likes: 31 },
];
// Each note has an id of its own, so rows keep their place even when two
// notes say the same thing.
type Note = { id: string; text: string };
const notes: Note[] = [{ id: "first", text: "Buy more coffee" }];
const families = ["Fern", "Palm", "Cactus", "Ivy", "Fig"];
const plants: Plant[] = Array.from({ length: 30 }, (_, index) => ({
id: index + 1,
name: `${families[index % 5]} ${String.fromCharCode(65 + (index % 26))}${index + 1}`,
family: families[index % 5] ?? "Fern",
height: 10 + ((index * 37) % 90),
}));
let loads = 0;
// state.load: loaded once, cached under its key, refreshed on demand
const feed = state.load("gallery-posts", async () => {
await wait(700);
loads += 1;
return posts.map((post) => ({ ...post }));
});
// State that loads, keyed by other state, follows it
let chosen = state("1");
const detail = state.load(
() => ["gallery-post", chosen],
async (key) => {
await wait(400);
const found = posts.find((post) => post.id === Number(key[1]));
if (found === undefined) throw new Error("There is no such post.");
return found;
},
);
// action: optimistic, rolled back when the server refuses
const like = action(
async (post: Post) => {
await wait(500);
if (post.id === 3) throw new Error("Likes are closed on this post.");
const liked = posts.find((each) => each.id === post.id);
if (liked !== undefined) liked.likes += 1;
return post;
},
{
retry: false,
optimistic: {
key: "gallery-posts",
update: (current: Post[] | undefined, liked) =>
(current ?? []).map((each) => (each.id === liked.id ? { ...each, likes: each.likes + 1 } : each)),
},
invalidates: ["gallery-posts"],
},
);
// Queued writes: offline, a note waits and is sent when the network is back
const savedNotes = state.load("gallery-notes", async () => {
await wait(300);
return [...notes];
});
const addNote = action(
async (note: Note) => {
await wait(300);
notes.push(note);
return note;
},
{
queue: "gallery-notes",
optimistic: { key: "gallery-notes", update: (current: Note[] | undefined, note) => [...(current ?? []), note] },
invalidates: ["gallery-notes"],
},
);
let draft = state("Water the ferns");
let offline = state(false);
function saveNote() {
if (draft.trim() === "") return;
addNote.run({ id: `${Date.now()}-${Math.random().toString(36).slice(2)}`, text: draft.trim() });
draft = "";
}
// pagedList and listView
const catalogue = pagedList(async (page: number | undefined) => {
await wait(400);
const start = ((page ?? 1) - 1) * 8;
const items = plants.slice(start, start + 8);
return { items, next: start + 8 < plants.length ? (page ?? 1) + 1 : undefined };
});
const shown = listView(() => catalogue.items, {
search: (plant, query) => containsText(`${plant.name} ${plant.family}`, query),
sorts: { name: byText((plant: Plant) => plant.name), height: byNumber((plant: Plant) => plant.height) },
});
let query = state("");
let sort = state("");
effect(() => (shown.query = query));
effect(() => (shown.sortBy = sort as "" | "name" | "height"));
const sorts = [
{ value: "", label: "Loaded" },
{ value: "name", label: "Name" },
{ value: "height", label: "Height" },
];
// Validation
const password = field("", required("Choose a password."), minLength(8));
const signUp = form({
name: field("", required("Tell us your name."), maxLength(30)),
username: field("", required("Pick a username."), matches(/^[a-z0-9_]+$/, "Use lowercase letters, digits and _.")),
email: field("", required("We need an email."), email()),
password,
confirmation: field("", custom((value) => value === password.value, "The passwords do not match.")),
});
// The kit's fields bind to state; each follows into its form field once typed in.
let nameText = state("");
let usernameText = state("");
let emailText = state("");
let passwordText = state("");
let confirmationText = state("");
effect(() => typeInto(signUp.fields.name, nameText));
effect(() => typeInto(signUp.fields.username, usernameText));
effect(() => typeInto(signUp.fields.email, emailText));
effect(() => typeInto(signUp.fields.password, passwordText));
effect(() => typeInto(signUp.fields.confirmation, confirmationText));
function typeInto(target: { value: string }, text: string) {
if (target.value !== text) target.value = text;
}
let welcome = state("");
function sendSignUp() {
signUp.submit((values) => (welcome = `Welcome, ${values.name}!`));
}
// Settings per build, with their defaults
const settings = environment({ region: "eu-west", pageSize: 8, beta: false });
// The same work as a list view, as plain functions: the three tallest ferns of all thirty.
const tallestFerns = sortItems(
filterItems(plants, "fern", { search: (plant, text) => containsText(plant.family, text) }),
byNumber((plant: Plant) => plant.height),
true,
).slice(0, 3);
let likedSummary = derived(() => (feed.data ?? []).reduce((sum, post) => sum + post.likes, 0));
---
<screen title="Data">
<AreaScreen
title="Data"
intro="Everything here talks to a pretend server kept in memory, with real delays, failures and an offline switch."
>
<Demo
title="state.load"
note="Loading, then cached; refresh loads again while the old value shows."
>
<show when={feed.loading}>
<Skeleton lines={3} label="Loading posts" />
</show>
<otherwise>
<list each={feed.data ?? []} as="post" key={post.id} class="gap-2">
<view class="row items-center gap-3 p-3 rounded-md bg-raised">
<text class="grow text-body text-ink truncate">{post.title}</text>
<Button
label={`♥ ${post.likes}`}
size="sm"
variant="secondary"
onPress={() => like.run(post)}
/>
</view>
</list>
</otherwise>
<view class="row items-center justify-between">
<text class="text-caption text-muted">
{feed.refreshing ? "Refreshing…" : `${likedSummary} likes, loaded ${loads === 1 ? "once" : `${loads} times`}`}
</text>
<Button
label="Refresh"
icon="refresh"
size="sm"
variant="ghost"
onPress={() => feed.refresh()}
/>
</view>
</Demo>
<Demo
title="Optimistic action, rolled back"
note="Likes show at once. The third post refuses: its like is taken back."
>
<view class="row items-center gap-2">
<Badge
label={like.pending ? "Sending…" : "Idle"}
tone={like.pending ? "primary" : "neutral"}
/>
<show when={like.errorMessage}>
<text role="alert" class="text-caption text-danger">{describeError(like.error)}</text>
</show>
</view>
<Button
label="Like the third post"
variant="secondary"
onPress={() => posts[2] && like.run(posts[2])}
/>
</Demo>
<Demo title="A load keyed by state" note="Choosing another post loads it under its own key.">
<SegmentedControl
label="Post"
options={[
{ value: "1", label: "One" },
{ value: "2", label: "Two" },
{ value: "3", label: "Three" },
]}
bind:value={chosen}
/>
<text class="text-body text-ink">
{detail.loading ? "Loading…" : `“${detail.data?.title}”, ${detail.data?.likes} likes`}
</text>
</Demo>
<Demo title="Offline queue" note="Go offline, add notes, come back: they are sent in order.">
<ToggleRow
label="Pretend to be offline"
icon="wifi-off"
bind:checked={offline}
onChange={(isOffline) => network.pretendOffline(isOffline)}
/>
<view class="row items-end gap-2">
<view class="grow">
<TextField label="Note" bind:value={draft} />
</view>
<Button label="Add" icon="plus" onPress={saveNote} />
</view>
<list each={savedNotes.data ?? []} as="note" key={note.id} class="gap-1">
<text class="text-body text-ink">• {note.text}</text>
</list>
<list each={addNote.queued} as="waiting" key={waiting.id} class="gap-1">
<text class="text-caption text-primary">Waiting to send: {waiting.text}</text>
</list>
<text class="text-caption text-muted">Network: {network.online ? "online" : "offline"}</text>
</Demo>
<Demo
title="pagedList and listView"
note="Load more, page by page; search and sort what has loaded."
>
<TextField label="Search loaded plants" icon="search" bind:value={query} />
<SegmentedControl label="Sort" options={sorts} bind:value={sort} />
<list each={shown.items.slice(0, 6)} as="plant" key={plant.id} class="gap-1">
<view class="row justify-between px-3 py-2 rounded-md bg-raised">
<text class="text-body text-ink">{plant.name}</text>
<text class="text-caption text-muted">{plant.height} cm</text>
</view>
</list>
<view class="row items-center justify-between">
<text class="text-caption text-muted">
{shown.count} shown of {catalogue.items.length} loaded
</text>
<show when={catalogue.hasMore}>
<Button
label={catalogue.loading ? "Loading…" : "Load more"}
size="sm"
variant="secondary"
onPress={() => catalogue.loadMore()}
/>
</show>
</view>
</Demo>
<Demo title="Form validation" note="Errors show once you type in a field or try to send.">
<TextField label="Name" bind:value={nameText} error={signUp.fields.name.error} />
<TextField label="Username" bind:value={usernameText} error={signUp.fields.username.error} />
<TextField
label="Email"
type="email"
bind:value={emailText}
error={signUp.fields.email.error}
/>
<TextField
label="Password"
type="password"
bind:value={passwordText}
error={signUp.fields.password.error}
/>
<TextField
label="Confirm password"
type="password"
bind:value={confirmationText}
error={signUp.fields.confirmation.error}
/>
<Button label="Create account" full onPress={sendSignUp} />
<show when={welcome}>
<text role="status" class="text-label text-success">{welcome}</text>
</show>
</Demo>
<Demo
title="filterItems and sortItems"
note="A list view's work as plain functions: the tallest ferns."
>
<list each={tallestFerns} as="plant" key={plant.id} class="gap-1">
<view class="row justify-between px-3 py-2 rounded-md bg-raised">
<text class="text-body text-ink">{plant.name}</text>
<text class="text-caption text-muted">{plant.height} cm</text>
</view>
</list>
</Demo>
<Demo
title="Settings per build"
note="environment() gives each setting its default unless the build provides one."
>
<ListRow title="region" value={settings.region} />
<ListRow title="pageSize" value={String(settings.pageSize)} />
<ListRow title="beta" value={String(settings.beta)} />
</Demo>
</AreaScreen>
</screen>pages/index.duo
---
// The gallery's home: one card for each feature area. Each opens a screen of small live
// demos; FEATURES.md lists every feature and where it is shown.
import { colorScheme } from "@duolith/client";
import { IconButton, NavHeader } from "@duolith/kit";
const areas = [
{
href: "/language",
icon: "edit",
title: "Language",
blurb: "Markup, state, derived values, binding, events, forms, keyed lists and components.",
count: 12,
},
{
href: "/styling",
icon: "eye",
title: "Styling and themes",
blurb: "Every utility family, the state and window prefixes, page styles and dark mode.",
count: 11,
},
{
href: "/data",
icon: "download",
title: "Data",
blurb: "State that loads, optimistic actions, the offline queue, paging, list views and validation.",
count: 8,
},
{
href: "/navigation",
icon: "location",
title: "Navigation",
blurb: "Routes with parameters, the screen stack, back, guards, shared state and not found.",
count: 7,
},
{
href: "/kit-core",
icon: "check-circle",
title: "Kit core",
blurb: "Buttons, rows, cards, avatars, badges, fields, switches and feedback states.",
count: 10,
},
{
href: "/overlays",
icon: "copy",
title: "Overlays",
blurb: "Sheets, dialogs, alerts, menus, popovers, tooltips, toasts and a select.",
count: 7,
},
{
href: "/inputs-and-media",
icon: "image",
title: "Inputs and media",
blurb: "Date and time pickers, a stepper, search, chips, tabs, images and the zoomable viewer.",
count: 7,
},
{
href: "/navigation-parts",
icon: "menu",
title: "Navigation parts",
blurb: "The tab bar and rail around you, headers, a toolbar, breadcrumbs and links.",
count: 5,
},
];
function flipScheme() {
colorScheme.choose(colorScheme.isDark ? "light" : "dark");
}
---
<screen title="duolith gallery">
<NavHeader title="Gallery" large>
<piece name="trailing">
<IconButton
icon={colorScheme.isDark ? "sun" : "moon"}
label={colorScheme.isDark ? "Use light mode" : "Use dark mode"}
onPress={flipScheme}
/>
</piece>
</NavHeader>
<view class="page gap-6 p-4 pb-12 md:p-8">
<view class="hero gap-2 p-5 rounded-xl">
<text class="text-caption font-semibold hero-kicker">duolith, every feature</text>
<text role="heading" class="text-title hero-title">Examples of all and any of it</text>
<text class="text-body hero-text">
One app, written in .duo pages, showing each feature live. Press a card to open its demos;
everything runs in the page, with no network.
</text>
</view>
<list each={areas} as="area" key={area.href} class="areas">
<view
href={area.href}
class="area gap-3 p-4 rounded-xl bg-surface border pressed:bg-raised hover:shadow-md"
>
<view class="row items-center justify-between">
<view class="glyph items-center justify-center rounded-lg">
<icon name={area.icon} class="text-primary" />
</view>
<text class="text-caption text-muted">{area.count} demos</text>
</view>
<view class="gap-1">
<text class="text-heading text-ink">{area.title}</text>
<text class="text-body text-muted line-clamp-2">{area.blurb}</text>
</view>
<view class="row items-center gap-1 text-primary">
<text class="text-label">Open</text>
<icon name="chevron-right" />
</view>
</view>
</list>
</view>
</screen>
<style>
.page {
width: 100%;
max-width: 1120px;
margin: 0 auto;
}
.hero {
background: linear-gradient(135deg, var(--color-primary), var(--color-ink));
}
.hero-kicker,
.hero-text {
color: var(--color-on-primary);
opacity: 0.85;
}
.hero-title {
color: var(--color-on-primary);
}
.areas {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr));
gap: var(--space-4);
}
.area {
box-shadow: var(--shadow-sm);
transition: box-shadow 150ms;
}
.glyph {
width: 40px;
height: 40px;
background: var(--color-raised);
}
</style>pages/inputs-and-media.duo
---
// Inputs and media: the pickers, a stepper, search, chips, tabs, images from public/ with
// their placeholder and fallback, the zoomable viewer, and skeletons.
import { state } from "@duolith/client";
import { Button, Chip, ChipGroup, DatePicker, Image, ImageViewer, SearchField } from "@duolith/kit";
import { Skeleton, Stepper, Tabs, TimePicker } from "@duolith/kit";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
let day = state("2026-11-16");
let alarm = state("07:30");
let guests = state(2);
let query = state("");
let searched = state("");
let sort = state("near");
let diets = state(["vegetarian"]);
let openNow = state(true);
let tab = state("photos");
let viewing = state(false);
let shown = state(0);
let loading = state(true);
const photos = [
{ src: "/images/lake.svg", alt: "A lake below mountains at sunset" },
{ src: "/images/forest.svg", alt: "Pine trees in mist" },
{ src: "/images/dunes.svg", alt: "Sand dunes under a blue sky" },
{ src: "/images/city.svg", alt: "A city skyline at dusk" },
];
// One viewer for every thumbnail.
function open(src: string) {
shown = photos.findIndex((photo) => photo.src === src);
viewing = true;
}
const isWeekend = (date: string) => [0, 6].includes(new Date(`${date}T12:00:00`).getDay());
---
<screen title="Inputs and media">
<AreaScreen
title="Inputs and media"
intro="Pickers, search, chips and tabs bind both ways; images come from the app's public/ folder, are fetched once, and zoom full screen."
>
<Demo title="DatePicker" note={`Weekdays only. Chosen: ${day}.`}>
<DatePicker
label="Day"
min="2026-11-01"
max="2026-12-31"
disabledDates={isWeekend}
bind:value={day}
/>
</Demo>
<Demo title="TimePicker and Stepper" note={`Alarm at ${alarm}, ${guests} guests.`}>
<TimePicker label="Alarm" locale="en-GB" bind:value={alarm} />
<Stepper label="Guests" min={1} max={8} bind:value={guests} />
</Demo>
<Demo
title="SearchField, ChipGroup and Chip"
note={`Searched for: ${searched || "nothing yet"}.`}
>
<SearchField
label="Search places"
placeholder="Cafés, bakeries…"
bind:value={query}
onSubmit={(text) => (searched = text)}
/>
<ChipGroup
label="Sort by"
options={[
{ value: "near", label: "Nearest", icon: "location" },
{ value: "rated", label: "Top rated", icon: "star" },
{ value: "new", label: "Newest" },
]}
bind:value={sort}
/>
<ChipGroup
label="Diet"
multiple
options={[
{ value: "vegetarian", label: "Vegetarian" },
{ value: "vegan", label: "Vegan" },
{ value: "gluten-free", label: "Gluten-free" },
]}
bind:values={diets}
/>
<view class="row wrap gap-2">
<Chip label="Open now" icon="clock" bind:selected={openNow} />
<Chip label="Unavailable" disabled />
</view>
</Demo>
<Demo title="Tabs" note="In-page tabs; the arrow keys move between them.">
<Tabs
label="Place details"
tabs={[
{ value: "menu", label: "Menu" },
{ value: "photos", label: "Photos", icon: "image" },
{ value: "events", label: "Events", disabled: true },
]}
bind:selected={tab}
>
<show when={tab === "menu"}>
<text class="text-body text-ink">Soup of the day, sourdough and a seasonal tart.</text>
</show>
<show when={tab === "photos"}>
<view class="row gap-2">
<list each={photos} as="photo" key={photo.src} class="row gap-2 grow">
<view class="thumb">
<Image src={photo.src} alt={photo.alt} ratio="1:1" radius="md" />
</view>
</list>
</view>
</show>
</Tabs>
</Demo>
<Demo
title="Image"
note="Ratios, fit, a placeholder colour while loading, and a fallback piece."
>
<Image
src="/images/lake.svg"
alt="A lake below mountains at sunset"
ratio="16:9"
placeholder="#8a9bb0"
/>
<view class="row gap-3">
<view class="thumb">
<Image
src="/images/forest.svg"
alt="Pine trees in mist"
ratio="3:4"
placeholder="#9fbf9f"
/>
</view>
<view class="thumb">
<Image
src="/images/dunes.svg"
alt="Sand dunes under a blue sky"
ratio="3:4"
fit="contain"
/>
</view>
<view class="thumb">
<Image src="/images/not-a-picture.svg" alt="A photo that cannot be shown" ratio="3:4">
<piece name="fallback">
<text class="text-caption text-muted text-center">No photo</text>
</piece>
</Image>
</view>
</view>
</Demo>
<Demo
title="Zoom and ImageViewer"
note="Press a photo: pinch, wheel or double-tap to zoom, swipe down to close."
>
<Image src="/images/city.svg" alt="A city skyline at dusk" ratio="16:9" zoomable />
<view class="row gap-2">
<list each={photos} as="photo" key={photo.src} class="row gap-2 grow">
<button class="thumb" label={`Open ${photo.alt}`} on:press={() => open(photo.src)}>
<Image src={photo.src} decorative ratio="1:1" radius="md" />
</button>
</list>
</view>
<ImageViewer
src={photos[shown]?.src ?? ""}
alt={photos[shown]?.alt ?? ""}
bind:open={viewing}
/>
</Demo>
<Demo title="Skeleton" note="Placeholders in the shape of what is coming.">
<show when={loading}>
<view class="row items-center gap-3">
<Skeleton shape="circle" size="lg" />
<view class="grow">
<Skeleton lines={2} />
</view>
</view>
<Skeleton shape="block" label="Loading the photo" />
</show>
<otherwise>
<view class="row items-center gap-3">
<view class="avatar">
<Image src="/images/forest.svg" decorative ratio="1:1" radius="full" />
</view>
<view class="grow gap-1">
<text class="text-label text-ink">Forest walk</text>
<text class="text-caption text-muted">Loaded from public/images</text>
</view>
</view>
<Image src="/images/forest.svg" alt="Pine trees in mist" ratio="16:9" />
</otherwise>
<Button
label={loading ? "Finish loading" : "Load again"}
variant="secondary"
onPress={() => (loading = !loading)}
/>
</Demo>
</AreaScreen>
</screen>
<style>
.thumb {
flex: 1;
min-width: 0;
}
.avatar {
width: 48px;
}
</style>pages/kit-core.duo
---
// The kit's core parts: buttons, rows and sections, cards, avatars, badges, dividers,
// fields, the selection controls, and the feedback and empty states.
import { state } from "@duolith/client";
import { Avatar, Badge, Button, Card, Checkbox, Divider, EmptyState, ErrorState } from "@duolith/kit";
import { IconButton, Image, ListRow, ProgressBar, RadioGroup, Section, SegmentedControl } from "@duolith/kit";
import { Slider, Spinner, TextArea, TextField, ToggleRow } from "@duolith/kit";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
let saving = state(false);
let starred = state(true);
let pressed = state(0);
let name = state("Ada Lovelace");
let bio = state("");
let notifications = state(true);
let newsletter = state(false);
let plan = state("yearly");
let view = state("grid");
let volume = state(60);
let messages = state<string[]>([]);
let retrying = state(false);
let tries = state(1);
const plans = [
{ value: "monthly", label: "Monthly", hint: "£4 a month" },
{ value: "yearly", label: "Yearly", hint: "£40 a year, two months free" },
];
const views = [
{ value: "list", label: "List", icon: "menu" },
{ value: "grid", label: "Grid", icon: "image" },
];
function save() {
saving = true;
setTimeout(() => (saving = false), 1500);
}
function retry() {
retrying = true;
setTimeout(() => {
retrying = false;
tries += 1;
}, 1000);
}
---
<screen title="Kit core">
<AreaScreen
title="Kit core"
intro="Ready-made parts that look right in any theme, light and dark, and are accessible from the start."
>
<Demo title="Button and IconButton" note="Variants, sizes, icons, loading and disabled.">
<view class="row wrap gap-2">
<Button label="Primary" onPress={() => (pressed += 1)} />
<Button label="Secondary" variant="secondary" />
<Button label="Ghost" variant="ghost" />
<Button label="Danger" variant="danger" icon="trash" />
</view>
<view class="row wrap items-center gap-2">
<Button label="Small" size="sm" />
<Button label="Large" size="lg" iconEnd="arrow-right" />
<Button label="Disabled" disabled />
</view>
<Button
label={saving ? "Saving" : "Save"}
icon="check"
loading={saving}
full
onPress={save}
/>
<view class="row items-center gap-2">
<IconButton
icon="star"
label="Star"
selected={starred}
onPress={() => (starred = !starred)}
/>
<IconButton icon="share" label="Share" variant="secondary" />
<IconButton icon="trash" label="Delete" variant="danger" />
<text class="text-caption text-muted">Primary pressed {pressed} times</text>
</view>
</Demo>
<Demo
title="ListRow and Section"
note="Rows on one surface: links, buttons, values and pieces."
>
<Section title="Account" footer="Rows can lead with an avatar and trail with a badge.">
<ListRow title="Ada Lovelace" subtitle="Online now" chevron href="/kit-core">
<piece name="leading">
<Avatar name="Ada Lovelace" status="online" />
</piece>
<piece name="trailing">
<Badge label="New" tone="primary" />
</piece>
</ListRow>
<ListRow title="Email" value="ada@example.com" icon="mail" />
<ListRow
title="Notifications"
icon="bell"
value="On"
chevron
onPress={() => (notifications = !notifications)}
/>
<ListRow title="Delete account" icon="trash" destructive />
<ListRow title="Unavailable" icon="lock" disabled />
</Section>
</Demo>
<Demo title="Card, Avatar, Badge and Divider">
<Card title="Lake at dusk" subtitle="Card with a media piece">
<piece name="media">
<Image
src="/images/lake.svg"
alt="A lake below mountains at sunset"
ratio="16:9"
radius="none"
/>
</piece>
<text class="text-body text-muted">Cards hold related content on one surface.</text>
</Card>
<view class="row items-center gap-3">
<Avatar name="Grace Hopper" size="sm" />
<Avatar name="Alan Turing" status="away" />
<Avatar name="Katherine Johnson" size="lg" status="online" />
<Avatar name="City" src="/images/city.svg" size="xl" />
</view>
<Divider label="Badges" />
<view class="row wrap gap-2">
<Badge label="Neutral" />
<Badge label="Primary" tone="primary" />
<Badge label="Success" tone="success" icon="check" />
<Badge label="Danger" tone="danger" solid />
</view>
</Demo>
<Demo title="TextField and TextArea" note="Labels, hints, errors and a character count.">
<TextField label="Name" icon="user" hint="As it appears on your card" bind:value={name} />
<TextField label="Username" value="ada" error="That username is taken." />
<TextArea label="About you" placeholder="A line or two" limit={80} bind:value={bio} />
</Demo>
<Demo title="ToggleRow, Checkbox, RadioGroup" note="Bound both ways to state.">
<ToggleRow
label="Notifications"
hint="Messages and mentions"
icon="bell"
bind:checked={notifications}
/>
<Checkbox label="Send me the newsletter" hint="Once a month" bind:checked={newsletter} />
<RadioGroup label="Plan" options={plans} bind:value={plan} />
<text class="text-caption text-muted">
Notifications {notifications ? "on" : "off"}, newsletter {newsletter ? "yes" : "no"}, plan
{plan}.
</text>
</Demo>
<Demo title="SegmentedControl and Slider">
<SegmentedControl label="View" options={views} bind:value={view} />
<Slider label="Volume" unit="%" bind:value={volume} />
<text class="text-caption text-muted">{view} view at {volume}%.</text>
</Demo>
<Demo title="Spinner and ProgressBar">
<view class="row items-center gap-5 text-primary">
<Spinner size="sm" />
<Spinner />
<Spinner size="lg" label="Syncing" />
</view>
<ProgressBar label="Volume" value={volume / 100} showValue />
<ProgressBar label="Preparing" />
<ProgressBar label="Backed up" value={1} tone="success" showValue />
</Demo>
<Demo title="EmptyState and ErrorState">
<show when={messages.length > 0}>
<ListRow title={messages[0] ?? ""} icon="mail" />
<Button label="Clear" variant="ghost" onPress={() => (messages = [])} />
</show>
<otherwise>
<EmptyState
icon="inbox"
title="No messages yet"
message="When someone writes to you, it shows here."
action="Write one"
onAction={() => (messages = ["Hello from the kit"])}
/>
</otherwise>
<ErrorState
message={`We could not load your feed. Tried ${tries} times.`}
retrying={retrying}
onRetry={retry}
/>
</Demo>
</AreaScreen>
</screen>pages/language.duo
---
// The language: elements, state, derived values, binding, events, forms, keyed lists,
// control flow, components, conditional classes and the accessibility attributes.
import { derived, effect, onDispose, state, untracked } from "@duolith/client";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
import Panel from "../components/Panel.duo";
import Rating from "../components/Rating.duo";
// show and otherwise
let isOpen = state(true);
// A keyed list with an index
type Fruit = { id: number; name: string };
let fruits = state<Fruit[]>([
{ id: 1, name: "Apple" },
{ id: 2, name: "Fig" },
{ id: 3, name: "Pear" },
]);
let nextFruit = 4;
const names = ["Quince", "Lime", "Plum", "Kiwi", "Mango", "Date"];
function addFruit() {
fruits = [...fruits, { id: nextFruit, name: names[nextFruit % names.length] ?? "Fig" }];
nextFruit += 1;
}
// Derived values follow what they read
let price = state(4);
let quantity = state(3);
let total = derived(() => price * quantity);
let summary = derived(() => `${quantity} × £${price} = £${total}`);
// Two-way binding
let name = state("Ada");
let bio = state("Writes the first program.");
let volume = state(40);
let agreed = state(false);
let wifi = state(true);
// A form, sent without reloading
let email = state("");
let triedToSend = state(false);
let sent = state("");
let emailIsValid = derived(() => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email));
function send() {
triedToSend = true;
if (!emailIsValid) return;
sent = `Sent to ${email}`;
}
// Events
let presses = state(0);
let held = state(0);
let focusNote = state("Not focused");
let changed = state("");
let lastKey = state("none yet");
let imagesLoaded = state(0);
let imageFailed = state(false);
// Components with a bindable prop, slots and pieces
let stars = state(4);
// Conditional classes
let highlighted = state(false);
// Effects, cleanup and untracked reads
let seconds = state(0);
let changes = state(0);
const ticking = setInterval(() => (seconds += 1), 1000);
onDispose(() => clearInterval(ticking));
effect(() => {
void stars;
untracked(() => (changes += 1));
});
// The accessibility attributes
let guests = state(2);
let detailsShown = state(false);
function stepGuests(key: string) {
if (key === "ArrowUp") guests = Math.min(8, guests + 1);
if (key === "ArrowDown") guests = Math.max(1, guests - 1);
}
---
<screen title="Language">
<AreaScreen
title="Language"
intro="Every element and attribute of the page language, live. Each card is a few lines of markup and state."
>
<Demo title="show and otherwise" note="Flip the switch: one branch shows at a time.">
<view class="row items-center justify-between">
<text class="text-body text-ink">Door</text>
<toggle label="Door open" bind:checked={isOpen} />
</view>
<show when={isOpen}>
<view class="row items-center gap-2 p-3 rounded-md bg-raised">
<icon name="check-circle" class="text-success" />
<text class="text-body text-ink">The door is open.</text>
</view>
</show>
<otherwise>
<view class="row items-center gap-2 p-3 rounded-md bg-raised">
<icon name="lock" class="text-muted" />
<text class="text-body text-muted">The door is closed.</text>
</view>
</otherwise>
</Demo>
<Demo title="Keyed list with an index" note="Rows keep their identity when reordered.">
<list each={fruits} as="fruit" key={fruit.id} index="i" class="gap-2">
<view class="row items-center gap-3 px-3 py-2 rounded-md bg-raised">
<text class="text-caption text-muted">{i + 1}</text>
<text class="grow text-body text-ink">{fruit.name}</text>
<button
label={`Remove ${fruit.name}`}
class="text-danger"
on:press={() => (fruits = fruits.filter((each) => each.id !== fruit.id))}
>
<icon name="close" />
</button>
</view>
</list>
<view class="row gap-2">
<button class="chip" on:press={addFruit}>Add</button>
<button class="chip" on:press={() => (fruits = [...fruits].reverse())}>Reverse</button>
</view>
</Demo>
<Demo title="Derived values" note="total and summary follow price and quantity.">
<view class="row items-center justify-between">
<text class="text-body text-ink">Price £{price}</text>
<view class="row gap-2">
<button class="chip" label="Cheaper" on:press={() => (price = Math.max(1, price - 1))}>
−
</button>
<button class="chip" label="Dearer" on:press={() => (price += 1)}>+</button>
</view>
</view>
<view class="row items-center justify-between">
<text class="text-body text-ink">Quantity {quantity}</text>
<view class="row gap-2">
<button
class="chip"
label="Fewer"
on:press={() => (quantity = Math.max(0, quantity - 1))}
>
−
</button>
<button class="chip" label="More" on:press={() => (quantity += 1)}>+</button>
</view>
</view>
<text class="text-heading text-primary">{summary}</text>
</Demo>
<Demo title="Two-way binding" note="bind:value and bind:checked on the platform's own fields.">
<input label="Name" placeholder="Your name" bind:value={name} />
<textarea label="About you" rows="2" bind:value={bio} />
<view class="row items-center gap-3">
<icon name="sun" class="text-muted" />
<slider label="Volume" min="0" max="100" step="5" bind:value={volume} class="grow" />
<text class="text-caption text-muted">{volume}</text>
</view>
<view class="row items-center gap-2">
<checkbox label="I agree" bind:checked={agreed} />
<text class="text-body text-ink">I agree</text>
<view class="grow" />
<text class="text-body text-ink">Wi-Fi</text>
<toggle label="Wi-Fi" bind:checked={wifi} />
</view>
<text class="text-caption text-muted">
{name || "Nobody"}, {bio.length} characters, volume {volume},
{agreed ? "agreed" : "not agreed"}, Wi-Fi {wifi ? "on" : "off"}.
</text>
</Demo>
<Demo title="A form" note="Enter or the submit button sends it; the page never reloads.">
<form class="gap-2" on:submit={send}>
<input
type="email"
label="Email"
placeholder="ada@example.com"
bind:value={email}
invalid={triedToSend && !emailIsValid}
described-by="email-hint"
/>
<text
id="email-hint"
class="text-caption"
class:text-danger={triedToSend && !emailIsValid}
class:text-muted={!triedToSend || emailIsValid}
>
{triedToSend && !emailIsValid ? "That does not look like an email address." : "We only use it to reply."}
</text>
<button
submit
class="send px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:opacity-75"
>
Send
</button>
</form>
<show when={sent}>
<text role="status" class="text-label text-success">{sent}</text>
</show>
</Demo>
<Demo title="Events" note="Press, hold for half a second, focus, change, and the arrow keys.">
<view class="row gap-2">
<view
tab-stop
class="pad grow items-center justify-center p-3 rounded-md bg-raised pressed:bg-border"
on:press={() => (presses += 1)}
on:longpress={() => (held += 1)}
>
<text class="text-label text-ink">Press or hold</text>
<text class="text-caption text-muted">{presses} presses, {held} holds</text>
</view>
<view
tab-stop
label="Arrow keys"
class="pad grow items-center justify-center p-3 rounded-md bg-raised"
on:key={(event) => (lastKey = event.key)}
on:press={() => (lastKey = "pressed")}
>
<text class="text-label text-ink">Focus, then arrows</text>
<text class="text-caption text-muted">{lastKey}</text>
</view>
</view>
<input
label="Change me"
placeholder="Type, then leave the field"
on:focus={() => (focusNote = "Focused")}
on:blur={() => (focusNote = "Not focused")}
on:change={(event) => (changed = event.value ?? "")}
/>
<text class="text-caption text-muted">{focusNote}; last change: {changed || "none"}</text>
</Demo>
<Demo
title="Components"
note="Rating has a bindable prop; Panel has named slots filled by pieces."
>
<Panel tone="accent">
<piece name="header">
<icon name="star" class="text-primary" />
<text class="text-label text-ink">Rate the gallery</text>
</piece>
<Rating label="Gallery rating" bind:value={stars} />
<text class="text-caption text-muted">You gave it {stars} of 5.</text>
<piece name="footer">
<button class="chip" on:press={() => (stars = 5)}>Five stars</button>
</piece>
</Panel>
</Demo>
<Demo title="Conditional classes" note="class:name={condition} adds a utility while it holds.">
<view
class="row items-center justify-between p-3 rounded-md border"
class:bg-primary={highlighted}
class:shadow-md={highlighted}
>
<text class="text-body" class:text-on-primary={highlighted} class:text-ink={!highlighted}>
{highlighted ? "Highlighted" : "Plain"}
</text>
<toggle label="Highlight" bind:checked={highlighted} />
</view>
</Demo>
<Demo
title="effect, onDispose and untracked"
note="A timer stopped when the screen goes; an effect counting rating changes."
>
<view class="row items-center gap-3">
<icon name="clock" class="text-primary" />
<text class="text-heading text-ink">{seconds} s on this screen</text>
</view>
<text class="text-caption text-muted">The rating above has changed {changes - 1} times.</text>
</Demo>
<Demo title="Elements" note="progress, icon, scroll and image, each the platform's own.">
<progress label="Upload" value={(seconds % 10) / 10} />
<progress label="Working" />
<scroll>
<list
each={["home", "search", "bell", "heart", "star", "camera", "globe", "mail", "phone", "user"]}
as="glyph"
class="row gap-2"
>
<view class="tile items-center justify-center rounded-md bg-raised">
<icon name={glyph} label={glyph} class="text-ink" />
</view>
</list>
</scroll>
<view class="row gap-3">
<image
src="/images/forest.svg"
alt="Pine trees in mist"
placeholder="raised"
class="photo rounded-md"
on:load={() => (imagesLoaded += 1)}
/>
<image
src="/images/dunes.svg"
decorative
lazy
class="photo rounded-md"
on:load={() => (imagesLoaded += 1)}
/>
<image
src="/images/not-a-picture.svg"
alt="A file that is not a picture"
class="photo rounded-md"
on:error={() => (imageFailed = true)}
/>
</view>
<text class="text-caption text-muted">
on:load ran {imagesLoaded} times; on:error
{imageFailed ? "ran for the file that is not a picture" : "has not run"}.
</text>
</Demo>
<Demo
title="Accessibility attributes"
note="role, selected, tab-stop, the value attributes, controls and labelled-by."
>
<view class="row items-center gap-2">
<button
class="chip"
label="Fewer guests"
tab-stop={false}
on:press={() => stepGuests("ArrowDown")}
>
−
</button>
<view
tab-stop
role="spinbutton"
label="Guests"
value-now={guests}
value-min={1}
value-max={8}
value-text={guests === 1 ? "1 guest" : `${guests} guests`}
class="grow row items-center justify-between p-3 rounded-md bg-raised"
on:key={(event) => stepGuests(event.key)}
>
<text class="text-body text-ink">Guests (focus, then ↑ ↓)</text>
<text class="text-heading text-primary">{guests}</text>
</view>
<button
class="chip"
label="More guests"
tab-stop={false}
on:press={() => stepGuests("ArrowUp")}
>
+
</button>
</view>
<button
class="chip self-start"
controls="details-panel"
on:press={() => (detailsShown = !detailsShown)}
>
{detailsShown ? "Hide details" : "Show details"}
</button>
<view
id="details-panel"
role="group"
labelled-by="details-title"
class="gap-1 p-3 rounded-md border"
>
<text id="details-title" class="text-label text-ink">Details</text>
<text class="text-caption text-muted">
{detailsShown ? "Assistive technology names this group by its title and knows the button controls it." : "Hidden for now."}
</text>
</view>
</Demo>
</AreaScreen>
</screen>
<style>
.chip {
padding: var(--space-2) var(--space-4);
border-radius: var(--radius-full);
background: var(--color-raised);
color: var(--color-ink);
}
.chip:active {
background: var(--color-border);
}
.send {
align-self: flex-start;
}
.pad {
min-height: 72px;
cursor: pointer;
}
.tile {
flex: none;
width: 48px;
height: 48px;
}
.photo {
flex: 1;
min-width: 0;
height: 96px;
object-fit: cover;
}
</style>pages/navigation/docs/[...topic].duo
---
// A rest route: /navigation/docs/a/b/c gives topic = "a/b/c".
import { route } from "@duolith/client";
import { Breadcrumbs, NavHeader } from "@duolith/kit";
let { topic } = route();
const parts = topic.split("/");
const crumbs = [
{ label: "Navigation", href: "/navigation" },
// The last crumb is this page, so it has no link.
...parts.map((part, index) =>
index === parts.length - 1
? { label: part }
: { label: part, href: `/navigation/docs/${parts.slice(0, index + 1).join("/")}` },
),
];
---
<screen title={`Docs: ${topic}`}>
<NavHeader title="Docs" up="/navigation" upTitle="Navigation" />
<view class="gap-4 p-4">
<Breadcrumbs items={crumbs} />
<text role="heading" class="text-title text-ink">{parts[parts.length - 1]}</text>
<text class="text-body text-muted">topic here is “{topic}”, {parts.length} segments deep.</text>
</view>
</screen>pages/navigation/index.duo
---
// Navigation: links and navigate(), routes with parameters and a rest, the screen stack,
// back, a guard, shared state, transitions and the not-found screen.
import { navigate, state } from "@duolith/client";
import { Button, ListRow, Section, Stepper, ToggleRow } from "@duolith/kit";
import AreaScreen from "../../components/AreaScreen.duo";
import Demo from "../../components/Demo.duo";
// Shared with the item screens and the vault: one value for every screen that names it.
let taps = state(0, { shared: "gallery-taps" });
let unlocked = state(false, { shared: "gallery-unlocked" });
let item = state(7);
// No page serves this path, on purpose. A path written as text, or held
// in a const, must name a route (E0353), so the not-found demo joins it
// from parts; the router checks it when it is followed.
const nowhere = ["", "navigation", "nowhere"].join("/");
---
<screen title="Navigation">
<AreaScreen
title="Navigation"
intro="Each file in pages/ is a route. Pressing something with href pushes a screen; back shows the one beneath exactly as it was left."
>
<Demo title="Links with href" note="A fixed route, and one built from state.">
<Section>
<ListRow
title="Item 1"
subtitle={`href="/navigation/item/1"`}
icon="link"
href="/navigation/item/1"
chevron
/>
<ListRow
title={`Item ${item}`}
subtitle="href built from state"
icon="link"
href={`/navigation/item/${item}`}
chevron
/>
</Section>
<Stepper label="Which item" min={1} max={99} bind:value={item} />
</Demo>
<Demo
title="navigate() and replace"
note="Push from script, or replace this screen so back skips it."
>
<view class="row wrap gap-2">
<Button label="Push item 3" onPress={() => navigate("/navigation/item/3?tab=notes")} />
<Button
label="Replace with item 4"
variant="secondary"
onPress={() => navigate("/navigation/item/4", { replace: true })}
/>
</view>
<text class="text-caption text-muted">
A push slides the new screen in over this one; a replace and the tab bar crossfade. With
reduced motion, both are a short fade.
</text>
</Demo>
<Demo
title="A rest route"
note="pages/navigation/docs/[...topic].duo takes the rest of the path."
>
<Section>
<ListRow title="/navigation/docs/guides" href="/navigation/docs/guides" chevron />
<ListRow
title="/navigation/docs/guides/routing/params"
href="/navigation/docs/guides/routing/params"
chevron
/>
</Section>
</Demo>
<Demo
title="A guard"
note="The vault shows only while unlocked; otherwise it sends you to unlock it."
>
<ToggleRow label="Vault unlocked" icon="lock" bind:checked={unlocked} />
<Button
label="Open the vault"
icon="lock"
variant="secondary"
onPress={() => navigate("/navigation/vault")}
/>
</Demo>
<Demo
title="Shared state"
note={`Item screens add to the same count: state(0, { shared: "gallery-taps" }).`}
>
<view class="row items-center justify-between">
<text class="text-heading text-ink">{taps === 1 ? "1 tap" : `${taps} taps`}</text>
<Button label="Tap" size="sm" onPress={() => (taps += 1)} />
</view>
</Demo>
<Demo title="Not found" note="Any path no page serves shows pages/_not-found.duo.">
<ListRow title={nowhere} icon="alert" href={nowhere} chevron />
</Demo>
</AreaScreen>
</screen>pages/navigation/item/[id].duo
---
// One item, at /navigation/item/[id]: the route's parameter and query, a title that
// follows it, back, and the count shared with the Navigation screen. Its section links
// are hand-built: current= marks the one for this screen's ?tab, and the style block
// below draws it from [aria-current].
import { back, backTitle, canGoBack, navigate, route, state } from "@duolith/client";
import { Badge, Button, ListRow, NavHeader, Section } from "@duolith/kit";
let { id, query } = route();
let taps = state(0, { shared: "gallery-taps" });
const next = Number(id) + 1;
const tab = query["tab"] ?? "details";
---
<screen title={`Item ${id}`}>
<NavHeader title={`Item ${id}`} up="/navigation" upTitle="Navigation" />
<view class="page gap-4 p-4">
<view class="hero items-center justify-center gap-2 rounded-xl bg-primary">
<text class="text-caption text-on-primary">route().id</text>
<text class="number text-on-primary">{id}</text>
</view>
<view class="row gap-1 p-1 rounded-lg bg-raised" label="Item sections">
<view
href={`/navigation/item/${id}?tab=details`}
current={tab === "details"}
class="segment grow items-center py-2 rounded-md"
>
<text class="text-label">Details</text>
</view>
<view
href={`/navigation/item/${id}?tab=notes`}
current={tab === "notes"}
class="segment grow items-center py-2 rounded-md"
>
<text class="text-label">Notes</text>
</view>
<view
href={`/navigation/item/${id}?tab=history`}
current={tab === "history"}
class="segment grow items-center py-2 rounded-md"
>
<text class="text-label">History</text>
</view>
</view>
<Section title="This screen">
<ListRow title="Path" value={route().path} />
<ListRow title="Query tab" value={query["tab"] ?? "none"} />
<ListRow title="canGoBack()" value={String(canGoBack())} />
<ListRow title="backTitle()" value={backTitle() ?? "none"} />
</Section>
<view class="row items-center gap-3">
<Badge label={`${taps} shared taps`} tone="primary" />
<Button label="Tap" size="sm" variant="secondary" onPress={() => (taps += 1)} />
</view>
<view class="row wrap gap-2">
<Button label={`Push item ${next}`} onPress={() => navigate(`/navigation/item/${next}`)} />
<Button label="back()" variant="secondary" icon="arrow-left" onPress={back} />
</view>
</view>
</screen>
<style>
.page {
width: 100%;
max-width: 640px;
margin: 0 auto;
}
.hero {
min-height: 160px;
}
.segment {
color: var(--color-muted);
text-decoration: none;
}
.segment[aria-current] {
color: var(--color-ink);
background: var(--color-surface);
box-shadow: 0 1px 3px rgb(0 0 0 / 0.12);
}
.number {
font-size: 64px;
line-height: 1;
font-weight: 800;
}
</style>pages/navigation/unlock.duo
---
// Where the vault's guard sends you. Unlocking follows the query's next, only when it is a
// path in this app.
import { navigate, route, state } from "@duolith/client";
import { Button, NavHeader, ToggleRow } from "@duolith/kit";
let { query } = route();
let unlocked = state(false, { shared: "gallery-unlocked" });
const next =
query["next"]?.startsWith("/") && !query["next"].startsWith("//") && !query["next"].startsWith("/\\") ? query["next"] : "/navigation";
---
<screen title="Unlock">
<NavHeader title="Unlock the vault" up="/navigation" upTitle="Navigation" />
<view class="gap-4 p-4">
<text class="text-body text-muted">
The vault's guard sent you here, replacing its screen, so back does not return to it.
</text>
<ToggleRow label="Vault unlocked" icon="lock" bind:checked={unlocked} />
<Button
label="Continue to the vault"
disabled={!unlocked}
onPress={() => navigate(next, { replace: true })}
/>
</view>
</screen>pages/navigation/vault.duo
---
// A guarded screen: shown only while the shared "gallery-unlocked" state holds. Locking it
// here sends you to unlock it, because the guard follows the state.
import { guard, state } from "@duolith/client";
import { EmptyState, NavHeader, ToggleRow } from "@duolith/kit";
let unlocked = state(false, { shared: "gallery-unlocked" });
guard(() => unlocked || "/navigation/unlock?next=/navigation/vault");
---
<screen title="Vault">
<NavHeader title="Vault" up="/navigation" upTitle="Navigation" />
<view class="gap-4 p-4">
<EmptyState
icon="lock"
title="You are in the vault"
message="The guard let you in because the vault is unlocked."
/>
<ToggleRow label="Vault unlocked" hint="Lock it to be sent away" bind:checked={unlocked} />
</view>
</screen>pages/navigation-parts.duo
---
// The kit's navigation parts: the TabBar around you (a rail on a wide window), this
// screen's NavHeader with pieces, a Toolbar, Breadcrumbs and Links.
import { navigate, state } from "@duolith/client";
import { Breadcrumbs, IconButton, Link, NavHeader, Toolbar } from "@duolith/kit";
import Demo from "../components/Demo.duo";
let unseen = state(3, { shared: "gallery-unseen" });
let bold = state(false);
let starred = state(false);
let status = state("Nothing pressed yet");
---
<screen title="Navigation parts">
<NavHeader title="Navigation parts" up="/" upTitle="Gallery">
<piece name="trailing">
<IconButton icon="search" label="Search" onPress={() => navigate("/search")} />
</piece>
</NavHeader>
<view class="page gap-5 p-4 pb-12 md:p-8">
<text class="text-body text-muted">
This screen's header is a NavHeader with an up button and a trailing action. The bar at the
bottom, or the rail at the side of a wide window, is the gallery's TabBar.
</text>
<view class="demos">
<Demo title="TabBar and TabBarItem" note="Badges count; the current tab follows the route.">
<view class="row items-center justify-between">
<text class="text-body text-ink">Search badge: {unseen}</text>
<view class="row gap-2">
<IconButton
icon="minus"
label="One fewer"
variant="secondary"
onPress={() => (unseen = Math.max(0, unseen - 1))}
/>
<IconButton
icon="plus"
label="One more"
variant="secondary"
onPress={() => (unseen += 1)}
/>
</view>
</view>
</Demo>
<Demo title="Toolbar" note="One Tab stop; the arrow keys move between its controls.">
<Toolbar label="Formatting">
<IconButton icon="edit" label="Bold" selected={bold} onPress={() => (bold = !bold)} />
<IconButton
icon="star"
label="Star"
selected={starred}
onPress={() => (starred = !starred)}
/>
<IconButton icon="copy" label="Copy" onPress={() => (status = "Copied")} />
<IconButton icon="share" label="Share" onPress={() => (status = "Shared")} />
</Toolbar>
<text role="status" class="text-caption text-muted">{status}</text>
</Demo>
<Demo title="Breadcrumbs" note="The last item is the current page.">
<Breadcrumbs
items={[
{ label: "Gallery", href: "/" },
{ label: "Navigation", href: "/navigation" },
{ label: "Parts" },
]}
/>
</Demo>
<Demo title="Link" note="In-app links, a muted one, and one to another site.">
<Link href="/navigation">Open the Navigation area</Link>
<Link href="/appearance" muted>Appearance settings</Link>
<Link href="https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/">The toolbar pattern</Link>
</Demo>
<Demo title="NavHeader" note="Large titles, back and up, and leading and trailing pieces.">
<text class="text-body text-ink">
The gallery's home has a large title that hands over to the bar as you scroll. Screens you
push show back; a screen opened from its address shows up instead.
</text>
<Link href="/navigation/item/2">Push a screen with back</Link>
</Demo>
</view>
</view>
</screen>
<style>
.page {
width: 100%;
max-width: 1120px;
margin: 0 auto;
}
.demos {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
align-items: start;
gap: var(--space-4);
}
</style>pages/overlays.duo
---
// Overlays: every overlay part, toast() from @duolith/client, and the overlay element itself.
import { dismissToast, state, toast, visibleToasts } from "@duolith/client";
import { AlertDialog, Button, Dialog, IconButton, Menu, Popover, Select } from "@duolith/kit";
import { Sheet, TextField, Toast, Tooltip } from "@duolith/kit";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
let sheetOpen = state(false);
let detent = state<"medium" | "large">("medium");
let dialogOpen = state(false);
let deleteOpen = state(false);
let hintOpen = state(false);
let name = state("Ada");
let draft = state("Ada");
let last = state("nothing yet");
let size = state("m");
const actions = [
{ label: "Edit", icon: "edit", onSelect: () => (last = "Edit") },
{ label: "Share", icon: "share", onSelect: () => (last = "Share") },
{ label: "Archive", disabled: true },
{ divider: true },
{ label: "Delete", icon: "trash", destructive: true, onSelect: () => (deleteOpen = true) },
];
const sizes = [
{ value: "s", label: "Small" },
{ value: "m", label: "Medium" },
{ value: "l", label: "Large" },
];
function saveName() {
name = draft;
dialogOpen = false;
toast("Name saved", { tone: "success" });
}
function deleteIt() {
last = "Deleted";
toast("Deleted", { action: { label: "Undo", onPress: () => (last = "Restored") } });
}
---
<screen title="Overlays">
<AreaScreen
title="Overlays"
intro="Everything that shows above the screen, on one overlay layer: focus moves in, the page behind modal ones is inert, and Escape closes."
>
<Demo title="Sheet" note="Drag the handle between detents, or down to dismiss.">
<Sheet title="Share" bind:open={sheetOpen} bind:detent={detent}>
<piece name="trigger">
<Button label="Open sheet" icon="share" />
</piece>
<text class="text-body text-muted">Choose where to send it. Detent: {detent}.</text>
<Button
label="Copy link"
icon="copy"
variant="secondary"
full
onPress={() => (sheetOpen = false)}
/>
<Button
label="Send by mail"
icon="mail"
variant="secondary"
full
onPress={() => (sheetOpen = false)}
/>
</Sheet>
</Demo>
<Demo title="Dialog and AlertDialog" note={`Your name is ${name}. Last action: ${last}.`}>
<view class="row wrap gap-2">
<Dialog title="Edit name" message="This is how others see you." bind:open={dialogOpen}>
<piece name="trigger">
<Button label="Edit name" icon="edit" variant="secondary" />
</piece>
<TextField label="Name" bind:value={draft} />
<piece name="actions">
<Button label="Cancel" variant="ghost" onPress={() => (dialogOpen = false)} />
<Button label="Save" onPress={saveName} />
</piece>
</Dialog>
<AlertDialog
title="Delete this post?"
message="It is removed for everyone. You can undo for a few seconds."
confirmLabel="Delete"
destructive
bind:open={deleteOpen}
onConfirm={deleteIt}
>
<piece name="trigger">
<Button label="Delete" icon="trash" variant="danger" />
</piece>
</AlertDialog>
</view>
</Demo>
<Demo
title="Menu, Popover and Tooltip"
note="Arrow keys and letters move in a menu; hover or focus shows a tooltip."
>
<view class="row wrap items-center gap-2">
<Menu label="Post actions" items={actions}>
<piece name="trigger">
<Button label="Actions" iconEnd="chevron-down" variant="secondary" />
</piece>
</Menu>
<Popover label="About this post">
<piece name="trigger">
<Button label="Details" icon="info" variant="ghost" />
</piece>
<text class="text-label text-ink">Posted 2 hours ago</text>
<text class="text-body text-muted">Seen by 1,204 people.</text>
</Popover>
<Tooltip text="Add to favourites">
<IconButton icon="heart" label="Favourite" variant="secondary" />
</Tooltip>
</view>
</Demo>
<Demo title="Toast" note="toast() from anywhere; the Toast region is placed once per screen.">
<view class="row wrap gap-2">
<Button label="Show toast" variant="secondary" onPress={() => toast("Draft saved")} />
<Button label="With undo" variant="secondary" onPress={deleteIt} />
<Button
label="Error toast"
variant="secondary"
onPress={() => toast("Could not send. Check your connection.", { tone: "danger" })}
/>
</view>
<view class="row items-center justify-between">
<text class="text-caption text-muted">
{visibleToasts().length} showing (visibleToasts)
</text>
<Button
label="Dismiss all"
size="sm"
variant="ghost"
onPress={() => visibleToasts().forEach((shown) => dismissToast(shown.id))}
/>
</view>
</Demo>
<Demo title="Select" note="A combobox that opens a listbox.">
<Select label="Size" options={sizes} bind:value={size} />
<Select label="Region" options={sizes} placeholder="Not available here" disabled />
</Demo>
<Demo
title="The overlay element"
note="What the parts are built on: kind, open, anchor and on:dismiss."
>
<button
id="hint-anchor"
class="hint self-start text-label"
on:press={() => (hintOpen = !hintOpen)}
>
{hintOpen ? "Hide the hint" : "Show a hint"}
</button>
<overlay
kind="popover"
anchor="hint-anchor"
placement="bottom-start"
open={hintOpen}
label="Hint"
class="bubble gap-1 p-3 rounded-lg bg-surface border shadow-lg"
on:dismiss={() => (hintOpen = false)}
>
<text class="text-label text-ink">A plain popover overlay</text>
<text class="text-caption text-muted">Press outside or Escape to close it.</text>
</overlay>
</Demo>
</AreaScreen>
<Toast />
</screen>
<style>
.hint {
padding: var(--space-2) var(--space-4);
border-radius: var(--radius-full);
background: var(--color-raised);
color: var(--color-ink);
}
.bubble {
max-width: 260px;
}
</style>pages/search.duo
---
// Search every feature in the gallery: a SearchField over a listView, sorted by name or
// by area, each result a row that opens its area.
import { byText, containsText, effect, listView, state } from "@duolith/client";
import { EmptyState, ListRow, NavHeader, SearchField, Section, SegmentedControl } from "@duolith/kit";
type Feature = { name: string; area: string; href: string };
const areas: Record<string, string> = {
Language: "/language",
Styling: "/styling",
Data: "/data",
Navigation: "/navigation",
"Kit core": "/kit-core",
Overlays: "/overlays",
"Inputs and media": "/inputs-and-media",
"Navigation parts": "/navigation-parts",
};
const names: [string, string][] = [
["show and otherwise", "Language"],
["Keyed lists with an index", "Language"],
["Derived values", "Language"],
["bind:value and bind:checked", "Language"],
["Forms and on:submit", "Language"],
["on:press, on:longpress and on:key", "Language"],
["Components, slots and pieces", "Language"],
["class: conditional classes", "Language"],
["effect, onDispose and untracked", "Language"],
["progress, icon, scroll and image", "Language"],
["Accessibility attributes", "Language"],
["Layout utilities", "Styling"],
["Spacing and sizing", "Styling"],
["Colour tokens", "Styling"],
["Type styles", "Styling"],
["Borders, radius and shadows", "Styling"],
["pressed:, hover:, focus:, disabled:", "Styling"],
["md:, lg: and dark:", "Styling"],
["Page style blocks", "Styling"],
["state.load", "Data"],
["Optimistic actions", "Data"],
["Offline queue", "Data"],
["pagedList and listView", "Data"],
["Form validation", "Data"],
["environment", "Data"],
["Route parameters", "Navigation"],
["Rest routes", "Navigation"],
["navigate() and back()", "Navigation"],
["Guards", "Navigation"],
["Shared state", "Navigation"],
["Not found", "Navigation"],
["Button and IconButton", "Kit core"],
["ListRow and Section", "Kit core"],
["Card, Avatar, Badge, Divider", "Kit core"],
["TextField and TextArea", "Kit core"],
["ToggleRow, Checkbox, RadioGroup", "Kit core"],
["SegmentedControl and Slider", "Kit core"],
["Spinner and ProgressBar", "Kit core"],
["EmptyState and ErrorState", "Kit core"],
["Sheet", "Overlays"],
["Dialog and AlertDialog", "Overlays"],
["Menu, Popover, Tooltip", "Overlays"],
["toast()", "Overlays"],
["Select", "Overlays"],
["The overlay element", "Overlays"],
["DatePicker, TimePicker, Stepper", "Inputs and media"],
["SearchField and chips", "Inputs and media"],
["Tabs", "Inputs and media"],
["Image and public/", "Inputs and media"],
["ImageViewer and zoom", "Inputs and media"],
["Skeleton", "Inputs and media"],
["TabBar and rail", "Navigation parts"],
["NavHeader", "Navigation parts"],
["Toolbar", "Navigation parts"],
["Breadcrumbs and Link", "Navigation parts"],
];
const features: Feature[] = names.map(([name, area]) => ({ name, area, href: areas[area] ?? "/" }));
const results = listView(() => features, {
search: (feature, text) => containsText(`${feature.name} ${feature.area}`, text),
sorts: { name: byText((feature: Feature) => feature.name), area: byText((feature: Feature) => feature.area) },
});
let query = state("");
let order = state("area");
effect(() => (results.query = query));
effect(() => (results.sortBy = order === "area" ? "area" : "name"));
// Opening Search counts as having seen what is new: the tab's badge clears.
let unseen = state(3, { shared: "gallery-unseen" });
unseen = 0;
---
<screen title="Search">
<NavHeader title="Search" large />
<view class="page gap-4 p-4 pb-12">
<SearchField label="Search features" placeholder="Try “sheet” or “guard”" bind:value={query} />
<SegmentedControl
label="Order"
options={[
{ value: "area", label: "By area" },
{ value: "name", label: "By name" },
]}
bind:value={order}
/>
<show when={results.count > 0}>
<Section title={results.count === 1 ? "1 feature" : `${results.count} features`}>
<list each={results.items} as="feature" key={feature.name}>
<ListRow title={feature.name} subtitle={feature.area} href={feature.href} chevron />
</list>
</Section>
</show>
<otherwise>
<EmptyState
icon="search"
title="No features match"
message={`Nothing is called “${query}”.`}
/>
</otherwise>
</view>
</screen>
<style>
.page {
width: 100%;
max-width: 720px;
margin: 0 auto;
}
</style>pages/styling.duo
---
// Styling: every utility family, the state, scheme and window prefixes, a page style block
// and the app's own choice of light or dark.
import { colorScheme, state } from "@duolith/client";
import AreaScreen from "../components/AreaScreen.duo";
import Demo from "../components/Demo.duo";
let isBusy = state(false);
---
<screen title="Styling and themes">
<AreaScreen
title="Styling and themes"
intro="Utilities apply the theme's tokens, worked out when the app is built. Prefixes make them conditional: pressed:, hover:, focus:, disabled:, dark:, md: and lg:."
>
<Demo title="Layout" note="Every container is a stack; row lays children sideways.">
<view class="row gap-2">
<view class="box grow p-2 rounded-md bg-primary" />
<view class="box grow p-2 rounded-md bg-primary opacity-75" />
<view class="box grow p-2 rounded-md bg-primary opacity-50" />
</view>
<view class="row items-center justify-between p-2 rounded-md bg-raised">
<text class="text-caption text-ink">justify-between</text>
<view class="dot rounded-full bg-success" />
</view>
<list
each={["row", "wrap", "grow", "items-center", "justify-end", "self-start", "shrink-0"]}
as="word"
class="row wrap gap-2"
>
<text class="px-2 py-1 rounded-sm bg-raised text-caption text-ink">{word}</text>
</list>
</Demo>
<Demo title="Spacing" note="Padding and gaps from one scale.">
<view class="row items-end gap-2">
<view class="items-center gap-1">
<view class="p-1 rounded-sm bg-primary">
<view class="unit rounded-sm bg-surface" />
</view>
<text class="text-caption text-muted">p-1</text>
</view>
<view class="items-center gap-1">
<view class="p-2 rounded-sm bg-primary">
<view class="unit rounded-sm bg-surface" />
</view>
<text class="text-caption text-muted">p-2</text>
</view>
<view class="items-center gap-1">
<view class="p-3 rounded-sm bg-primary">
<view class="unit rounded-sm bg-surface" />
</view>
<text class="text-caption text-muted">p-3</text>
</view>
<view class="items-center gap-1">
<view class="p-4 rounded-sm bg-primary">
<view class="unit rounded-sm bg-surface" />
</view>
<text class="text-caption text-muted">p-4</text>
</view>
<view class="items-center gap-1">
<view class="p-6 rounded-sm bg-primary">
<view class="unit rounded-sm bg-surface" />
</view>
<text class="text-caption text-muted">p-6</text>
</view>
</view>
</Demo>
<Demo title="Sizing" note="Fractions of the parent, the space scale, and fixed shapes.">
<view class="w-full h-2 rounded-full bg-raised">
<view class="w-2/3 h-2 rounded-full bg-primary" />
</view>
<view class="w-1/2 h-2 rounded-full bg-success" />
<view class="row gap-3 items-center">
<view class="w-12 aspect-square rounded-md bg-raised items-center justify-center">
<text class="text-caption text-muted">1:1</text>
</view>
<view class="w-24 aspect-video rounded-md bg-raised items-center justify-center">
<text class="text-caption text-muted">16:9</text>
</view>
</view>
</Demo>
<Demo title="Position" note="relative and absolute, insets and z order.">
<view class="relative z-0 h-24 rounded-lg bg-raised overflow-hidden">
<view class="absolute inset-0 bg-primary opacity-25" />
<view class="absolute top-2 left-2 px-2 py-1 rounded-sm bg-surface z-10">
<text class="text-caption text-ink">top-2 left-2</text>
</view>
<view class="absolute bottom-2 right-2 w-6 h-6 rounded-full bg-danger z-20" />
</view>
</Demo>
<Demo title="Colour" note="Every colour token, with its own dark value.">
<view class="swatches">
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-canvas" />
<text class="text-caption text-muted">canvas</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-surface" />
<text class="text-caption text-muted">surface</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-raised" />
<text class="text-caption text-muted">raised</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-border" />
<text class="text-caption text-muted">border</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-primary" />
<text class="text-caption text-muted">primary</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-ink" />
<text class="text-caption text-muted">ink</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-muted" />
<text class="text-caption text-muted">muted</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-danger" />
<text class="text-caption text-muted">danger</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-success" />
<text class="text-caption text-muted">success</text>
</view>
<view class="items-center gap-1">
<view class="swatch rounded-md border bg-scrim" />
<text class="text-caption text-muted">scrim</text>
</view>
</view>
</Demo>
<Demo title="Type" note="Text styles, weights, alignment, truncation and clamping.">
<text class="text-title text-ink">Title</text>
<text class="text-heading text-ink">Heading</text>
<text class="text-body text-ink">
Body
<text class="font-bold">bold</text>
and
<text class="font-medium">medium</text>
</text>
<text class="text-label text-primary">Label</text>
<text class="text-caption text-muted text-right">Caption, aligned right</text>
<text class="text-body text-ink truncate">
A long line that does not fit ends with an ellipsis rather than wrapping.
</text>
<text class="text-body text-muted line-clamp-2">
Clamped text shows at most two lines and ends with an ellipsis, however much more there is
to read in the paragraph below the fold.
</text>
</Demo>
<Demo title="Borders and radius">
<view class="row wrap gap-2">
<view class="corner items-center justify-center border-2 border-primary rounded-none">
<text class="text-caption text-muted">none</text>
</view>
<view class="corner items-center justify-center border-2 border-primary rounded-sm">
<text class="text-caption text-muted">sm</text>
</view>
<view class="corner items-center justify-center border-2 border-primary rounded-md">
<text class="text-caption text-muted">md</text>
</view>
<view class="corner items-center justify-center border-2 border-primary rounded-lg">
<text class="text-caption text-muted">lg</text>
</view>
<view class="corner items-center justify-center border-2 border-primary rounded-xl">
<text class="text-caption text-muted">xl</text>
</view>
<view class="corner items-center justify-center border-2 border-primary rounded-full">
<text class="text-caption text-muted">full</text>
</view>
</view>
<view class="row gap-2">
<view class="grow p-2 border-t">
<text class="text-caption text-muted">border-t</text>
</view>
<view class="grow p-2 border-b">
<text class="text-caption text-muted">border-b</text>
</view>
<view class="grow p-2 border-4 border-success rounded-md">
<text class="text-caption text-muted">border-4</text>
</view>
</view>
</Demo>
<Demo title="Shadows and opacity">
<view class="row gap-3 p-2">
<view class="lift grow items-center justify-center rounded-md bg-surface shadow-none">
<text class="text-caption text-muted">none</text>
</view>
<view class="lift grow items-center justify-center rounded-md bg-surface shadow-sm">
<text class="text-caption text-muted">sm</text>
</view>
<view class="lift grow items-center justify-center rounded-md bg-surface shadow-md">
<text class="text-caption text-muted">md</text>
</view>
<view class="lift grow items-center justify-center rounded-md bg-surface shadow-lg">
<text class="text-caption text-muted">lg</text>
</view>
</view>
<view class="row gap-2">
<view class="grow h-8 rounded-md bg-primary opacity-25" />
<view class="grow h-8 rounded-md bg-primary opacity-50" />
<view class="grow h-8 rounded-md bg-primary opacity-75" />
<view class="grow h-8 rounded-md bg-primary opacity-100" />
</view>
</Demo>
<Demo title="State prefixes" note="Press, hover and tab to these; the last one is disabled.">
<view class="row wrap gap-2">
<button
class="px-4 py-2 rounded-md bg-primary text-on-primary text-label pressed:opacity-75"
>
pressed:
</button>
<button
class="px-4 py-2 rounded-md bg-raised text-ink text-label hover:bg-border pressed:bg-border"
>
hover:
</button>
<button
class="px-4 py-2 rounded-md bg-raised text-ink text-label focus:shadow-md pressed:shadow-md"
>
focus:
</button>
<button
disabled={!isBusy}
class="px-4 py-2 rounded-md bg-primary text-on-primary text-label disabled:opacity-50"
>
disabled:
</button>
</view>
<view class="row items-center justify-between">
<text class="text-caption text-muted">Enable the last button</text>
<toggle label="Enable the disabled: button" bind:checked={isBusy} />
</view>
</Demo>
<Demo title="Window and scheme prefixes" note="Widen the window, or switch to dark mode.">
<view class="col md:row gap-2">
<view class="grow p-3 rounded-md bg-raised md:bg-primary lg:bg-success">
<text class="text-label text-ink md:text-on-primary">
<text class="md:hidden">Phone width</text>
<text class="hidden md:flex lg:hidden">md: 768px and wider</text>
<text class="hidden lg:flex">lg: 1024px and wider</text>
</text>
</view>
<view class="grow p-3 rounded-md border dark:border-primary dark:shadow-md">
<text class="text-label text-ink">
{colorScheme.isDark ? "dark: a primary border" : "dark: adds a border in dark mode"}
</text>
</view>
</view>
</Demo>
<Demo
title="A page style block"
note="When no utility fits, a class of this page's own, using tokens."
>
<view class="stripes h-12 rounded-lg" />
<view class="row wrap gap-2">
<button class="chip" on:press={() => colorScheme.choose("light")}>Light</button>
<button class="chip" on:press={() => colorScheme.choose("dark")}>Dark</button>
<button class="chip" on:press={() => colorScheme.choose("system")}>System</button>
</view>
<text class="text-caption text-muted">
Showing {colorScheme.isDark ? "dark" : "light"} values; chosen: {colorScheme.choice}.
</text>
</Demo>
</AreaScreen>
</screen>
<style>
.box {
min-height: 32px;
}
.dot {
width: 12px;
height: 12px;
}
.unit {
width: 12px;
height: 12px;
}
.swatches {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: var(--space-2);
}
.swatch {
width: 100%;
aspect-ratio: 1;
}
.corner {
width: 56px;
height: 44px;
}
.lift {
height: 48px;
}
.stripes {
background: repeating-linear-gradient(
135deg,
var(--color-primary) 0 12px,
var(--color-raised) 12px 24px
);
}
.chip {
padding: var(--space-2) var(--space-4);
border-radius: var(--radius-full);
background: var(--color-raised);
color: var(--color-ink);
}
</style>