Surface / foldkit-surface

Projections

A Projection<Root, Value> pairs a Model codec for Value with a pure read(root) => Value, its dependencies (Model paths), and opaque metadata attached by other packages (such as foldkit-remote query requirements).

ts
const Summary = Projection.struct({
  todos: App.model.todos,
  selectedTodoId: App.model.selectedTodoId,
})
const Titles = Projection.of(Todo)({ title: true }) // from the Schema
Projection.array(Titles) // Projection<ReadonlyArray<Root>, ReadonlyArray<Value>>
Projection.option(Titles) // Projection<Option<Root>, Option<Value>>
// Escape hatch for a value that is no ModelRef:
Projection.fromReader(Schema.Number, (model: typeof Model.Type) => model.todos.length)

Projection.struct accepts ModelRefs and nested Projections, merging dependencies and metadata upward so a Surface can combine local fields with remote or synced slices.

Derivations

Views often compute derived values on every render, such as filtered lists, counts, or summaries. Projection.derive(on, derive) caches the computed value and recomputes only when an object at one of on's dependency paths changes identity:

ts
const Open = Projection.derive([App.model.todos], model =>
  model.todos.filter(todo => !todo.done),
)
Open.read(model) // returns the same array reference while `model.todos` is unchanged

Pass field references or Projections in on (an empty on throws), and read only those dependencies inside derive. In development, pass { verify: import.meta.env?.DEV === true } to re-run derive on cache hits and throw via Equal.equals if an untracked field changed; keep verify off in production since it doubles the work.

derive caches the single most recent result and returns the previous object reference whenever a new result has shallowly equal fields, matching foldkit-mixins' SlotView.region. Remote queries declare metadata rather than static Model paths, so passing a Remote query alone in on recomputes on every read. Name the store field (such as App.model.remote) in on and read the Remote query inside derive so the cache holds while the store stays unchanged.

To include a derived value inside Projection.struct, supply its output Model Schema:

ts
const Count = Projection.derive([App.model.todos], model => model.todos.length, {
  Model: Schema.Number,
})
const Board = Projection.struct({ count: Count, selected: App.model.selectedTodoId })

A Derived value carries no metadata of its own, so Remote reads used inside it are still planned by the Remote read itself rather than by the struct. Omitting Model when placing a Derived inside Projection.struct is a type error (and throws at runtime if bypassed).

Metadata

Metadata is re-exported from foldkit-metadata so applications need only one import. Each package declares its own key once and reads only its own entries:

ts
import { Metadata } from 'foldkit-surface'

const Flags = Metadata.key<string>('flags', {
  merge: (flags: ReadonlyArray<string>) => [...new Set(flags)],
  summarize: (flag: string) => flag,
})

const beta = Projection.fromReader(Schema.Boolean, (_model: typeof Model.Type) => false, {
  metadata: Flags.of('beta'),
})
Flags.get(Projection.struct({ beta, todos: App.model.todos }).metadata) // ['beta']

As projections compose, entries merge per key using that key's merge function. Lookup uses key object identity rather than string names, preventing collisions across packages (avoid duplicate installs or reloaded modules that create two instances of a key). Metadata values are opaque and frozen; Surface.inspect and Module format them using summarize.

Closure

A projection is closed when its value after a Message depends only on the projection's previous value and that Message. foldkit-sync requires durable slices to be closed so edits replay identically across devices. Closure.reads tests closure by running update on the Model and again with every non-projection top-level field reset to initial, returning [] when closed or naming any outside fields that changed the output:

ts
import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { Closure, Projection, Surface } from 'foldkit-surface'

const Model = Schema.Struct({
  todos: Schema.Array(Schema.Struct({ id: Schema.String, title: Schema.String })),
  filter: Schema.String,
})
type Model = typeof Model.Type
const Message = defineMessageUnion({ ClearedShown: {} })
const initial: Model = { todos: [], filter: '' }
const update = (model: Model, _message: typeof Message.Type) => ({
  // Removes the todos whose title is the local `filter`.
  model: { ...model, todos: model.todos.filter(todo => todo.title !== model.filter) },
})

const App = Surface.application({ Model, Message })
const shown: Model = { todos: [{ id: 'a', title: 'x' }], filter: 'x' }

Closure.reads({ initial, update }, Projection.pick(App.model.todos), shown, Message.ClearedShown())
// ['filter']: the slice after ClearedShown depends on it

Returned Commands are ignored and nothing is persisted during this check. Sync.mount runs Closure.reads on every durable dispatch; see the Sync README.

A closed Surface

Setting closed: true on a Surface declares that its messages depend only on the Surface's own projection and that other Messages leave its projection unchanged. Closure.violations(app, surfaces) builds a step checker (before, message, after) => violations for tests and walks (parameterized Surfaces are excluded since they have no single static projection):

ts
import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { Closure, Surface } from 'foldkit-surface'

const Model = Schema.Struct({ todos: Schema.Array(Schema.String), tally: Schema.Number })
type Model = typeof Model.Type
const Message = defineMessageUnion({ Emptied: {}, Counted: {} })
const initial: Model = { todos: ['a'], tally: 0 }
const update = (model: Model, message: typeof Message.Type) => ({
  model: Message.match(message, {
    Emptied: () => ({ ...model, todos: [] }),
    Counted: () => ({ ...model, tally: model.tally + 1 }),
  }),
})

const App = Surface.application({ Model, Message, initial, update })
const Shown = App.surface('Shown', {
  model: ({ model }) => ({ todos: model.todos }),
  messages: [Message.Emptied],
  closed: true,
})

const check = Closure.violations(App, [Shown])
const counted = Message.Counted()
check(initial, counted, update(initial, counted).model)
// []: Counted is outside the Surface and leaves its projection alone

Each violation is a ClosureViolation: Reads({ surface, fields }) when an allowed Message reads outside fields, or Outside({ surface }) when an outside Message mutates the projection (match with ClosureViolation.$match). Surface.contract preserves closed: true.