Skip to content
VIP-76 · Formally Verified (Z3 + Lean 4) · Effect-TS/ui Official Docs Rewritten

Effect UI Docs: TypeScript API vs. VibeLang + TSRX

Every chapter below comes directly from Effect-TS/ui/ai-docs. Flip the toggle (or press T) to switch the entire documentation between the standard @effect/ui TypeScript API and VibeLang's TSRX Typed JSX — with 100% identical type safety across Msg, R bubbling, exact DOM tag identity, VoidElement, keepAlive, and OpenTui.

CHAPTER 01 · Effect-TS/ui/ai-docs/src/10_ui/fixtures/domain/Note.ts + services/Notes.ts

Domain Schemas, Errors & Services

48 lines vs 61 TS (-21%)

Every @effect/ui app starts with Schema models, typed TaggedErrors, and an Effect service that owns all I/O so components stay pure.

✓ Schema Codec✓ TaggedError✓ Service R✓ exactOptionalPropertyTypes
Note.ts / Notes.ts · @effect/ui TypeScript API
import { Query } from "@effect/ui"
import { Context, Effect, Layer, Schema } from "effect"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"

export const Note = Schema.Struct({
  id: Schema.String,
  title: Schema.String,
  body: Schema.String
})
export type Note = typeof Note.Type

export const NoteSort = Schema.Literals(["asc", "desc"])
export type NoteSort = typeof NoteSort.Type

export class NoteNotFound
  extends Schema.TaggedError<NoteNotFound>()("NoteNotFound", {
    id: Schema.String
  })
{}

export class NoteSaveError
  extends Schema.TaggedError<NoteSaveError>()("NoteSaveError", {
    reason: Schema.String
  })
{}

export const NotesTag = Query.Tag("notes")

export class Notes extends Context.Service<Notes, {
  readonly list: Effect.Effect<ReadonlyArray<Note>>
  get(id: string): Effect.Effect<Note, NoteNotFound>
  save(note: Note): Effect.Effect<Note, NoteSaveError>
}>()("app/Notes") {
  static readonly layerHttp = Layer.effect(
    Notes,
    Effect.gen(function*() {
      const client = (yield* HttpClient.HttpClient).pipe(
        HttpClient.mapRequestInput(HttpClientRequest.prependUrl("/api")),
        HttpClient.filterStatusOk
      )
      return Notes.of({
        list: client.get("/notes").pipe(
          Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Array(Note))),
          Effect.orDie
        ),
        get: (id) =>
          client.get(`/notes/${id}`).pipe(
            Effect.flatMap(HttpClientResponse.schemaBodyJson(Note)),
            Effect.mapError(() => new NoteNotFound({ id }))
          ),
        save: (note) =>
          HttpClientRequest.put(`/notes/${note.id}`).pipe(
            HttpClientRequest.bodyJsonUnsafe(note),
            client.execute,
            Effect.flatMap(HttpClientResponse.schemaBodyJson(Note)),
            Effect.mapError((cause) => new NoteSaveError({ reason: cause.message }))
          )
      })
    })
  )
}
Note.vibe / Notes.vibe · VibeLang + TSRX Typed JSX
import { Query } from "@effect/ui"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"

export schema Note {
  readonly id: string
  readonly title: string
  readonly body: string
}

export schema NoteSort = "asc" | "desc"

export schema error NoteNotFound { id: string }
export schema error NoteSaveError { reason: string }

export const NotesTag = Query.Tag("notes")

export service Notes {
  static readonly key = "app/Notes"
  readonly list: ReadonlyArray<Note>!!
  get(id: string): Note!NoteNotFound
  save(note: Note): Note!NoteSaveError
}

export const NotesHttpLive = Layer.effect(Notes, effect {
  const client = (try HttpClient.HttpClient)
    |> HttpClient.mapRequestInput(%, HttpClientRequest.prependUrl("/api"))
    |> HttpClient.filterStatusOk(%)

  return {
    list: effect {
      const res = try orDie(client.get("/notes"))
      return try orDie(HttpClientResponse.schemaBodyJson(Schema.Array(Note))(res))
    },
    get: effect (id) => {
      const res = client.get(`/notes/${id}`) catch effect () => { throw new NoteNotFound({ id }) }
      return HttpClientResponse.schemaBodyJson(Note)(res)
        catch effect () => { throw new NoteNotFound({ id }) }
    },
    save: effect (note) => {
      const req = HttpClientRequest.put(`/notes/${note.id}`)
        |> HttpClientRequest.bodyJsonUnsafe(%, note)
      const res = client.execute(req)
        catch effect (e) => { throw new NoteSaveError({ reason: e.message }) }
      return HttpClientResponse.schemaBodyJson(Note)(res)
        catch effect (e) => { throw new NoteSaveError({ reason: e.message }) }
    }
  }
})
  • schema + schema error eliminate duplicate const/type declarations and class boilerplate
  • service Notes replaces Context.Service<Notes, {...}>()(...) with A!E!R shorthand
  • effect { ... } + try replace nested Effect.gen / pipe chains
