Primitives / foldkit-primitives/state

history

function · packages/primitives/src/state/history.ts:215

function history<const Name extends string, Value>(config: {
  readonly name: Name
  readonly value: Schema.Codec<Value, unknown>
  readonly capacity?: number | undefined
  readonly within?: number | undefined
  readonly equals?: ((present: Value, value: Value) => boolean) | undefined
}): Bundle.Bundle<
  Name,
  { readonly initial: Value },
  {
    readonly past: readonly Value[]
    readonly present: Value
    readonly future: readonly Value[]
    readonly group: string | null
    readonly groupedAt: Option.Option<number>
  },
  | { readonly _tag: 'Clear' }
  | { readonly _tag: 'Undo' }
  | { readonly _tag: 'Redo' }
  | {
      readonly _tag: 'Push'
      readonly value: Value
      readonly at?: number | undefined
      readonly group?: string | undefined
    }
  | { readonly _tag: 'GoTo'; readonly step: number },
  never,
  never,
  never,
  NoView,
  {},
  {},
  undefined
> & {
  Message: MessageUnion<{
    readonly Push: {
      readonly value: Schema.Codec<Value, unknown, never, never>
      readonly group: Schema.optional<Schema.String>
      readonly at: Schema.optional<Schema.Number>
    }
    readonly Undo: {}
    readonly Redo: {}
    readonly GoTo: { readonly step: Schema.Number }
    readonly Clear: {}
  }>
}

Undo/redo as a bundle factory: the past, present, and future of one value live in the Model, so every step replays. A value that names its own step ({ document, label, source }) is how a menu reads "Undo rename" from present and "Redo paste" from future[0].

A push may name a group. Consecutive pushes of the same group are one step: the present moves and nothing new is recorded, so typing a word undoes as a whole. The application names what belongs together, and may pass at with within so a pause starts a new step. Without equals, an unchanged value is recorded; with it, a value equal to the present is not.

The steps are also pure functions (History.push, undo, redo, goTo, clear), for a parent that records an edit in the same transition that makes it rather than dispatching a Message to a placed bundle.