# Isolink apps

How to make an Isolink app: a database with its own screens, written in TSX, shared with your people and published to the Isolink store. Then every component an app can use, with its props and an example.

The guide, with pictures, is at https://isolink.app/docs/apps.html and the component directory at https://isolink.app/docs/app-components.html. Database schemas, field types, roles and queries are in [databases.md](databases.md).

## What an app is

An Isolink app is a database with its own screens. The database holds the app's tables, lives on people's
own devices, syncs like messages and is end-to-end encrypted. The screens are written in TSX (TypeScript
with JSX) against the `isolink` module, and run in a small sandbox (QuickJS) on each device. They draw
with Isolink's own components, so an app looks at home on every phone and computer, in light and dark.

Shopping, Todo and Notes are apps from the store. Timers, Birthdays and Plans come with Isolink. Every app
also opens in Isolink's own views (Table, from the app's ⋯ menu), so nothing is locked inside an app.

An app's code can only reach its own databases. Everything else, from a website to the calendar, it lists in
`needs`, people see that list before they get it, and Isolink checks every call against it.

## Your first app

An app is a folder:

```
apps/community/water/
  app.json        its id, name, icon, schema, starter rows and needs
  src/app.tsx     its screens
  src/app.css     its looks (optional)
  l10n/es.json    its words in other languages (optional)
  listing.json    who made it, its licence and version (store only)
```

`app.json`:

```json
{
  "id": "water",
  "name": "Water",
  "icon": "eco",
  "accent": 4280391411,
  "version": 1,
  "main": "src/app.tsx",
  "schema": {
    "tables": {
      "plants": {
        "title": "name",
        "fields": {
          "name": { "id": 1, "type": "text", "max": 40, "required": true },
          "every": { "id": 2, "type": "number" },
          "watered": { "id": 3, "type": "date" }
        }
      }
    }
  },
  "starter": { "plants": [{ "name": "Monstera", "every": 7 }] },
  "summary": { "table": "plants", "none": "No plants yet", "one": "1 plant", "many": "{p0} plants" }
}
```

`src/app.tsx`:

```tsx
import { defineApp, Screen, List, ListItem, Text, Fab, Sheet, Stack, TextField, Stepper, Button,
         useQuery, useData, useLocal, format } from 'isolink';

type Plant = { id: string; name: string; every?: number; watered?: string };

function Home() {
  const plants = useQuery('plants', { sort: ['name'] }) as Plant[];
  const data = useData();
  const [adding, setAdding] = useLocal(false);
  const [name, setName] = useLocal('');
  const [every, setEvery] = useLocal(7);

  const add = () => {
    if (!name.trim()) return;
    data.add('plants', { name: name.trim(), every });
    setName('');
    setAdding(false);
  };
  const today = format.date(Date.now(), 'iso');

  return (
    <Screen title="Water" fab={<Fab icon="add" onPress={() => setAdding(true)} />}>
      <List>
        {plants.map((p) => (
          <ListItem
            key={p.id}
            title={p.name}
            subtitle={p.watered ? `Watered ${format.date(p.watered)}` : 'Not watered yet'}
            trailing={<Text tone="muted">every {p.every ?? 7} days</Text>}
            onPress={() => data.edit('plants', p.id, { watered: today })}
          />
        ))}
      </List>
      <Sheet open={adding} onClose={() => setAdding(false)}>
        <Stack gap={3}>
          <TextField value={name} onChange={setName} placeholder="Name" onSubmit={add} autofocus />
          <Stepper value={every} min={1} max={60} onChange={setEvery} />
          <Button expand onPress={add}>Add</Button>
        </Stack>
      </Sheet>
    </Screen>
  );
}

export default defineApp({ screens: { Home } });
```

That's a whole app. Get makes a database from the schema with the starter rows, and it opens on `Home`.
The bar at the top shows the database's name (a picker when there are several) and the ⋯ menu with Share,
Table, Allowed and Pin to You; `title` shows there once you've gone a screen deeper.

## app.json