CHAPTER 02 · Effect-TS/ui/ai-docs/src/10_ui/10_basics.ts + fixtures/notes/components/NoteEditor.ts

Building a Component, Commands & Subscriptions

74 lines vs 76 TS (-3%)

A note editor with a queued Command.Service, an autosave stream subscription, controlled textarea, and TSRX JSX view with @if and on:* event handlers.

✓ Scoped Msg✓ Command.Service R✓ VoidElement✓ on:ev:prevent
NoteEditor.ts · @effect/ui TypeScript API
import { Command, Subscription, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Effect, Schema, Stream } from "effect"

export const NoteEditorMessage = UiSchema.TaggedEnum({
  UpdatedBody: { body: Schema.String },
  RequestedSave: {},
  SucceededSaveNote: { note: Note },
  FailedSaveNote: { reason: Schema.String }
})

export class SaveNote extends Command.Service<SaveNote>()("notes/SaveNote", {
  args: { note: Note },
  success: NoteEditorMessage,
  mode: "queue",
  invalidates: () => [NotesTag]
}) {
  static readonly layer = this.toLayer(
    Effect.gen(function*() {
      const notes = yield* Notes
      return ({ note }) =>
        notes.save(note).pipe(
          Effect.match({
            onSuccess: (note) => NoteEditorMessage.SucceededSaveNote({ note }),
            onFailure: (error) => NoteEditorMessage.FailedSaveNote({ reason: error.reason })
          })
        )
    })
  )
}

const NoteEditorDef = Html.component({
  name: "NoteEditor",
  props: Schema.Struct({ note: Note }),
  model: Schema.Struct({
    draft: Schema.String,
    saved: Schema.String,
    error: Schema.NullOr(Schema.String)
  }),
  message: NoteEditorMessage
})

