Skip to content

Composition ​

A single Model, a single update - and yet an application is not one file. The way out is that a tea-effect module is just four exports, so a module can contain another one.

The parent embeds the child's model, and re-labels the child's messages as its own. Three functions do the re-labelling: Cmd.map, Sub.map and Html.map.

The child ​

An ordinary module that knows nothing about any parent:

Field.tsx
tsx
import * as Cmd from 'tea-effect/Cmd'
import type * as TeaReact from 'tea-effect/React'

// A small, self-contained module. It knows nothing about any parent.
export type Model = {
  readonly value: string
  readonly touched: boolean
}

export type Msg =
  | { readonly type: 'Changed'; readonly value: string }
  | { readonly type: 'Blurred' }

export const init = (value: string): readonly [Model, Cmd.Cmd<Msg>] => [
  { value, touched: false },
  Cmd.none
]

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'Changed':
      return [{ ...model, value: msg.value }, Cmd.none]

    case 'Blurred':
      return [{ ...model, touched: true }, Cmd.none]
  }
}

export const view =
  (model: Model): TeaReact.Html<Msg> =>
  (dispatch) => (
    <input
      value={model.value}
      onChange={(event) => dispatch({ type: 'Changed', value: event.target.value })}
      onBlur={() => dispatch({ type: 'Blurred' })}
    />
  )

The tagger ​

The parent needs one function that wraps a child message in a parent message:

tsx
// The tagger lives at module level, and that placement is load-bearing.
// `Html.map` caches the mapped dispatch per `(f, dispatch)` pair; an inline arrow
// is a new key on every render and silently defeats the cache. (`Cmd.map` has no
// cache and needs no stable `f` - it only preserves `Cmd.none`.)
const EmailMsg = (msg: Field.Msg): Msg => ({ type: 'EmailMsg', msg })

Keep it at module level

This placement is load-bearing, not style. Html.map caches the mapped dispatch per (f, dispatch) pair so that a memoised child can bail out of re-rendering. An inline arrow - Html.map((msg) => ({ type: 'EmailMsg', msg })) written inside the view - is a new function on every render, so it is a new cache key every time, and nothing below that boundary can ever be memoised.

Nothing breaks visibly. You just lose the optimisation silently.

Starting the child ​

tsx
// The child hands back its own model and command; the parent stores one and
// re-labels the other. Same two moves as in `update`, just at startup.
const [emailModel, emailCmd] = Field.init('')

export const init: readonly [Model, Cmd.Cmd<Msg>] = [
  { email: emailModel, submitted: false },
  Cmd.map(EmailMsg)(emailCmd)
]

Two moves, and they are the same two you will see in update: keep the child's model in a field, re-label the child's command.

Here Field.init returns Cmd.none, and Cmd.map gives back none itself rather than a wrapper around an empty stream - so "this branch does nothing" stays visible after crossing the boundary.

Delegating in update ​

tsx
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'EmailMsg': {
      // Delegate to the child, then re-label whatever command it returned so the
      // runtime sends the resulting messages back to the parent.
      const [email, cmd] = Field.update(msg.msg, model.email)
      return [{ ...model, email }, Cmd.map(EmailMsg)(cmd)]
    }

    case 'Submitted':
      return [{ ...model, submitted: true }, Cmd.none]
  }
}

Two things happen in the EmailMsg branch: the child's update runs on the child's slice of the model, and the command it returned is re-labelled so its messages come back to the parent.

Forgetting the Cmd.map is a type error, not a silent bug - the child's Cmd does not fit the parent's signature.

Delegating in the view ​

tsx
export const view =
  (model: Model): TeaReact.Html<Msg> =>
  (dispatch) => (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        dispatch({ type: 'Submitted' })
      }}
    >
      {/* The child's view dispatches Field.Msg; `map` wraps each one in EmailMsg. */}
      {Html.map(EmailMsg)(Field.view(model.email))(dispatch)}
      <button type="submit">Save</button>
    </form>
  )

Html.map(EmailMsg)(Field.view(model.email)) is an Html<Dom, Form.Msg> - a function from dispatch to an element. Applying it to the parent's dispatch renders the child with a dispatch that wraps everything it sends.

The complete file, imports included
tsx
import * as Cmd from 'tea-effect/Cmd'
import * as Html from 'tea-effect/Html'
import type * as TeaReact from 'tea-effect/React'
import * as Field from './Field'

export type Model = {
  readonly email: Field.Model
  readonly submitted: boolean
}

export type Msg =
  | { readonly type: 'EmailMsg'; readonly msg: Field.Msg }
  | { readonly type: 'Submitted' }

// #region tagger
// The tagger lives at module level, and that placement is load-bearing.
// `Html.map` caches the mapped dispatch per `(f, dispatch)` pair; an inline arrow
// is a new key on every render and silently defeats the cache. (`Cmd.map` has no
// cache and needs no stable `f` - it only preserves `Cmd.none`.)
const EmailMsg = (msg: Field.Msg): Msg => ({ type: 'EmailMsg', msg })
// #endregion tagger

// #region init
// The child hands back its own model and command; the parent stores one and
// re-labels the other. Same two moves as in `update`, just at startup.
const [emailModel, emailCmd] = Field.init('')

export const init: readonly [Model, Cmd.Cmd<Msg>] = [
  { email: emailModel, submitted: false },
  Cmd.map(EmailMsg)(emailCmd)
]
// #endregion init

// #region update
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'EmailMsg': {
      // Delegate to the child, then re-label whatever command it returned so the
      // runtime sends the resulting messages back to the parent.
      const [email, cmd] = Field.update(msg.msg, model.email)
      return [{ ...model, email }, Cmd.map(EmailMsg)(cmd)]
    }

    case 'Submitted':
      return [{ ...model, submitted: true }, Cmd.none]
  }
}
// #endregion update

// #region view
export const view =
  (model: Model): TeaReact.Html<Msg> =>
  (dispatch) => (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        dispatch({ type: 'Submitted' })
      }}
    >
      {/* The child's view dispatches Field.Msg; `map` wraps each one in EmailMsg. */}
      {Html.map(EmailMsg)(Field.view(model.email))(dispatch)}
      <button type="submit">Save</button>
    </form>
  )
// #endregion view

What flows through ​

Cmd.map(f)Re-labels a child's commands. none maps to none itself, so "this branch does nothing" survives the boundary, and a Cmd.latest key goes up with the command.
Sub.map(f)Re-labels a child's subscriptions, keeping their identity so a mapped timer is not restarted on every model change.
Html.map(f)Re-labels a child's view.

E and R pass through all three untouched. A child whose commands require an ApiClient produces a parent whose commands require an ApiClient - the requirement propagates up the tree on its own, and gets provided once at the root. See dependency injection.

How far to take it ​

Modules are cheap but not free: every level adds a message wrapper and a branch in update. A reasonable rule is to split when a piece has its own state and its own effects - a form, a page, a data table. A button does not need a module; it needs a function that returns Html.

For pages, the natural shape is one module per route, with the parent's Model holding the current page's model as a union:

ts
type Page =
  | { readonly _tag: 'users'; readonly model: Users.Model }
  | { readonly _tag: 'settings'; readonly model: Settings.Model }

which pairs directly with the route union from routing.

Next ​

Released under the MIT License.