| Key | What it is |
| --- | --- |
| `id` | The folder's name: small letters, digits, `_` and `-`, up to 32. |
| `name` | 1 to 40 characters. |
| `icon` | An icon name (see [Icons](#icons)), drawn white on the app's tile in `accent`. Themes don't change it. |
| `accent` | A colour as a number, `0xAARRGGBB` written in decimal. Buttons, rings and the app's tile use it. |
| `version` | A whole number from 1. Raise it when the schema changes, so databases [upgrade](#upgrades). |
| `api` | The `isolink` module's version, 1 today. |
| `main` | The entry file, `src/app.tsx` (or `.ts`, or `.iso`). Without it the app opens in Isolink's own views. |
| `schema` | Its tables and fields ([Schemas](databases.md#schemas)), or put it in `schema.json` beside app.json. |
| `starter` | Rows a new database starts with, by table. At most 200. |
| `summary` | What's waiting, for the app's tile when it's pinned to You: `{table, where?, none?, one?, many?}`, the count as `{p0}`. |
| `needs` | What it reaches beyond its own databases: `web`, `device`, `system`, `secrets`, `chat` ([Needs](#needs)). |
| `chat` | Its items in a message's menu, and the cards it sends into chats ([In chats](#in-chats)). |
| `view` | How it opens on a computer: `full` (the default) fills the window beside the sidebar and stays open while you're in your chats, `split` opens beside the list like a chat. Phones always open apps full. |

A built app is at most 1 MB, its code at most 200 files and 2 MB before it's bundled.

## Screens and moving between them

`defineApp({ screens, start, migrate })` names the app's screens. Each is a function component; the first
(or `start`) opens first. `useNav()` moves between them:

```tsx
function Home() {
  const nav = useNav();
  return <Screen><Button onPress={() => nav.push('Plant', { id: 'abc' })}>Open</Button></Screen>;
}

function Plant() {
  const { params, pop } = useNav();
  const plant = useRecord('plants', params.id);
  return <Screen title={plant?.name ?? ''}><Button onPress={pop}>Done</Button></Screen>;
}

export default defineApp({ screens: { Home, Plant } });
```

`push(name, params)` goes deeper, `pop()` goes back (as does the system's back), `go(name, params)` starts
again from that screen. `screen`, `params` and `depth` say where you are.

`defineApp({ screens, split: ['Recipes'] })` makes a list screen a master: on a wide window a screen pushed
from it opens beside it, and the next one pushed takes its place; on a phone it's pushed as ever.
A full-bleed master (`immersive`, a board or a map) keeps the whole window. `split` can also be a function
returning the names, which Isolinks before 0.26.53 ignore: use it when an older one would split badly.

Wrap each screen in `<Screen>`. Its `title`, `actions` (buttons for the top bar), `fab` (a `<Fab>`) and
`footer` (a bar along the bottom, kept above the keyboard) go in the app's own bars; its children scroll.

## Components and props

Components are Isolink's own, imported from `isolink` by name. They take props like any JSX: strings,
numbers, booleans, lists, objects, other elements (`leading={<Icon name="star" />}`) and functions
(`onPress`). Every one is in the [component directory](#component-directory), with its props and an
example.

Every component also takes:

| Prop | What it does |
| --- | --- |
| `class` | Class names from the app's stylesheet (`className` works too). A list or `{name: true}` object is fine. |
| `style` | One element's own styles, `style={{ background: '#fde68a', borderRadius: 12 }}`. Numbers are px. |
| `key` | Tells items in a list apart, so each keeps its state as the list changes. |
| `hidden` | `true` draws nothing. |
| `pad` | Space inside: one number, `[vertical, horizontal]` or `[top, right, bottom, left]`. |
| `width`, `height` | A size. |
| `disabled` | Faded, and taps do nothing. |
| `grow` | Inside a `Row` or `Stack`, takes the room left (`grow={2}` takes twice as much). |
| `transition` | `fade`, `slide` or `scale` as it appears. |

Space is a step from 0 to 6 (0, 4, 8, 12, 16, 24 and 32 px) or, above 6, px: `gap={3}` is 12 px and
`gap={20}` is 20 px.

Text and numbers can be children anywhere: `<Button>Add</Button>` is the same as `<Button label="Add" />`.
`{cond && <X />}`, `{list.map(...)}` and `<>…</>` work as in React.

## State

| Hook | What it gives |
| --- | --- |
| `useLocal(initial)` | `[value, set]`, kept while the screen is open. `useState` is the same. |
| `useStore(key, initial)` | `[value, set]`, kept on this device between opens (up to 16 KB a key). Not synced. |
| `useRef(initial)` | `{ current }`, kept between draws without drawing again. |
| `useMemo(make, deps)`, `useCallback(f, deps)` | As in React. |
| `useEffect(effect, deps)` | Runs after a draw when `deps` change; a function it returns cleans up. |
| `useAsync(make, deps)` | `{ loading, data, error }` for a promise. |
| `useForm(fields, { onSubmit })` | Values and errors for a form: `field(name)` gives `{value, error, onChange}`. Fields take `required`, `max`, `min`, `pattern`, `message`, `default`. |
| `useNow(ms)` | The time, drawn again every `ms` (at least 250). For clocks and countdowns. |
| `useMe()` | `{ id, name, role, lang }`: who's using the app and their role in this database. |
| `useLayout()` | `{ width, height, dark, reduceMotion, pointer, insets }` of the screen: `pointer` is `mouse` or `touch`, `reduceMotion` is the person's setting. |
| `usePlatform()` | `{ os, desktop, apple, form, mod }`: `os` is `mac`, `windows`, `ios`, `android` or `linux`; `form` is `desktop`, `tablet` or `phone`; `mod` is ⌘ or Ctrl, for labels. |
| `useFrame(cb)` | Calls `cb(dt)` about 30 times a second while the screen shows, for games and live drawing. `useFrame(cb, false)` pauses it. |
| `useSafeArea()` | `{ top, left, right, bottom }`: what's in the way along each edge of a full-bleed screen (the bar, the sidebar's glass, the system's own). Keep your own controls inside it. |

## Data

The app's data is its database's tables, read from this device's own copy:

```tsx
const open = useQuery('tasks', { where: [['done', '=', false]], sort: ['-due'], limit: 50 });
const task = useRecord('tasks', id);         // one row, or null
const data = useData();
const id = data.add('tasks', { title: 'Buy milk' });
data.edit('tasks', id, { done: true });
data.remove('tasks', id);
```

`useQuery(table, query)` is live: a screen draws again when its rows change, here or on anyone's device. A
query takes `where`, `sort` (`'field'`, `'-field'` for descending, or `[field, 'asc' | 'desc']`), `limit`
(500 by default; more reads extra pages from this device's copy), `search`, `fields`, `group` and counts; the shape is in
[Queries](databases.md#queries). Rows come with their `id`.

Writes are checked against the schema and the person's role (Admin, Edit, Add, View). One that isn't
allowed isn't written, and the person sees why. `add` gives the new row's id at once.

`useChat()` lists the database's members, `{id, name, role}`.

## Talking to the person

```tsx
const toast = useToast();
const dialog = useDialog();
toast('Saved');
useScroll().to('L');   // brings the box with mark="L" into view
if (await dialog.confirm({ title: 'Delete this note?', body: 'It goes for everyone.', ok: 'Delete', danger: true })) { … }
const name = await dialog.prompt({ title: 'New folder', placeholder: 'Name', value: '' });   // text, or null
const picked = await dialog.menu([{ id: 'pin', label: 'Pin', icon: 'push_pin' }, { divider: true },
                                  { id: 'delete', label: 'Delete', icon: 'delete', danger: true }]);
// A colour to pick: `color` draws its icon in that colour.
const c = await dialog.menu([{ id: 'yellow', label: 'Yellow', icon: 'circle', color: '#fde68a' }]);
// Isolink's own sheets, from a tap: the app gets only what's picked, or null.
const chat = await dialog.chat();       // a chat, one of its messages, a starred message or a link sent in one
const person = await dialog.person();   // { id, name }: one of the person's people
const emoji = await dialog.sticker();   // a sticker's emoji
const files = await dialog.file();      // pictures and files sent in chats (see In chats)
```

`dialog.chat()` answers `{ kind, chat, message?, title, text?, url?, by?, byName?, at?, starred? }`: `kind`
is `chat`, `message` or `link`. Keep it as it is and give it to a `ChatCard` or `ChatChip`, which show it as
it is now and open it where the chat is on this device, and what was picked elsewhere. Check
`has('pick.chat')`, `has('pick.person')` and `has('pick.sticker')` first.

Also `useHaptics()` (a tap you can feel: `haptic()`, `haptic.impact('heavy')`, `haptic.success()`, `.warning()`, `.error()`), `useClipboard().copy(text)`, `useShare().share(text)` (the
system's share sheet) and `useKeys({ 'mod+k': open })`, the app's keyboard shortcuts on a computer. Give one a name, `{ 'mod+n': { run: add, label: t('New') } }`, and it's listed under Shortcuts in the ⋯ menu.

`useShare().share({ app: 'shopping', text })` hands words to another of the person's apps instead, one that
lists `share` in `needs.system`: it opens with them as `useShared()`, with `from` set to this app's name. It
answers `false` when they don't have that app. Use an app's id, such as `shopping` or `recipes`.

## Words in other languages

Write the app's words in English and wrap them in `t()`:

```tsx
import { t } from 'isolink';
<Text>{t('Got · {n}', { n: got.length })}</Text>
```

Then put `l10n/<lang>.json` beside app.json for `es`, `fr`, `de`, `pt`, `zh` and `ar`, English to the
translation: `{ "Got · {n}": "Comprado · {n}" }`. People see their language, or the English as written.
The `summary` words are looked up there too.

`format` writes numbers and dates the same on every device: `format.number(1234.5, { decimals: 1 })`,
`format.money(3.5, 'EUR')`, `format.date(v, 'day' | 'time' | 'full' | 'iso')`, `format.relative(v)`
("in 3d", "2h ago") and `format.duration(ms)`.

## Looks

Import a stylesheet and use its classes:

```tsx
import s from './app.css';
<Pressable class={s.card} onPress={open}>…</Pressable>
```

```css
.card { background: var(--surface); border-radius: var(--radius-lg); padding: 14px; display: flex; gap: 8px; }
.card:pressed { background: var(--accent-soft); }
.list .card:last-child { margin-bottom: 0; }
@media (min-width: 600px) { .card { padding: 20px; } }
@media (prefers-color-scheme: dark) { .card { border: 1px solid var(--outline); } }
```

Isolink has no CSS engine on the device: the compiler turns a stylesheet into a table of properties that the
components draw. So it's a subset:

- **Selectors**: a class, more classes (`.a.b`), `[attribute="value"]` on the element's props, one
  ancestor (`.list .card`), `:first-child` and `:last-child`, and the states `:pressed` (`:active`),
  `:hover`, `:focus`, `:disabled`, `:selected` and `:checked`.
- **Media**: `min-width`, `max-width` (px) and `prefers-color-scheme`.
- **Drawn**: `display` (`flex`, `grid`, `none`), `flex-direction`, `flex`, `flex-grow`, `flex-wrap`, `gap`,
  `align-items`, `justify-content`, `place-items`, `grid-template-columns`; `width`, `height`, their `min-`
  and `max-`, `aspect-ratio`; `padding` and `margin` (and each side, `-block`, `-inline`); `background`
  (colours and gradients), `border` and its sides, `border-radius`, `box-shadow`, `opacity`, `overflow`,
  `filter` (`blur`, `grayscale`), `backdrop-filter`; `color`, `font-size`, `font-weight`, `font-style`,
  `font-family`, `line-height`, `letter-spacing`, `text-align`, `text-transform`, `text-decoration`,
  `line-clamp`, `writing-mode` (`vertical-rl` reads down, `sideways-lr` up); `transform`, `translate`, `scale`,
  `rotate`, `transform-origin` and `transition` (which animates transforms too); `position: absolute` with `inset`,
  `top`, `right`, `bottom`, `left` and `z-index`, laid over the parent's other children.
- **Not drawn yet**, though the compiler takes them: `align-self`, `grid-column`, `white-space` and `animation`.
  `position: fixed` and `url()` (except `asset:`) are refused.

Theme tokens keep an app in the person's look: `var(--accent)`, `--accent-soft`, `--on-accent`,
`--surface`, `--bg`, `--ink`, `--muted`, `--outline`, `--success`, `--warning`, `--danger`; `--space-1` to
`--space-6`; `--radius-sm`, `-md`, `-lg`, `-xl`; `--shadow-1` to `-3`; `--font-body`, `-display`, `-mono`, `-serif` (a printed page) and `-hand` (handwriting).

A class's text styles beat a `Text`'s `variant`, as in CSS. A stylesheet has at most 400 rules.

## Your own components

A function is a component, as in React:

```tsx
function Price({ value, currency }: { value: number; currency?: string }) {
  return <Text bold>{format.money(value, currency)}</Text>;
}
```

`defineComponent` makes one usable as an `iso-` tag, with named parts and events. In a `.iso` file, its
`<script>`, `<template>` and `<style>` go together:

```html
<script lang="ts">
  import { defineComponent } from 'isolink';
  export default defineComponent({
    slug: 'pack-list',
    props: { rows: 'list' },
    parts: { header: 'one' },
    events: ['pick'],
  });
</script>

<template>
  <Box class="list">
    <Text variant="title">{parts.header}</Text>
    {rows.map((row) => (
      <Pressable key={row.id} class="row" @press={() => emit('pick', row)}>
        <Text>{row.name}</Text>
      </Pressable>
    ))}
  </Box>
</template>

<style>
  .list { background: var(--surface); border-radius: var(--radius-lg); padding: var(--space-2); }
  .row:pressed { background: var(--accent-soft); }
</style>
```

```tsx
import './pack-list.iso';
<iso-pack-list :rows={items} @pick={(r) => open(r.id)}>
  <iso-pack-list.header>Packing</iso-pack-list.header>
</iso-pack-list>
```

`:name` passes a value, `@name` a handler for an event, and `<iso-slug.part>` fills a part (`one`, or `many`
for a list). A slug is 2 to 48 small letters, digits and hyphens. A `.iso` component's `<style>` applies to
it alone.

## The web and keys

`fetch(url, { method, headers, body })` reaches the https hosts in `needs.web` (up to 16) and nothing else,
with no redirects. It answers `{ status, ok, offline, headers, text(), json() }`. `Image` loads pictures from the
same hosts.

Apps work offline. Their code is on the device, and database edits wait and sync when it's back online.
Pictures `Image` loads are kept on the device and asked for again with their ETag at most once a day. A
plain GET's last good answer is kept too: with no connection `fetch` gives it back with `offline: true`,
and online it asks with its ETag, so an unchanged answer isn't sent twice. Requests with a key are never
kept.

For an API key, list it in `needs.secrets`: `{"key": "openai", "name": "OpenAI key", "hosts":
["api.openai.com"]}`, its hosts in `needs.web`. Write `{secret:openai}` in a header, body or query. Isolink
asks for the key the first time, keeps it in the device's keychain and fills it in outside the app's code,
only for those hosts. The code never sees it, and it never syncs. Keys, in the ⋯ menu, sets or removes it.

## Needs

`needs` is everything an app reaches beyond its own databases. The checker refuses anything else.

```json
"needs": {
  "web": ["api.example.com"],
  "device": ["camera"],
  "system": ["notify", { "name": "calendar.add", "optional": true }],
  "secrets": [{ "key": "example", "name": "Example key", "hosts": ["api.example.com"] }]
}
```

`chat` names `take` (the app's items under Apps in a message's menu, and files from chats) and `send` (its
cards sent into chats): see [In chats](#in-chats).

`device` names `camera` (`Camera`, `Scanner`), `location` (My location on `Map` and `PlacePicker`) and
`microphone` (`Recorder`). Without one, those components show what they'd need instead.

### The phone or computer: needs.system

Each entry in `system` is a name, or `{ "name": …, "optional": true }` for one a feature uses rather than
the app as a whole.

- **Essential** ones (no `optional`) are asked for together, in one sheet, when the app first opens, then
  the system's own permission. Declined, the app shows what it needs and an Allow button.
- **Optional** ones are asked the first time the app uses them, from a tap: "Plans wants to see your
  calendar", Allow or Not now, then the system's own. Not now makes that call fail and leaves `has()`
  true, so the app can offer it again later.
- The system's own sheets (`calendar.add`, `contacts.pick`, `files`, `photos.save`) and `open` need no
  ask: the sheet, or the other app, is the yes. They, `clipboard.paste` and `lock` work only from a tap.
- Browse shows what an app can use before Get. ⋯ › Allowed has a switch for each.
- `has('calendar')` is false when it isn't declared, isn't on this device or is switched off. Check it
  before showing a button for it.

| Name | What it does | Android | iOS | Mac | Windows |
| --- | --- | --- | --- | --- | --- |
| `remind` | Reminders that follow the account and ring on every device, with Done and Later | yes | yes | yes | yes |
| `notify` | Notifications on this device, at most 64 waiting | yes | yes | yes | while Isolink runs |
| `calendar.add` | A new event, through the calendar's own sheet | sheet | sheet | saved to the default calendar | .ics opened in Calendar |
| `calendar` | Read events | yes | yes | yes | – |
| `reminders` | An item in Apple's Reminders | – | yes | yes | – |
| `alarms` | An alarm or a timer | clock app | notification | notification | notification |
| `contacts.pick` | One contact, from the system's picker | yes | yes | – | – |
| `files` | Open (up to 4 MB) and save files, through the picker | yes | yes | yes | yes |
| `photos.save` | Save a picture to Photos | yes | yes | yes | save dialog |
| `open` | Directions, a call, a text or an email in the person's own apps | yes | yes | yes | yes |
| `clipboard.paste` | Read the clipboard | yes | yes | yes | yes |
| `lock` | Fingerprint, face or passcode | yes | yes | Touch ID | – |
| `share` | Listed when something is shared to Isolink; `useShared()` has it | yes | yes | yes | yes |
| `shortcuts` | Not yet: `has('shortcuts')` is false everywhere | – | – | – | – |

They're in `isolink/system`:

```tsx
import { remind, notify, calendar, reminders, alarms, contacts, files, photos, open, clipboard, lock,
         useReminders, useCalendar, useShared } from 'isolink/system';

await remind.set({ key: task.id, text: 'Buy milk', at, repeat: 'weekly',
                   done: { table: 'tasks', row: task.id, set: { done: true } } });
remind.cancel(task.id);
const mine = useReminders();                                  // this app's reminders
await notify.schedule({ id: 'tea', title: 'Tea', body: 'Time’s up', at: Date.now() + 180_000 });
notify.cancel('tea');
const added = await calendar.add({ title, start, end, allDay, place, notes, alert: 15 });
const week = useCalendar({ from, to });                       // { loading, data: [{ id, title, start, end, allDay, place, calendar }] }
await reminders.add({ title, due, notes });
await alarms.set({ hour: 7, minute: 0, label: 'Up' });
await alarms.timer({ seconds: 180, label: 'Tea' });
const person = await contacts.pick();                         // { name, phones, emails } or null
const file = await files.open({ types: ['csv'] });            // { name, size, text } or null; as: 'base64'
await files.save({ name: 'export.csv', text });
await photos.save({ name: 'card.png', base64 });
open.directions('Cafe Nero'); open.call(number); open.text(number, body); open.email({ to, subject, body }); open.link('https://…');
const text = await clipboard.paste();
const ok = await lock.check();
const shared = useShared();                                   // { text, files: [{ name, size }] } or null
// useHandoff() from 'isolink' has the same share with files the app can keep: see In chats.
```

Times are a `Date`, ms since 1970 or an ISO string. `remind`'s `repeat` is `never`, `daily`, `weekdays`,
`weekly`, `monthly` or a count such as `d2` (every 2 days) or `m12` (every year). Its `done` is what the
notification's Done button changes, in this app's database, under the person's role; Later rings again in
an hour. Every app notification and reminder is titled with the app's name.

## Bots

A bot the person chats with can do things in an app the way its buttons do, when it's asked to: start a timer,
add a birthday with its reminder. Declare them as `actions`; the person sees each one before it runs, unless
they set the bot to Always.

```tsx
export default defineApp({
  screens: { Home },
  actions: {
    start: {
      title: 'Start a timer',
      params: { name: 'string', minutes: { type: 'number', optional: true } },
      run: async ({ name, minutes }, { data, store, system }) => {
        // ...the same as the Start button
        return { ends: new Date(at).toISOString() };
      },
    },
  },
});
```

- `params` are by name: `'string'`, `'number'` or `'boolean'`, or `{ type, title?, optional?, options? }`.
  Isolink checks what the bot sends against them before anyone is asked.
- `run(args, ctx)` gets `data` (as `useData()`), `store` (`get(key)` and `set(key, value)`, the same values
  as `useStore`) and `system` (`isolink/system`). It runs without a screen, so toasts and dialogs do nothing.
  What it returns goes back to the bot; throw an `Error` to say why it can't.
- To read or change rows, a bot asks to use the app instead, and the person picks See or Edit.

## In chats

An app can take what a person picks in a chat. Its items sit behind one **Apps** row in a message's menu
(right-click, or hold on a phone): Save to Notes, Add task. Picking one hands the app that message, and
nothing else of the chat.

Declare the items in `app.json`, with `take` in `needs.chat`:

```json
"needs": { "chat": ["take"] },
"chat": {
  "actions": [
    { "id": "save", "title": "Save to Notes", "icon": "note_add",
      "takes": ["text", "link", "image", "video", "voice", "file"],
      "many": true, "max": { "items": 30, "bytes": 26214400 },
      "open": "sheet", "sheet": "Save" }
  ]
}
```

| Key | What it is |
| --- | --- |
| `id` | A small letter, then small letters, digits or `_`, up to 32. |
| `title` | What the row says, up to 24 characters, looked up in the app's `l10n`. Left out: the app's name. |
| `icon` | An icon name. The app's own icon is drawn beside the row. |
| `takes` | The kinds of message it shows on: `text`, `link`, `image`, `video`, `voice`, `file`. A message matches when it has any of them. |
| `types` | For files, up to 16 extensions (`pdf`) or starts of a type (`image/`). Left out: any. |
| `many` | `true`: it also shows for several messages picked together, and for a group of pictures. |
| `max` | `{ items, bytes }`: the most messages (30 unless set, at most 100) and the biggest file (25 MB unless set, at most 100 MB). Past either, the item doesn't show. |
| `open` | `sheet` (the default): the app's sheet over the chat. `quiet`: its code runs with no screen. `app`: the app opens at a screen. |
| `sheet`, `run`, `screen` | Which one, by name, for `sheet`, `quiet` and `app`. Left out: one named as the `id`. |

An app has at most 6 items. Whether one shows is read from app.json alone: none of the app's code runs until
the person picks it. Items never show on deleted messages, view-once and timed snaps, SOS messages, polls,
cards, or files still on their way.

The first time someone picks an app's item, Isolink asks once: "Let Notes save messages you choose?", and
says who else uses the database when it's shared. ⋯ › Allowed has a Message menu switch for each app, and
Settings › Chats › Apps in chats turns the row off for every app. `has('chat.take')` is false when it's
switched off or not declared.

### What the app gets: a handoff

```ts
type Handoff = {
  via: 'message' | 'share' | 'drop';
  action: string;                  // the item's id
  items: {
    text: string;
    links: string[];
    files: HandoffFile[];
    by?: { name: string; me: boolean };
    at?: number;                   // ms since 1970
    ref?: ChatRef;                 // for a ChatCard or ChatChip, as dialog.chat() gives
  }[];                             // one per message picked, oldest first
  chat?: { title: string };
  ref?: ChatRef;
};
type HandoffFile = {
  name: string; mime: string; size: number;
  kind: 'image' | 'video' | 'voice' | 'file';
  keep(): Promise<FileValue>;      // makes it the app's own: the value for a `file` field
};
```

The app never gets a file's bytes. `Image`, `Viewer`, `Audio` and `Video` show a `HandoffFile` as it is
(`<Image src={file} />`), and `await file.keep()` copies it into the app's files and answers with the value
for a `file` field, as `Upload` does.

### A sheet over the chat

Name the app's sheets in `defineApp`. A sheet is a component drawn inside Isolink's own frame, which has the
app's icon, its name and Close; it isn't wrapped in `Screen`. It's a bottom sheet on a phone and a panel
beside the message on a computer.

```tsx
import { defineApp, Stack, TextField, Image, Button, useData, useLocal, useHandoff, useSheet, t } from 'isolink';

function Save() {
  const handoff = useHandoff();
  const sheet = useSheet();
  const data = useData();
  const first = handoff.items[0];
  const [title, setTitle] = useLocal(first.text.split('\n')[0].slice(0, 200));

  const save = async () => {
    const photo = first.files[0] ? await first.files[0].keep() : undefined;
    const id = data.add('notes', {
      title, photo,
      body: handoff.items.map((i) => i.text).filter(Boolean).join('\n\n'),
    });
    sheet.close({ toast: t('Saved'), open: { screen: 'Note', params: { id } } });
  };

  return (
    <Stack gap={3}>
      <TextField value={title} onChange={setTitle} placeholder={t('Title')} autofocus />
      {first.files[0] && <Image src={first.files[0]} height={120} />}
      <Button expand onPress={save}>{t('Save')}</Button>
    </Stack>
  );
}

export default defineApp({
  screens: { Home, Note },
  sheets: { Save },
});
```

| | What it gives |
| --- | --- |
| `sheets` in `defineApp` | The app's sheets by name: a component, or `{ view, width }` to ask for a width on a computer (360 unless set, 280 to 560). |
| `useHandoff()` | What this sheet or screen opened for, or `null`. |
| `useSheet()` | `{ open, close(result), setTitle(text) }`. `close({ toast, open })` closes it; Isolink shows `toast`, with an Open button when `open` names one of the app's screens (`{ screen, params }`). `setTitle` changes the frame's title from the app's name. |

A sheet works in the app's first database, with the person's role there, and the app's own `needs` and
limits. Someone who can only view that database isn't shown the app's items.

### With no screen, or in the app

`"open": "quiet"` runs `chat.quiet[run]` with the handoff and no screen, as a bot's action runs, so toasts and
dialogs do nothing there. What it returns is the same `{ toast, open }`:

```tsx
export default defineApp({
  screens: { Home, Note },
  chat: {
    quiet: {
      later: async (handoff, { data, store, system }) => {
        const id = data.add('notes', { body: handoff.items[0].text });
        return { toast: t('Saved'), open: { screen: 'Note', params: { id } } };
      },
    },
  },
});
```

`"open": "app"` opens the app itself at `screen`, where `useHandoff()` has what was picked.

### Sending into a chat

An app can send one of its own cards into a chat: a note, a recipe, a ticket. Everyone in the chat sees it,
with the app or without, because the card carries its own code and runs in the card sandbox like any other
card. Someone who has the app also gets a button under it that takes it in.

Write the card with `defineCard` in a file of its own, and name it in `app.json`, with `send` in
`needs.chat`:

```json
"needs": { "chat": ["take", "send"] },
"chat": {
  "cards": [
    { "id": "note", "src": "src/cards/note.tsx",
      "data": { "title": "text", "body": "text" },
      "receive": "note", "button": "Save" }
  ]
}
```

| Key | What it is |
| --- | --- |
| `id` | A small letter, then letters, digits or `_`, up to 32. |
| `src` | The card's file. The store compiles it into the app; it can be up to 48 KB compiled. |
| `data` | What it's sent with: up to 24 names, each `text`, `number`, `bool` or `list` (of text). Isolink checks it as it's sent and before `receive` runs. All of it fits in 8 KB. |
| `receive` | The `chat.receive` handler that takes one in, for someone who has the app. Left out: there's no button. |
| `button` | What the button says, up to 24 characters, looked up in the app's `l10n`. Left out: Save. |

An app has at most 4 cards. The card gets its data as `ctx.params` in `init`:

```tsx
// src/cards/note.tsx
import { defineCard, Stack, Text, Markdown, useCard } from 'isolink';

function View() {
  const { state } = useCard();
  return (
    <Stack gap={2}>
      {state.title ? <Text variant="headline">{state.title}</Text> : null}
      <Markdown compact text={state.body} />
    </Stack>
  );
}

export default defineCard({
  name: 'Note',
  init: (ctx) => ({ title: String(ctx.params?.title ?? ''), body: String(ctx.params?.body ?? '') }),
  View,
});
```

A card can't reach the app's database, the web or the device: it draws what it was sent with. It can have
`actions`, which everyone in the chat shares, as in any card (see [Cards in the isolink
language](databases.md#cards-in-the-isolink-language)).

Send it with `useSend()`, from a tap:

```tsx
const send = useSend();
const share = async () => {
  const sent = await send({
    card: 'note',
    data: { title: note.title, body: note.body },
    text: note.title,            // shown where the card's code can't run
  });
  if (sent) toast(t('Sent'));    // { ref, sent }: a ChatRef for a ChatChip, and how many chats; null if none
};
```

Isolink shows the card as it will look in its own share view, where the person ticks who gets it and taps
Send. Nothing is sent by code alone: not from a timer, a bot's action, a quiet action or `receive`. An app
can send 20 times an hour. ⋯ › Allowed has a Send to chats switch for each app, and `has('chat.send')` is
false when it's off or not declared.

Taking one in:

```tsx
export default defineApp({
  screens: { Home, Note },
  chat: {
    receive: {
      note: (sent, { data }) => {
        const id = data.add('notes', { title: sent.title, body: sent.body });
        return { toast: t('Saved'), open: { screen: 'Note', params: { id } } };
      },
    },
  },
});
```

`receive` runs with no screen, in the person's own first database with their own role, when they tap the
button under the card. Treat `sent` as a stranger's: Isolink has checked it against `data`, and nothing more.
The button shows only under a card whose code is exactly the card this device has for that app from the
store, so a card that only says it's from Notes gets none.

Not yet: files sent along with a card, and a Get button for people who don't have the app.

### Files from chats, inside the app

`dialog.file()` opens Isolink's own sheet over the pictures and files sent in the person's chats, newest
first, with search. It works from a tap, for an app with `take` in `needs.chat`, and answers with the ones
picked as `HandoffFile`s, or `null` when it's closed:

```tsx
const dialog = useDialog();
const attach = async () => {
  const files = await dialog.file({ kinds: ['image', 'file'], many: true, max: { items: 10 } });
  if (!files) return;
  for (const f of files) data.add('attachments', { note: id, file: await f.keep() });
};
```

| Option | What it is |
| --- | --- |
| `kinds` | Some of `image`, `video`, `file`. Left out: all. |
| `many` | `true`: several are ticked, then Add. Left out: one, picked by a tap. |
| `max` | `{ items, bytes }`, as for an item: 30 files and 25 MB each unless set. Bigger files don't show. |

The app learns nothing about the chats: only the names, types and sizes of what was picked. Check
`has('pick.file')` first.

### Files dragged in

On a computer, files dragged into Isolink's window, from Finder or Explorer or out of a chat, can be let go
on an app under **Apps** in the drop view. An app is there when one of its items takes `image`, `video` or
`file`. Its first item that takes what was dropped opens, with `via: 'drop'`: files from the computer come
as one item with no words, and messages dragged out of a chat come as they do from the message's menu.
A `DropZone` inside the app takes the same drags with no change.

### Shared from another app

An app that lists `share` in `needs.system` also gets what's shared to it as a handoff, with `via: 'share'`
and one item: `useHandoff().items[0].files` are files it can show and `keep()`. `useShared()` still gives
their names and sizes.

## Upgrades

When a database is older than its app's `version`, the first Admin to open it upgrades it, as ordinary edits
that sync like any other:

1. The new schema is merged in. Fields and options are only ever added; one left out stays.
2. A field with `"from": "<old field>"` takes over the old one's values (anything to text; text to a number,
   yes or no, a date, tags or a choice; one to many and back), and the old field is retired.
3. An option with `"was": ["old", "ids"]` replaces those options in every row.
4. The code's `migrate` runs on each row, for each version in between:

```tsx
export default defineApp({
  screens: { Home },
  migrate: { 2: (row, table) => (table === 'plants' ? { ...row, every: row.every ?? 7 } : row) },
});
```

## Publish it to the store

Apps reach people through the [Isolink store](https://github.com/orimovo/isolink-store), the same way theme
packs and cards do.

1. **Fork the store** and add your app's folder under `apps/community/<id>/`, with app.json, `src/` and a
   `listing.json` (below).
2. **Check it.** From `packages/isolink_js` in the Isolink repo,
   `dart run bin/theme_store.dart check <your store folder>` compiles the code and checks the app with the
   same rules the store uses. Errors name the file and line.
3. **Open a pull request.** The store's check runs on it in a minute or two and says what to fix. A pull
   request may only change `apps/community/<id>/`.
4. **A maintainer reviews and merges it.** Within the hour it's signed and published, and shows in
   Apps › Browse.

`listing.json` says who made it:

```json
{ "version": 1, "by": "Your name", "licence": "CC-BY-4.0", "desc": "Remember when each plant was watered.",
  "tags": ["apps"], "minApp": "0.26.39" }
```

`minApp` is the oldest Isolink it runs on: `0.26.55` for `chat` and `needs.chat` (older ones refuse an app
that lists a need they don't know), `0.26.37` for `needs.system`, and `0.26.39` for `Masonry`,
`StickyNote`, a `ProgressRing` with children, `style={{}}`, `dialog.menu` and `summary`. `desc` is at most 200
characters and `tags` at most 8. The rest of the store's rules are in its
[README](https://github.com/orimovo/isolink-store#readme).

To change it, edit the folder and raise `version` in listing.json (and in app.json when the schema
changes). Apps update themselves: Isolink looks once a day, and when Apps opens, for a newer version of each
app it has a database for. One that asks for more than before (a new need, website or key) waits under
Updates until the person taps Update, and so does every new version of an app whose Auto-update is off
in its ⋯ menu. Nothing is ever downgraded.

## Apps Isolink comes with

Timers, Birthdays and Plans are in the Isolink repo at `app/apps/<id>/`, laid out like a store app
(app.json and `src/app.tsx`). After changing one, rebuild them:

```
cd packages/isolink_js
dart run tool/default_apps.dart
```

That writes `app/assets/apps/<id>.isoapp`. `test/default_apps_test.dart` fails while they're out of date.
Shopping, Todo and Notes live in the store's `apps/official/`, so they change with the store, not an app
update. Isolink comes with a copy of each for until the store's arrives; refresh the copies now and then
by giving the tool a checkout of the store (`dart run tool/default_apps.dart ../../../isolink-store`).
Where the code can't run they open in Isolink's own database views.

## Limits and safety

- The sandbox has no `eval`, no `Function`, no modules but `isolink`, `isolink/system` and the app's own
  files, and no I/O. Each call has a memory cap, a stack cap and a time limit.
- At most 5000 components on screen and 64 inside each other.
- Code can't see other databases, chats or contacts, only what `needs` lists, and Isolink checks every call.
- From a chat it gets only the messages a person picks for it, and never a file's bytes.
- Where there's no engine (the browser today), or the code fails to start, the database opens in Isolink's
  own views instead.
- The time and `Math.random` are the device's own. Anything every device must agree on goes in the database.

## Component directory

Every component is imported from `isolink` by name. Each also takes the props every component takes (`class`, `style`, `key`, `hidden`, `pad`, `width`, `height`, `disabled`, `grow`, `transition`). `Resizable` is `Split`, `InfiniteScroll` is `VirtualList`, `Outline` is `Comments`, and `Dialog` and `Popover` are `Sheet`.

### Layout

Boxes that place what's inside them.

#### Box

A plain box. Its children stack downwards; with `display: flex` in its class they go in a row, with `display: grid` in columns.

| Prop | Takes | What it does |
| --- | --- | --- |
| `gap` | `space` | Space between children. Lays them out as a flex box. |
| `align` | `start`, `center`, `end`, `stretch` | How children line up across. |
| `justify` | `start`, `center`, `end`, `between`, `around`, `evenly` | How children spread along. |
| `wrap` | `bool` | Children wrap onto more lines. |
| `center` | `bool` | Puts its content in the middle. |
| `cursor` | `string` | The mouse pointer over it: `pointer`, `grab`, `grabbing`, `text`, `move`, `crosshair`, `zoom-in`, `not-allowed`… Any component takes it. |
| `onHover` | `(over) => void` | The mouse came over it (`true`) or left (`false`). Any component takes it. |
| `mark` | `string` | A name `useScroll().to(name)` scrolls to, such as a letter in an A to Z list. Any component takes it. |
| `onWidth` | `(w) => void` | How wide it may be, once laid out and again when that changes; for laying things out in rows yourself. Any component takes it. |

```tsx
<Box class={s.card} gap={2}>
  <Text variant="title">Monstera</Text>
  <Text tone="muted">Every 7 days</Text>
</Box>
```

#### Stack

Children one under another.

| Prop | Takes | What it does |
| --- | --- | --- |
| `gap` | `space` | Space between them. |
| `align` | `start`, `center`, `end`, `stretch` | Across. `stretch` by default. |
| `justify` | `start`, `center`, `end`, `between`, `around`, `evenly` | Along. |
| `wrap` | `bool` | Wrap onto more lines. |

```tsx
<Stack gap={3}>
  <TextField value={name} onChange={setName} placeholder="Name" />
  <Button expand onPress={add}>Add</Button>
</Stack>
```

#### Row

Children side by side. Give one `grow` to take the room left.

| Prop | Takes | What it does |
| --- | --- | --- |
| `gap` | `space` | Space between them. |
| `align` | `start`, `center`, `end`, `stretch` | Across. `center` by default. |
| `justify` | `start`, `center`, `end`, `between`, `around`, `evenly` | Along. |
| `wrap` | `bool` | Wrap onto more lines. |

```tsx
<Row gap={2}>
  <Icon name="eco" tone="accent" />
  <Text grow>Monstera</Text>
  <Badge count={2} />
</Row>
```

#### Grid

Children in equal columns.

| Prop | Takes | What it does |
| --- | --- | --- |
| `columns` | `number` | How many. Without it, as many as fit `min` wide. |
| `min` | `number` | The narrowest a column gets when `columns` isn't set. 140 by default. |
| `gap` | `space` | Space between cells. 8 px by default. |

```tsx
<Grid columns={2} gap={3}>
  {timers.map((t) => <Card key={t.id}><Text>{t.name}</Text></Card>)}
</Grid>
```

#### Masonry

Columns of different heights, filled in turn so the order reads across, like a board of notes. A mouse drags one to a new place; a finger holds it first. While it's carried over the others they slide out of its way. Dropped on a `Filter` option with `onDrop`, it goes there instead.

| Prop | Takes | What it does |
| --- | --- | --- |
| `columns` | `number` | How many. Without it, as many as fit `min` wide, up to 6. |
| `min` | `number` | The narrowest a column gets. 150 by default. |
| `gap` | `space` | 12 px by default. |
| `onReorder` | `(id, index) => void` | One was dragged to `index`. Give each child an `id` (or `key`). |
| `grows` | `boolean` | Filling the view, one put past the board's top or left grows it that way, so `x` and `y` can be below zero: give their fields room for that. Without it, it goes back onto the board. |
| `onHold` | `(id) => void` | One was held and let go without moving, or right-clicked: open its menu. |

```tsx
<Masonry columns={2} onReorder={move} onHold={menu}>
  {notes.map((n) => (
    <StickyNote key={n.id} id={n.id} color={n.color} onPress={() => open(n.id)}>
      <Markdown text={n.body} />
    </StickyNote>
  ))}
</Masonry>
```

#### Spacer

Empty space. Inside a `Row` or `Stack` it takes the room left.

| Prop | Takes | What it does |
| --- | --- | --- |
| `size` | `space` | A fixed size instead. |

```tsx
<Row>
  <Text>Total</Text>
  <Spacer />
  <Text bold>£12.40</Text>
</Row>
```

#### Divider

A thin line.

| Prop | Takes | What it does |
| --- | --- | --- |
| `space` | `space` | Room it takes up and down. |

```tsx
<Divider space={4} />
```

#### Scroll

Its children scroll, for a strip wider than the screen. A screen scrolls already.

| Prop | Takes | What it does |
| --- | --- | --- |
| `direction` | `vertical` or `horizontal` | `vertical` by default. |

```tsx
<Scroll direction="horizontal">
  {days.map((d) => <Chip key={d} label={d} />)}
</Scroll>
```

#### Split

Two children side by side on a wide screen, one under the other on a phone. `Resizable` is the same.

| Prop | Takes | What it does |
| --- | --- | --- |
| `first` | `number` | The first one's share, 0 to 1. 0.38 by default. |
| `stackBelow` | `number` | Narrower than this, one goes under the other. 720 by default. |
| `gap` | `space` | Room between the two. None by default. |

```tsx
<Split first={0.35}>
  <List>…</List>
  <Box>…</Box>
</Split>
```

#### Overlay

Its first child fills it; the rest sit on top. Give one an `at` to place it in a corner or along an edge, kept clear of the bars, the sidebar and the home indicator.

| Prop | Takes | What it does |
| --- | --- | --- |
| `safeArea` | `bool` | `false` lets placed children run right to the edges. |
| `gap` | `space` | How far placed children sit from the edges, 3 by default. |

```tsx
<Overlay>
  <Map fill rows={stops} />
  <Glass at="bottom-right"><Button onPress={add}>Add stop</Button></Glass>
</Overlay>
```

#### Glass

What floats over a full-bleed view, in each platform's own material: Liquid Glass on a Mac, frosted on iOS, a solid layer on Windows, a tonal surface on Android.

| Prop | Takes | What it does |
| --- | --- | --- |
| `radius` | `number` | Its corners. A pill by default. |
| `padding` | `space` | Room inside, 2 by default. |

With one child, a new `key` on it swaps it animated: the old one fades out and the new one in as the glass grows or shrinks to fit, as a toolbar trading its buttons for a row of colours.

```tsx
<Glass at="top"><Segmented value={mode} onChange={setMode} options={['Map', 'List']} /></Glass>
```

#### Section

A titled group, like the parts of a settings screen.

| Prop | Takes | What it does |
| --- | --- | --- |
| `title` | `string` | Its heading. |
| `folded` | `bool` | With it, the heading folds the section. `true` starts folded. |
| `action` | `element` | Something by the heading, such as an `IconButton`. |

```tsx
<Section title="Done" folded>
  {done.map((t) => <ListItem key={t.id} title={t.title} />)}
</Section>
```

#### Accordion

A heading that opens to show its children.

| Prop | Takes | What it does |
| --- | --- | --- |
| `title` | `string` | The heading. |
| `open` | `bool` | Starts open. |

```tsx
<Accordion title="Ingredients">
  <Markdown text={recipe.ingredients} />
</Accordion>
```

#### Card

A raised card. Its children stack with no gap; use `gap` on a Stack inside for more.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onPress` | `() => void` | Makes it tappable. |
| `onLongPress` | `() => void` | Held, or right-clicked: its menu. |
| `pad` | `space` | 16 px by default. |

```tsx
<Card onPress={() => nav.push('Plant', { id: p.id })}>
  <Text variant="title">{p.name}</Text>
  <Text tone="muted">Watered {format.relative(p.wateredAt)}</Text>
</Card>
```

#### StickyNote

A paper note with a folded corner, in one of six colours. Text on it is in dark ink on any theme.

| Prop | Takes | What it does |
| --- | --- | --- |
| `color` | `yellow`, `pink`, `blue`, `green`, `orange`, `purple` | `yellow` by default. |
| `tilt` | `number` | Degrees. |
| `fold` | `number` | The folded corner's size. 20 by default. |
| `size` | `[w, h]` | Its own shape, in points: laid out that wide and at least that tall wherever it shows, and scaled to fit, so it's the same shape on a board, in a grid and opened, and a sketch stays where it was drawn. |
| `most` | `number` | The tallest it's drawn, in its points: a longer note fades out at its foot. |
| `scroll` | `bool` | With `most`, the rest scrolls inside it instead, by a mouse's wheel or a finger (a mouse's drag still moves it on a board). `has('stickyNote.scroll')`. |
| `pinned` | `bool` | Shows a pin. |
| `stickers` | `{emoji, x, y}[]` | Stickers stuck on the paper, in its points. Always drawn all on the paper. |
| `sketch` | `file` | A drawing on the paper itself, over what's written. |
| `sketching` | `bool` | Draw on the paper now. |
| `onSketch` | `(file) => void` | The drawing, when it's saved. |
| `onPress` | `() => void` | Tapped. |
| `onLongPress` | `() => void` | Held, or right-clicked. |

```tsx
<StickyNote color="pink" tilt={-1.5} pinned onPress={open}>
  <Text bold>Call the vet</Text>
  <Text>Before Friday</Text>
</StickyNote>
```

#### Corkboard

A cork board with its children pinned where they were dropped. Drag one with a mouse, or hold and drag with a finger, to move it. On a full-bleed screen it fills the whole view, under the bars, with notes at their own size: drag the cork, scroll or pinch to move around, and Fit zooms out to every note (tap again for full size). Otherwise it fills the width; + and − zoom in, and a zoomed board pans any way and pinches. Each child gives its own `id`, `x` and `y` (in the board's units); one without `x` and `y` goes in rows across the top.

| Prop | Takes | What it does |
| --- | --- | --- |
| `width` | `number` | The board's units across, 1000 by default. |
| `height` | `number` | Its units down, 700 by default. Not used full bleed, where it fits the view. |
| `item` | `number` | How wide each child is, in its units. 180 by default. |
| `links` | `[id, id][]` | Red string between these children's pins. |
| `onMove` | `(id, x, y) => void` | One was dragged and let go there. Without it nothing moves. Filling the view, the board grows right and down to hold what's put on it, and up and left too with `grows`. On a phone's two columns, one held and let go on another takes its place, and the ones between move along into each other's spots. |
| `onHold` | `(id) => void` | One was held and let go without moving, or right-clicked. |
| `zoom` | `number` | How far in, 1 to 3. The app can set it. |
| `onZoom` | `(zoom) => void` | Zoomed in or out. |
| `onTapEmpty` | `({x, y}) => void` | Bare cork tapped, in board units: add a note there. |
| `onAdd` | `(x, y) => void` | Bare cork double-clicked or double-tapped: a new note with its top-left corner there, in board units. Single taps wait a moment to tell them apart. |
| `onTilt` | `(id, tilt, x, y) => void` | One was turned about its middle: by a mouse dragging its top-left corner, or two fingers twisting it. Save its new `tilt` and `x`, `y` together (a `StickyNote` hangs from its pin, so it moves as it turns). |
| `selected` | `string[]` | Notes drawn picked. |
| `onSelect` | `(ids) => void` | A box dragged over bare cork with the mouse: the notes in it. |
| `editing` | `string` | The note being written on, there on the board: lifted and still, with `tools` over it and `under` under it. One with no `x` and `y` yet goes in the middle of the view and `onMove` pins it there. On a phone it comes up to the top over the dimmed board. `has('corkboard.editing')`. |
| `tools` | `node` | Over the note being written on, on a computer: its `FormatBar`. On a phone put it in the screen's `footer`, on the keyboard. |
| `under` | `node` | Under the note being written on: its colours, tags and Done. |
| `onDone` | `() => void` | Bare cork tapped, or Esc, while a note is being written on. |
| `onResize` | `(id, w, h) => void` | A note was made bigger or smaller by its bottom-right corner (any note with a mouse; the one being written on with a finger too), in board units. Save it and give it back as the note's `size`. |
| `placing` | `string` | A child just added with no `x` and `y`: it goes in the middle of the view and `onMove` pins it there. |
| `onPin` | `(id, colour) => void` | A pin was tapped and one of its colours picked: `red`, `blue`, `green`, `yellow`, `purple`, `black` or `white`. Give it back as the child's `pin`. |
| `onTie` | `(id, to) => void` | String was dragged from one pin to another. Add it to `links`. |
| `onCut` | `(id, id) => void` | A string was tapped and Cut. |
| `onDrop` | `(id, onto, x, y) => void` | One was let go over another, `x` and `y` where on it: a sticker onto a note. After `onMove`. |
| `onStick` | `(from, index, onto, x, y) => void` | Sticker `index` of a child's `stickers` was peeled off and let go: on a note or card `onto` (the same one too), `x` and `y` where on it, or on bare cork (`onto` is `null`), `x` and `y` where an 84 by 70 `Sticker` goes on the board. With it the board draws every child's `stickers` itself, to peel off. `has('corkboard.stickers')`. |
| `onBin` | `(id, index?) => void` | Something was dropped in the bin that rises while it's carried: a note, card or `Sticker` on the board (no `index`), or `stickers[index]` of a note or card. |

Each child's `pin` is its pin's colour; `pin={false}` has none, and nor has a `Sticker` unless it says. A
child's `size` sets how wide it is on the board. `has('corkboard.pins')` for `onPin`, `onTie`, `onCut`,
`onDrop`, `placing` and the components below.

On a phone, full bleed, the board is two scrolling columns of its notes on the cork, top to bottom and across in the order they sit on the board, and the note being written on fills the screen with `under` after it. A note dragged onto a `Filter` option with `onDrop` goes there instead of moving.

```tsx
<Corkboard height={800} onMove={(id, x, y) => edit('notes', id, { x, y })}>
  {notes.map((n) => (
    <StickyNote key={n.id} id={n.id} x={n.x} y={n.y} tilt={n.tilt} color={n.color}>
      <Text bold>{n.title}</Text>
    </StickyNote>
  ))}
</Corkboard>
```

#### Sticker, ChatCard, PersonCard and ChatChip

Things to put on a board, or in a note. `Sticker` is an emoji cut out with a white edge (`emoji`); on a board
its `size` is the room it takes. `ChatCard` shows a chat, message or link from `dialog.chat()` (`ref`) as a card;
tapped, it opens there, or `onPress`. `PersonCard` is one of the person's people (`person`, their id, and
`name`), with a button to message them. `ChatChip` is a chat or message as a small pill, for in a note's
words; `onRemove` when it's held. Each takes `tilt` on a board.

```tsx
<ChatCard id={r.id} x={r.x} y={r.y} pin="blue" ref={r.ref} size={[220, 120]} />
<PersonCard id={r.id} x={r.x} y={r.y} person={r.ref.id} name={r.ref.name} size={[210, 76]} />
<Sticker id={r.id} x={r.x} y={r.y} emoji="⭐" size={[84, 70]} />
```

### Text

Words, formatted.

#### Text

Words. Its children are the text.

| Prop | Takes | What it does |
| --- | --- | --- |
| `variant` | `display`, `title`, `headline`, `label`, `caption`, `mono` | Its size and weight. Body text without it. |
| `bold` | `bool` | Bold body text. |
| `tone` | `tone` | Its colour: `accent`, `success`, `warning`, `danger` or `muted`. |
| `strike` | `bool` | Struck through, for something done. |
| `lines` | `number` | At most this many lines, then … |
| `align` | `center` or `end` | Where it sits. |

```tsx
<Text variant="title">Today</Text>
<Text tone="muted" lines={2}>{note.body}</Text>
<Text strike={task.done}>{task.title}</Text>
```

#### Markdown

Markdown: headings, bold, lists, checkboxes, links and code. The words can be picked and copied.

| Prop | Takes | What it does |
| --- | --- | --- |
| `text` | `string` | The Markdown. Or give it as children. |
| `onChange` | `(text) => void` | Makes its `- [ ]` boxes tickable: the text with the box ticked or unticked. |
| `compact` | `bool` | On a card: headings little bigger than the words, and lines break where they were typed. |
| `embeds` | `{[key]: {src?, kind?, ref?, name?, ratio?}}` | What `![words](isolink:key)` draws where it sits: a photo (`src`, an image file), a voice clip (an audio file), a file (`kind: 'file'`), or a chat, message or person (`ref`) as a chip. `has('markdown.embeds')`. |

Times, dates, places, sums and links show as smart pills, as in chats.

```tsx
<Markdown text={note.body} />
```

#### Code

Monospaced text in a box, with a Copy button.

| Prop | Takes | What it does |
| --- | --- | --- |
| `text` | `string` | The code. Or as children. |

```tsx
<Code text={'curl https://example.com'} />
```

#### Highlight

Text with every match of a search marked.

| Prop | Takes | What it does |
| --- | --- | --- |
| `text` | `string` | The text. Or as children. |
| `query` | `string` | What to mark, case ignored. |

```tsx
<Highlight text={note.title} query={search} />
```

### Buttons and menus

Things to tap.

#### Button

A button. Its children, or `label`, are its words.

| Prop | Takes | What it does |
| --- | --- | --- |
| `label` | `string` | Its words. |
| `icon` | `icon` | An icon before them. |
| `variant` | `filled`, `tonal`, `plain`, `danger` | `filled` by default. |
| `onPress` | `() => void` | Tapped. |
| `loading` | `bool` | A spinner instead of the words. |
| `expand` | `bool` | As wide as it can be. |
| `disabled` | `bool` | Faded; taps do nothing. |

```tsx
<Button icon="add" onPress={add}>Add</Button>
<Button variant="tonal" onPress={skip}>Skip</Button>
<Button variant="danger" onPress={remove}>Delete</Button>
```

#### IconButton

A button that's an icon.

| Prop | Takes | What it does |
| --- | --- | --- |
| `icon` | `icon` | The icon. |
| `label` | `string` | What it does, for screen readers and the tooltip. |
| `variant` | `filled` | Filled with the accent. |
| `size` | `number` | Its round's width and height, 44 by default. |
| `onPress` | `() => void` | Tapped. |

```tsx
<IconButton icon="search" label="Search" onPress={() => setSearching(true)} />
```

#### Fab

The screen's main button. Put it in `<Screen fab={…}>` and Isolink draws it the platform's way: a round button of glass on Mac, iPhone and iPad, a command button that says what it does on Windows, a Material button on Android. People who can only view the database don't get it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `icon` | `icon` | `add` by default. |
| `label` | `string` | With words, it's a wide button. |
| `onPress` | `() => void` | Tapped. |

```tsx
<Screen title="Plants" fab={<Fab icon="add" onPress={() => setAdding(true)} />}>…</Screen>
```

#### Toolbar

A row of actions. As many as fit show as buttons; the rest go in a ⋯ menu. Computers show their names when there's room, phones show icons.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `{id, label, icon, onPress, danger}[]` | The actions, most used first. |
| `max` | `number` | The most shown before ⋯: 5 on a computer, 3 on a phone. |
| `labels` | `bool` | `false` keeps a computer to icons too. |

```tsx
<Toolbar items={[
  { id: 'share', label: t('Share'), icon: 'share', onPress: share },
  { id: 'print', label: t('Print'), icon: 'print', onPress: print },
  { id: 'delete', label: t('Delete'), icon: 'delete', danger: true, onPress: remove },
]} />
```

#### SplitButton

A button with a menu beside it for the other choices.

| Prop | Takes | What it does |
| --- | --- | --- |
| `label` | `string` | The main button's words. |
| `icon` | `icon` | Its icon. |
| `onPress` | `() => void` | The main button. |
| `items` | `menu items` | A list of `{id, label, icon, danger}`, or `{divider: true}` for a line. |
| `onPick` | `(id) => void` | A menu item was picked. |

```tsx
<SplitButton label="Send" onPress={send}
  items={[{ id: 'later', label: 'Send later', icon: 'schedule' }]}
  onPick={(id) => id === 'later' && setScheduling(true)} />
```

#### Menu

A button that opens a menu.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `menu items` | `{id, label, icon, danger, checked, shortcut, disabled, items}`, or `{divider: true}` for a line. `shortcut` shows as ⌘N on a Mac and Ctrl+N on Windows, and not on phones; `checked` ticks it; `items` opens a submenu. |
| `onPick` | `(id) => void` | The id picked. |
| `icon` | `icon` | The button's icon, `more` by default. Or give children to be the button. |

```tsx
<Menu items={[{ id: 'rename', label: 'Rename', icon: 'edit' },
               { id: 'delete', label: 'Delete', icon: 'delete', danger: true }]}
      onPick={pick} />
```

#### ContextMenu

A menu on its children: a long press on a phone, a right click on a computer. Inside something that drags (a `Board`, `Masonry` or `Draggable`), a hold drags it, and the menu opens when it's held and let go in place.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `menu items` | The same rows as a `Menu`'s, dividers, shortcuts, ticks and submenus too. |
| `onPick` | `(id) => void` | The id picked. |

```tsx
<ContextMenu items={[{ id: 'pin', label: 'Pin', icon: 'push_pin' }]} onPick={pick}>
  <ListItem title={n.title} />
</ContextMenu>
```

#### Chip

A small pill to pick or filter with.

| Prop | Takes | What it does |
| --- | --- | --- |
| `label` | `string` | Its words. Or as children. |
| `icon` | `icon` | An icon before them. |
| `selected` | `bool` | Picked. |
| `onPress` | `() => void` | Tapped. |

```tsx
{tags.map((t) => <Chip key={t} label={t} selected={t === tag} onPress={() => setTag(t)} />)}
```

#### Filter

One of a few choices to narrow what shows. On a computer it is a row of chips; in a full-bleed screen's top row on a Mac, one round of glass the bar's height, with the picked one lifted; on phones and tablets it is one pill that drops down a menu.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `options` | A list of strings, or `{value, label, icon}`. |
| `value` | `string` | The one picked. |
| `onChange` | `(value) => void` | Another was picked. |
| `onAdd` | `() => void` | Adds a way to add another, at the end. |
| `addLabel` | `string` | Words for adding, `New` by default. |
| `onHold` | `(value) => void` | An option was right-clicked or held (on a phone, the picked one): its menu, to rename or delete it. |
| `onDrop` | `(value, id) => void` | A note from a `Corkboard` or `Masonry` was dropped on an option, on a computer: put it in that folder. |

```tsx
<Filter value={folder} options={[{ value: '', label: 'All' }, ...folders]} onChange={setFolder}
        onAdd={newFolder} addLabel="Folder" />
```

#### FilterTabs

A row of icon tabs to narrow what shows, like Mail's: only the picked one opens up to show its name. Glass rounds on a Mac, toggle buttons on Windows, filter chips on Android. Too many for the row and it scrolls sideways. Check `has('filterTabs')` and fall back to `Filter` on older Isolinks.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `options` | `{value, label, icon, color, badge}`. `label` shows on the picked tab and as the others' tooltip. `color` is the picked tab's own: `blue`, `green`, `red`, `orange`, `yellow`, `purple`, `pink`, `teal`, `indigo`, `brown`, `grey`, or any CSS colour; the theme's otherwise. `badge` is a count. |
| `value` | `string` | The one picked. |
| `onChange` | `(value) => void` | Another was picked. |
| `onHold` | `(value) => void` | A tab was right-clicked or held: its menu. |
| `labels` | `'picked' \| 'all'` | Name only the picked tab (the default), or every tab. |

```tsx
<FilterTabs value={box} onChange={setBox} options={[
  { value: 'people', label: 'People', icon: 'person' },
  { value: 'orders', label: 'Orders', icon: 'shopping_cart', color: 'green', badge: 3 },
  { value: 'all', label: 'All', icon: 'inbox' },
]} />
```

#### Segmented

Two to five choices joined in one control.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `options` | A list of strings, or `{value, label, icon}` (`id` and `name` work too). |
| `value` | `string` | The one picked. |
| `onChange` | `(value) => void` | Another was picked. |

```tsx
<Segmented options={['Day', 'Week', 'Month']} value={view} onChange={setView} />
```

#### Pressable

Makes anything tappable. Its class can style `:pressed` and `:hover`; `display: flex` lays its children in a row.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onPress` | `() => void` | Tapped. |
| `onLongPress` | `() => void` | Held, or right-clicked. |
| `onDoubleTap` | `() => void` | Tapped twice. |

```tsx
<Pressable class={s.tile} onPress={open} onLongPress={menu}>
  <Icon name="timer" />
  <Text>{t.name}</Text>
</Pressable>
```

#### KeyboardShortcut

Runs something when keys are pressed while its children are shown. For the whole app, `useKeys` is simpler.

| Prop | Takes | What it does |
| --- | --- | --- |
| `keys` | `string` | Such as `ctrl+k`, `cmd+enter`, `shift+n` or `esc`. |
| `onPress` | `() => void` | Pressed. |

```tsx
<KeyboardShortcut keys="ctrl+n" onPress={add}>…</KeyboardShortcut>
```

### Input

Fields and pickers. Each is controlled: give it `value` and change it in `onChange`.

#### TextField

A text box.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | What's in it. |
| `onChange` | `(text) => void` | Typed in. A `number` field gives a number when it reads as one. |
| `placeholder` | `string` | Shown while it's empty. |
| `label` | `string` | A label above it. |
| `error` | `string` | A problem, in red under it. |
| `type` | `text`, `number`, `email`, `phone`, `url`, `password` | The keyboard, and hides a password. |
| `multiline` | `bool` | Up to 4 lines. |
| `lines` | `number` | Up to this many lines. |
| `max` | `number` | At most this many characters, with a count. |
| `autofocus` | `bool` | The keyboard opens on it. |
| `onSubmit` | `(text) => void` | Enter, or the keyboard's Done. |
| `plain` | `bool` | No box: just the words, in the text style around it. With `onSubmit` it's one line and Enter submits, from Isolink 0.26.47 (`has('field.submit')`). |

```tsx
<TextField value={name} onChange={setName} placeholder="Name" max={40} onSubmit={add} autofocus />
```

#### SearchField

A search box with a magnifier.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | What's in it. |
| `onChange` | `(text) => void` | Typed in. |
| `placeholder` | `string` | Shown while it's empty. |

```tsx
<SearchField value={search} onChange={setSearch} placeholder="Search" />
```

#### Editor

A big box for writing. With `toolbar`, buttons add Markdown (heading, bold, italic, list, checkbox, code, quote).

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | The text. |
| `onChange` | `(text) => void` | Changed. |
| `placeholder` | `string` | Shown while it's empty. |
| `lines` | `number` | 12 by default. |
| `toolbar` | `bool` | The Markdown buttons. |
| `plain` | `bool` | No box, for writing straight onto a note. |
| `rich` | `bool` | Formatted as it's written: headings, bold, italic, lists and checkboxes look as they will, and a box ticks with a tap. The Markdown marks never show. Return on a list carries it on. |
| `embeds` | `object` | With `rich`, what `![words](isolink:key)` draws in place, as on `Markdown`. |
| `titled` | `bool` | With `rich`, the first line is the title, in bold (not a list's first box). |
| `onCaret` | `(offset) => void` | Where the caret moved to, to put something in there: when the app's `value` comes back with text added at the caret, the caret goes after it. |
| `id` | `string` | For a `FormatBar` elsewhere on the screen. |
| `autofocus` | `bool` | The keyboard opens on it. |
| `bar` | `element` | Floats over the words that are picked, on the platform's glass: a `FormatBar` for this Editor, say. Under them on a touch screen, clear of Copy and Paste. From Isolink 0.26.53 (`has('editor.float')`). |
| `caret` | `element` | Floats just past the end of the line the caret's on, once typing pauses: a button to put a photo or a file in right there. |

```tsx
<StickyNote color={note.color}>
  <Editor plain value={body} onChange={save} placeholder="Note" autofocus />
</StickyNote>
```

#### FormatBar

The Markdown buttons (heading, bold, italic, list, checkbox) for an `Editor` elsewhere on the screen, with the app's own buttons after them. Put it in the Screen's `footer` on a phone, so it sits over the keyboard.

| Prop | Takes | What it does |
| --- | --- | --- |
| `for` | `string` | The Editor's `id`. The last one on screen without it. |

```tsx
<FormatBar for="note">
  <Upload variant="icon" icon="photo_camera" label="Photo" accept="png,jpg" onUpload={addPhoto} />
  <IconButton icon="brush" label="Sketch" onPress={() => setSketching(true)} />
</FormatBar>
```

#### MoneyField

A `TextField` with a number keyboard. `onChange` gives a number.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | The amount. |
| `onChange` | `(amount) => void` | Changed. |
| `label` | `string` | A label. |

```tsx
<MoneyField label="Price" value={price} onChange={setPrice} />
```

#### MentionField

A `TextField` for now; suggesting people as you type `@` is still to come.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | What's in it. |
| `onChange` | `(text) => void` | Typed in. |

```tsx
<MentionField value={text} onChange={setText} placeholder="Comment" />
```

#### TagInput

Tags as chips, with a box to add more (Enter adds one).

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string[]` | The tags. |
| `onChange` | `(tags) => void` | One added or removed. |
| `placeholder` | `string` | In the box. |

```tsx
<TagInput value={note.tags ?? []} onChange={(tags) => data.edit('notes', note.id, { tags })} placeholder="Add a tag" />
```

#### Composer

The chat's own message box, for an add bar: a pill while it's one line that grows as the text wraps,
the buttons you put in it before a send button on a round of the accent. Put it in a `Screen`'s
`footer` and it floats over the page as the chat's does. Inside it, `IconButton`s and `Menu`s look like
the chat's attach and camera. From Isolink 0.26.52 (`has('composer')`).

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | What's typed. |
| `onChange` | `(text) => void` | Typed in. |
| `onSubmit` | `(text) => void` | Send pressed, or Enter (the keyboard's send key on a phone). Only while there's text, or `ready`. |
| `placeholder` | `string` | In the box. |
| `sendIcon` | `string` | The send button's icon. Default `arrow_upward`. |
| `sendLabel` | `string` | The send button's tooltip. Default "Send". |
| `ready` | `bool` | Send works with no text, as when a file is picked. |
| `multiline` | `bool` | Enter on a phone's keyboard starts a new line rather than sending. |
| `max` | `number` | The most characters. |
| `maxWidth` | `number` | How wide it gets on a big screen. Default 720. |
| `top` | `element` | Inside the box, over the text: a title over a note's words. From Isolink 0.26.53 (`has('composer.top')`). |
| `onFocus` | `() => void` | The cursor came into the box, or into anything in it. |
| `onBlur` | `() => void` | The cursor left the box and everything in it. |

```tsx
<Composer value={draft} onChange={setDraft} onSubmit={add} placeholder="New task" sendIcon="add" sendLabel="Add">
  <IconButton icon="event" label="Date" onPress={pickDate} />
</Composer>
```

#### Checkbox

A tick box, with words beside it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `checked` | `bool` | Ticked. |
| `onChange` | `(checked) => void` | Tapped. |
| `label` | `string` | Its words. Or as children. |
| `round` | `bool` | A circle, as in Todo. |

```tsx
<Checkbox round checked={!!t.done} onChange={(done) => data.edit('tasks', t.id, { done })}>{t.title}</Checkbox>
```

#### Toggle

An on and off switch, with words before it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `checked` | `bool` | On. `value` works too. |
| `onChange` | `(on) => void` | Flipped. |
| `label` | `string` | Its words. Or as children. |

```tsx
<Toggle label="Remind me" checked={remind} onChange={setRemind} />
```

#### Radio

One of a list.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `options` | A list of strings, or `{value, label, icon}` (`id` and `name` work too). |
| `value` | `string` | The one picked. |
| `onChange` | `(value) => void` | Another was picked. |

```tsx
<Radio options={['Daily', 'Weekly', 'Monthly']} value={every} onChange={setEvery} />
```

#### Select

One of a list, from a menu.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `options` | A list of strings, or `{value, label, icon}` (`id` and `name` work too). |
| `value` | `string` | The one picked. |
| `onChange` | `(value) => void` | Another was picked. |
| `placeholder` | `string` | Shown while none is picked. |
| `label` | `string` | A label. |
| `variant` | `chip` | A small chip instead of a field. |

```tsx
<Select label="Aisle" value={item.aisle} onChange={(aisle) => data.edit('items', item.id, { aisle })}
  options={[{ value: 'dairy', label: 'Dairy' }, { value: 'bakery', label: 'Bakery' }]} />
```

#### Slider

A number on a track.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | Where it is. |
| `min` | `number` | 0 by default. |
| `max` | `number` | 100 by default. |
| `step` | `number` | Snaps to these steps. |
| `label` | `string` | Shown while dragging. |
| `onChange` | `(value) => void` | Dragged. |

```tsx
<Slider value={volume} min={0} max={10} step={1} onChange={setVolume} />
```

#### RangeSlider

Two ends on a track.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `[number, number]` | The two ends. |
| `min` | `number` | 0 by default. |
| `max` | `number` | 100 by default. |
| `step` | `number` | Snaps to these steps. |
| `onChange` | `([from, to]) => void` | Dragged. |

```tsx
<RangeSlider value={[low, high]} min={0} max={500} step={10} onChange={([a, b]) => { setLow(a); setHigh(b); }} />
```

#### Stepper

A number with − and + buttons.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | The number. |
| `step` | `number` | 1 by default. |
| `min` | `number` | The lowest. |
| `max` | `number` | The highest. |
| `onChange` | `(value) => void` | Changed. |

```tsx
<Stepper value={qty} min={1} max={99} onChange={setQty} />
```

#### Rating

Stars, or an emoji, to tap. Tapping the one picked clears it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | How many. |
| `max` | `number` | 5 by default. |
| `emoji` | `string` | An emoji instead of stars. |
| `onChange` | `(value) => void` | Tapped. |

```tsx
<Rating value={r.stars ?? 0} onChange={(stars) => data.edit('recipes', r.id, { stars })} />
```

#### ColorPicker

Dots of the theme's colours: `accent`, `success`, `warning`, `danger` and `muted`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | The name picked. |
| `onChange` | `(name) => void` | Another was picked. |

```tsx
<ColorPicker value={label.color} onChange={(color) => data.edit('labels', label.id, { color })} />
```

#### DatePicker

A chip that opens the date picker. Dates are `YYYY-MM-DD`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | The date. |
| `onChange` | `(date) => void` | Picked. |
| `placeholder` | `string` | Shown while none is set. |
| `late` | `bool` | In red, for something overdue. |
| `min` | `string` | The earliest day it offers. 1900-01-01 if not set. |
| `max` | `string` | The latest day it offers. 2100-12-31 if not set. |

```tsx
<DatePicker value={t.due} late={!!t.due && t.due < today} onChange={(due) => data.edit('tasks', t.id, { due })} />
```

#### TimePicker

A chip that opens the time picker. Times are `HH:MM`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | The time. |
| `onChange` | `(time) => void` | Picked. |
| `placeholder` | `string` | Shown while none is set. |

```tsx
<TimePicker value={alarm} onChange={setAlarm} />
```

#### DurationPicker

A chip that opens an hours and minutes wheel. Durations are whole minutes, shown as `1:30`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | The minutes. |
| `onChange` | `(minutes) => void` | Picked. |
| `placeholder` | `string` | Shown while none is set. |
| `min` | `number` | The fewest minutes. |
| `max` | `number` | The most minutes. |

```tsx
<DurationPicker value={minutes} min={5} onChange={setMinutes} />
```

#### PersonPicker

Picks one of the database's members. Shows their picture once picked.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | The account id. |
| `onChange` | `(id) => void` | Picked. |

```tsx
<PersonPicker value={chore.who} onChange={(who) => data.edit('chores', chore.id, { who })} />
```

#### PlacePicker

A row showing a place, opening a sheet with search and a map to drag under a pin. My location is there when the app has `needs.device` `location`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `{lat, lng, name}` | The place. |
| `onChange` | `(place) => void` | Picked. |
| `label` | `string` | `Place` by default. |
| `disabled` | `bool` | Shown, not changed. |

```tsx
<PlacePicker value={trip.place} onChange={(place) => data.edit('trips', trip.id, { place })} />
```

#### Keypad

A number pad.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onKey` | `(key) => void` | `0` to `9`, `.` or `back`. |

```tsx
<Keypad onKey={(k) => setAmount(k === 'back' ? amount.slice(0, -1) : amount + k)} />
```

#### EmojiPicker

A row of emoji to pick from.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onPick` | `(emoji) => void` | Picked. |

```tsx
<EmojiPicker onPick={(icon) => data.edit('habits', h.id, { icon })} />
```

#### Reactions

The same row, for reacting.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onReact` | `(emoji) => void` | Picked. |

```tsx
<Reactions onReact={(e) => data.add('reactions', { post: post.id, emoji: e })} />
```

#### Form

A group of fields, one under another. Pair it with `useForm`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `gap` | `space` | Space between fields. |

```tsx
const form = useForm({ name: { required: true, max: 40 } }, { onSubmit: (v) => data.add('plants', v) });
<Form gap={3}>
  <TextField label="Name" {...form.field('name')} />
  <Button onPress={form.submit}>Save</Button>
</Form>
```

### Showing things

Pictures, numbers and progress.

#### Icon

An icon by name (see [Icons](#icons)).

| Prop | Takes | What it does |
| --- | --- | --- |
| `name` | `icon` | Which one. Or as children. |
| `size` | `number` | 20 by default. |
| `tone` | `tone` | Its colour: `accent`, `success`, `warning`, `danger` or `muted`. Muted by default. |

```tsx
<Icon name="cake" tone="accent" size={24} />
```

#### Avatar

Someone's picture.

| Prop | Takes | What it does |
| --- | --- | --- |
| `person` | `string` | An account id: their own picture. |
| `name` | `string` | Without `person`, a circle drawn from this name. |
| `size` | `number` | 36 by default. |

```tsx
<Avatar person={row.who} size={28} />
```

#### AvatarStack

Pictures overlapping, and +n for more.

| Prop | Takes | What it does |
| --- | --- | --- |
| `people` | `string[]` | Account ids. |
| `max` | `number` | How many pictures before +n. 4 by default. |
| `size` | `number` | 28 by default. |
| `onPress` | `() => void` | Tapped. |

```tsx
<AvatarStack people={trip.going ?? []} onPress={() => setPicking(true)} />
```

#### Image

A picture: a `file` field's value, or an https address on a host in `needs.web`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `src` | `file or string` | The picture. |
| `alt` | `string` | What it shows, for screen readers, and shown if it can't load. |
| `fit` | `cover`, `contain`, `fill` | `cover` by default. |
| `ratio` | number or `'16:9'` | Its shape. |
| `onPress` | `() => void` | Tapped. |

```tsx
<Image src={recipe.photo} alt={recipe.name} ratio="4:3" />
```

#### Gallery

Files' pictures in a grid. Tapping one opens them full screen.

| Prop | Takes | What it does |
| --- | --- | --- |
| `files` | `file[]` | The pictures. |
| `columns` | `number` | 3 by default. |
| `onPress` | `(index) => void` | Tapped, instead of opening them. |

```tsx
<Gallery files={trip.photos ?? []} columns={3} />
```

#### Viewer

Photos one at a time, filling its box: swipe between them, pinch or double-tap to zoom. Use it as a lightbox on a full-bleed screen.

| Prop | Takes | What it does |
| --- | --- | --- |
| `files` | `file[]` | The photos. |
| `index` | `number` | The one showing. |
| `onIndex` | `(i) => void` | Swiped to another. |
| `onClose` | `() => void` | Swiped down: close the lightbox. |
| `background` | `string` | `none` for no black behind. |

```tsx
<Screen immersive statusBar={false}>
  <Viewer files={photos} index={i} onIndex={setI} onClose={nav.pop} />
</Screen>
```

#### Carousel

Its children side by side, swiped through one at a time.

| Prop | Takes | What it does |
| --- | --- | --- |
| `height` | `number` | 180 by default. |

```tsx
<Carousel height={200}>{ideas.map((i) => <Card key={i.id}><Text>{i.title}</Text></Card>)}</Carousel>
```

#### SwipeDeck

The first child as a card to swipe away left or right.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onSwipe` | `('left' | 'right') => void` | Swiped. Drop that child to show the next. |

```tsx
<SwipeDeck onSwipe={(side) => vote(films[0].id, side)}>
  {films.map((f) => <Card key={f.id}><Text variant="title">{f.name}</Text></Card>)}
</SwipeDeck>
```

#### Badge

A count, or a small label.

| Prop | Takes | What it does |
| --- | --- | --- |
| `count` | `number` | A number in a dot. |
| `label` | `string` | Words in a pill instead. Or as children. |
| `tone` | `tone` | The pill's colour: `accent`, `success`, `warning`, `danger` or `muted`. |

```tsx
<Badge count={waiting} />
<Badge label="Today" tone="accent" />
```

#### Stat

A big number with a label.

| Prop | Takes | What it does |
| --- | --- | --- |
| `label` | `string` | What it is. |
| `value` | `string` | The number. Or as children. |
| `tone` | `tone` | The number's colour: `accent`, `success`, `warning`, `danger` or `muted`. |
| `change` | `string` | Such as `+12%`, green, or `-3`, red. |

```tsx
<Stat label="This week" value={format.money(spent)} change="-8%" />
```

#### Progress

A bar.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | 0 to 1. |
| `tone` | `tone` | Its colour: `accent`, `success`, `warning`, `danger` or `muted`. The accent by default. |
| `label` | `bool or string` | `true` shows the percentage beside it; a string shows that. |

```tsx
<Progress value={got / items.length} label />
```

#### ProgressRing

A ring, with its children in the middle.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | From `min` to `max`. |
| `min` | `number` | 0 by default. |
| `max` | `number` | 1 by default. |
| `size` | `number` | 44 by default. |
| `stroke` | `number` | The ring's width. A tenth of `size` by default. |
| `tone` | `tone` | Its colour: `accent`, `success`, `warning`, `danger` or `muted`. |
| `label` | `string` | Words in the middle, without children. |

```tsx
<ProgressRing value={left / total} size={104} stroke={7}>
  <Text class={s.time}>{clock(left)}</Text>
</ProgressRing>
```

#### Gauge

A `ProgressRing` from 0 to 100 by default, 96 across, showing its value.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | The value. |
| `min` | `number` | 0 by default. |
| `max` | `number` | 100 by default. |
| `label` | `string` | Instead of the value. |

```tsx
<Gauge value={score} />
```

#### Steps

Numbered steps along a line, with those done ticked.

| Prop | Takes | What it does |
| --- | --- | --- |
| `steps` | `string[]` | Their names. |
| `current` | `number` | The one you're on, from 0. |

```tsx
<Steps steps={['Pack', 'Travel', 'Arrive']} current={1} />
```

#### Countdown

Time left until a moment, ticking every second.

| Prop | Takes | What it does |
| --- | --- | --- |
| `to` | `ms or ISO string` | The moment. |
| `done` | `string` | Shown once it's passed. `0:00` by default. |
| `label` | `string` | A label above it. |

```tsx
<Countdown to={trip.leaves} label="Leaving in" done="Off we go" />
```

#### Timer

Counts down from when it's first shown, and says so when it's done. For a timer that keeps going when the app closes, store when it ends and use `notify`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `seconds` | `number` | 60 by default. |
| `onDone` | `() => void` | Reached zero. |
| `label` | `string` | A label above it. |

```tsx
<Timer seconds={180} label="Tea" onDone={() => toast('Tea’s ready')} />
```

#### Stopwatch

Counts up, with a play and pause button.

| Prop | Takes | What it does |
| --- | --- | --- |
| `label` | `string` | A label above it. |

```tsx
<Stopwatch label="Run" />
```

#### Timeline

Events down a line.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `{title, time, body}[]` | The events, in order. |

```tsx
<Timeline items={days.map((d) => ({ title: d.title, time: format.date(d.date), body: d.notes }))} />
```

#### QR

A QR code.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `string` | What it holds. Or as children. |
| `size` | `number` | 160 by default. |

```tsx
<QR value={`https://example.com/t/${ticket.id}`} />
```

#### Skeleton

Grey lines while something loads.

| Prop | Takes | What it does |
| --- | --- | --- |
| `lines` | `number` | 3 by default. |

```tsx
{weather.loading ? <Skeleton lines={2} /> : <Text>{weather.data.summary}</Text>}
```

#### Banner

A strip with a message, and maybe a button.

| Prop | Takes | What it does |
| --- | --- | --- |
| `text` | `string` | The message. Or as children. |
| `icon` | `icon` | An info icon by default, an error icon with `tone="danger"`. |
| `tone` | `danger` | For a problem. |
| `action` | `string` | A button's words. |
| `onAction` | `() => void` | The button. |
| `onDismiss` | `() => void` | Shows a close button. |

```tsx
<Banner tone="danger" text="Couldn't reach the weather" action="Retry" onAction={reload} />
```

#### Tooltip

Words shown when its children are hovered or held.

| Prop | Takes | What it does |
| --- | --- | --- |
| `text` | `string` | The words. `label` works too. |
| `shortcut` | `string` | Its keys, as `mod+n`: shown as ⌘N on a Mac and Ctrl+N elsewhere. |

```tsx
<Tooltip text="Every 7 days"><Icon name="autorenew" /></Tooltip>
```

#### Motion

Its children fade, slide or grow in as they appear. Any component's `transition` prop does the same.

| Prop | Takes | What it does |
| --- | --- | --- |
| `enter` | `fade`, `slide`, `scale` | `fade` by default. |

```tsx
<Motion enter="slide"><Card>…</Card></Motion>
```

#### Confetti

A burst of confetti, again each time `active` turns true.

| Prop | Takes | What it does |
| --- | --- | --- |
| `active` | `bool` | `true` by default. |

```tsx
{allDone && <Confetti />}
```

#### Dice

A die to tap.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `number` | 1 to 6. |
| `size` | `number` | 48 by default. |
| `onRoll` | `() => void` | Tapped. |

```tsx
<Dice value={roll} onRoll={() => setRoll(1 + Math.floor(Math.random() * 6))} />
```

#### Toast

Draws nothing: call `useToast()` instead.

```tsx
const toast = useToast();
toast('Saved');
```

### Lists and data

Rows from the database, as lists, tables, boards and charts.

#### List

Rows in a group. With `onReorder`, a long press drags one to a new place. It can also take `items` and a function as its children.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `any[]` | With a function as children, draws each item; each is keyed by its `id`. |
| `onReorder` | `(id, index) => void` | One was dragged to `index`. Give each child an `id` (or `key`). |

```tsx
<List items={tasks}>
  {(t) => <ListItem title={t.title} onPress={() => open(t.id)} />}
</List>
```

#### ListItem

A row in a list: a title, a line under it, and something at each end. Swipe actions are optional.

| Prop | Takes | What it does |
| --- | --- | --- |
| `title` | `string` | Its words. Or as children. |
| `subtitle` | `string` | A line under them. |
| `subtitleTone` | `tone` | That line's colour: `accent`, `success`, `warning`, `danger` or `muted`. |
| `leading` | `element or string` | At the start, such as a `Checkbox` or `Avatar`. |
| `trailing` | `element or string` | At the end. |
| `onPress` | `() => void` | Tapped. |
| `onLongPress` | `() => void` | Held, or right-clicked. |
| `onSwipe` | `{start, end}` | Swipe actions, each `{icon, tone, do, keep}`: `do` runs when swiped; with `tone: 'danger'` the row goes unless `keep`. |

```tsx
<ListItem
  key={t.id}
  title={t.title}
  subtitle={t.due ? format.date(t.due) : undefined}
  leading={<Checkbox round checked={!!t.done} onChange={(done) => data.edit('tasks', t.id, { done })} />}
  onSwipe={{ end: { icon: 'delete', tone: 'danger', do: () => data.remove('tasks', t.id) } }}
/>
```

#### VirtualList

A long list. With `height`, it scrolls inside that height; with `onEnd`, it asks for more as the end shows. `InfiniteScroll` is the same.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `any[]` | With a function as children, draws each item. |
| `height` | `number` | Scrolls inside this height. |
| `onEnd` | `() => void` | The end came into view: load more. |

```tsx
<VirtualList items={rows} height={480} onEnd={() => setLimit(limit + 50)}>
  {(r) => <ListItem title={r.name} />}
</VirtualList>
```

#### PullToRefresh

Pull down on its children to refresh.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onRefresh` | `() => void` | Pulled. |

```tsx
<PullToRefresh onRefresh={reload}>…</PullToRefresh>
```

#### Table

Rows in columns, like a planner. A column can draw any component in its cells. Columns sort when tapped, rows group by a field, and on a phone it can show cards instead.

| Prop | Takes | What it does |
| --- | --- | --- |
| `rows` | `row[]` | The rows, each with an `id`. |
| `columns` | `column[]` | `{key, title, width, grow, sort, align, hidden}`. Or `<Table.Column>` children, whose function draws each cell. |
| `select` | `bool` | A tick box on each row. With `<Table.Bulk>`, a Done button runs its function with the ticked ids. |
| `group` | `string` | A field to group rows by, each group folding. |
| `phone` | `cards` | Under 600 px wide, a card for each row. |
| `onAdd` | `(group, title) => void` | An Add row under the rows (under each group). |
| `onRowPress` | `(id) => void` | A row was opened. `<Table.Detail>` does the same with the row itself. |

```tsx
<Table rows={tasks} group="status" onAdd={(status, title) => data.add('tasks', { status, title })}>
  <Table.Column key="title" title="Task" grow />
  <Table.Column key="who" title="Who" width={80}>{(t) => <Avatar person={t.who} size={24} />}</Table.Column>
  <Table.Column key="due" title="Due" sort>{(t) => <DatePicker value={t.due} onChange={(due) => data.edit('tasks', t.id, { due })} />}</Table.Column>
  <Table.Detail>{(t) => nav.push('Task', { id: t.id })}</Table.Detail>
</Table>
```

#### Board

Columns by a field, a card for each item, dragged between columns.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `row[]` | The items, each with an `id`. |
| `by` | `string` | The field the columns are, `status` by default. |
| `columns` | `options` | A list of strings, or `{value, label, icon}` (`id` and `name` work too): the field's values. |
| `height` | `number` | 420 by default. |
| `onMove` | `(id, column) => void` | An item was dropped in a column. A mouse drags one at once; a finger holds it first. |
| `onHold` | `(id) => void` | One was held and let go without moving, or right-clicked: open its menu. |

```tsx
<Board items={tasks} by="status" columns={[{ value: 'todo', label: 'To do' }, { value: 'done', label: 'Done' }]}
  onMove={(id, status) => data.edit('tasks', id, { status })}>
  {(t) => <Card><Text>{t.title}</Text></Card>}
</Board>
```

#### Calendar

A month, with a dot on each day that has items.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `{id, date, title}[]` | Items by their `date` (`YYYY-MM-DD`). |
| `month` | `string` | A date in the month to show first. This month by default. |
| `onPick` | `(date) => void` | A day was tapped. |

```tsx
<Calendar items={plans} onPick={setDay} />
```

#### Schedule

One day's items in time order.

| Prop | Takes | What it does |
| --- | --- | --- |
| `items` | `{id, date, title, start, end}[]` | Items, with `start` and `end` times. |
| `day` | `string` | The day, `YYYY-MM-DD`. Today by default. |
| `onPick` | `(id) => void` | An item was tapped. |

```tsx
<Schedule day={day} items={plans} onPick={(id) => nav.push('Plan', { id })} />
```

#### Chart

A chart of numbers.

| Prop | Takes | What it does |
| --- | --- | --- |
| `kind` | `bar`, `line`, `area`, `pie`, `ring`, `sparkline` | `bar` by default. |
| `data` | `number[] or {label, value}[]` | The numbers. |
| `height` | `number` | 160 by default, 36 for a sparkline. |

```tsx
<Chart kind="bar" data={weeks.map((w) => ({ label: w.name, value: w.total }))} />
```

#### Heatmap

Weeks of days, darker the more each has, like a streak.

| Prop | Takes | What it does |
| --- | --- | --- |
| `days` | `{[date]: number}` | A number for each `YYYY-MM-DD`. |
| `weeks` | `number` | 12 by default. |

```tsx
<Heatmap days={Object.fromEntries(checkins.map((c) => [c.day, 1]))} weeks={16} />
```

#### Leaderboard

Names and scores, first at the top.

| Prop | Takes | What it does |
| --- | --- | --- |
| `rows` | `{name, score}[]` | In order. |

```tsx
<Leaderboard rows={players.map((p) => ({ name: p.name, score: p.points }))} />
```

#### Poll

Options with bars for their votes.

| Prop | Takes | What it does |
| --- | --- | --- |
| `options` | `{id, label, votes}[]` | The options. |
| `onVote` | `(id) => void` | One was tapped. |

```tsx
<Poll options={places.map((p) => ({ id: p.id, label: p.name, votes: p.votes }))}
  onVote={vote} />
```

#### Comments

Its children one under another, for now. `Outline` is the same.

```tsx
<Comments>{comments.map((c) => <ListItem key={c.id} title={c.text} />)}</Comments>
```

#### DatabasePicker

The database's name, and when this app has more than one database, a menu to switch. The top bar already has one.

```tsx
<DatabasePicker />
```

### Camera, sound and drawing

Components that make or play files. What they make is a value for a `file` field: sealed like a chat file, sent to every member's devices, at most 25 MB.

#### Upload

A box to pick a file, then the files under it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onUpload` | `(file) => void` | One was picked and kept. Put it in a `file` field. |
| `value` | `file or file[]` | The files to list. |
| `onRemove` | `(file) => void` | Shows a remove button on each. |
| `accept` | `string` | Extensions, such as `pdf,png,jpg`. |
| `label` | `string` | `Add a file` by default. |
| `variant` | `icon` | Just a button, with `label` as its tooltip. |
| `icon` | `string` | The button's icon. |

```tsx
<Upload value={trip.tickets ?? []} accept="pdf,png,jpg"
  onUpload={(f) => data.edit('trips', trip.id, { tickets: [...(trip.tickets ?? []), f] })} />
```

#### Camera

The camera, with a shutter. Needs `needs.device` `camera`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onCapture` | `(file) => void` | A photo was taken, as a JPEG. |
| `size` | `number` | The longest side of the photo. 2048 by default. |
| `facing` | `front` | The front camera. |
| `height` | `number` | 260 by default. |

```tsx
<Camera onCapture={(photo) => data.edit('plants', p.id, { photo })} />
```

#### Scanner

Reads barcodes and QR codes. Needs `needs.device` `camera`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onScan` | `({text, format}) => void` | A code was read (the same one again only after 3 seconds). |
| `formats` | `string[]` | Only these, such as `qr`, `ean13`. All by default. |
| `height` | `number` | 180 by default. |

```tsx
<Scanner formats={['ean13']} onScan={({ text }) => data.add('items', { name: text })} />
```

#### Recorder

Records sound. Needs `needs.device` `microphone`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onDone` | `(file) => void` | A recording, with its `duration` in ms. |
| `label` | `string` | `Record` by default. |

```tsx
<Recorder onDone={(memo) => data.add('memos', { memo })} />
```

#### Video

Plays a video file.

| Prop | Takes | What it does |
| --- | --- | --- |
| `src` | `file` | The video. |
| `autoplay` | `bool` | Starts as soon as it's loaded. |
| `loop` | `bool` | Plays again from the start. |
| `muted` | `bool` | No sound. |
| `controls` | `bool` | `false` for a bare picture with no play button or bar, as a backdrop. |
| `fullscreen` | `bool` | A button that opens it over everything. |
| `fill` | `bool` | Fills its box, cropped to fit. |
| `onEnd` | `() => void` | Played to the end. |

```tsx
<Video src={clip.file} />
```

#### Audio

Plays a sound file, with its waveform.

| Prop | Takes | What it does |
| --- | --- | --- |
| `src` | `file` | The sound. |

```tsx
<Audio src={m.memo} />
```

#### ImageCrop

Crops a picture to a shape.

| Prop | Takes | What it does |
| --- | --- | --- |
| `src` | `file` | The picture. |
| `ratio` | `string` | The shape it starts on, `1:1` by default. |
| `ratios` | `string[]` | Shapes to pick from. `1:1`, `4:3` and `16:9` by default. |
| `onDone` | `(file) => void` | The cropped picture. |
| `size` | `number` | Its width. 1600 by default. |

```tsx
<ImageCrop src={photo} ratios={['1:1', '4:3']} onDone={(cover) => data.edit('recipes', r.id, { cover })} />
```

#### Sketch

A pad to draw on with a finger.

| Prop | Takes | What it does |
| --- | --- | --- |
| `value` | `file` | A drawing to start from. |
| `onChange` | `(file) => void` | The drawing, when it's saved. |
| `height` | `number` | 200 by default. |
| `fill` | `bool` | As tall as it's given instead. |
| `clear` | `bool` | No pad of its own: drawn over what's under it, and saved see-through. |

```tsx
<Sketch value={plan.map} onChange={(map) => data.edit('plans', plan.id, { map })} />
```

#### Canvas

Shapes the app draws, in the canvas's own units. `{t: 'image', src, x, y, w, h, rotate}` draws a file. With `useFrame` it redraws about 30 times a second, for games.

| Prop | Takes | What it does |
| --- | --- | --- |
| `width` | `number` | Units across, 300 by default. It fills the width and keeps its shape. |
| `height` | `number` | Units down, 200 by default. |
| `shapes` | `shape[]` | `{t: 'rect', x, y, w, h, r}`, `{t: 'circle', x, y, r}`, `{t: 'line', x1, y1, x2, y2}`, `{t: 'path', points: [[x, y], …], closed}` and `{t: 'text', x, y, text, size, bold}`, each with `fill`, `stroke` and `width`. Colours can be tokens such as `accent`. |
| `onPress` | `({x, y}) => void` | Tapped, in its units. |
| `fill` | `bool` | Takes its whole box. Without a `width` its units are the box's own points. |
| `zoomable` | `bool` | Pans and pinches. |
| `maxZoom` | `number` | The furthest in, 6 by default. |
| `onDrag` | `({phase, x, y}) => void` | A drag across it, in its units: `phase` is `start`, `move` or `end`. |

```tsx
<Canvas width={100} height={100} shapes={[
  { t: 'circle', x: 50, y: 50, r: 40, stroke: 'outline', width: 6 },
  { t: 'text', x: 38, y: 40, text: `${done}`, size: 18, bold: true },
]} />
```

#### Svg

A picture drawn from SVG the app writes: shapes, paths and gradients. Nothing it names is fetched.

| Prop | Takes | What it does |
| --- | --- | --- |
| `src` | `string` | The SVG markup, up to 64 KB. |
| `width` | `number` | Its width. Its own by default. |
| `height` | `number` | Its height. |

```tsx
<Svg width={40} height={40} src={`<svg viewBox="0 0 40 40"><circle cx="20" cy="20" r="16" fill="#f5a524"/></svg>`} />
```

#### Map

A map with pins, lines and areas, and where the person is when the app has `needs.device` `location`. Drag to look round; pinch, scroll or use + and − to zoom. Tiles come from OpenStreetMap when the person allows map tiles, darkened in a dark theme.

| Prop | Takes | What it does |
| --- | --- | --- |
| `pins` | `{lat, lng, label}[]` | Pins. |
| `rows` | `row[]` | Rows to pin by their place field. |
| `place` | `string` | The rows' place field, `place` by default. |
| `pin` | `string` | The rows' label field, `name` by default. |
| `center` | `{lat, lng}` | Where it looks. It fits the pins by default. |
| `zoom` | `number` | Where it starts. It fits the pins by default. |
| `minZoom` | `number` | The furthest out. 2 by default. |
| `maxZoom` | `number` | The furthest in. 18 by default. |
| `me` | `bool` | Shows where the person is. |
| `height` | `number` | 260 by default. |
| `onPress` | `(pin) => void` | A pin was tapped: its row or pin. |
| `lines` | `{points, color, width}[]` | Routes: `points` are `{lat, lng}`. |
| `areas` | `{points, color, fill}[]` | Shapes on the map. |
| `follow` | `bool` | Keeps the person's place in the middle as they move. |
| `fill` | `bool` | Takes its whole box, full bleed, with its buttons clear of the bars. |
| `dark` | `bool` | Darkened tiles. Follows the theme by default. |
| `controls` | `bool` | `false` hides the zoom buttons. |
| `onRegion` | `({lat, lng, zoom}) => void` | Moved or zoomed, once it settles. |
| `onZoom` | `(zoom) => void` | Zoomed. |
| `onLongPress` | `({lat, lng}) => void` | Held: where, to drop a pin. |

```tsx
<Map rows={stops} place="where" pin="title" me onPress={(stop) => nav.push('Stop', { id: stop.id })} />
```

### Screens and sheets

#### Screen

A screen's frame. Its children scroll; the rest go in the app's bars.

| Prop | Takes | What it does |
| --- | --- | --- |
| `title` | `string` | Shown in the top bar once you've gone a screen deeper. The first screen shows the database's name. |
| `subtitle` | `string` | A line under the first screen's big title, such as a count. Don't draw your own heading: the first screen already shows the database's name big, as the system does. From Isolink 0.26.48 (`has('screen.title')`). |
| `actions` | `element` | Buttons in the top bar, before the ⋯ menu. With a screen open beside the list on a computer (`split`), the open one's title and `actions` sit up in the bar's row over it, its buttons on one pill with the list's and the ⋯ menu. |
| `bar` | `element` | Controls in the top bar's row after the title, on a computer: a list's folders as a `Filter`. From Isolink 0.26.53 (`has('screen.bar')`). |
| `fab` | `element` | A `Fab`, drawn the platform's way. Hidden from people who can only view. |
| `footer` | `element` | A bar along the bottom, kept above the keyboard. |
| `tabs` | `options` | The app's own tabs, 2 to 5: strings, or `{value, label, icon}`. Drawn the platform's way: a Liquid Glass bar on Mac, iPhone and iPad, a Material bar on Android phones and a rail on wider Android screens, along the top on Windows, and in the sidebar beside the app on a computer. |
| `tab` | `string` | The tab showing. |
| `onTab` | `(value) => void` | Another tab was picked. |
| `onBack` | `() => void` | Back (the button, the gesture, the system's) does this instead of leaving: put down what's being edited, then set it back to `undefined`. `has('screen.onBack')`. |
| `awake` | `bool` | Keeps the display on while this screen shows, such as for cooking from it. |
| `immersive` | `bool` | Full bleed: the last child fills the whole view, under the bars, with the back button, title and menu floating over it. The other children float along its top, or on a computer sit in the top row beside the title. Same as `safeArea={false}`. For a `Corkboard` or a map. |
| `maxWidth` | `number` | How wide its content gets in a wide window, centred. Default 840; `0` for the whole width (a wide grid). Two panes side by side always fill the window. |
| `safeArea` | `bool | edges` | On by default: content stays clear of the bars and glass. `false` runs it under them on every edge (full bleed); a list such as `['bottom']` keeps only those edges clear. Read the gaps with `useSafeArea()`. |
| `shell` | `auto | collapsed | fixed` | On a computer, the sidebar beside a full-bleed app: `auto` the person can fold it away, `collapsed` it starts folded, `fixed` it can't fold. Nothing on phones. |
| `menu` | `list` | Rows of the app's own in the ⋯ menu, after Isolink's: `{label, icon, onPress}`. |
| `statusBar` | `bool` | `false` hides the system's bars on phones and tablets, for photos and video. |
| `orientation` | `'portrait' | 'landscape'` | Holds the screen one way on phones and tablets. |

```tsx
<Screen
  title="Shopping"
  actions={<IconButton icon="search" label="Search" onPress={toggleSearch} />}
  footer={<TextField value={item} onChange={setItem} placeholder="Add an item" onSubmit={add} />}
>
  …
</Screen>
```

#### Tabs

Tabs along the top, with the picked one's content under them.

| Prop | Takes | What it does |
| --- | --- | --- |
| `tabs` | `options` | A list of strings, or `{value, label, icon}` (`id` and `name` work too). `options` works too. |
| `value` | `string` | The tab picked. |
| `onChange` | `(value) => void` | Another was tapped. |

```tsx
<Tabs tabs={['To do', 'Done']} value={tab} onChange={setTab}>
  {tab === 'Done' ? <DoneList /> : <TodoList />}
</Tabs>
```

#### Sheet

Shown while `open` is true. `Sheet` slides up from the bottom (it drops down where you clicked on a computer); `Dialog` is a centred box with its own buttons; `Popover` opens beside its `anchor`.

| Prop | Takes | What it does |
| --- | --- | --- |
| `open` | `bool` | Shown. |
| `onClose` | `() => void` | Closed by the person: set `open` back to false. |
| `detents` | `('small' | 'medium' | 'large' | number)[]` | A sheet that rests part way up and drags to full, as iOS's do: `['medium', 'large']`. On phones and tablets. |
| `title` | `string` | A dialog's heading. |
| `actions` | `{label, onPress, primary, danger, close}[]` | A dialog's buttons, laid out as the platform does. Each closes it unless `close` is false. |
| `dismissible` | `bool` | `false`: a dialog stays when you click outside it. |
| `anchor` | `node` | What a popover opens from: drawn in its place. |
| `width` | `number` | A popover's or dialog's width. |

```tsx
<Sheet open={adding} onClose={() => setAdding(false)}>
  <Stack gap={3}>
    <TextField value={name} onChange={setName} placeholder="Name" autofocus />
    <Button expand onPress={add}>Add</Button>
  </Stack>
</Sheet>
```

#### Draggable

Its children can be dragged onto a `DropZone`: at once with a mouse, after a hold with a finger.

| Prop | Takes | What it does |
| --- | --- | --- |
| `data` | `any` | What a `DropZone` gets. `id` works too. |
| `onHold` | `() => void` | Held and let go without moving, or right-clicked: its menu. |
| `lifted` | `node` | What it looks like in the hand. A copy of itself by default. |
| `forms` | `{[kind]: node}` | What it turns into over a `DropZone` of each `kind`, such as a spine over a shelf of spines. |
| `away` | `'fade'` or `'collapse'` | What's left in its place: faded, or closed up so the things beside it move in. |
| `onDragStart` | `() => void` | Picked up. |
| `onDragEnd` | `(dropped) => void` | Let go: `true` when a `DropZone` took it. |

```tsx
<Draggable data={item.id}><Card>{item.name}</Card></Draggable>
```

#### DropZone

Takes a `Draggable` dropped on it, and lights up while one is over it.

| Prop | Takes | What it does |
| --- | --- | --- |
| `onDrop` | `(data) => void` | Something was dropped. |
| `accept` | `'files' | string[]` | Files dragged in from Finder or Explorer, on a computer: `'files'` for any, or kinds such as `['image', 'pdf']`. |
| `onFiles` | `(files) => void` | Files dropped, each kept as the app's file. |
| `kind` | `string` | What it is, for a `Draggable`'s `forms`. |
| `onEnter` | `(data) => void` | A `Draggable` came over it: make room for it. |
| `onLeave` | `(data) => void` | It went again. |
| `tint` | `bool` | `false`: it doesn't light up. |

```tsx
<DropZone onDrop={(id) => data.edit('items', id, { got: true })}><Text>Got</Text></DropZone>
```

#### Gesture

Pans, pinches, turns, swipes and the mouse wheel on its children. Each says where (`x`, `y` in its box) and with what (`pointer`: touch, mouse, pen or trackpad).

| Prop | Takes | What it does |
| --- | --- | --- |
| `onPan` | `({dx, dy}) => void` | Moved since last time: `{dx, dy, x, y, pointer}`. |
| `onPinch` | `(scale) => void` | Pinched: `(scale, {x, y})`, around the point between the fingers. |
| `onRotate` | `(degrees) => void` | Turned. |
| `onSwipe` | `('left' | 'right') => void` | Swiped. |
| `onDoubleTap` | `() => void` | Tapped twice. |
| `onStart` | `({x, y, pointer, fingers}) => void` | A pan or pinch began. |
| `onEnd` | `({vx, vy}) => void` | Let go, with the fling's speed in points a second. |
| `onTap` | `() => void` | Tapped. |
| `onLongPress` | `({x, y}) => void` | Held, or right-clicked. |
| `onWheel` | `({dx, dy, x, y, zoom}) => void` | The mouse wheel or a trackpad: `zoom` is true while ⌘ or Ctrl is held. |

```tsx
<Gesture onSwipe={(side) => setDay(side === 'left' ? next(day) : prev(day))}>…</Gesture>
```

#### FocusScope

Keeps the keyboard's focus moving inside its children.

```tsx
<FocusScope>…</FocusScope>
```

### Icons

Icons are named: `add`, `cake`, `timer`, `shopping_cart` and the rest below. A name it doesn't know is drawn as a circle; in a chat action's menu row it falls back to the app's icon. These short names work too: `plus` (add), `minus` (remove), `trash` (delete_outline), `delete` (delete_outline), `cart` (shopping_cart), `gear` (settings), `cog` (settings), `x` (close), `tick` (check), `done` (check), `more` (more_horiz), `pen` (edit), `pencil` (edit), `calendar` (calendar_month), `clock` (schedule), `note` (sticky_note_2), `list` (format_list_bulleted), `info` (info_outline), `warning` (warning_amber), `heart` (favorite), `user` (person), `people` (groups), `chat` (chat_bubble), `pin` (push_pin), `flag` (flag), `dice` (casino), `book` (menu_book), `mail` (mail_outline), `bell` (notifications), `up` (arrow_upward), `down` (arrow_downward), `back` (arrow_back), `next` (arrow_forward).

`ac_unit` `account_box` `account_circle` `account_tree` `add` `add_box` `add_circle_outline` `add_comment` `add_location_alt` `add_photo_alternate` `add_reaction` `add_shopping_cart` `add_task` `admin_panel_settings` `air` `alarm` `alarm_off` `alarm_on` `all_inclusive` `alt_route` `animation` `app_shortcut` `archive` `arrow_back` `arrow_downward` `arrow_drop_down` `arrow_forward` `arrow_upward` `article` `assignment` `attach_file` `auto_awesome` `auto_fix_high` `autorenew` `back_hand` `backspace` `backup` `badge` `bar_chart` `battery_alert` `battery_charging_full` `battery_saver` `beach_access` `bedtime` `block` `bluetooth` `bluetooth_connected` `bluetooth_disabled` `bluetooth_searching` `blur_on` `bolt` `bookmark` `bookmark_add` `bookmark_added` `border_bottom` `border_color` `border_left` `border_outer` `border_right` `border_top` `brightness_auto` `broken_image` `brush` `bubble_chart` `bug_report` `build` `burst_mode` `cable` `cake` `calculate` `calendar_month` `call` `call_end` `call_split` `camera_alt` `cameraswitch` `campaign` `cancel` `casino` `category` `celebration` `cell_tower` `center_focus_weak` `chat_bubble` `chat_bubble_outline` `check` `check_box` `check_box_outline_blank` `check_circle` `check_circle_outline` `checklist` `chevron_left` `chevron_right` `circle` `close` `close_fullscreen` `cloud` `cloud_done` `cloud_off` `cloud_queue` `cloud_sync` `cloud_upload` `code` `collections` `compress` `computer` `confirmation_number` `connect_without_contact` `construction` `contact_page` `contacts` `content_copy` `content_paste` `content_paste_go` `contrast` `copy` `copy_all` `create_new_folder` `crop_portrait` `cyclone` `dark_mode` `dashboard_customize` `data_object` `data_saver_on` `data_usage` `delete_forever` `delete_outline` `delete_sweep` `description` `desktop_windows` `devices` `devices_other` `directions_car` `directions_run` `diversity_3` `dns` `do_not_disturb_on` `done_all` `double_arrow` `download` `download_done` `download_for_offline` `downloading` `drag_handle` `drag_indicator` `drive_file_move` `drive_folder_upload` `eco` `edit` `edit_calendar` `edit_note` `edit_square` `emoji_emotions` `emoji_events` `emoji_people` `emoji_symbols` `enhanced_encryption` `error` `error_outline` `event` `event_available` `expand_less` `expand_more` `explore` `explore_off` `extension` `extension_off` `face` `face_retouching_natural` `favorite` `fiber_manual_record` `file_copy` `file_download` `file_open` `file_upload` `fingerprint` `flag` `flare` `flash_auto` `flash_off` `flash_on` `flight` `flip` `folder` `folder_open` `folder_zip` `format_align_center` `format_align_left` `format_align_right` `format_bold` `format_italic` `format_list_bulleted` `format_list_numbered` `format_quote` `format_shapes` `format_size` `forum` `forward` `forward_10` `fullscreen` `fullscreen_exit` `functions` `gavel` `gpp_bad` `gpp_maybe` `gradient` `graphic_eq` `grass` `grid_off` `grid_on` `grid_view` `group` `group_add` `groups` `handshake` `health_and_safety` `hearing` `help` `help_outline` `hide_image` `hiking` `history` `history_toggle_off` `home` `horizontal_rule` `hourglass_bottom` `hourglass_empty` `hourglass_top` `how_to_reg` `how_to_vote` `hub` `image` `image_not_supported` `inbox` `info_outline` `insert_drive_file` `insights` `install_mobile` `inventory_2` `ios_share` `key` `keyboard` `keyboard_arrow_down` `keyboard_arrow_up` `keyboard_command_key` `keyboard_hide` `keyboard_tab` `keyboard_voice` `kitchen` `label_outline` `lan` `landscape` `language` `laptop` `laptop_mac` `layers` `layers_clear` `lens_blur` `light_mode` `lightbulb` `lightbulb_outline` `linear_scale` `link` `link_off` `local_bar` `local_cafe` `local_shipping` `location_off` `location_on` `lock` `lock_open` `lock_outline` `lock_person` `login` `logout` `luggage` `mail_outline` `manage_accounts` `manage_search` `map` `maps_ugc` `mark_chat_read` `mark_chat_unread` `menu` `menu_book` `menu_open` `mic` `mic_none` `mic_off` `monitor` `monitor_heart` `mood` `more_horiz` `more_vert` `motion_photos_off` `motion_photos_paused` `move_to_inbox` `movie` `music_note` `my_location` `navigation` `new_releases` `nightlight` `noise_aware` `note_add` `notes` `notification_important` `notifications` `notifications_active` `notifications_none` `notifications_off` `open_in_full` `open_in_new` `open_with` `outbox` `outlined_flag` `palette` `panorama` `password` `pause` `pause_circle_outline` `payments` `pending` `people` `people_alt` `people_outline` `perm_media` `person` `person_add_alt` `person_add_alt_1` `person_outline` `person_remove` `pets` `phone_android` `phone_in_talk` `phonelink_erase` `phonelink_off` `phonelink_setup` `photo` `photo_album` `photo_camera` `photo_filter` `photo_library` `photo_size_select_large` `photo_size_select_small` `picture_as_pdf` `picture_in_picture_alt` `pin` `pinch` `place` `play_arrow` `play_circle` `play_circle_fill` `play_circle_outline` `poll` `privacy_tip` `psychology` `public` `public_off` `push_pin` `qr_code` `qr_code_2` `qr_code_scanner` `quiz` `radar` `radio_button_checked` `radio_button_off` `radio_button_unchecked` `receipt_long` `record_voice_over` `redeem` `redo` `refresh` `remove` `remove_circle_outline` `replay_10` `reply` `report` `restart_alt` `restaurant` `restaurant_menu` `rocket_launch` `rotate_right` `route` `rule` `save_alt` `schedule` `schedule_send` `school` `science` `screen_share` `search` `search_off` `security_update_good` `segment` `sell` `send` `send_to_mobile` `sensors` `sentiment_neutral` `settings` `settings_backup_restore` `settings_remote` `settings_suggest` `settings_voice` `share` `shield` `shield_moon` `shop` `shopping_bag` `shopping_cart` `short_text` `shortcut` `shuffle` `signal_cellular_connected_no_internet_0_bar` `smart_button` `smart_toy` `smartphone` `sms` `sos` `space_bar` `space_dashboard` `speed` `sports_esports` `sports_soccer` `star` `star_outline` `sticky_note_2` `stop` `stop_circle` `stop_screen_share` `storefront` `straighten` `style` `subdirectory_arrow_right` `support_agent` `swap_horiz` `swap_vert` `sync` `sync_problem` `system_update` `system_update_alt` `tab` `tablet` `tablet_android` `tag` `tap_and_play` `terminal` `text_decrease` `text_fields` `text_format` `text_increase` `timer` `timer_off` `title` `token` `touch_app` `train` `translate` `tune` `unarchive` `undo` `unfold_less` `unfold_more` `update` `upgrade` `upload` `upload_file` `verified` `verified_user` `vertical_align_top` `vibration` `video_library` `videocam` `videocam_off` `view_agenda` `view_carousel` `view_column` `view_kanban` `view_list` `view_sidebar` `visibility` `visibility_off` `volume_off` `volume_up` `wallpaper` `warning` `warning_amber` `watch` `waving_hand` `wb_cloudy` `wb_sunny` `web_asset` `where_to_vote` `widgets` `wifi` `wifi_off` `wifi_tethering` `work` `wrap_text`
