Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
48 lines (45 loc) · 1.91 KB
/
Copy pathapp.ts
File metadata and controls
48 lines (45 loc) · 1.91 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
import { Option, Schema } from 'effect'
import { modifyFields } from 'foldkit/struct'
import { defineMessageUnion } from 'foldkit/message'
import type * as Update from 'foldkit/update'
const Todo = Schema.Struct({ id: Schema.String, title: Schema.String })
export const Shared = Schema.Struct({ todos: Schema.Array(Todo) })
export type Shared = typeof Shared.Type
export const Model = Schema.Struct({
...Shared.fields,
// Local to this tab and never stored: only the shared slice is persisted.
selectedTodoId: Schema.Option(Schema.String),
lastError: Schema.Option(Schema.String),
})
export type Model = typeof Model.Type
export const Message = defineMessageUnion({
CreatedTodo: { id: Schema.String, title: Schema.String },
RenamedTodo: { id: Schema.String, title: Schema.String },
DeletedTodo: { id: Schema.String },
SelectedTodo: { id: Schema.String },
})
export type Message = typeof Message.Type
export const initialModel: Model = {
todos: [],
selectedTodoId: Option.none(),
lastError: Option.none(),
}
// IDs and all other nondeterministic inputs come from the Message.
export const update = (model: Model, message: Message): Update.Return<Model, Message> => ({
model: Message.match(message, {
CreatedTodo: ({ id, title }) =>
modifyFields(model, {
todos: () =>
model.todos.some(todo => todo.id === id) ? model.todos : [...model.todos, { id, title }],
}),
RenamedTodo: ({ id, title }) =>
modifyFields(model, {
todos: () => model.todos.map(todo => (todo.id === id ? { ...todo, title } : todo)),
}),
DeletedTodo: ({ id }) =>
modifyFields(model, { todos: () => model.todos.filter(todo => todo.id !== id) }),
SelectedTodo: ({ id }) => modifyFields(model, { selectedTodoId: () => Option.some(id) }),
}),
})
export const decodeMessage = Schema.decodeUnknownSync(Message, { onExcessProperty: 'error' })
export const encodeMessage = Schema.encodeSync(Message)