Repository navigation
Expand file tree
/
Copy pathsync.ts
More file actions
60 lines (55 loc) · 2.06 KB
/
Copy pathsync.ts
File metadata and controls
60 lines (55 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import type { Document, HtmlBuilder } from 'foldkit/html'
import { MessageSet, Projection, Surface } from 'foldkit-surface'
import {
DocumentId,
forApplication,
mount,
type Mounted,
type Replica,
type ReplicaError,
type Sync as SyncContract,
} from 'foldkit-sync'
import { Message, Model, initialModel, update, type Shared } from './app.js'
const App = Surface.application({ Model, Message, initial: initialModel, update })
const Todos = Projection.pick(App.model.todos)
const TodoChanges = MessageSet.make(App, [
Message.CreatedTodo,
Message.RenamedTodo,
Message.DeletedTodo,
])
/**
* The replicated-state contract for the todo document: `forApplication`
* derives the shared projection, the durable subset, the initial snapshot, and
* replay from one application declaration.
*/
const definition = forApplication(App).make({
documentId: DocumentId.make('todos'),
shared: Todos,
durable: TodoChanges,
// Renames the server has not seen yet go as one: the last title wins either way.
coalesce: (last, next) => {
if (last._tag !== 'RenamedTodo' || next._tag !== 'RenamedTodo' || last.id !== next.id)
return undefined
return next
},
})
/**
* The same value, seen through the low-level `Sync` type: this example emits
* declarations, and the inferred type expands a Foldkit-private alias that
* declaration emit cannot name.
*/
export const TodoSync: SyncContract<Message, Shared> = definition
/**
* Runs the application over a replica with `mount`: one reducer, durable
* Messages applied at once and persisted after, the shared slice re-installed
* when an exchange or a failure changes it. Named here so the example can emit
* declarations without naming the contract's inferred type.
*/
export const mountTodos = (
replica: Replica<Message, Shared>,
options: {
readonly container: HTMLElement
readonly view: (model: Model, h: HtmlBuilder<Message>) => Document
readonly onPersistenceFailure?: (model: Model, error: ReplicaError) => Model
},
): Mounted<Model, Message, Shared> => mount(App, definition, { replica, ...options })