Learn / Events, folds and gates

Fold Messages into state

Start with a standard Foldkit application tracking todos and a local filter:

ts
import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import type * as Update from 'foldkit/update'
import { MessageSet, Projection, Surface } from 'foldkit-surface'
import { DocumentId, forApplication } from 'foldkit-sync'

const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, done: Schema.Boolean })
const Model = Schema.Struct({
  todos: Schema.Array(Todo),
  filter: Schema.Literals(['all', 'done']),
})
type Model = typeof Model.Type

const Message = defineMessageUnion({
  CreatedTodo: { id: Schema.String, title: Schema.String },
  CompletedTodo: { id: Schema.String },
  ClearedTodos: { ids: Schema.Array(Schema.String) },
  ChoseFilter: { filter: Schema.Literals(['all', 'done']) },
})
type Message = typeof Message.Type

const initial: Model = { todos: [], filter: 'all' }

type Return = Update.Return<Model, Message>

const update = (model: Model, message: Message): Return =>
  Message.match<Return>(message, {
    CreatedTodo: ({ id, title }) => ({
      model: modifyFields(model, { todos: () => [...model.todos, { id, title, done: false }] }),
    }),
    CompletedTodo: ({ id }) => ({
      model: modifyFields(model, {
        todos: () => model.todos.map(todo => (todo.id === id ? { ...todo, done: true } : todo)),
      }),
    }),
    ClearedTodos: ({ ids }) => ({
      model: modifyFields(model, {
        todos: () => model.todos.filter(todo => !ids.includes(todo.id)),
      }),
    }),
    ChoseFilter: ({ filter }) => ({ model: modifyFields(model, { filter: () => filter }) }),
  })

const App = Surface.application({ Model, Message, initial, update })

Folding a sequence of Messages through update gives the Model directly:

ts
const history: ReadonlyArray<Message> = [
  Message.CreatedTodo({ id: 'a', title: 'Write the guide' }),
  Message.CreatedTodo({ id: 'b', title: 'Review it' }),
  Message.CompletedTodo({ id: 'a' }),
]

const folded = history.reduce((model, message) => update(model, message).model, initial)
console.log(folded)

Running that fold prints:

{
  todos: [
    { id: 'a', title: 'Write the guide', done: true },
    { id: 'b', title: 'Review it', done: false }
  ],
  filter: 'all'
}

Todo a (done) is never stored as a separate record locally; it is the result of folding those three Messages. In a plain local app, the Foldkit runtime runs each Message through update and discards the Message immediately.