export const NoteEditorNoDeps = NoteEditorDef.make({
  init: ({ props }) => ({ draft: props.note.body, saved: props.note.body, error: null }),
  update: {
    UpdatedBody: ($, { body }) => $.evolve({ draft: body, error: null }),
    RequestedSave: ($) =>
      $.model.draft === $.model.saved
        ? $.model
        : $.run(SaveNote.make({ note: { ...$.props.note, body: $.model.draft } })),
    SucceededSaveNote: ($, { note }) => $.evolve({ saved: note.body }),
    FailedSaveNote: ($, { reason }) => $.evolve({ error: reason })
  },
  subscriptions: ({ model }) => [
    model.draft !== model.saved &&
      Subscription.make("autosave", 1, () =>
        Stream.sleep("2 seconds").pipe(Stream.as(NoteEditorMessage.RequestedSave()))
      )
  ],
  view: (h, model) =>
    h.form.on("submit", NoteEditorMessage.RequestedSave()).children(
      h.textarea
        .attr("aria-label", "Note body")
        .value(model.draft)
        .on("input", ({ value }) => NoteEditorMessage.UpdatedBody({ body: value }))
        .on("keydown", ({ key, ctrl, meta }) =>
          key === "s" && (ctrl || meta) ? NoteEditorMessage.RequestedSave() : undefined,
          { preventDefault: true }
        ),
      model.error !== null &&
        h.p.attr("role", "alert").children(model.error),
      h.button.attr("type", "submit").children(
        h.isRunning(SaveNote) ? "Saving…" : "Save"
      )
    )
})
NoteEditor.vibex · VibeLang + TSRX Typed JSX
import { Command, Subscription, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"

export const NoteEditorMessage = UiSchema.TaggedEnum({
  UpdatedBody: { body: Schema.String },
  RequestedSave: {},
  SucceededSaveNote: { note: Note },
  FailedSaveNote: { reason: Schema.String }
})

export class SaveNote extends Command.Service<SaveNote>()("notes/SaveNote", {
  args: { note: Note },
  success: NoteEditorMessage,
  mode: "queue",
  invalidates: () => [NotesTag]
}) {
  static readonly layer = this.toLayer(effect {
    const notes = try Notes
    return effect ({ note }) =>
      notes.save(note) catch (err) =>
        NoteEditorMessage.FailedSaveNote({ reason: err.reason })
      |> map(%, (saved) => NoteEditorMessage.SucceededSaveNote({ note: saved }))
  })
}

effect function* autosaveTick() {
  try sleep("2 seconds")
  yield NoteEditorMessage.RequestedSave()
}

schema NoteEditorModel {
  readonly draft: string
  readonly saved: string
  readonly error: string | null
}

export const NoteEditorNoDeps = Html.component({
  name: "NoteEditor",
  props: Schema.Struct({ note: Note }),
  model: NoteEditorModel,
  message: NoteEditorMessage
}).make({
  init: ({ props }) => ({ draft: props.note.body, saved: props.note.body, error: null }),
  update: {
    UpdatedBody: ($, { body }) => $.evolve({ draft: body, error: null }),
    RequestedSave: ($) =>
      $.model.draft === $.model.saved
        ? $.model
        : $.run(SaveNote.make({ note: { ...$.props.note, body: $.model.draft } })),
    SucceededSaveNote: ($, { note }) => $.evolve({ saved: note.body }),
    FailedSaveNote: ($, { reason }) => $.evolve({ error: reason })
  },
  subscriptions: ({ model }) => [
    model.draft !== model.saved && Subscription.make("autosave", 1, () => autosaveTick())
  ],
  view: (h, model) => @{
    <form on:submit={NoteEditorMessage.RequestedSave()}>
      <textarea
        aria-label="Note body"
        value={model.draft}
        on:input={({ value }) => NoteEditorMessage.UpdatedBody({ body: value })}
        on:keydown:prevent={({ key, ctrl, meta }) =>
          key === "s" && (ctrl || meta) ? NoteEditorMessage.RequestedSave() : undefined
        }
      />
      @if (model.error !== null) {
        <p role="alert">{model.error}</p>
      }
      <button type="submit">
        {h.isRunning(SaveNote) ? "Saving…" : "Save"}
      </button>
    </form>
  }
})
  • @{ ... } TSRX view lowers directly to h.<tag> builders — same Html.Element<Msg, R, E, Node, Tag>
  • effect function* autosaveTicks replaces Stream.tick + Stream.map boilerplate
  • on:input, on:submit, and on:keydown:prevent check NoteEditorMessage at compile time
CHAPTER 03 · Effect-TS/ui/ai-docs/src/10_ui/20_composition.ts + fixtures/pages/notes/NotePage.ts

Composing Components, Queries, Slots & R Bubbling

54 lines vs 45 TS (+20%)

Load a note with Query.Service, render child components and Feature.Service inside slots, and bubble GetNote | NoteActivity requirements straight through JSX.

✓ Effect R Bubbling✓ Feature.Service✓ Typed Slots✓ Failure Boundaries
NotePage.ts · @effect/ui TypeScript API
export const NotePageNoDeps = Html.component({
  name: "NotePage",
  props: Schema.Struct({ id: Schema.String }),
  model: Schema.Struct({ notice: Schema.String }),
  message: NotePageMessage,
  queries: { note: { query: GetNote, args: ({ props }) => ({ id: props.id }) } }
}).make({
  init: () => ({ notice: "" }),
  update: ($, message) =>
    NotePageMessage.match(message, {
      SavedNote: () => $.evolve({ notice: "Saved" }),
      FailedEditor: () => $.evolve({ notice: "The editor crashed" })
    }),
  view: (h, model) =>
    AsyncResult.match(h.queries.note, {
      onInitial: () => h.p("Loading note…"),
      onFailure: () => h.p("This note doesn't exist."),
      onSuccess: ({ value: note }) =>
        h.article(
          Collapsible(h, {
            key: "note",
            slots: {
              summary: h.h2(note.title),
              body: [
                NoteEditor(h, {
                  key: note.id,
                  props: { note },
                  onEmit: { Saved: () => NotePageMessage.SavedNote() },
                  onFailure: () => NotePageMessage.FailedEditor(),
                  fallback: () => h.p("The editor is unavailable.")
                }),
                NoteActivity.render(h, {
                  key: "activity",
                  props: { noteId: note.id },
                  fallback: (result) =>
                    h.p(AsyncResult.isInitial(result) ? "Loading activity…" : "No activity.")
                })
              ]
            }
          }),
          model.notice !== "" &&
            h.p.attr("role", "status").children(model.notice)
        )
    })
})
NotePage.vibex · VibeLang + TSRX Typed JSX
schema NotePageModel {
  readonly notice: string
}

export const NotePageNoDeps = Html.component({
  name: "NotePage",
  props: Schema.Struct({ id: Schema.String }),
  model: NotePageModel,
  message: NotePageMessage,
  queries: { note: { query: GetNote, args: ({ props }) => ({ id: props.id }) } }
}).make({
  init: () => ({ notice: "" }),
  update: {
    SavedNote: ($) => $.evolve({ notice: "Saved" }),
    FailedEditor: ($) => $.evolve({ notice: "The editor crashed" })
  },
  view: (h, model) => @{
    {AsyncResult.match(h.queries.note, {
      onInitial: () => <p>Loading note…</p>,
      onFailure: () => <p>This note doesn't exist.</p>,
      onSuccess: ({ value: note }) => (
        <article>
          <Collapsible
            key="note"
            slots={{
              summary: <h2>{note.title}</h2>,
              body: (
                <>
                  <NoteEditor
                    key={note.id}
                    props={{ note }}
                    onEmit={{ Saved: () => NotePageMessage.SavedNote() }}
                    onFailure={() => NotePageMessage.FailedEditor()}
                    fallback={() => <p>The editor is unavailable.</p>}
                  />
                  <NoteActivity.render
                    key="activity"
                    props={{ noteId: note.id }}
                    fallback={(result) => (
                      <p>{AsyncResult.isInitial(result) ? "Loading activity…" : "No activity."}</p>
                    )}
                  />
                </>
              )
            }}
          />
          @if (model.notice !== "") {
            <p role="status">{model.notice}</p>
          }
        </article>
      )
    })}
  }
})
  • Requirements from <NoteEditor /> and <NoteActivity.render /> bubble through <article> into NotePageNoDeps
  • Slots accept JSX directly: slots={{ summary: <h2>{note.title}</h2>, body: <>...</> }}
  • Forgetting Component.provide([GetNote.layer, NoteActivity.toLayer(ActivityLog)]) is still a compile error
CHAPTER 04 · Effect-TS/ui/ai-docs/src/10_ui/21_view-functions.ts

Reusable View Functions & Preserving Child R

39 lines vs 36 TS (+8%)

Plain generic view functions take Html.H<M> and return builders or elements without erasing nested children's Effect service requirements.

✓ Generic Html.H<M>✓ Preserved Child R✓ VoidElement
21_view-functions.ts · @effect/ui TypeScript API
import type { View } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const Card = <M>(h: Html.H<M>) => h.section.class("card")

const Field = <M, C extends View.Children<M>>(h: Html.H<M>, options: {
  readonly label: string
  readonly children: C
}) =>
  h.label.children(
    options.label,
    h.div.class("control").children(options.children)
  )

const Framed = <M>(h: Html.H<M>) =>
  h.div.class("control").forward((control) =>
    h.div.class("frame").children(control)
  )

export const Form = Html.component({
  name: "Form",
  model: Schema.String,
  message: Schema.String
}).make({
  init: () => "",
  update: (_, value) => value,
  view: (h, value) =>
    Card(h).children(
      Field(h, {
        label: "Name",
        children: [h.input.value(value).on("input", ({ value }) => value)]
      }),
      Framed(h).class("wide").children(value)
    )
})
21_view-functions.vibex · VibeLang + TSRX Typed JSX
import type { View } from "@effect/ui"
import { Html } from "@effect/ui/html"

function Card<M>(h: Html.H<M>) @{
  <section class="card" />
}

function Field<M, C extends View.Children<M>>(
  h: Html.H<M>,
  options: { readonly label: string; readonly children: C }
) @{
  <label>
    {options.label}
    <div class="control">{options.children}</div>
  </label>
}

const Framed = <M,>(h: Html.H<M>) =>
  h.div.class("control").forward((control) => @(h){
    <div class="frame">{control}</div>
  })

export const Form = Html.component({
  name: "Form",
  model: Schema.String,
  message: Schema.String
}).make({
  init: () => "",
  update: (_, value) => value,
  view: (h, value) => @{
    <Card>
      <Field
        label="Name"
        children={<input value={value} on:input={({ value }) => value} />}
      />
      {Framed(h).class("wide").children(value)}
    </Card>
  }
})
  • TSRX function body syntax `function Field<M, C>(h: Html.H<M>, options) @{ ... }`
  • Generic `C extends View.Children<M>` retains the exact union of child requirements
  • Self-closing `<input value={value} on:input={...} />` stays a VoidElement
CHAPTER 05 · Effect-TS/ui/ai-docs/src/10_ui/22_headless-components.ts + @effect/ui-kit Dialog

Headless Components & Exact DOM Tag Safety

49 lines vs 43 TS (+14%)

Headless components like Dialog and Listbox own ARIA, keyboard navigation, and state — and statically enforce exact HTML element tags on parts like dialog.trigger(<button>).

✓ Exact Tag "button"✓ HTMLDialogElement✓ Headless Parts✓ ARIA
CartDialog.ts · @effect/ui TypeScript API
const CartDialog = AppDef.fragment((h, model: AppModel) => {
  const total = model.cart.reduce((sum, domain) => sum + domain.price, 0)
  return Dialog(h, {
    key: "cart",
    props: { open: model.popup === "Cart" },
    onEmit: {
      RequestedOpen: () => AppMessage.RequestedOpenPopup({ popup: "Cart" }),
      RequestedClose: () => AppMessage.RequestedClosePopup({ popup: "Cart" }),
      Settled: () => undefined
    },
    view: (dialog) =>
      h.div.children(
        dialog.trigger(
          h.button.attrs({
            id: "cart-button",
            "aria-label": `Cart, ${model.cart.length} domains`
          }).class("button")
        ).children(`Cart (${model.cart.length})`),
        dialog.portal(h.dialog.class("dialog-overlay"))?.children(
          dialog.backdrop(h.div),
          dialog.popup(h.div.class("dialog-panel")).children(
            dialog.title(h.h2).children(`Your Cart (${model.cart.length})`),
            model.cart.length === 0
              ? h.p.class("domain-meta").children("No domains added yet.")
              : h.ul.class("cart-list").children(
                model.cart.map((item) =>
                  h.li.key(item.name).class("cart-item").children(
                    h.span(`${item.name} · ${formatPrice(item.price)}`),
                    Button(h, {
                      onPress: AppMessage.ClickedRemoveDomain({ name: item.name })
                    }).class("button").children("Remove")
                  )
                )
              ),
            h.div.class("cart-item").children(
              h.strong(`Total: ${formatPrice(total)}`),
              dialog.close(h.button.class("button")).children("Close")
            )
          )
        )
      )
  })
})
CartDialog.vibex · VibeLang + TSRX Typed JSX
const CartDialog = AppDef.fragment((h, model: AppModel) => @{
  const total = model.cart.reduce((sum, d) => sum + d.price, 0)
  <Dialog
    key="cart"
    props={{ open: model.popup === "Cart" }}
    onEmit={{
      RequestedOpen: () => AppMessage.RequestedOpenPopup({ popup: "Cart" }),
      RequestedClose: () => AppMessage.RequestedClosePopup({ popup: "Cart" }),
      Settled: () => undefined
    }}
    view={(dialog) => (
      <div>
        <dialog.trigger>
          <button
            id="cart-button"
            aria-label={`Cart, ${model.cart.length} domains`}
            class="button"
          >
            Cart ({model.cart.length})
          </button>
        </dialog.trigger>
        {dialog.portal(<dialog class="dialog-overlay" />)?.children(
          <dialog.backdrop><div /></dialog.backdrop>,
          <dialog.popup>
            <div class="dialog-panel">
              <dialog.title><h2>Your Cart ({model.cart.length})</h2></dialog.title>
              <ul class="cart-list">
                @for (const item of model.cart; key item.name) {
                  <li class="cart-item">
                    <span>{item.name} · {formatPrice(item.price)}</span>
                    <Button onPress={AppMessage.ClickedRemoveDomain({ name: item.name })}>
                      Remove
                    </Button>
                  </li>
                } @empty {
                  <p class="domain-meta">No domains added yet.</p>
                }
              </ul>
              <div class="cart-item">
                <strong>Total: {formatPrice(total)}</strong>
                <dialog.close><button class="button">Close</button></dialog.close>
              </div>
            </div>
          </dialog.popup>
        )}
      </div>
    )}
  />
})
  • <dialog.trigger><button ...>Cart</button></dialog.trigger> preserves exact tag "button"
  • Swapping <button> to <div> is a compile error — impossible in stock TS JSX
  • @for + @empty render cart items cleanly inside the modal popup
CHAPTER 06 · Effect-TS/ui/LLMS.md#keep-alive-children

Keep-Alive Children & Literal-Key Safety

31 lines vs 19 TS (+63%)

Keep hidden tabs or filtered list rows alive with h.keepAlive((s) => ...). Without a predicate, keys must be string literals — enforced identically in TSRX.

✓ KeepAlive<Msg, Ends>✓ Literal Key Check✓ Scoped Builder Shadowing
SettingsTabs.ts · @effect/ui TypeScript API
// Literal keys without a predicate (tabs):
const TabsView = (h: Html.H<SettingsMessage>, model: SettingsModel) =>
  model.tab === "profile"
    ? h.keepAlive((s) => Profile(s, { key: "profile" }))
    : h.keepAlive((s) => Billing(s, { key: "billing" }))

// Dynamic list keys with a termination predicate:
const NotesListView = (
  h: Html.H<NotesMessage>,
  model: NotesModel,
  visible: ReadonlyArray<string>
) =>
  h.keepAlive(
    ({ key, model }) => key in model.notes,
    (s) =>
      visible.map((id) =>
        NoteRow(s, { key: id, props: { note: model.notes[id] } })
      )
  )
SettingsTabs.vibex · VibeLang + TSRX Typed JSX
// Literal keys without a predicate (tabs):
function TabsView(h: Html.H<SettingsMessage>, model: SettingsModel) @{
  @switch (model.tab) {
    @case "profile": {
      h.keepAlive((s) => @{
        <Profile key="profile" />
      })
    }
    @default: {
      h.keepAlive((s) => @{
        <Billing key="billing" />
      })
    }
  }
}

// Dynamic list keys with a termination predicate:
function NotesListView(
  h: Html.H<NotesMessage>,
  model: NotesModel,
  visible: ReadonlyArray<string>
) @{
  h.keepAlive(
    ({ key, model }) => key in model.notes,
    (s) => @{
      @for (const id of visible) {
        <NoteRow key={id} props={{ note: model.notes[id] }} />
      }
    }
  )
}
  • Inside h.keepAlive((s) => @{ ... }), JSX automatically binds to `s: KeepAlive<Msg, Ends>`
  • Dynamic non-literal key without a predicate triggers KeepAliveKeyHint compile error
  • Ordinary .map((s) => <span>{s}</span>) never collides with keepAlive's `s`
CHAPTER 07 · Effect-TS/ui/ai-docs/src/10_ui/23_shared-state.ts

Shared State (TooltipProvider & Tooltip)

33 lines vs 25 TS (+32%)

A headless provider shares state with descendants through `shares` and `reads`. Reading `h.reads.provider` adds Component.Shared<"TooltipProvider"> to R until wrapped by the provider.

✓ Component.Shared R✓ Scoped Msg✓ ARIA role="tooltip"
Tooltip.ts · @effect/ui TypeScript API
export const Tooltip = Html.component({
  name: "Tooltip",
  props: Schema.Struct({ label: Schema.String, tip: Schema.String }),
  model: Schema.Null,
  message: TooltipMessage,
  reads: { provider: TooltipProvider }
}).make({
  init: () => null,
  update: ($, message) =>
    message._tag === "BlurredTooltip" && $.reads.provider.open !== message.id
      ? $.model
      : $.send(TooltipProvider, message),
  view: (h) => {
    const id = h.id("tip")
    return h.span(
      h.button
        .on("focus", TooltipMessage.FocusedTooltip({ id }))
        .on("blur", TooltipMessage.BlurredTooltip({ id }))
        .attr("aria-describedby", id)
        .children(h.props.label),
      h.reads.provider.open === id &&
        h.span.id(id).attr("role", "tooltip").children(h.props.tip)
    )
  }
})
Tooltip.vibex · VibeLang + TSRX Typed JSX
schema TooltipProps {
  readonly label: string
  readonly tip: string
}

export const Tooltip = Html.component({
  name: "Tooltip",
  props: TooltipProps,
  model: Schema.Null,
  message: TooltipMessage,
  reads: { provider: TooltipProvider }
}).make({
  init: () => null,
  update: ($, message) =>
    message._tag === "BlurredTooltip" && $.reads.provider.open !== message.id
      ? $.model
      : $.send(TooltipProvider, message),
  view: (h) => @{
    const id = h.id("tip")
    <span>
      <button
        on:focus={TooltipMessage.FocusedTooltip({ id })}
        on:blur={TooltipMessage.BlurredTooltip({ id })}
        aria-describedby={id}
      >
        {h.props.label}
      </button>
      @if (h.reads.provider.open === id) {
        <span id={id} role="tooltip">{h.props.tip}</span>
      }
    </span>
  }
})
  • Setup statement `const id = h.id("tip")` sits cleanly inside `@{ ... }` before markup
  • on:focus and on:blur dispatch typed TooltipMessage variants
  • @if (h.reads.provider.open === id) renders the accessible role="tooltip" span
CHAPTER 08 · Effect-TS/ui/ai-docs/src/10_ui/25_drawing-with-svg.ts

Drawing Icons & Progress Charts with SVG

35 lines vs 37 TS (-5%)

SVG tags check case-sensitive SVG attributes per tag (viewBox, stroke-width, stroke-dasharray), and <svg:text> lowers cleanly to h.svgText.

✓ Case-Sensitive SVG Attrs✓ <svg:text> -> h.svgText✓ Generic Html.H<M>
25_drawing-with-svg.ts · @effect/ui TypeScript API
const CheckIcon = <M>(h: Html.H<M>) =>
  h.svg
    .class("icon")
    .attrs({
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "aria-hidden": "true"
    })
    .children(h.path.attr("d", "M5 12l5 5L20 7"))

const Ring = <M>(h: Html.H<M>, done: number, total: number) => {
  const r = 16
  const length = 2 * Math.PI * r
  const shown = total === 0 ? 0 : done / total
  return h.svg.attrs({
    viewBox: "0 0 40 40",
    role: "img",
    "aria-label": `${done} of ${total} done`
  }).children(
    h.circle.attrs({
      cx: "20", cy: "20", r: String(r),
      fill: "none", stroke: "lightgray", "stroke-width": "4"
    }),
    h.circle.attrs({
      cx: "20", cy: "20", r: String(r),
      fill: "none", stroke: "currentColor", "stroke-width": "4",
      "stroke-dasharray": `${length * shown} ${length}`,
      transform: "rotate(-90 20 20)"
    }),
    h.svgText.attrs({
      x: "20", y: "24", "text-anchor": "middle", "font-size": "10"
    }).children(`${done}/${total}`)
  )
}
25_drawing-with-svg.vibex · VibeLang + TSRX Typed JSX
function CheckIcon<M>(h: Html.H<M>) @{
  <svg
    class="icon"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    aria-hidden="true"
  >
    <path d="M5 12l5 5L20 7" />
  </svg>
}

function Ring<M>(h: Html.H<M>, done: number, total: number) @{
  const r = 16
  const length = 2 * Math.PI * r
  const shown = total === 0 ? 0 : done / total
  <svg viewBox="0 0 40 40" role="img" aria-label={`${done} of ${total} done`}>
    <circle cx="20" cy="20" r={String(r)} fill="none" stroke="lightgray" stroke-width="4" />
    <circle
      cx="20"
      cy="20"
      r={String(r)}
      fill="none"
      stroke="currentColor"
      stroke-width="4"
      stroke-dasharray={`${length * shown} ${length}`}
      transform="rotate(-90 20 20)"
    />
    <svg:text x="20" y="24" text-anchor="middle" font-size="10">
      {done}/{total}
    </svg:text>
  </svg>
}
  • Natural <svg viewBox="0 0 40 40"><circle ... /><svg:text>...</svg:text></svg>
  • Mistyping viewbox or strok-width is still a compile error via per-tag SVG attr types
  • Setup math (`const r = 16; const length = 2 * Math.PI * r`) lives right inside `@{ ... }`
CHAPTER 09 · Effect-TS/ui/ai-docs/src/10_ui/30_routing.ts + fixtures/App.ts

Typed Routing, Exhaustive Views & Document Head

51 lines vs 49 TS (+4%)

Key each page by AppRoute.printPath(route) and switch exhaustively across routes using native Vibe match inside TSRX.

✓ Exhaustive match (EK4701)✓ Typed Route Params✓ Router R
App.ts · @effect/ui TypeScript API
export const App = Html.component({
  name: "App",
  props: Schema.Struct({ route: AppRoute }),
  model: Schema.Struct({ route: AppRoute }),
  message: AppMessage
}).make({
  init: ($) => ({ route: $.props.route }),
  update: ($, message) =>
    AppMessage.match(message, {
      ChangedRoute: ({ route }) => ({ route }),
      ClickedBackToNotes: () =>
        $.run(Router.push(AppRoute, indexRoute).pipe(Command.asNoop))
    }),
  subscriptions: ({ model }) => [
    Router.subscription(AppRoute, model.route, (route) =>
      AppMessage.ChangedRoute({ route })
    )
  ],
  head: () => [
    Head.titleTemplate((title) => `${title} · Notes`),
    HtmlHead.lang("en")
  ],
  view: (h, { route }) =>
    h.div(
      h.header(
        h.a.attr("href", AppRoute.print(indexRoute)).children("Notes"),
        h.a.attr("href", AppRoute.print(searchRoute)).children("Search")
      ),
      h.main(
        AppRoute.match(route, {
          Index: (route) => NotesIndex(h, { key: AppRoute.printPath(route) }),
          Search: (route) =>
            SearchPage(h, { key: AppRoute.printPath(route), props: { route } }),
          Note: (route) =>
            NotePage(h, {
              key: AppRoute.printPath(route),
              props: { id: route.params.id }
            }),
          NotFound: () =>
            h.section(
              h.h1("Page not found"),
              h.button.on("click", AppMessage.ClickedBackToNotes()).children(
                "Back to all notes"
              )
            )
        })
      )
    )
})
App.vibex · VibeLang + TSRX Typed JSX
schema AppState {
  readonly route: AppRoute
}

export const App = Html.component({
  name: "App",
  props: AppState,
  model: AppState,
  message: AppMessage
}).make({
  init: ($) => ({ route: $.props.route }),
  update: {
    ChangedRoute: (_, { route }) => ({ route }),
    ClickedBackToNotes: ($) =>
      $.run(Router.push(AppRoute, indexRoute) |> Command.asNoop(%))
  },
  subscriptions: ({ model }) => [
    Router.subscription(AppRoute, model.route, (route) =>
      AppMessage.ChangedRoute({ route })
    )
  ],
  head: () => [
    Head.titleTemplate((title) => `${title} · Notes`),
    HtmlHead.lang("en")
  ],
  view: (h, { route }) => @{
    <div>
      <header>
        <a href={AppRoute.print(indexRoute)}>Notes</a>
        <a href={AppRoute.print(searchRoute)}>Search</a>
      </header>
      <main>
        {match (route) {
          when { _tag: "Index" }:
            <NotesIndex key={AppRoute.printPath(route)} />;
          when { _tag: "Search" }:
            <SearchPage key={AppRoute.printPath(route)} props={{ route }} />;
          when { _tag: "Note", let params }:
            <NotePage key={AppRoute.printPath(route)} props={{ id: params.id }} />;
          when { _tag: "NotFound" }:
            <section>
              <h1>Page not found</h1>
              <button on:click={AppMessage.ClickedBackToNotes()}>
                Back to all notes
              </button>
            </section>;
        }}
      </main>
    </div>
  }
})
  • Exhaustive `match (route)` inside `<main>` rejects missing route branches at compile time
  • Each page component (<NotesIndex />, <SearchPage />, <NotePage />) keeps its own R & key
  • Zero boilerplate around header links and NotFound action button
CHAPTER 10 · Effect-TS/ui/ai-docs/src/10_ui/60_opentui.ts

Terminal Apps with OpenTUI (Multi-Host JSX)

58 lines vs 49 TS (+18%)

The exact same TSRX syntax targets terminal UIs via @effect/ui-opentui — automatically scoping valid tags to OpenTUI (<box>, <input>, <select>, <text>, <b>) and rejecting HTML tags like <div>.

✓ OpenTui.Host✓ Cross-Host Tag Rejection✓ Controlled Focus Ring
60_opentui.ts · @effect/ui TypeScript API
const TaskModel = Schema.Struct({
  draft: Schema.String,
  items: Schema.Array(Schema.String),
  selectedIndex: Schema.Number,
  focus: Schema.Literals(["input", "list"])
})

export const TaskBoard = OpenTui.component({
  name: "TaskBoard",
  model: TaskModel,
  message: TaskMessage
}).make({
  init: () => ({
    draft: "",
    items: ["Wire OpenTUI host", "Add terminal Snake example"],
    selectedIndex: 0,
    focus: "input" as const
  }),
  update: {
    UpdatedDraft: ($, { value }) => $.evolve({ draft: value }),
    SubmittedDraft: ($) => {
      const next = $.model.draft.trim()
      if (next === "") return $.model
      return $.evolve({ draft: "", items: (items) => [...items, next] })
    },
    ChangedSelection: ($, { index }) => $.evolve({ selectedIndex: index }),
    SwitchedFocus: ($) =>
      $.evolve({ focus: (f) => (f === "input" ? "list" : "input") }),
    RequestedQuit: ($) => $.run(OpenTuiCommand.quit())
  },
  view: (h, model) =>
    h.box.style({
      border: true, flexDirection: "column", padding: 1, gap: 1, width: 50
    }).title("Tasks").children(
      h.input.style({ width: 44 }).placeholder("New task...").value(model.draft)
        .focused(model.focus === "input")
        .on("input", ({ value }) => TaskMessage.UpdatedDraft({ value }))
        .on("enter", TaskMessage.SubmittedDraft()),
      h.select.style({ width: 44, height: 6 })
        .options(model.items.map((name) => ({ name, description: "" })))
        .selectedIndex(model.selectedIndex)
        .focused(model.focus === "list")
        .on("selectionChanged", ({ index }) =>
          TaskMessage.ChangedSelection({ index })),
      h.text.style({ fg: "#9ca3af" }).children(
        h.b("Tab"), ": switch focus  ", h.b("Enter"), ": add  ", h.b("q"), ": quit"
      )
    )
})
60_opentui.vibex · VibeLang + TSRX Typed JSX
schema TaskFocus = "input" | "list"

schema TaskModel {
  readonly draft: string
  readonly items: ReadonlyArray<string>
  readonly selectedIndex: number
  readonly focus: TaskFocus
}

export const TaskBoard = OpenTui.component({
  name: "TaskBoard",
  model: TaskModel,
  message: TaskMessage
}).make({
  init: () => ({
    draft: "",
    items: ["Wire OpenTUI host", "Add terminal Snake example"],
    selectedIndex: 0,
    focus: "input"
  }),
  update: {
    UpdatedDraft: ($, { value }) => $.evolve({ draft: value }),
    SubmittedDraft: ($) => {
      const next = $.model.draft.trim()
      if (next === "") return $.model
      return $.evolve({ draft: "", items: (items) => [...items, next] })
    },
    ChangedSelection: ($, { index }) => $.evolve({ selectedIndex: index }),
    SwitchedFocus: ($) =>
      $.evolve({ focus: (f) => (f === "input" ? "list" : "input") }),
    RequestedQuit: ($) => $.run(OpenTuiCommand.quit())
  },
  view: (h, model) => @{
    <box
      style={{ border: true, flexDirection: "column", padding: 1, gap: 1, width: 50 }}
      call:title="Tasks"
    >
      <input
        style={{ width: 44 }}
        call:placeholder="New task..."
        value={model.draft}
        focused={model.focus === "input"}
        on:input={({ value }) => TaskMessage.UpdatedDraft({ value })}
        on:enter={TaskMessage.SubmittedDraft()}
      />
      <select
        style={{ width: 44, height: 6 }}
        options={model.items.map((name) => ({ name, description: "" }))}
        selectedIndex={model.selectedIndex}
        focused={model.focus === "list"}
        on:selectionChanged={({ index }) => TaskMessage.ChangedSelection({ index })}
      />
      <text style={{ fg: "#9ca3af" }}>
        <b>Tab</b>: switch focus  <b>Enter</b>: add  <b>q</b>: quit
      </text>
    </box>
  }
})
  • OpenTui.component supplies OpenTui.H<TaskMessage> — writing <div> here is a compile error
  • Controlled terminal focus ring via focused={model.focus === "input"} and on:enter / on:selectionChanged
  • call:title="Tasks" and call:placeholder="New task..." invoke OpenTUI builder methods cleanly