duratom 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +86 -2
- package/dist/chunk-7TXOG3GB.js +973 -0
- package/dist/chunk-URKFBGPT.js +165 -0
- package/dist/core/index.d.ts +150 -0
- package/dist/core/index.js +44 -0
- package/dist/equality-AjtpnVrF.d.ts +20 -0
- package/dist/index.d.ts +102 -0
- package/dist/index.js +182 -0
- package/dist/react/index.d.ts +52 -0
- package/dist/react/index.js +43 -0
- package/dist/shape-CMa7XFjy.d.ts +390 -0
- package/dist/typed-atom-t7tvnXSS.d.ts +127 -0
- package/llms-full.txt +1658 -0
- package/llms.txt +24 -0
- package/package.json +102 -3
- package/skills/duratom/SKILL.md +171 -0
package/llms-full.txt
ADDED
|
@@ -0,0 +1,1658 @@
|
|
|
1
|
+
# duratom: full documentation
|
|
2
|
+
|
|
3
|
+
Every duratom doc in one file: the guide, the recipes and the API reference.
|
|
4
|
+
|
|
5
|
+
<!-- docs/guide.md -->
|
|
6
|
+
|
|
7
|
+
## duratom
|
|
8
|
+
|
|
9
|
+
Durable, live Jotai atoms over a Y.Doc: read typed values, write validated patches, and re-render only when what an atom shows changes.
|
|
10
|
+
|
|
11
|
+
A [Y.Doc](https://docs.yjs.dev) is the shared, conflict-free state that sync providers keep the same on every device. duratom turns a node of it into a Jotai atom: you read a value your schema has checked, you write a patch that is merged into the doc and validated first, and a component re-renders only when the value it shows changes, whoever changed the doc. Persistence and network sync come from existing Yjs providers; duratom has no provider code of its own.
|
|
12
|
+
|
|
13
|
+
### Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install duratom jotai jotai-family yjs
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Add a [Standard Schema](https://standardschema.dev) validator for typed atoms, such as zod, valibot or arktype, and React for `duratom/react`. duratom needs `yjs` 13.6.33 or later, `jotai` 2.9 or later and `jotai-family`.
|
|
20
|
+
|
|
21
|
+
### Quick start
|
|
22
|
+
|
|
23
|
+
Paste this into `src/main.tsx` of a new Vite React app (`npm create vite@latest my-app -- --template react-ts`), then `npm install duratom jotai jotai-family yjs zod` and `npm run dev`.
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
// src/main.tsx of a new Vite React app: npm create vite@latest my-app -- --template react-ts
|
|
27
|
+
import { docAtom, select, typedAtom } from 'duratom'
|
|
28
|
+
import { createStore, Provider, useAtom } from 'jotai'
|
|
29
|
+
import { StrictMode } from 'react'
|
|
30
|
+
import { createRoot } from 'react-dom/client'
|
|
31
|
+
import * as Y from 'yjs'
|
|
32
|
+
import { z } from 'zod'
|
|
33
|
+
|
|
34
|
+
// What a todo is, and where it lives in the doc: the map `first` in the root map `todos`.
|
|
35
|
+
// `title` is collaborative text, so two people typing in it both keep their edits.
|
|
36
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
37
|
+
const todoAtom = typedAtom(select.map('todos').child('first'), Todo, { title: 'text' })
|
|
38
|
+
|
|
39
|
+
// One Y.Doc per Jotai store. A sync provider would connect this doc to other devices.
|
|
40
|
+
const store = createStore()
|
|
41
|
+
store.set(docAtom, new Y.Doc())
|
|
42
|
+
|
|
43
|
+
function TodoRow() {
|
|
44
|
+
// undefined while the todo is missing, { issues } while it's invalid, { value } otherwise.
|
|
45
|
+
const [todo, setTodo] = useAtom(todoAtom)
|
|
46
|
+
if (!todo) {
|
|
47
|
+
// Setting a missing node with a whole valid value creates it.
|
|
48
|
+
return <button onClick={() => setTodo({ title: 'Learn duratom', done: false })}>Add</button>
|
|
49
|
+
}
|
|
50
|
+
if (todo.issues) return <p>Can't read this todo: {todo.issues[0]?.message}</p>
|
|
51
|
+
return (
|
|
52
|
+
<label>
|
|
53
|
+
{/* A patch changes only the fields it names. */}
|
|
54
|
+
<input
|
|
55
|
+
type="checkbox"
|
|
56
|
+
checked={todo.value.done}
|
|
57
|
+
onChange={(e) => setTodo({ done: e.target.checked })}
|
|
58
|
+
/>
|
|
59
|
+
<input value={todo.value.title} onChange={(e) => setTodo({ title: e.target.value })} />
|
|
60
|
+
</label>
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
createRoot(document.getElementById('root')!).render(
|
|
65
|
+
<StrictMode>
|
|
66
|
+
<Provider store={store}>
|
|
67
|
+
<TodoRow />
|
|
68
|
+
</Provider>
|
|
69
|
+
</StrictMode>,
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Add a sync provider to the doc ([sync recipe](recipes/sync.md)) and the same atom shows and edits the todo on every device, with no change to the atom or the component.
|
|
74
|
+
|
|
75
|
+
### Rules
|
|
76
|
+
|
|
77
|
+
Four rules cover how duratom behaves; the [API reference](https://duratom.karolnov.dev/api) has the details.
|
|
78
|
+
|
|
79
|
+
- **One doc per store.** Atoms read the Y.Doc in `docAtom`, so set it once on each Jotai store before reading an atom. An app with several docs gives an atom its own doc atom: `typedAtom(locator, Schema, shape, { docAtom: otherDocAtom })`.
|
|
80
|
+
- **Patches merge.** Setting a typed atom with `{ priority: 'high' }` reads the node as it is in the doc at that moment, merges the patch into it and writes only what changed, so a peer's concurrent edit to another field survives. `set(prev => patch)` gets that fresh value as `prev`. On a node with no valid value, the patch is the whole value: that creates a missing node, or repairs an invalid one.
|
|
81
|
+
- **Results, not exceptions.** A typed atom reads as `undefined` while its node is missing, `{ issues }` while the node doesn't satisfy the schema, and `{ value }` otherwise. Setting it returns the schema's result; an invalid patch changes nothing and returns `{ issues }`. Only misconfiguration throws: an async schema (`AsyncValidationUnsupportedError`), a value a `Y.Map` can't store (`UnsupportedValueError`), or no doc in `docAtom`.
|
|
82
|
+
- **Subscribed atoms follow the doc.** An atom observes its node while something is subscribed to it (a component, or `store.sub`), and then only that node. Read with `store.get` while nothing is subscribed, it can show a value from before a peer's edit; it does see its own writes. Use `live` from `duratom/core` to read the doc as it is now outside Jotai.
|
|
83
|
+
|
|
84
|
+
### Shapes
|
|
85
|
+
|
|
86
|
+
A schema says what a value is; a shape says which of its fields are Yjs shared types, so that peers editing them at once merge their edits. Every field the shape doesn't name is a plain value, where the last writer wins.
|
|
87
|
+
|
|
88
|
+
- `'text'`: a `Y.Text`, read as a string. Two people typing in it both keep their edits.
|
|
89
|
+
- `'xml'`: a `Y.XmlFragment`, read as the fragment itself, for rich-text editors.
|
|
90
|
+
- `map(shape)`: a nested `Y.Map` with fixed keys, read as an object.
|
|
91
|
+
- `record(itemShape)`: a `Y.Map` of item maps with any keys, read as an object of objects.
|
|
92
|
+
- `array()`: a `Y.Array` of plain values, read as an array.
|
|
93
|
+
|
|
94
|
+
A shape's keys are checked against the schema's type, so a key the schema doesn't have, or a kind its field can't hold, is a type error. An empty shape, `{}`, makes every field plain.
|
|
95
|
+
|
|
96
|
+
### Collections
|
|
97
|
+
|
|
98
|
+
`collection` covers a map of items: an `ids` atom that changes only when an item is added or removed, a typed atom per item, and `create` and `remove`.
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
import { collection, select } from 'duratom'
|
|
102
|
+
import { useAtom, useAtomValue, useSetAtom } from 'jotai'
|
|
103
|
+
import { z } from 'zod'
|
|
104
|
+
|
|
105
|
+
const Todo = z.object({ title: z.string().min(1), done: z.boolean() })
|
|
106
|
+
|
|
107
|
+
// Every todo in the root map `todos`, each one a Y.Map read through `Todo`.
|
|
108
|
+
const todos = collection(select.map('todos'), Todo, { title: 'text' })
|
|
109
|
+
|
|
110
|
+
export function TodoList() {
|
|
111
|
+
// Changes only when a todo is added or removed, not when one is edited.
|
|
112
|
+
const ids = useAtomValue(todos.ids)
|
|
113
|
+
const create = useSetAtom(todos.create)
|
|
114
|
+
const add = () => {
|
|
115
|
+
const result = create({ title: 'New todo', done: false })
|
|
116
|
+
if (result.issues) console.warn(result.issues)
|
|
117
|
+
}
|
|
118
|
+
return (
|
|
119
|
+
<>
|
|
120
|
+
<ul>
|
|
121
|
+
{ids.map((id) => (
|
|
122
|
+
<TodoItem key={id} id={id} />
|
|
123
|
+
))}
|
|
124
|
+
</ul>
|
|
125
|
+
<button onClick={add}>Add</button>
|
|
126
|
+
</>
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function TodoItem({ id }: { id: string }) {
|
|
131
|
+
// The same typed atom for the same id; it re-renders this row only.
|
|
132
|
+
const [todo, setTodo] = useAtom(todos.item(id))
|
|
133
|
+
const remove = useSetAtom(todos.remove)
|
|
134
|
+
if (!todo || todo.issues) return <li>Unreadable todo</li>
|
|
135
|
+
return (
|
|
136
|
+
<li>
|
|
137
|
+
<input
|
|
138
|
+
type="checkbox"
|
|
139
|
+
checked={todo.value.done}
|
|
140
|
+
onChange={(e) => setTodo({ done: e.target.checked })}
|
|
141
|
+
/>
|
|
142
|
+
{todo.value.title}
|
|
143
|
+
<button onClick={() => remove(id)}>Remove</button>
|
|
144
|
+
</li>
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Typed atoms in a hook
|
|
150
|
+
|
|
151
|
+
`useTypedAtom` from `duratom/react` is `typedAtom` for a path that depends on props. It returns `[result, set]`, as `useAtom` does, and rebuilds the atom only when `deps` change.
|
|
152
|
+
|
|
153
|
+
```tsx
|
|
154
|
+
import { select } from 'duratom'
|
|
155
|
+
import { useTypedAtom } from 'duratom/react'
|
|
156
|
+
import { z } from 'zod'
|
|
157
|
+
|
|
158
|
+
const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
|
|
159
|
+
|
|
160
|
+
// The card's path depends on a prop: the hook rebuilds the atom only when `id` changes.
|
|
161
|
+
export function CardRow({ id }: { id: string }) {
|
|
162
|
+
const [card, setCard] = useTypedAtom(
|
|
163
|
+
() => select.map('cards').child(id),
|
|
164
|
+
Card,
|
|
165
|
+
{ title: 'text' },
|
|
166
|
+
[id],
|
|
167
|
+
)
|
|
168
|
+
if (!card) return <button onClick={() => setCard({ title: 'New', priority: 'low' })}>Add</button>
|
|
169
|
+
if (card.issues) return <span>Unreadable card</span>
|
|
170
|
+
return (
|
|
171
|
+
<label>
|
|
172
|
+
{card.value.title}
|
|
173
|
+
<input
|
|
174
|
+
type="checkbox"
|
|
175
|
+
checked={card.value.priority === 'high'}
|
|
176
|
+
onChange={(e) => setCard({ priority: e.target.checked ? 'high' : 'low' })}
|
|
177
|
+
/>
|
|
178
|
+
</label>
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Key-value stores
|
|
184
|
+
|
|
185
|
+
State that is written very often in alternating order, such as knobs and XY pads, makes a `Y.Map` grow. y-utility's [`YKeyValue`](https://github.com/yjs/y-utility) keeps it small: `{ key, val }` entries in a `Y.Array`, where the rightmost entry per key is the current one and a write deletes the older ones. `select.keyValue(name)` reads and writes the same entries, so duratom and a `YKeyValue` can share a doc, and duratom needs no y-utility of its own.
|
|
186
|
+
|
|
187
|
+
`typedAtom(path.key(k), schema)` is one validated key: it re-renders only when that key's current value changes, and setting it takes the whole value, since a key holds a plain value rather than fields. `keyValueAtom(path, schemas)` reads several keys with a schema each. A current value the schema rejects reads as `{ issues }`, like an invalid map field, and writing a valid value repairs it.
|
|
188
|
+
|
|
189
|
+
```tsx
|
|
190
|
+
import { keyValueAtom, select, typedAtom } from 'duratom'
|
|
191
|
+
import { useAtom, useAtomValue } from 'jotai'
|
|
192
|
+
import { z } from 'zod'
|
|
193
|
+
|
|
194
|
+
// The root array `master` holds a y-utility YKeyValue: { key, val } entries, the rightmost wins.
|
|
195
|
+
const master = select.keyValue('master')
|
|
196
|
+
|
|
197
|
+
// One key: re-renders only when `tone` changes, not when another knob moves.
|
|
198
|
+
const toneAtom = typedAtom(master.key('tone'), z.number().min(-1).max(1))
|
|
199
|
+
|
|
200
|
+
export function ToneKnob() {
|
|
201
|
+
const [tone, setTone] = useAtom(toneAtom)
|
|
202
|
+
const value = tone && !tone.issues ? tone.value : 0
|
|
203
|
+
return (
|
|
204
|
+
<input
|
|
205
|
+
type="range"
|
|
206
|
+
min={-1}
|
|
207
|
+
max={1}
|
|
208
|
+
step={0.01}
|
|
209
|
+
value={value}
|
|
210
|
+
// Validated, then written as YKeyValue#set writes it: append, delete the older entry.
|
|
211
|
+
onChange={(e) => setTone(Number(e.target.value))}
|
|
212
|
+
/>
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Several keys at once, a schema per key; keys it doesn't name are ignored.
|
|
217
|
+
const XY = z.object({ x: z.number(), y: z.number() })
|
|
218
|
+
const masterAtom = keyValueAtom(master, { tone: z.number(), filter: XY })
|
|
219
|
+
|
|
220
|
+
export function MasterSummary() {
|
|
221
|
+
const { tone, filter } = useAtomValue(masterAtom)
|
|
222
|
+
return (
|
|
223
|
+
<p>
|
|
224
|
+
tone {tone && !tone.issues ? tone.value : '–'}, filter{' '}
|
|
225
|
+
{filter && !filter.issues ? `${filter.value.x}, ${filter.value.y}` : '–'}
|
|
226
|
+
</p>
|
|
227
|
+
)
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
`.get(key, fallback)`, `.keys()` and `.toJSON()` read a key-value store without a schema, and `readKey`, `writeKey` and `keyReader` from `duratom/core` work without Jotai. Values are plain only: a `YKeyValue` holds no shared types.
|
|
232
|
+
|
|
233
|
+
### Custom projections
|
|
234
|
+
|
|
235
|
+
`liveAtom` is the read-only atom under `typedAtom`, for values a schema doesn't describe: one field, a count, anything computed from a node. `select` builds what it reads, and the atom re-renders only when the result changes.
|
|
236
|
+
|
|
237
|
+
```tsx
|
|
238
|
+
import { liveAtom, select } from 'duratom'
|
|
239
|
+
import { useLiveAtom } from 'duratom/react'
|
|
240
|
+
import { useAtomValue } from 'jotai'
|
|
241
|
+
import * as Y from 'yjs'
|
|
242
|
+
|
|
243
|
+
// One field, with a fallback for a missing map, a missing key or a value of another type.
|
|
244
|
+
const boardName = liveAtom(select.map('board').get('name', 'Untitled'))
|
|
245
|
+
|
|
246
|
+
// Your own projection: re-renders only when the counts change, not on every edit to a todo.
|
|
247
|
+
const progress = liveAtom(
|
|
248
|
+
select.map('todos').project((todos) => {
|
|
249
|
+
let done = 0
|
|
250
|
+
todos?.forEach((todo) => {
|
|
251
|
+
if (todo instanceof Y.Map && todo.get('done') === true) done++
|
|
252
|
+
})
|
|
253
|
+
return { done, total: todos?.size ?? 0 }
|
|
254
|
+
}),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
export function Header() {
|
|
258
|
+
const name = useAtomValue(boardName)
|
|
259
|
+
const { done, total } = useAtomValue(progress)
|
|
260
|
+
return (
|
|
261
|
+
<h1>
|
|
262
|
+
{name}: {done} of {total} done
|
|
263
|
+
</h1>
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// A selector that depends on props: the hook rebuilds the atom only when `id` changes.
|
|
268
|
+
export function Title({ id }: { id: string }) {
|
|
269
|
+
const title = useLiveAtom(() => select.map('todos').child(id).text('title'), [id])
|
|
270
|
+
return <span>{title}</span>
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### Several docs
|
|
275
|
+
|
|
276
|
+
Every atom takes a last argument, `{ docAtom }`, naming the atom that holds its doc. Atoms without it read `docAtom`.
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
import { select, typedAtom } from 'duratom'
|
|
280
|
+
import { atom, createStore } from 'jotai'
|
|
281
|
+
import * as Y from 'yjs'
|
|
282
|
+
import { z } from 'zod'
|
|
283
|
+
|
|
284
|
+
// A second doc, beside the one in `docAtom`: settings kept apart from the shared board, say.
|
|
285
|
+
const settingsDocAtom = atom<Y.Doc | null>(null)
|
|
286
|
+
|
|
287
|
+
const Settings = z.object({ theme: z.enum(['light', 'dark']) })
|
|
288
|
+
const settingsAtom = typedAtom(
|
|
289
|
+
select.map('settings').child('user'),
|
|
290
|
+
Settings,
|
|
291
|
+
{},
|
|
292
|
+
{
|
|
293
|
+
docAtom: settingsDocAtom,
|
|
294
|
+
},
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
const store = createStore()
|
|
298
|
+
store.set(settingsDocAtom, new Y.Doc())
|
|
299
|
+
store.set(settingsAtom, { theme: 'dark' })
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
### Without Jotai
|
|
303
|
+
|
|
304
|
+
`duratom/core` has the pieces under the atoms, for other state libraries or none: `live` follows one node of a doc, and `read` and `write` read and write a `Y.Map` through a schema.
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
import { live, read, select, write } from 'duratom/core'
|
|
308
|
+
import * as Y from 'yjs'
|
|
309
|
+
import { z } from 'zod'
|
|
310
|
+
|
|
311
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
312
|
+
const doc = new Y.Doc()
|
|
313
|
+
const todo = doc.getMap('todos').set('first', new Y.Map())
|
|
314
|
+
|
|
315
|
+
// Validated writes and typed reads, on any Y.Map.
|
|
316
|
+
write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: false })
|
|
317
|
+
const result = read(Todo, { title: 'text' }, todo) // { value: { title: 'Learn duratom', done: false } }
|
|
318
|
+
|
|
319
|
+
// A live value in the shape useSyncExternalStore takes, for any state library or none.
|
|
320
|
+
const done = live(doc, select.map('todos').child('first').get('done', false))
|
|
321
|
+
const stop = done.subscribe((value) => console.log('done is now', value))
|
|
322
|
+
write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: true }) // logs: done is now true
|
|
323
|
+
stop()
|
|
324
|
+
|
|
325
|
+
export { result }
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
### Docs
|
|
329
|
+
|
|
330
|
+
- [API reference](https://duratom.karolnov.dev/api): every export, generated from the TSDoc.
|
|
331
|
+
- Recipes: [sync between devices](recipes/sync.md), [offline storage](recipes/offline.md), [repair a broken node](recipes/repair.md).
|
|
332
|
+
- Example apps: [a two-pane shared todo list](https://github.com/KarolNov/duratom/tree/main/examples/todo), and [an offline-first todo list synced through a Durable Object](https://github.com/KarolNov/duratom/tree/main/examples/sync), with end-to-end tests.
|
|
333
|
+
- For AI agents: [`llms.txt`](https://duratom.karolnov.dev/llms.txt), [`llms-full.txt`](https://duratom.karolnov.dev/llms-full.txt) (every doc in one file) and an agent skill, [`skills/duratom/SKILL.md`](https://github.com/KarolNov/duratom/tree/main/skills/duratom/SKILL.md). The npm package ships `llms-full.txt` and the skill, so an agent finds them in `node_modules/duratom`.
|
|
334
|
+
|
|
335
|
+
Every code snippet in these docs is compiled against the source in CI, and so is every `@example` in the TSDoc.
|
|
336
|
+
|
|
337
|
+
<!-- docs/recipes/sync.md -->
|
|
338
|
+
|
|
339
|
+
## Sync between devices
|
|
340
|
+
|
|
341
|
+
Connect the doc in `docAtom` to a sync server with y-partyserver on Cloudflare; every atom then shows and edits the shared state, with no change to the atoms.
|
|
342
|
+
|
|
343
|
+
duratom atoms read whatever is in their doc, and a Yjs provider keeps a doc the same on every device. So sync is a provider attached to the doc you put in `docAtom`: atoms, components and schemas stay as they are. This recipe uses [y-partyserver](https://github.com/cloudflare/partykit/tree/main/packages/y-partyserver), which runs one Durable Object per room on Cloudflare Workers; any Yjs provider, such as y-websocket, plugs in the same way.
|
|
344
|
+
|
|
345
|
+
### Client
|
|
346
|
+
|
|
347
|
+
```bash
|
|
348
|
+
npm install y-partyserver
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
import { docAtom } from 'duratom'
|
|
353
|
+
import { createStore } from 'jotai'
|
|
354
|
+
import YProvider from 'y-partyserver/provider'
|
|
355
|
+
import * as Y from 'yjs'
|
|
356
|
+
|
|
357
|
+
const doc = new Y.Doc()
|
|
358
|
+
// Connects the doc to the room `my-board` of the `Docs` server, and keeps it in sync both ways.
|
|
359
|
+
// The host is the Worker's: localhost:8787 under `wrangler dev`.
|
|
360
|
+
const provider = new YProvider('localhost:8787', 'my-board', doc, { party: 'docs' })
|
|
361
|
+
|
|
362
|
+
export const store = createStore()
|
|
363
|
+
store.set(docAtom, doc)
|
|
364
|
+
|
|
365
|
+
// Before closing the app, or when the doc is no longer needed:
|
|
366
|
+
export const disconnect = () => provider.destroy()
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Pass `store` to Jotai's `<Provider store={store}>`. Edits made before the provider connects, or while it's offline, are sent when it connects.
|
|
370
|
+
|
|
371
|
+
### Server
|
|
372
|
+
|
|
373
|
+
```bash
|
|
374
|
+
npm install partyserver y-partyserver yjs
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
// src/index.ts of a Cloudflare Worker.
|
|
379
|
+
import { routePartykitRequest } from 'partyserver'
|
|
380
|
+
import { YServer } from 'y-partyserver'
|
|
381
|
+
import * as Y from 'yjs'
|
|
382
|
+
|
|
383
|
+
interface Env {
|
|
384
|
+
// The binding's name, in kebab case, is the `party` the client connects to: `docs`.
|
|
385
|
+
Docs: DurableObjectNamespace<Docs>
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** One Durable Object per room, holding that room's doc and saving it to its own storage. */
|
|
389
|
+
export class Docs extends YServer<Env> {
|
|
390
|
+
override async onLoad() {
|
|
391
|
+
const saved = await this.ctx.storage.get<Uint8Array>('doc')
|
|
392
|
+
if (saved) Y.applyUpdate(this.document, saved)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// Called a few seconds after edits, and when the last client leaves.
|
|
396
|
+
override async onSave() {
|
|
397
|
+
await this.ctx.storage.put('doc', Y.encodeStateAsUpdate(this.document))
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export default {
|
|
402
|
+
async fetch(request, env) {
|
|
403
|
+
return (await routePartykitRequest(request, env)) ?? new Response('Not found', { status: 404 })
|
|
404
|
+
},
|
|
405
|
+
} satisfies ExportedHandler<Env>
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
Bind the class as a Durable Object in `wrangler.jsonc`, then run `npx wrangler dev`, or `npx wrangler deploy` and point the client at the Worker's host:
|
|
409
|
+
|
|
410
|
+
```jsonc
|
|
411
|
+
{
|
|
412
|
+
"name": "my-app-sync",
|
|
413
|
+
"main": "src/index.ts",
|
|
414
|
+
"compatibility_date": "2026-11-01",
|
|
415
|
+
"durable_objects": { "bindings": [{ "name": "Docs", "class_name": "Docs" }] },
|
|
416
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Docs"] }],
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
Without `onLoad` and `onSave`, a room keeps its doc only while someone is connected. Durable Object storage limits the size of one value, so store a doc that grows past it in R2, or as several updates.
|
|
421
|
+
|
|
422
|
+
### Offline as well
|
|
423
|
+
|
|
424
|
+
Sync and [offline storage](offline.md) work together: attach both providers to the same doc. Edits made offline are saved locally and sent when the connection comes back.
|
|
425
|
+
|
|
426
|
+
<!-- docs/recipes/offline.md -->
|
|
427
|
+
|
|
428
|
+
## Offline storage
|
|
429
|
+
|
|
430
|
+
Save the doc in the browser with y-indexeddb, so the app opens with the last state and works offline; atoms don't change.
|
|
431
|
+
|
|
432
|
+
A Yjs provider that stores the doc locally is all it takes: [y-indexeddb](https://github.com/yjs/y-indexeddb) writes every change to IndexedDB and loads it back when the app starts.
|
|
433
|
+
|
|
434
|
+
```bash
|
|
435
|
+
npm install y-indexeddb
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import { docAtom } from 'duratom'
|
|
440
|
+
import { createStore } from 'jotai'
|
|
441
|
+
import { IndexeddbPersistence } from 'y-indexeddb'
|
|
442
|
+
import * as Y from 'yjs'
|
|
443
|
+
|
|
444
|
+
const doc = new Y.Doc()
|
|
445
|
+
// Saves every change to IndexedDB under this name, and loads what was saved last time.
|
|
446
|
+
const persistence = new IndexeddbPersistence('my-app', doc)
|
|
447
|
+
|
|
448
|
+
export const store = createStore()
|
|
449
|
+
store.set(docAtom, doc)
|
|
450
|
+
|
|
451
|
+
// Atoms read the doc as soon as it's set; this resolves once the saved state is loaded into it.
|
|
452
|
+
export const loaded = persistence.whenSynced
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Atoms can be read before `loaded` resolves: a typed atom reads `undefined` for a node that isn't loaded yet, then its value once it is, like a node a peer creates. To avoid showing an empty app for a moment, wait for `loaded` before rendering.
|
|
456
|
+
|
|
457
|
+
Use a name per doc: two docs saved under one name are merged into one. To share the doc between devices as well, add a [sync provider](sync.md) to the same doc.
|
|
458
|
+
|
|
459
|
+
<!-- docs/recipes/repair.md -->
|
|
460
|
+
|
|
461
|
+
## Repair a broken node
|
|
462
|
+
|
|
463
|
+
Fix a node a peer stored with data your schema rejects, by setting its typed atom with a whole valid value.
|
|
464
|
+
|
|
465
|
+
A peer running an older or buggy version of an app can store a value your schema rejects: a string where a boolean belongs, a missing field. duratom never throws for it. The node's typed atom reads `{ issues }`, and a collection still lists its id, so the app can show it as broken and offer to fix it.
|
|
466
|
+
|
|
467
|
+
Repairing is app code, because only the app knows what a sensible value is. While a node has no valid value, setting its typed atom takes a whole value and replaces what the schema rejected, keeping keys neither the shape nor the value names, such as fields a newer peer added.
|
|
468
|
+
|
|
469
|
+
```ts
|
|
470
|
+
import { collection, docAtom, select } from 'duratom'
|
|
471
|
+
import { atom } from 'jotai'
|
|
472
|
+
import * as Y from 'yjs'
|
|
473
|
+
import { z } from 'zod'
|
|
474
|
+
|
|
475
|
+
const Todo = z.object({ title: z.string().min(1), done: z.boolean() })
|
|
476
|
+
const todos = collection(select.map('todos'), Todo, { title: 'text' })
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Repairs a todo a peer stored with a value the schema rejects. While an item has no valid value,
|
|
480
|
+
* setting its atom takes a whole value and replaces what the schema rejected. Only the app knows
|
|
481
|
+
* what a sensible value is: here, the stored title when there is one, and not done.
|
|
482
|
+
*/
|
|
483
|
+
export const repairTodo = atom(null, (get, set, id: string) => {
|
|
484
|
+
const stored = get(docAtom)?.getMap<unknown>('todos').get(id)
|
|
485
|
+
const title = stored instanceof Y.Map ? String(stored.get('title') ?? '').trim() : ''
|
|
486
|
+
return set(todos.item(id), { title: title || 'Repaired todo', done: false })
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
/** Whether a todo needs repair: listed, but read as `{ issues }` or not a map at all. */
|
|
490
|
+
export const needsRepair = (id: string) =>
|
|
491
|
+
atom((get) => {
|
|
492
|
+
const result = get(todos.item(id))
|
|
493
|
+
return !result || result.issues !== undefined
|
|
494
|
+
})
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
A row can read `needsRepair(id)` to show a repair button, and call `useSetAtom(repairTodo)(id)` when it's pressed. `repairTodo` returns the schema's result: `{ issues }` if the value it built is still invalid, in which case nothing changed.
|
|
498
|
+
|
|
499
|
+
An entry a peer stored as a plain value is replaced the same way: the item's typed atom reads `undefined`, and setting it with a whole value stores a new map in its place. An entry stored as another shared type, such as a `Y.Text`, reads as `{ issues }` and can't be replaced through the item's atom; delete it with the collection's `remove` and create the item again.
|
|
500
|
+
|
|
501
|
+
<!-- docs/api.md -->
|
|
502
|
+
|
|
503
|
+
## API reference
|
|
504
|
+
|
|
505
|
+
duratom has three entry points. `duratom` is the one most apps need; `duratom/react` adds hooks, and `duratom/core` has the pieces that work without Jotai.
|
|
506
|
+
|
|
507
|
+
### `duratom`
|
|
508
|
+
|
|
509
|
+
#### Functions and values
|
|
510
|
+
|
|
511
|
+
##### `array`
|
|
512
|
+
|
|
513
|
+
```ts
|
|
514
|
+
const array: () => ArrayKind
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
A `Y.Array` of plain values, read as a plain array. Writing it changes only the items that
|
|
518
|
+
differ, so items peers add at once are all kept.
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
const Card = z.object({ tags: z.array(z.string()) })
|
|
522
|
+
const card = typedAtom(select.map('cards').child('card-1'), Card, { tags: array() })
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
##### `isMap`
|
|
526
|
+
|
|
527
|
+
```ts
|
|
528
|
+
const isMap: (value: unknown) => value is Y.Map<unknown>
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
Whether `value` is a `Y.Map` that duratom reads as one: a `Y.XmlHook` extends `Y.Map`, but peers
|
|
532
|
+
decode it as its own type, so it isn't.
|
|
533
|
+
|
|
534
|
+
```ts
|
|
535
|
+
const stored = doc.getMap('todos').get(id)
|
|
536
|
+
if (isMap(stored)) console.log(stored.get('title'))
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
##### `map`
|
|
540
|
+
|
|
541
|
+
```ts
|
|
542
|
+
const map: <const S extends AnyShape>(shape: S) => MapKind<S>
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
A nested `Y.Map` with the fixed keys `shape` describes, read as a plain object.
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
const Card = z.object({ title: z.string(), meta: z.object({ note: z.string() }) })
|
|
549
|
+
const card = typedAtom(select.map('cards').child('card-1'), Card, { meta: map({ note: 'text' }) })
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
##### `record`
|
|
553
|
+
|
|
554
|
+
```ts
|
|
555
|
+
const record: <const S extends AnyShape>(itemShape: S) => RecordKind<S>
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
A `Y.Map` with dynamic keys whose every value is a `Y.Map` following `itemShape`.
|
|
559
|
+
|
|
560
|
+
```ts
|
|
561
|
+
const Board = z.object({ cards: z.record(z.string(), z.object({ title: z.string() })) })
|
|
562
|
+
const board = typedAtom(select.map('boards').child('b1'), Board, { cards: record({ title: 'text' }) })
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
##### `ArrayPath`
|
|
566
|
+
|
|
567
|
+
```ts
|
|
568
|
+
class ArrayPath<V = unknown>
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
A path to a `Y.Array`. End it with a projection to get a `Selector`.
|
|
572
|
+
|
|
573
|
+
```ts
|
|
574
|
+
const log = select.map('board').child('log', 'array')
|
|
575
|
+
const entries = liveAtom(log.length())
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
- `toArray(): Selector<V[]>`
|
|
579
|
+
|
|
580
|
+
The items as stored, `[]` when the array is missing. Compared shallowly.
|
|
581
|
+
|
|
582
|
+
- `length(): Selector<number>`
|
|
583
|
+
|
|
584
|
+
The number of items, 0 when the array is missing.
|
|
585
|
+
|
|
586
|
+
- `toJSON(): Selector<unknown[]>`
|
|
587
|
+
|
|
588
|
+
`toJSON()` of the array and everything under it, `[]` when missing. Observes deeply; compared deeply.
|
|
589
|
+
|
|
590
|
+
- `readonly locator: Locator<Y.Array<V>>`
|
|
591
|
+
- `project<T>(project: (node: Y.Array<V> | undefined) => T, options?: ProjectOptions<T>): Selector<T>`
|
|
592
|
+
|
|
593
|
+
Your own projection of the node, `undefined` when it is missing or of
|
|
594
|
+
another kind. Observes deeply and compares with `deepEqual` unless
|
|
595
|
+
`options` say otherwise; `keys` alone observes only those keys.
|
|
596
|
+
|
|
597
|
+
- `project<T>(projection: Projection<T>): Selector<T>`
|
|
598
|
+
|
|
599
|
+
A packaged projection, such as `reader(schema, shape)`, with its own
|
|
600
|
+
observe options and `equals`. It gets the node as stored, whatever its kind.
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
##### `at`
|
|
604
|
+
|
|
605
|
+
```ts
|
|
606
|
+
const at: {
|
|
607
|
+
map: <V = unknown>(name: string) => Locator<Y.Map<V>>;
|
|
608
|
+
array: <V = unknown>(name: string) => Locator<Y.Array<V>>;
|
|
609
|
+
}
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
Starts a `Locator` at a root type of the doc. `select` builds on it, and is what most code
|
|
613
|
+
uses; `at` is for a `LiveSpec` written by hand.
|
|
614
|
+
|
|
615
|
+
```ts
|
|
616
|
+
const spec = {
|
|
617
|
+
locate: () => at.map('cards').child<Y.Map<unknown>>('card-1'),
|
|
618
|
+
project: (card: Y.Map<unknown> | undefined) => card?.size ?? 0,
|
|
619
|
+
}
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
##### `deepEqual`
|
|
623
|
+
|
|
624
|
+
```ts
|
|
625
|
+
const deepEqual: (a: unknown, b: unknown) => boolean
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
Compares arrays and plain objects all the way down, and bytes byte by byte.
|
|
629
|
+
Any other object (a `Map`, a `Set`, a `Date`, a shared type) equals only itself.
|
|
630
|
+
|
|
631
|
+
```ts
|
|
632
|
+
deepEqual({ tags: ['a'] }, { tags: ['a'] }) // true
|
|
633
|
+
const tags = liveAtom({ ...select.map('card').get('tags', []), equals: deepEqual })
|
|
634
|
+
```
|
|
635
|
+
|
|
636
|
+
##### `KeyPath`
|
|
637
|
+
|
|
638
|
+
```ts
|
|
639
|
+
class KeyPath
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
One key of a key-value array (see `KeyValuePath`): `select.keyValue(name).key(k)`. `typedAtom`
|
|
643
|
+
takes one for a validated atom over that key's current value.
|
|
644
|
+
|
|
645
|
+
```ts
|
|
646
|
+
const tone = select.keyValue('master').key('tone')
|
|
647
|
+
const toneAtom = typedAtom(tone, z.number())
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
- `constructor(/** Where the key-value array is. */ readonly locator: Locator<Y.Array<unknown>>, readonly key: string)`
|
|
651
|
+
- `readonly locator: Locator<Y.Array<unknown>>`
|
|
652
|
+
|
|
653
|
+
Where the key-value array is.
|
|
654
|
+
|
|
655
|
+
- `readonly key: string`
|
|
656
|
+
|
|
657
|
+
##### `KeyValuePath`
|
|
658
|
+
|
|
659
|
+
```ts
|
|
660
|
+
class KeyValuePath<V = unknown>
|
|
661
|
+
```
|
|
662
|
+
|
|
663
|
+
A path to a `Y.Array` that holds y-utility's `YKeyValue`: `{ key, val }` entries where the
|
|
664
|
+
rightmost entry per key is the current one. duratom reads and writes the same entries as
|
|
665
|
+
`YKeyValue`, so the two can share a doc. Items that aren't entries are skipped. End it with a
|
|
666
|
+
projection, or pass `key(k)` to `typedAtom` for a validated, writable atom over one key.
|
|
667
|
+
|
|
668
|
+
```ts
|
|
669
|
+
const master = select.keyValue('master')
|
|
670
|
+
const tone = liveAtom(master.get('tone', 0))
|
|
671
|
+
const toneAtom = typedAtom(master.key('tone'), z.number().min(-1).max(1))
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
- `key(key: string): KeyPath`
|
|
675
|
+
|
|
676
|
+
The entry for `key`, for `typedAtom(path.key(k), schema)`.
|
|
677
|
+
|
|
678
|
+
- `get(key: string): Selector<V | undefined>`
|
|
679
|
+
|
|
680
|
+
The current value of `key` as stored, `undefined` when it has no entry or the array is
|
|
681
|
+
missing. Notifies only when an entry for `key` is added or deleted and the value changed.
|
|
682
|
+
|
|
683
|
+
- `get<D>(key: string, fallback: D): Selector<undefined extends D ? V | Checked<D> : Checked<D>>`
|
|
684
|
+
|
|
685
|
+
The current value of `key` when it has `fallback`'s kind, else `fallback`, as `MapPath#get`
|
|
686
|
+
checks it. Notifies only when an entry for `key` changes the value.
|
|
687
|
+
|
|
688
|
+
- `keys(): Selector<string[]>`
|
|
689
|
+
|
|
690
|
+
The keys that have an entry, sorted so every peer sees the same order. `[]` when missing.
|
|
691
|
+
|
|
692
|
+
- `toJSON(): Selector<Record<string, V>>`
|
|
693
|
+
|
|
694
|
+
The current value of every key, as stored. `{}` when missing. Compared deeply.
|
|
695
|
+
|
|
696
|
+
- `readonly locator: Locator<Y.Array<unknown>>`
|
|
697
|
+
- `project<T>(project: (node: Y.Array<unknown> | undefined) => T, options?: ProjectOptions<T>): Selector<T>`
|
|
698
|
+
|
|
699
|
+
Your own projection of the node, `undefined` when it is missing or of
|
|
700
|
+
another kind. Observes deeply and compares with `deepEqual` unless
|
|
701
|
+
`options` say otherwise; `keys` alone observes only those keys.
|
|
702
|
+
|
|
703
|
+
- `project<T>(projection: Projection<T>): Selector<T>`
|
|
704
|
+
|
|
705
|
+
A packaged projection, such as `reader(schema, shape)`, with its own
|
|
706
|
+
observe options and `equals`. It gets the node as stored, whatever its kind.
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
##### `Locator`
|
|
710
|
+
|
|
711
|
+
```ts
|
|
712
|
+
class Locator<N extends Y.AbstractType<any> = Y.AbstractType<any>>
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
A path from a root type to the node a component cares about. It is a path
|
|
716
|
+
rather than a bare function of the doc so the subscription can watch the key
|
|
717
|
+
in each parent map: that is how a node that does not exist yet (a card that
|
|
718
|
+
another tab has not created) or that gets deleted is noticed without
|
|
719
|
+
observing the whole doc.
|
|
720
|
+
|
|
721
|
+
```ts
|
|
722
|
+
const card = at.map('cards').child<Y.Map<unknown>>('card-1')
|
|
723
|
+
card.resolve(doc) // the Y.Map, or undefined while it's missing
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
- `constructor(readonly steps: readonly Step[])`
|
|
727
|
+
- `readonly steps: readonly Step[]`
|
|
728
|
+
- `child<C extends Y.AbstractType<any> = Y.AbstractType<any>>(key: string): Locator<C>`
|
|
729
|
+
|
|
730
|
+
Descend into the Y type stored under `key` of a map.
|
|
731
|
+
|
|
732
|
+
- `resolve(doc: Y.Doc): N | undefined`
|
|
733
|
+
|
|
734
|
+
##### `MapPath`
|
|
735
|
+
|
|
736
|
+
```ts
|
|
737
|
+
class MapPath<V = unknown>
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
A path to a `Y.Map`. Descend with `child`, or end with a projection to get a `Selector`.
|
|
741
|
+
`select.map(name)` starts one; `typedAtom` and `collection` take one as their locator.
|
|
742
|
+
|
|
743
|
+
```ts
|
|
744
|
+
const card = select.map('cards').child('card-1')
|
|
745
|
+
const title = liveAtom(card.text('title'))
|
|
746
|
+
const flags = liveAtom(card.pick({ done: false, starred: false }))
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
- `child<W = V extends Y.Map<infer X> ? X : unknown>(key: string): MapPath<W>`
|
|
750
|
+
|
|
751
|
+
Descend into the `Y.Map` stored under `key`.
|
|
752
|
+
|
|
753
|
+
- `child<W = V extends Y.Array<infer X> ? X : unknown>(key: string, kind: 'array'): ArrayPath<W>`
|
|
754
|
+
|
|
755
|
+
Descend into the `Y.Array` stored under `key`.
|
|
756
|
+
|
|
757
|
+
- `child<W = unknown>(key: string, kind: 'keyValue'): KeyValuePath<W>`
|
|
758
|
+
|
|
759
|
+
Descend into the `Y.Array` under `key` that holds a y-utility `YKeyValue`.
|
|
760
|
+
|
|
761
|
+
- `get(key: string): Selector<V | undefined>`
|
|
762
|
+
|
|
763
|
+
The value under `key`, or `undefined` when it or the map is missing. Observes only `key`.
|
|
764
|
+
|
|
765
|
+
- `get<D>(key: string, fallback: D): Selector<undefined extends D ? V | Checked<D> : Checked<D>>`
|
|
766
|
+
|
|
767
|
+
The value under `key` when it has the same type as `fallback` (`typeof`,
|
|
768
|
+
with null, arrays, bytes and plain objects told apart), else `fallback`. So
|
|
769
|
+
a missing map, a missing key and a value of the wrong type all read as
|
|
770
|
+
`fallback`. An `undefined` fallback reads the value as `get(key)` does.
|
|
771
|
+
A literal type widens to its primitive, since only the kind is checked; the
|
|
772
|
+
items of an array and the fields of an object aren't checked. An array or
|
|
773
|
+
object fallback is read frozen, a bytes fallback as a copy. Observes only `key`.
|
|
774
|
+
|
|
775
|
+
- `pick<D extends Record<string, unknown>>(defaults: D): Selector<{ [K in keyof D]: Checked<D[K]> }>`
|
|
776
|
+
|
|
777
|
+
An object with each key of `defaults`, read as `get(key, defaults[key])`
|
|
778
|
+
reads it. Observes only those keys; compared shallowly.
|
|
779
|
+
|
|
780
|
+
- `text(key: string): Selector<string>`
|
|
781
|
+
|
|
782
|
+
The string of the `Y.Text` under `key`, `''` when it is missing or not a
|
|
783
|
+
`Y.Text` (a `Y.XmlText` included). Follows edits to the text.
|
|
784
|
+
|
|
785
|
+
- `keys(): Selector<string[]>`
|
|
786
|
+
|
|
787
|
+
The map's keys, sorted so every peer sees the same order. `[]` when the
|
|
788
|
+
map is missing. Only a key added or deleted counts, not a value replaced.
|
|
789
|
+
Its own `event` filter does that, so a spec that adds an `event` filter
|
|
790
|
+
calls it from its own: `{ ...ids, event: (e) => ids.event!(e) && mine(e) }`.
|
|
791
|
+
|
|
792
|
+
- `toJSON(): Selector<Record<string, unknown>>`
|
|
793
|
+
|
|
794
|
+
`toJSON()` of the map and everything under it, `{}` when missing. Observes deeply; compared deeply.
|
|
795
|
+
|
|
796
|
+
- `readonly locator: Locator<Y.Map<V>>`
|
|
797
|
+
- `project<T>(project: (node: Y.Map<V> | undefined) => T, options?: ProjectOptions<T>): Selector<T>`
|
|
798
|
+
|
|
799
|
+
Your own projection of the node, `undefined` when it is missing or of
|
|
800
|
+
another kind. Observes deeply and compares with `deepEqual` unless
|
|
801
|
+
`options` say otherwise; `keys` alone observes only those keys.
|
|
802
|
+
|
|
803
|
+
- `project<T>(projection: Projection<T>): Selector<T>`
|
|
804
|
+
|
|
805
|
+
A packaged projection, such as `reader(schema, shape)`, with its own
|
|
806
|
+
observe options and `equals`. It gets the node as stored, whatever its kind.
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
##### `select`
|
|
810
|
+
|
|
811
|
+
```ts
|
|
812
|
+
const select: {
|
|
813
|
+
map: <V = unknown>(name: string) => MapPath<V>;
|
|
814
|
+
array: <V = unknown>(name: string) => ArrayPath<V>;
|
|
815
|
+
keyValue: <V = unknown>(name: string) => KeyValuePath<V>;
|
|
816
|
+
}
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
Builds selectors: `select.map('cards').child(id).get('title', '')`. Starts
|
|
820
|
+
at a root type of the doc, like `at`.
|
|
821
|
+
|
|
822
|
+
```ts
|
|
823
|
+
const title = liveAtom(select.map('cards').child('card-1').get('title', ''))
|
|
824
|
+
const ids = liveAtom(select.map('cards').keys())
|
|
825
|
+
const order = liveAtom(select.array<string>('order').toArray())
|
|
826
|
+
const tone = liveAtom(select.keyValue('master').get('tone', 0))
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
##### `shallowEqual`
|
|
830
|
+
|
|
831
|
+
```ts
|
|
832
|
+
const shallowEqual: (a: unknown, b: unknown) => boolean
|
|
833
|
+
```
|
|
834
|
+
|
|
835
|
+
Whether two values are the same, or objects or arrays whose own keys hold the same values
|
|
836
|
+
(`Object.is`). The default `equals` of a `LiveSpec`.
|
|
837
|
+
|
|
838
|
+
```ts
|
|
839
|
+
shallowEqual({ done: 1, total: 2 }, { done: 1, total: 2 }) // true
|
|
840
|
+
shallowEqual({ tags: ['a'] }, { tags: ['a'] }) // false: two different arrays
|
|
841
|
+
```
|
|
842
|
+
|
|
843
|
+
##### `docAtom`
|
|
844
|
+
|
|
845
|
+
```ts
|
|
846
|
+
const docAtom: PrimitiveAtom<Y.Doc | null> & { init: Y.Doc | null;}
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
Holds the live Y.Doc handle that atoms read by default. Set once per store; the doc never
|
|
850
|
+
changes, so this atom never notifies.
|
|
851
|
+
|
|
852
|
+
```ts
|
|
853
|
+
const store = createStore()
|
|
854
|
+
store.set(docAtom, new Y.Doc())
|
|
855
|
+
```
|
|
856
|
+
|
|
857
|
+
##### `liveAtom`
|
|
858
|
+
|
|
859
|
+
```ts
|
|
860
|
+
function liveAtom<N extends Y.AbstractType<any>, T>(
|
|
861
|
+
spec: LiveSpec<N, T>,
|
|
862
|
+
options: AtomOptions = {},
|
|
863
|
+
): Atom<T>
|
|
864
|
+
```
|
|
865
|
+
|
|
866
|
+
A read-only atom over one node of the doc in `docAtom` (or the doc atom given in `options`),
|
|
867
|
+
built on `live` from `duratom/core`. While something is subscribed it observes only the
|
|
868
|
+
located node, re-runs `project` on matching transactions and updates only when `equals` says
|
|
869
|
+
the result changed. Unsubscribes when the last subscriber goes away.
|
|
870
|
+
|
|
871
|
+
Read while nothing is subscribed (`store.get` outside a component), it can be stale: Jotai
|
|
872
|
+
keeps an unmounted atom's value until one of its atom dependencies changes, and a doc edit
|
|
873
|
+
isn't one. It projects the doc on its first read and again whenever it is mounted, but not
|
|
874
|
+
after later doc edits made while unmounted. Subscribe (`useAtomValue`, `store.sub`) to follow
|
|
875
|
+
the doc; outside Jotai, `live` from `duratom/core` reads the doc as it is now.
|
|
876
|
+
|
|
877
|
+
A change skipped by the `origin` filter is not remembered: the value catches up at the next
|
|
878
|
+
accepted change.
|
|
879
|
+
|
|
880
|
+
```ts
|
|
881
|
+
const titleAtom = liveAtom(select.map('cards').child('card-1').get('title', ''))
|
|
882
|
+
```
|
|
883
|
+
|
|
884
|
+
##### `collection`
|
|
885
|
+
|
|
886
|
+
```ts
|
|
887
|
+
function collection<Schema extends StandardSchemaV1, const S extends object>(
|
|
888
|
+
locator: Locator<any> | MapPath<any>,
|
|
889
|
+
schema: Schema,
|
|
890
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
891
|
+
options: AtomOptions = {},
|
|
892
|
+
): Collection<StandardSchemaV1.InferOutput<Schema>>
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
A collection over the `Y.Map` at `locator`, whose every entry is an item `Y.Map` read through
|
|
896
|
+
`schema` and `shape`. `ids` lists the items and stays quiet while their fields change, `item(id)`
|
|
897
|
+
is a `typedAtom` per item, and `create` and `remove` add and delete items.
|
|
898
|
+
|
|
899
|
+
Like any duratom atom, `ids` and `item(id)` can read stale while nothing is subscribed, except
|
|
900
|
+
right after the collection's own `create` or `remove`, or a write through `item(id)` that
|
|
901
|
+
created the item. An entry a peer stored as something other than a `Y.Map` is still listed in
|
|
902
|
+
`ids`, so it can be found and repaired; its `item` atom reads it as `{ issues }`, or as
|
|
903
|
+
`undefined` for a plain value.
|
|
904
|
+
|
|
905
|
+
```ts
|
|
906
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
907
|
+
const todos = collection(select.map('todos'), Todo, { title: 'text' })
|
|
908
|
+
|
|
909
|
+
const { id } = store.set(todos.create, { title: 'Buy milk', done: false }) as { id: string }
|
|
910
|
+
store.get(todos.ids) // [id]
|
|
911
|
+
store.set(todos.item(id), { done: true }) // changes only done
|
|
912
|
+
store.set(todos.remove, id)
|
|
913
|
+
```
|
|
914
|
+
|
|
915
|
+
##### `typedAtom`
|
|
916
|
+
|
|
917
|
+
```ts
|
|
918
|
+
function typedAtom<Schema extends StandardSchemaV1, const S extends object>(
|
|
919
|
+
locator: Locator<any> | MapPath<any>,
|
|
920
|
+
schema: Schema,
|
|
921
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
922
|
+
options?: AtomOptions,
|
|
923
|
+
): TypedAtom<StandardSchemaV1.InferOutput<Schema>>
|
|
924
|
+
function typedAtom<Schema extends StandardSchemaV1>(
|
|
925
|
+
key: KeyPath,
|
|
926
|
+
schema: Schema,
|
|
927
|
+
options?: AtomOptions,
|
|
928
|
+
): TypedKeyAtom<StandardSchemaV1.InferOutput<Schema>>
|
|
929
|
+
```
|
|
930
|
+
|
|
931
|
+
A typed, writable atom over the `Y.Map` at `locator`, read through `schema` and `shape`: a
|
|
932
|
+
`liveAtom` over `reader(schema, shape)` with a setter. It observes only that node, skips edits
|
|
933
|
+
inside its `'xml'` fields, and re-renders only when the result changes. Like a `liveAtom`, it
|
|
934
|
+
can read stale while nothing is subscribed, except right after its own setter wrote.
|
|
935
|
+
|
|
936
|
+
Setting it reads the node as it is in the doc at write time, not the atom's last value, and
|
|
937
|
+
merges the patch into it: fields the patch leaves out, and keys the schema doesn't know, are
|
|
938
|
+
written back unchanged, so `write` changes only the patched fields and a peer's concurrent
|
|
939
|
+
edit to another field survives. A function patch gets that fresh value as `prev`.
|
|
940
|
+
|
|
941
|
+
Invalid data never throws: the setter returns the schema's result, and `{ issues }` changes
|
|
942
|
+
nothing.
|
|
943
|
+
|
|
944
|
+
While the node has no valid value, the patch is the whole value and a function patch gets
|
|
945
|
+
`undefined` as `prev`. On a missing node a valid value creates the `Y.Map` in its parent; when
|
|
946
|
+
the parent map is missing too, nothing is created and the result holds one issue saying so. On
|
|
947
|
+
an invalid node a valid value replaces what the schema rejected, keeping keys neither the shape
|
|
948
|
+
nor the value names: that is how a node a peer broke is repaired. A shared type of another kind
|
|
949
|
+
where the map belongs reads as issues, and only writing its parent can replace it.
|
|
950
|
+
|
|
951
|
+
A typed, writable atom over one key of a key-value array (y-utility's `YKeyValue`), read
|
|
952
|
+
through `schema`: `select.keyValue(name).key(k)`. It reads the key's current entry (the
|
|
953
|
+
rightmost) as `undefined`, `{ issues }` or `{ value }`, and re-renders only when an entry for
|
|
954
|
+
that key changes its result, not when other keys change or a stale entry is cleaned up. A
|
|
955
|
+
current value the schema rejects reads as `{ issues }`; it does not fall back to an older entry.
|
|
956
|
+
|
|
957
|
+
Setting it validates the whole value, then writes it as `YKeyValue#set` does: pushes
|
|
958
|
+
`{ key, val }` and deletes the key's older entries, so a `YKeyValue` on the same doc reads it.
|
|
959
|
+
A function gets the key's valid value at write time, or `undefined`. `{ issues }` changes
|
|
960
|
+
nothing, and so does a missing array. Values are plain: a `YKeyValue` holds no shared types.
|
|
961
|
+
|
|
962
|
+
```ts
|
|
963
|
+
const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
|
|
964
|
+
const cardAtom = typedAtom(select.map('cards').child('card-1'), Card, { title: 'text' })
|
|
965
|
+
|
|
966
|
+
store.get(cardAtom) // undefined, { issues } or { value }
|
|
967
|
+
store.set(cardAtom, { title: 'Ship it', priority: 'low' }) // creates the card
|
|
968
|
+
store.set(cardAtom, { priority: 'high' }) // changes only priority
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
```ts
|
|
972
|
+
const toneAtom = typedAtom(select.keyValue('master').key('tone'), z.number().min(-1).max(1))
|
|
973
|
+
|
|
974
|
+
store.get(toneAtom) // undefined, { issues } or { value }
|
|
975
|
+
store.set(toneAtom, -0.6)
|
|
976
|
+
store.set(toneAtom, (prev) => Math.min(1, (prev ?? 0) + 0.1))
|
|
977
|
+
```
|
|
978
|
+
|
|
979
|
+
##### `keyValueAtom`
|
|
980
|
+
|
|
981
|
+
```ts
|
|
982
|
+
function keyValueAtom<const S extends Schemas>(
|
|
983
|
+
path: KeyValuePath<any>,
|
|
984
|
+
schemas: S,
|
|
985
|
+
options: AtomOptions = {},
|
|
986
|
+
): KeyValueAtom<S>
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
A typed, writable atom over a whole key-value array (y-utility's `YKeyValue`), with one schema
|
|
990
|
+
per key. Keys `schemas` doesn't name are left out of the read and never written. It re-renders
|
|
991
|
+
only when an entry for one of its keys changes a result; for one key alone, use
|
|
992
|
+
`typedAtom(path.key(k), schema)`, which also ignores the other keys.
|
|
993
|
+
|
|
994
|
+
Setting it validates every key of the patch first: when any is invalid, nothing is written and
|
|
995
|
+
the result holds their issues, each path starting at its key. Otherwise each key is written as
|
|
996
|
+
`YKeyValue#set` does, in one transaction. A missing array changes nothing.
|
|
997
|
+
|
|
998
|
+
```ts
|
|
999
|
+
const master = keyValueAtom(select.keyValue('master'), {
|
|
1000
|
+
tone: z.number().min(-1).max(1),
|
|
1001
|
+
filter: z.object({ x: z.number(), y: z.number() }),
|
|
1002
|
+
})
|
|
1003
|
+
|
|
1004
|
+
store.get(master).tone // undefined, { issues } or { value }
|
|
1005
|
+
store.set(master, { tone: -0.6 })
|
|
1006
|
+
```
|
|
1007
|
+
|
|
1008
|
+
#### Types
|
|
1009
|
+
|
|
1010
|
+
##### `ArrayKind`
|
|
1011
|
+
|
|
1012
|
+
```ts
|
|
1013
|
+
interface ArrayKind {
|
|
1014
|
+
readonly kind: 'array'
|
|
1015
|
+
}
|
|
1016
|
+
```
|
|
1017
|
+
|
|
1018
|
+
An `array()` field: a Shared array of plain values.
|
|
1019
|
+
|
|
1020
|
+
##### `MapKind`
|
|
1021
|
+
|
|
1022
|
+
```ts
|
|
1023
|
+
interface MapKind<S> {
|
|
1024
|
+
readonly kind: 'map'
|
|
1025
|
+
readonly shape: S
|
|
1026
|
+
}
|
|
1027
|
+
```
|
|
1028
|
+
|
|
1029
|
+
A `map(shape)` field: a `Y.Map` with the fixed keys `shape` describes.
|
|
1030
|
+
|
|
1031
|
+
##### `RecordKind`
|
|
1032
|
+
|
|
1033
|
+
```ts
|
|
1034
|
+
interface RecordKind<S> {
|
|
1035
|
+
readonly kind: 'record'
|
|
1036
|
+
readonly shape: S
|
|
1037
|
+
}
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
A `record(itemShape)` field: a `Y.Map` of item `Y.Map`s, each following `itemShape`.
|
|
1041
|
+
|
|
1042
|
+
##### `Shape`
|
|
1043
|
+
|
|
1044
|
+
```ts
|
|
1045
|
+
type Shape<T> = {
|
|
1046
|
+
readonly [K in KeyOf<T>]?: KindOf<FieldOf<T, K>>
|
|
1047
|
+
}
|
|
1048
|
+
```
|
|
1049
|
+
|
|
1050
|
+
Which fields of a node are Shared fields, and of what kind. Every key it doesn't mention is a
|
|
1051
|
+
Plain field. Keys are constrained to the fields of `T`, the schema's output, in any member of a
|
|
1052
|
+
union, and each kind to fields its read value can fill.
|
|
1053
|
+
|
|
1054
|
+
##### `At`
|
|
1055
|
+
|
|
1056
|
+
```ts
|
|
1057
|
+
type At = typeof at
|
|
1058
|
+
```
|
|
1059
|
+
|
|
1060
|
+
The type of `at`, which a `LiveSpec`'s `locate` gets.
|
|
1061
|
+
|
|
1062
|
+
##### `ObserveOptions`
|
|
1063
|
+
|
|
1064
|
+
```ts
|
|
1065
|
+
interface ObserveOptions {
|
|
1066
|
+
/** Use `observeDeep` on the located node, so changes in nested types count. */
|
|
1067
|
+
deep?: boolean
|
|
1068
|
+
/**
|
|
1069
|
+
* Only count Y.Map changes to these keys. In deep mode, changes to the located
|
|
1070
|
+
* node itself (children added or removed) always count.
|
|
1071
|
+
*/
|
|
1072
|
+
keys?: readonly string[]
|
|
1073
|
+
/** Return false to ignore a transaction by its origin. */
|
|
1074
|
+
origin?: (origin: unknown) => boolean
|
|
1075
|
+
/**
|
|
1076
|
+
* Return false to ignore a change by its event. It decides whether a
|
|
1077
|
+
* transaction counts, not what is seen: in deep mode it is called with the
|
|
1078
|
+
* transaction's events under the node until one is accepted, so it may not
|
|
1079
|
+
* see them all. It runs while the observer runs, so `event.changes` and
|
|
1080
|
+
* `event.path` (relative to the located node) can be read.
|
|
1081
|
+
*/
|
|
1082
|
+
event?: (event: Y.YEvent<any>) => boolean
|
|
1083
|
+
}
|
|
1084
|
+
```
|
|
1085
|
+
|
|
1086
|
+
Which changes to the located node count, for `observeLocated`, `live` and every atom.
|
|
1087
|
+
|
|
1088
|
+
##### `Projection`
|
|
1089
|
+
|
|
1090
|
+
```ts
|
|
1091
|
+
interface Projection<T> extends ProjectOptions<T> {
|
|
1092
|
+
project: (node: Y.AbstractType<any> | undefined) => T
|
|
1093
|
+
}
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
A projection packaged with how to observe and compare it, such as
|
|
1097
|
+
`reader(schema, shape)` from `@y-modern/schema`. Hand it to `project`, or
|
|
1098
|
+
spread it into a spec beside `locate`. It takes the node as stored, of any
|
|
1099
|
+
shared type, so it can report one of another kind than its path says, as
|
|
1100
|
+
`reader` does, rather than see it as missing.
|
|
1101
|
+
|
|
1102
|
+
##### `ProjectOptions`
|
|
1103
|
+
|
|
1104
|
+
```ts
|
|
1105
|
+
interface ProjectOptions<T> {
|
|
1106
|
+
/** Default: `deepEqual`, since a custom projection usually builds a fresh value. */
|
|
1107
|
+
equals?: (a: T, b: T) => boolean
|
|
1108
|
+
/** Default: true without `keys`, so a change anywhere under the node counts; false with `keys`. */
|
|
1109
|
+
deep?: boolean
|
|
1110
|
+
keys?: readonly string[]
|
|
1111
|
+
/** Return false to ignore a change by its event, as `ObserveOptions#event` says. */
|
|
1112
|
+
event?: (event: Y.YEvent<any>) => boolean
|
|
1113
|
+
}
|
|
1114
|
+
```
|
|
1115
|
+
|
|
1116
|
+
Options of `project`: how to observe the node and compare projections.
|
|
1117
|
+
|
|
1118
|
+
##### `Selector`
|
|
1119
|
+
|
|
1120
|
+
```ts
|
|
1121
|
+
type Selector<T> = LiveSpec<any, T>
|
|
1122
|
+
```
|
|
1123
|
+
|
|
1124
|
+
A ready `LiveSpec`: path, observed keys, projection and equality in one
|
|
1125
|
+
plain object. Pass it to `live` or a binding's `liveAtom` as it is, or
|
|
1126
|
+
spread it to add an option (`{ ...selector, origin }`).
|
|
1127
|
+
|
|
1128
|
+
##### `AtomOptions`
|
|
1129
|
+
|
|
1130
|
+
```ts
|
|
1131
|
+
interface AtomOptions {
|
|
1132
|
+
/**
|
|
1133
|
+
* The atom holding the doc this atom reads, for apps with several docs. Defaults to
|
|
1134
|
+
* `docAtom`.
|
|
1135
|
+
*
|
|
1136
|
+
* @example
|
|
1137
|
+
* const boardDocAtom = atom<Y.Doc | null>(null)
|
|
1138
|
+
* const title = liveAtom(select.map('meta').get('title', ''), { docAtom: boardDocAtom })
|
|
1139
|
+
*/
|
|
1140
|
+
docAtom?: Atom<Y.Doc | null | undefined>
|
|
1141
|
+
}
|
|
1142
|
+
```
|
|
1143
|
+
|
|
1144
|
+
Options every duratom atom takes.
|
|
1145
|
+
|
|
1146
|
+
##### `LiveSpec`
|
|
1147
|
+
|
|
1148
|
+
```ts
|
|
1149
|
+
interface LiveSpec<N extends Y.AbstractType<any>, T> extends ObserveOptions {
|
|
1150
|
+
locate: (at: At) => Locator<N>
|
|
1151
|
+
/** Plain snapshot. `undefined` when the located node does not exist. */
|
|
1152
|
+
project: (node: N | undefined) => T
|
|
1153
|
+
/** Whether two projections are the same; an equal result keeps the old reference and does not notify. Default: shallow. */
|
|
1154
|
+
equals?: (a: T, b: T) => boolean
|
|
1155
|
+
}
|
|
1156
|
+
```
|
|
1157
|
+
|
|
1158
|
+
What `live` and `liveAtom` read: where the node is, how to turn it into a value, and when the
|
|
1159
|
+
value counts as changed. `select` builds one; write your own for anything it can't express.
|
|
1160
|
+
|
|
1161
|
+
##### `Collection`
|
|
1162
|
+
|
|
1163
|
+
```ts
|
|
1164
|
+
interface Collection<T> {
|
|
1165
|
+
/**
|
|
1166
|
+
* The ids of every entry of the map, sorted so every peer sees the same order; `[]` while the
|
|
1167
|
+
* map is missing. Notifies only when an id is added or removed, never when an item's fields
|
|
1168
|
+
* change.
|
|
1169
|
+
*/
|
|
1170
|
+
readonly ids: Atom<string[]>
|
|
1171
|
+
/**
|
|
1172
|
+
* The typed atom of the item under `id`, the same atom for the same id: it reads `undefined`,
|
|
1173
|
+
* `{ issues }` or `{ value }` and merges a patch when set, as `typedAtom` does; setting a
|
|
1174
|
+
* missing item creates it. The collection's `remove` drops the item's atom from the family, and
|
|
1175
|
+
* `item.remove(id)` or `item.setShouldRemove` can drop others; an atom a caller still holds keeps
|
|
1176
|
+
* working after it's dropped.
|
|
1177
|
+
*/
|
|
1178
|
+
readonly item: AtomFamily<string, TypedAtom<T>>
|
|
1179
|
+
/**
|
|
1180
|
+
* Validates a whole value and adds it as a new item under `id`, or under a random UUID when no
|
|
1181
|
+
* id is given. Returns the schema's result with the id. An invalid value, an id already in use,
|
|
1182
|
+
* or a missing map adds nothing and returns `{ issues }`: the value's own issues when it has
|
|
1183
|
+
* any, else one saying why it couldn't be added.
|
|
1184
|
+
*/
|
|
1185
|
+
readonly create: WritableAtom<null, [value: T, id?: string], CreateResult<T>>
|
|
1186
|
+
/** Removes the item under `id`. Returns whether there was one. */
|
|
1187
|
+
readonly remove: WritableAtom<null, [id: string], boolean>
|
|
1188
|
+
}
|
|
1189
|
+
```
|
|
1190
|
+
|
|
1191
|
+
Atoms over a `Y.Map` of items, each item a `Y.Map` read through one schema. Write with
|
|
1192
|
+
`store.set` or `useSetAtom`, like any Jotai atom.
|
|
1193
|
+
|
|
1194
|
+
##### `CreateResult`
|
|
1195
|
+
|
|
1196
|
+
```ts
|
|
1197
|
+
type CreateResult<T> =
|
|
1198
|
+
| (StandardSchemaV1.SuccessResult<T> & { readonly id: string })
|
|
1199
|
+
| StandardSchemaV1.FailureResult
|
|
1200
|
+
```
|
|
1201
|
+
|
|
1202
|
+
What a collection's `create` returns: the schema's result, with the new item's id when valid.
|
|
1203
|
+
|
|
1204
|
+
##### `KeyUpdate`
|
|
1205
|
+
|
|
1206
|
+
```ts
|
|
1207
|
+
type KeyUpdate<T> = T | ((prev: T | undefined) => T)
|
|
1208
|
+
```
|
|
1209
|
+
|
|
1210
|
+
What a key atom's setter takes: the whole new value, or a function of the key's value as it is
|
|
1211
|
+
in the doc at write time (`undefined` while it has no valid value) returning one.
|
|
1212
|
+
|
|
1213
|
+
##### `Patch`
|
|
1214
|
+
|
|
1215
|
+
```ts
|
|
1216
|
+
type Patch<T> = Partial<T> | ((prev: T | undefined) => Partial<T>)
|
|
1217
|
+
```
|
|
1218
|
+
|
|
1219
|
+
What a typed atom's setter takes: a patch of the fields to change, or a function of the node's
|
|
1220
|
+
value as it is in the doc at write time (`undefined` while it has no valid value) returning one.
|
|
1221
|
+
|
|
1222
|
+
##### `TypedAtom`
|
|
1223
|
+
|
|
1224
|
+
```ts
|
|
1225
|
+
type TypedAtom<T> = WritableAtom<
|
|
1226
|
+
StandardSchemaV1.Result<T> | undefined,
|
|
1227
|
+
[patch: Patch<T>],
|
|
1228
|
+
StandardSchemaV1.Result<T>
|
|
1229
|
+
>
|
|
1230
|
+
```
|
|
1231
|
+
|
|
1232
|
+
A Jotai atom over one `Y.Map` of the doc, read through a schema. It reads as `undefined` while
|
|
1233
|
+
the node is missing, `{ issues }` while it doesn't satisfy the schema, and `{ value }`
|
|
1234
|
+
otherwise. Setting it merges a patch and returns the schema's result.
|
|
1235
|
+
|
|
1236
|
+
##### `TypedKeyAtom`
|
|
1237
|
+
|
|
1238
|
+
```ts
|
|
1239
|
+
type TypedKeyAtom<T> = WritableAtom<
|
|
1240
|
+
StandardSchemaV1.Result<T> | undefined,
|
|
1241
|
+
[update: KeyUpdate<T>],
|
|
1242
|
+
StandardSchemaV1.Result<T>
|
|
1243
|
+
>
|
|
1244
|
+
```
|
|
1245
|
+
|
|
1246
|
+
A Jotai atom over one key of a key-value array (y-utility's `YKeyValue`), read through a schema.
|
|
1247
|
+
It reads as `undefined` while the key has no entry, `{ issues }` while its current value doesn't
|
|
1248
|
+
satisfy the schema, and `{ value }` otherwise. Setting it validates and writes the whole value,
|
|
1249
|
+
and returns the schema's result.
|
|
1250
|
+
|
|
1251
|
+
##### `KeyValueAtom`
|
|
1252
|
+
|
|
1253
|
+
```ts
|
|
1254
|
+
type KeyValueAtom<S extends Schemas> = WritableAtom<
|
|
1255
|
+
{ [K in keyof S]: StandardSchemaV1.Result<Values<S>[K]> | undefined },
|
|
1256
|
+
[patch: Partial<Values<S>> | ((prev: Partial<Values<S>>) => Partial<Values<S>>)],
|
|
1257
|
+
StandardSchemaV1.Result<Partial<Values<S>>>
|
|
1258
|
+
>
|
|
1259
|
+
```
|
|
1260
|
+
|
|
1261
|
+
A Jotai atom over the keys of a key-value array that `schemas` names, each read through its
|
|
1262
|
+
own schema. It reads as an object with one result per key: `undefined` while the key has no
|
|
1263
|
+
entry, `{ issues }` while its value is invalid, `{ value }` otherwise. Setting it takes a patch
|
|
1264
|
+
of the keys to change, or a function of their valid values returning one.
|
|
1265
|
+
|
|
1266
|
+
### `duratom/react`
|
|
1267
|
+
|
|
1268
|
+
#### Functions and values
|
|
1269
|
+
|
|
1270
|
+
##### `useLiveAtom`
|
|
1271
|
+
|
|
1272
|
+
```ts
|
|
1273
|
+
function useLiveAtom<N extends Y.AbstractType<any>, T>(
|
|
1274
|
+
spec: LiveSpec<N, T> | (() => LiveSpec<N, T>),
|
|
1275
|
+
deps: DependencyList,
|
|
1276
|
+
options?: AtomOptions,
|
|
1277
|
+
): T
|
|
1278
|
+
function useLiveAtom<N extends Y.AbstractType<any>, T>(
|
|
1279
|
+
locate: LiveSpec<N, T>['locate'],
|
|
1280
|
+
project: LiveSpec<N, T>['project'],
|
|
1281
|
+
options?: SpecOptions<N, T>,
|
|
1282
|
+
deps?: DependencyList,
|
|
1283
|
+
): T
|
|
1284
|
+
```
|
|
1285
|
+
|
|
1286
|
+
Hook form of `liveAtom`, taking a whole spec, such as a selector from `select`, or a function
|
|
1287
|
+
that builds it: `useLiveAtom(() => select..., [id])` builds it only when `deps` change, rather
|
|
1288
|
+
than on every render. The atom is rebuilt only when `deps` change, so list whatever the spec
|
|
1289
|
+
closes over (an id, say), as with useMemo. `deps` is required: a spec built inline from props
|
|
1290
|
+
would otherwise keep its first value. `options.docAtom` reads another doc than `docAtom`.
|
|
1291
|
+
|
|
1292
|
+
Hook form of `liveAtom`. The atom is rebuilt only when `deps` change, so list whatever
|
|
1293
|
+
`locate` and `project` close over (an id, say), as with useMemo. `options.docAtom` reads
|
|
1294
|
+
another doc than `docAtom`.
|
|
1295
|
+
|
|
1296
|
+
```ts
|
|
1297
|
+
const title = useLiveAtom(() => select.map('cards').child(id).get('title', ''), [id])
|
|
1298
|
+
```
|
|
1299
|
+
|
|
1300
|
+
```ts
|
|
1301
|
+
const title = useLiveAtom(
|
|
1302
|
+
(at) => at.map('cards').child(id),
|
|
1303
|
+
(card: Y.Map<unknown> | undefined) => String(card?.get('title') ?? ''),
|
|
1304
|
+
{ keys: ['title'] },
|
|
1305
|
+
[id],
|
|
1306
|
+
)
|
|
1307
|
+
```
|
|
1308
|
+
|
|
1309
|
+
##### `useTypedAtom`
|
|
1310
|
+
|
|
1311
|
+
```ts
|
|
1312
|
+
function useTypedAtom<Schema extends StandardSchemaV1, const S extends object>(
|
|
1313
|
+
locator: Locator<any> | MapPath<any> | (() => Locator<any> | MapPath<any>),
|
|
1314
|
+
schema: Schema,
|
|
1315
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
1316
|
+
deps: DependencyList,
|
|
1317
|
+
options?: AtomOptions,
|
|
1318
|
+
): [
|
|
1319
|
+
result: StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined,
|
|
1320
|
+
set: (
|
|
1321
|
+
patch: Patch<StandardSchemaV1.InferOutput<Schema>>,
|
|
1322
|
+
) => StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>,
|
|
1323
|
+
]
|
|
1324
|
+
```
|
|
1325
|
+
|
|
1326
|
+
Hook form of `typedAtom`, returning `[result, set]` as `useAtom` does: `result` is `undefined`
|
|
1327
|
+
while the node is missing, `{ issues }` while it's invalid and `{ value }` otherwise, and
|
|
1328
|
+
`set(patch)` merges a patch and returns the schema's result. `locator` can be a function that
|
|
1329
|
+
builds it, so it's built only when `deps` change. The atom is rebuilt only when `deps` change,
|
|
1330
|
+
so list whatever the locator closes over (an id, say), as with useMemo; `schema` and `shape`
|
|
1331
|
+
are taken from the render that built it. `options.docAtom` reads another doc than `docAtom`.
|
|
1332
|
+
|
|
1333
|
+
```ts
|
|
1334
|
+
const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
|
|
1335
|
+
const [card, setCard] = useTypedAtom(() => select.map('cards').child(id), Card, { title: 'text' }, [id])
|
|
1336
|
+
if (card && !card.issues) setCard({ priority: 'high' })
|
|
1337
|
+
```
|
|
1338
|
+
|
|
1339
|
+
### `duratom/core`
|
|
1340
|
+
|
|
1341
|
+
Also exports `deepEqual`, `shallowEqual`, `LiveSpec`, `at`, `Locator`, `At`, `ObserveOptions`, `ArrayPath`, `KeyPath`, `KeyValuePath`, `MapPath`, `select`, `Projection`, `ProjectOptions`, `Selector`, documented under `duratom`.
|
|
1342
|
+
|
|
1343
|
+
#### Functions and values
|
|
1344
|
+
|
|
1345
|
+
##### `live`
|
|
1346
|
+
|
|
1347
|
+
```ts
|
|
1348
|
+
function live<N extends Y.AbstractType<any>, T>(
|
|
1349
|
+
doc: Y.Doc,
|
|
1350
|
+
spec: LiveSpec<N, T>,
|
|
1351
|
+
): Live<T, N>
|
|
1352
|
+
```
|
|
1353
|
+
|
|
1354
|
+
A live projection of one node of `doc`. While anything is subscribed it
|
|
1355
|
+
observes only the located node (see `observeLocated`), re-runs `project` on
|
|
1356
|
+
matching transactions and notifies only when `equals` says the result
|
|
1357
|
+
changed. With no subscribers nothing is observed and `get` projects the
|
|
1358
|
+
current doc on each call.
|
|
1359
|
+
|
|
1360
|
+
A change skipped by the `origin` filter is not remembered while subscribed:
|
|
1361
|
+
the value catches up at the next accepted change. With no subscribers there
|
|
1362
|
+
is nothing to filter, so `get` shows every change made so far.
|
|
1363
|
+
|
|
1364
|
+
```ts
|
|
1365
|
+
const title = live(doc, select.map('cards').child('card-1').get('title', ''))
|
|
1366
|
+
const stop = title.subscribe((value, prev) => console.log(prev, '->', value))
|
|
1367
|
+
title.get() // the title now
|
|
1368
|
+
stop()
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
##### `observeLocated`
|
|
1372
|
+
|
|
1373
|
+
```ts
|
|
1374
|
+
function observeLocated(
|
|
1375
|
+
doc: Y.Doc,
|
|
1376
|
+
locator: Locator,
|
|
1377
|
+
options: ObserveOptions,
|
|
1378
|
+
onChange: () => void,
|
|
1379
|
+
): () => void
|
|
1380
|
+
```
|
|
1381
|
+
|
|
1382
|
+
Calls `onChange` after a transaction that may have changed what the locator
|
|
1383
|
+
points at. Watches the located node (and nothing else in the doc) plus, for
|
|
1384
|
+
each step of the path, that one key of the parent map. Returns an unsubscribe.
|
|
1385
|
+
|
|
1386
|
+
```ts
|
|
1387
|
+
const stop = observeLocated(doc, at.map('cards').child('card-1'), { deep: true }, () =>
|
|
1388
|
+
console.log('card-1 changed, or was created or deleted'),
|
|
1389
|
+
)
|
|
1390
|
+
stop()
|
|
1391
|
+
```
|
|
1392
|
+
|
|
1393
|
+
##### `AsyncValidationUnsupportedError`
|
|
1394
|
+
|
|
1395
|
+
```ts
|
|
1396
|
+
class AsyncValidationUnsupportedError
|
|
1397
|
+
```
|
|
1398
|
+
|
|
1399
|
+
Thrown by `read` and `write` when the schema's `~standard.validate` returns a Promise. The layer
|
|
1400
|
+
validates synchronously only, so an async schema is a configuration error, not bad data.
|
|
1401
|
+
|
|
1402
|
+
```ts
|
|
1403
|
+
const Slow = z.object({ title: z.string() }).refine(async () => true)
|
|
1404
|
+
try {
|
|
1405
|
+
store.set(typedAtom(select.map('cards').child('c1'), Slow, {}), { title: 'Hi' })
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
if (error instanceof AsyncValidationUnsupportedError) console.error(error.vendor) // 'zod'
|
|
1408
|
+
}
|
|
1409
|
+
```
|
|
1410
|
+
|
|
1411
|
+
- `constructor(vendor: string)`
|
|
1412
|
+
- `readonly vendor: string`
|
|
1413
|
+
- `name: string`
|
|
1414
|
+
- `message: string`
|
|
1415
|
+
- `stack?: string`
|
|
1416
|
+
- `cause?: unknown`
|
|
1417
|
+
|
|
1418
|
+
##### `create`
|
|
1419
|
+
|
|
1420
|
+
```ts
|
|
1421
|
+
function create<Schema extends StandardSchemaV1, const S extends object>(
|
|
1422
|
+
schema: Schema,
|
|
1423
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
1424
|
+
parent: Y.Map<unknown>,
|
|
1425
|
+
key: string,
|
|
1426
|
+
value: StandardSchemaV1.InferOutput<Schema>,
|
|
1427
|
+
): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>
|
|
1428
|
+
```
|
|
1429
|
+
|
|
1430
|
+
Validates `value` with `schema` and, if it's valid, stores it as a new `Y.Map` under `key` of
|
|
1431
|
+
`parent`, replacing whatever was stored there. Returns the schema's own result; an invalid
|
|
1432
|
+
value creates nothing, and a value the shape can't store throws before anything is created.
|
|
1433
|
+
|
|
1434
|
+
```ts
|
|
1435
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
1436
|
+
create(Todo, { title: 'text' }, doc.getMap('todos'), 'todo-1', { title: 'Buy milk', done: false })
|
|
1437
|
+
```
|
|
1438
|
+
|
|
1439
|
+
##### `keyReader`
|
|
1440
|
+
|
|
1441
|
+
```ts
|
|
1442
|
+
function keyReader<Schema extends StandardSchemaV1>(
|
|
1443
|
+
schema: Schema,
|
|
1444
|
+
key: string,
|
|
1445
|
+
): KeyReader<StandardSchemaV1.InferOutput<Schema>>
|
|
1446
|
+
```
|
|
1447
|
+
|
|
1448
|
+
`readKey(schema, node, key)` packaged as a projection for `select.keyValue(name).project(...)`:
|
|
1449
|
+
it counts only changes that add or delete an entry for `key`, and compares results deeply.
|
|
1450
|
+
`typedAtom(path.key(k), schema)` reads through it.
|
|
1451
|
+
|
|
1452
|
+
```ts
|
|
1453
|
+
const tone = live(doc, select.keyValue('master').project(keyReader(z.number(), 'tone')))
|
|
1454
|
+
tone.subscribe((result) => console.log(result?.issues ?? result?.value))
|
|
1455
|
+
```
|
|
1456
|
+
|
|
1457
|
+
##### `read`
|
|
1458
|
+
|
|
1459
|
+
```ts
|
|
1460
|
+
function read<Schema extends StandardSchemaV1, const S extends object>(
|
|
1461
|
+
schema: Schema,
|
|
1462
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
1463
|
+
node: Y.AbstractType<any> | undefined,
|
|
1464
|
+
): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined
|
|
1465
|
+
```
|
|
1466
|
+
|
|
1467
|
+
Projects a located `Y.Map` following `shape` and validates it with `schema`, returning the
|
|
1468
|
+
schema's own result. An absent node returns `undefined` without validating, and a node with a
|
|
1469
|
+
shape mismatch, or a shared type that isn't a `Y.Map`, returns the layer's own issues without
|
|
1470
|
+
validating.
|
|
1471
|
+
|
|
1472
|
+
```ts
|
|
1473
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
1474
|
+
const result = read(Todo, { title: 'text' }, doc.getMap('todos').get(id) as Y.Map<unknown>)
|
|
1475
|
+
if (result?.issues) console.warn(result.issues)
|
|
1476
|
+
else if (result) console.log(result.value.title)
|
|
1477
|
+
```
|
|
1478
|
+
|
|
1479
|
+
##### `reader`
|
|
1480
|
+
|
|
1481
|
+
```ts
|
|
1482
|
+
function reader<Schema extends StandardSchemaV1, const S extends object>(
|
|
1483
|
+
schema: Schema,
|
|
1484
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
1485
|
+
): Reader<StandardSchemaV1.InferOutput<Schema>>
|
|
1486
|
+
```
|
|
1487
|
+
|
|
1488
|
+
`read(schema, shape, node)` as a `Reader`, for `select...project(reader(schema, shape))`.
|
|
1489
|
+
`typedAtom` reads through it; use it for a read-only typed value outside Jotai.
|
|
1490
|
+
|
|
1491
|
+
```ts
|
|
1492
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
1493
|
+
const todo = live(doc, select.map('todos').child(id).project(reader(Todo, { title: 'text' })))
|
|
1494
|
+
todo.subscribe((result) => console.log(result?.issues ?? result?.value))
|
|
1495
|
+
```
|
|
1496
|
+
|
|
1497
|
+
##### `readKey`
|
|
1498
|
+
|
|
1499
|
+
```ts
|
|
1500
|
+
function readKey<Schema extends StandardSchemaV1>(
|
|
1501
|
+
schema: Schema,
|
|
1502
|
+
array: Y.AbstractType<any> | undefined,
|
|
1503
|
+
key: string,
|
|
1504
|
+
): Result<Schema> | undefined
|
|
1505
|
+
```
|
|
1506
|
+
|
|
1507
|
+
Reads the current value of `key` in a key-value array (y-utility's `YKeyValue`: the rightmost
|
|
1508
|
+
`{ key, val }` entry per key wins) and validates it with `schema`, returning the schema's own
|
|
1509
|
+
result. A missing array or a key with no entry returns `undefined` without validating. A value
|
|
1510
|
+
holding a shared type returns the layer's own issue without validating, since a `YKeyValue`
|
|
1511
|
+
holds plain values only.
|
|
1512
|
+
|
|
1513
|
+
A current value the schema rejects reads as `{ issues }`, like an invalid map field: it does not
|
|
1514
|
+
fall back to an older entry, which a `YKeyValue` deletes anyway. Writing a valid value repairs it.
|
|
1515
|
+
|
|
1516
|
+
```ts
|
|
1517
|
+
const result = readKey(z.number(), doc.getArray('master'), 'tone')
|
|
1518
|
+
if (result && !result.issues) console.log(result.value)
|
|
1519
|
+
```
|
|
1520
|
+
|
|
1521
|
+
##### `UnsupportedValueError`
|
|
1522
|
+
|
|
1523
|
+
```ts
|
|
1524
|
+
class UnsupportedValueError
|
|
1525
|
+
```
|
|
1526
|
+
|
|
1527
|
+
Thrown by `write` when a plain field or `array()` item holds a value Yjs can't store faithfully: anything but
|
|
1528
|
+
JSON values, `undefined` and `Uint8Array` bytes, a cycle, a `__proto__` key, or a `constructor`
|
|
1529
|
+
key on the field's own object. The schema accepted it, so it's a schema that's too loose, not bad
|
|
1530
|
+
data. Nothing is written.
|
|
1531
|
+
|
|
1532
|
+
```ts
|
|
1533
|
+
const Event = z.object({ at: z.date() }) // a Date syncs as {}, so it can't be stored
|
|
1534
|
+
try {
|
|
1535
|
+
store.set(typedAtom(select.map('events').child('e1'), Event, {}), { at: new Date() })
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
if (error instanceof UnsupportedValueError) console.error(error.path) // ['at']
|
|
1538
|
+
}
|
|
1539
|
+
```
|
|
1540
|
+
|
|
1541
|
+
- `constructor(path: readonly PropertyKey[])`
|
|
1542
|
+
- `readonly path: readonly PropertyKey[]`
|
|
1543
|
+
|
|
1544
|
+
Where the value sits in the written value, starting at the field's key.
|
|
1545
|
+
|
|
1546
|
+
- `name: string`
|
|
1547
|
+
- `message: string`
|
|
1548
|
+
- `stack?: string`
|
|
1549
|
+
- `cause?: unknown`
|
|
1550
|
+
|
|
1551
|
+
##### `write`
|
|
1552
|
+
|
|
1553
|
+
```ts
|
|
1554
|
+
function write<Schema extends StandardSchemaV1, const S extends object>(
|
|
1555
|
+
schema: Schema,
|
|
1556
|
+
shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
|
|
1557
|
+
node: Y.Map<unknown>,
|
|
1558
|
+
value: StandardSchemaV1.InferOutput<Schema>,
|
|
1559
|
+
): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>
|
|
1560
|
+
```
|
|
1561
|
+
|
|
1562
|
+
Validates `value` with `schema` and, if it's valid, merges it into the located `Y.Map` so only
|
|
1563
|
+
the differences change. Returns the schema's own result; an invalid value changes nothing.
|
|
1564
|
+
Fields the value lacks are deleted, so pass the whole value; a typed atom merges a patch first.
|
|
1565
|
+
|
|
1566
|
+
```ts
|
|
1567
|
+
const Todo = z.object({ title: z.string(), done: z.boolean() })
|
|
1568
|
+
const node = doc.getMap('todos').get(id) as Y.Map<unknown>
|
|
1569
|
+
const result = write(Todo, { title: 'text' }, node, { title: 'Ship it', done: true })
|
|
1570
|
+
if (result.issues) console.warn(result.issues) // the doc is unchanged
|
|
1571
|
+
```
|
|
1572
|
+
|
|
1573
|
+
##### `writeKey`
|
|
1574
|
+
|
|
1575
|
+
```ts
|
|
1576
|
+
function writeKey<Schema extends StandardSchemaV1>(
|
|
1577
|
+
schema: Schema,
|
|
1578
|
+
array: Y.Array<any>,
|
|
1579
|
+
key: string,
|
|
1580
|
+
value: StandardSchemaV1.InferOutput<Schema>,
|
|
1581
|
+
): Result<Schema>
|
|
1582
|
+
```
|
|
1583
|
+
|
|
1584
|
+
Validates `value` with `schema` and, if it's valid, sets `key` of the key-value array as
|
|
1585
|
+
`YKeyValue#set` does: pushes `{ key, val }` to its end and deletes every older entry for `key`,
|
|
1586
|
+
in one transaction. Returns the schema's own result; an invalid value changes nothing, and so
|
|
1587
|
+
does a value equal to the current one. Throws `UnsupportedValueError` for a value Yjs can't store
|
|
1588
|
+
as written, since the schema accepted it.
|
|
1589
|
+
|
|
1590
|
+
```ts
|
|
1591
|
+
const result = writeKey(z.number().min(-1).max(1), doc.getArray('master'), 'tone', -0.6)
|
|
1592
|
+
if (result.issues) console.warn(result.issues) // the doc is unchanged
|
|
1593
|
+
```
|
|
1594
|
+
|
|
1595
|
+
#### Types
|
|
1596
|
+
|
|
1597
|
+
##### `Live`
|
|
1598
|
+
|
|
1599
|
+
```ts
|
|
1600
|
+
interface Live<T, N extends Y.AbstractType<any> = Y.AbstractType<any>> {
|
|
1601
|
+
/** The current projection. Keeps the same reference until `equals` says it changed. */
|
|
1602
|
+
get(): T
|
|
1603
|
+
/**
|
|
1604
|
+
* Calls `listener(value, prev)` after a change, with the new and the previous
|
|
1605
|
+
* projection. The first subscriber starts observing, the last one to leave stops.
|
|
1606
|
+
*/
|
|
1607
|
+
subscribe(listener: (value: T, prev: T) => void): () => void
|
|
1608
|
+
/** The located node as it is now, `undefined` when it does not exist. */
|
|
1609
|
+
resolve(): N | undefined
|
|
1610
|
+
/**
|
|
1611
|
+
* Runs `fn` in one transaction of the doc with the located node as it is
|
|
1612
|
+
* now, `undefined` when it does not exist, and returns what `fn` returns.
|
|
1613
|
+
* The change comes back through `subscribe` like any other, so a write whose
|
|
1614
|
+
* origin the `origin` filter rejects leaves `get()` behind the doc until the
|
|
1615
|
+
* next accepted change.
|
|
1616
|
+
*/
|
|
1617
|
+
write<R>(fn: (node: N | undefined, doc: Y.Doc) => R, origin?: unknown): R
|
|
1618
|
+
}
|
|
1619
|
+
```
|
|
1620
|
+
|
|
1621
|
+
A read-only value over one node of a doc, in the shape `useSyncExternalStore` takes.
|
|
1622
|
+
|
|
1623
|
+
##### `KeyReader`
|
|
1624
|
+
|
|
1625
|
+
```ts
|
|
1626
|
+
interface KeyReader<T> {
|
|
1627
|
+
project: (node: Y.AbstractType<any> | undefined) => StandardSchemaV1.Result<T> | undefined
|
|
1628
|
+
deep: false
|
|
1629
|
+
event: (event: Y.YEvent<any>) => boolean
|
|
1630
|
+
equals: (
|
|
1631
|
+
a: StandardSchemaV1.Result<T> | undefined,
|
|
1632
|
+
b: StandardSchemaV1.Result<T> | undefined,
|
|
1633
|
+
) => boolean
|
|
1634
|
+
}
|
|
1635
|
+
```
|
|
1636
|
+
|
|
1637
|
+
What `keyReader` returns: a projection of one key's validated value, with its event filter.
|
|
1638
|
+
|
|
1639
|
+
##### `Reader`
|
|
1640
|
+
|
|
1641
|
+
```ts
|
|
1642
|
+
interface Reader<T> {
|
|
1643
|
+
project: (node: Y.AbstractType<any> | undefined) => StandardSchemaV1.Result<T> | undefined
|
|
1644
|
+
deep: true
|
|
1645
|
+
event: (event: Y.YEvent<any>) => boolean
|
|
1646
|
+
equals: (
|
|
1647
|
+
a: StandardSchemaV1.Result<T> | undefined,
|
|
1648
|
+
b: StandardSchemaV1.Result<T> | undefined,
|
|
1649
|
+
) => boolean
|
|
1650
|
+
}
|
|
1651
|
+
```
|
|
1652
|
+
|
|
1653
|
+
`read` packaged as a store binding's projection: `project` reads a located node through
|
|
1654
|
+
`schema` and `shape`, `deep` observes every change under it, `event` skips edits inside an
|
|
1655
|
+
`'xml'` field, which a read returns as the fragment itself, and `equals` compares two results
|
|
1656
|
+
deeply, since each read returns a fresh tree. It has the shape `project` of a
|
|
1657
|
+
`select` selector and a `liveAtom` spec take, so the schema layer and the observation core
|
|
1658
|
+
stay independent of each other.
|