# React hooks

Headless hooks over a Hatch vault. Hatch keeps the data as plain notes that agents, sync and Obsidian read too. You bring the markup. Team (`apps/team`) is built on these hooks, so they are the same code Hatch's own screens run.

```tsx
import { HatchProvider, useBoard, useChannel, useVaultSearch } from '@hatchmd/react'

<HatchProvider vault={vault} me="Alex">
  <App />
</HatchProvider>
```

`vault` is a `Vault` from `@hatchmd/vault` (open one over any `FileSystem`: a folder, the browser's private storage, memory). `me` is the name posts and new tasks go out under.

## The hooks

| Hook | Gives you | Kept in |
|---|---|---|
| `useBoard(name)` | `{ project, columns, tasks, moveTask, addTask, updateTask }` | `Projects/<name>/`, one note per task |
| `useChannel(name)` | `{ messages, send, edit, remove, typing, notifyTyping, threadCounts, hasOlder, loadOlder }` | `Chat/<name>/<YYYY-MM-DD>.md`, one note per day |
| `useThread(channel, id)` | `{ replies, started, send, edit, remove, typing, notifyTyping }` | `Chat/<channel>/Threads/<id>.md` |
| `useVaultSearch()` | `{ query, setQuery, results }` | The vault's own index: tasks by id, status, assignee or label first, then every note by its text |
| `useVaultVersion()` | A number that goes up on every change, by anyone | |
| `useVaultValue(read)` | A value read from the vault, drawn again only when it changes | |
| `useGrow(count)` | `{ shown, edge }`: draw a long list a page at a time | |
| `useWebMcpTools(tools)` | Nothing: gives the AI built into the browser your component's actions as tools while it's on screen (WebMCP, see [webmcp.md](https://hatch-docs.pages.dev/building-on-hatch/tools-for-the-ai-in-the-browser-webmcp/)) | |

The formats are in `Team.md`, which `starterWorkspace()` from `@hatchmd/team-model` writes. An agent with only the MCP server can do anything the hooks do.

### A board

```tsx
function Board() {
  const { columns, moveTask } = useBoard('Website')
  return columns.map((c) => (
    <section key={c.status} onDrop={(e) => moveTask(e.dataTransfer.getData('text/plain'), c.status)} onDragOver={(e) => e.preventDefault()}>
      <h2>{c.status}</h2>
      {c.tasks.map((t) => (
        <div key={t.path} draggable onDragStart={(e) => e.dataTransfer.setData('text/plain', t.path)}>
          {t.title}
        </div>
      ))}
    </section>
  ))
}
```

`moveTask` shows the move at once, here and on everyone else's board, while the note is written. A board only draws again when a note under `Projects/` changes, so a busy chat never redraws it.

### A channel

```tsx
function Chat() {
  const { messages, send, typing, notifyTyping } = useChannel('general')
  const [text, setText] = useState('')
  return (
    <>
      {messages?.map((m) => <p key={m.id}><b>{m.author}</b> {m.body}</p>)}
      <small aria-live="polite">{typing.length ? `${typing.join(', ')} typing` : ''}</small>
      <input value={text} onChange={(e) => { setText(e.target.value); notifyTyping() }} onKeyDown={(e) => e.key === 'Enter' && send(text).then(() => setText(''))} />
    </>
  )
}
```

### Search

```tsx
const { query, setQuery, results } = useVaultSearch()
```

### Sync, people, roles and history

These take objects from `@hatchmd/sync`, so your app decides how it signs in and where it keeps things. `request` is fetch with the account's session (`createAccountClient(...).request` from `@hatchmd/account`).

```tsx
import { createSyncClient, memorySettings, vaultTeam } from '@hatchmd/sync'
import { mergeText } from '@hatchmd/text'

// The sync loop: any FileSystem, timers, focus, held deletes, merging, encrypted vaults
const client = createSyncClient({ request, fs: vault.fs, key: 'my-app', settings: localSettings, device: 'Laptop', merge: mergeText })
await client.link(remoteVault) // or client.resume() on the next start

// The same request and vault give back the same object, so this is fine in render.
// For an encrypted vault pass the client's sealed calls: vaultTeam({ request, vault, api: client.syncApi() })
const team = vaultTeam({ request, vault: remoteVault.id })

const sync = useSyncStatus(client) // { status: 'idle' | 'syncing' | 'offline' | ..., lastSync, error }
const { members, me } = useMembers(team) // roles: owner, manager, editor, viewer
const role = useRole(team, 'Projects/Plan.md') // folder rules applied; follows role changes; every hook on one team shares one load
await team.setRule({ folder: 'Finance', who: '*', role: 'none' }) // owners and managers: editor, viewer or none (hidden), null removes it
const { versions, open } = useHistory(client, 'Projects/Plan.md') // newest first, each with who saved it; follows uploads
```

`useHistory` takes the sync client (which opens encrypted vaults' versions and refreshes after each upload) or a `vaultTeam`. `settings` is any `get(key, fallback)` and `set(key, value)` store (`memorySettings()` for tests and scripts). An encrypted vault's keys go into IndexedDB as non-extractable keys; where there's no IndexedDB (Node) they stay in memory only, so each start asks for the passphrase. Pass `keys` to change that, for example `deviceKeyStore(settings)` when the settings are as private as the vault, since it writes the raw key there. Merges keep the last agreed version of each note in IndexedDB, or in memory without it (`bases` swaps that). The client's timers never keep a Node process running; call `stop()` when you're done. The notes app's own sync (`packages/app/src/cloud.ts`) is this client with the app's settings.

## Live

Typing, moves and "I changed something" travel between people as small hints. The notes stay the truth: a hint makes the others read the disk again sooner, and nothing breaks without it.

By default hints reach this device's other tabs (`BroadcastChannel`). To reach other people, pass a transport. Anything with `send`, `onMessage` and `close` works, including the `ChannelTransport` the app builds from a server room (`serverChannel` in `@hatchmd/live`):

```tsx
<HatchProvider vault={vault} me="Alex" live={{ connect: (key) => serverChannel({ client, vault: id, cipher, key }), refresh }} />
```

`refresh` is how the provider reads the disk again when someone says they changed it. Calls never overlap: one runs, and at most one more waits, however many hints arrive. Pass your own when your app already reads the disk on a timer, so the two take turns (Team does, and skips reads while its tab is hidden). `live={false}` keeps everything local. Writing `live` inline is fine: the provider reads it through a ref, so rooms aren't reopened on each render.

`scope` says which vault this is, so two tabs hear each other only when they have the same one. It's the vault's name unless you pass something more exact, such as the folder's location (Team does).

Every change made on this device sends a hint, whichever screen made it, new folders included. A catch-up with the disk that a hint asked for never does, so hints can't bounce.

## Where the code is

- `packages/react/src`: the provider, the hooks, `live.ts` (hints, the tabs transport, `LiveHub`) and `useSync.ts` (sync, people, roles, history).
- `packages/sync/src`: `client.ts` (the sync loop for any app), `team.ts` (`vaultTeam`), `engine.ts`, `http.ts`, `crypto.ts`.
- `packages/team-model/src`: the formats and `Team`, with no React and no DOM. Use it from a server, a script or another framework.
- `apps/team`: the app built on both. `scripts/e2e-team.py` checks the hooks in a real browser, two tabs included.
