Component unstable
A component is a value: Schemas for its props, Model, messages and events,
plus pure init, update and view functions.
Details
update returns the next Model, or a step that also runs Commands and
emits to the parent. The runtime holds each instance's Model, runs its
Commands in the instance's own Scope, and re-renders its view. Children are
declared in the view by calling them, Editor(h, { key, props }), and
communicate up through events and down through props. A component's
requirements, R, name the Commands and feature services it uses, never
what their implementations use.
A component is built in two steps: define takes its name and Schemas,
and make on the definition takes init, update and view. A large
component writes its update slices and view against the definition.
Example A todo row that saves through a Command and reports to its parent
import { Command, Component, UiSchema } from "effect/ui"import { Schema } from "effect"
const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, done: Schema.Boolean })const TodoItemMessage = UiSchema.TaggedEnum({ ClickedToggle: {}, ClickedSave: {} })const TodoItemEvents = UiSchema.TaggedEnum({ Toggled: { done: Schema.Boolean } })
class SaveTodo extends Command.Service<SaveTodo>()( "todos/SaveTodo", { args: Todo, success: Schema.Void }) {}
const TodoItem = Component.define({ name: "TodoItem", props: Schema.Struct({ todo: Todo }), model: Schema.Struct({}), message: TodoItemMessage, events: TodoItemEvents}).make({ init: ($) => $.set({}), update: ($, message) => TodoItemMessage.match(message, { ClickedToggle: () => $.emit(TodoItemEvents.Toggled({ done: !$.props.todo.done })), // Nothing to report: the save ends in `Component.noop`. ClickedSave: () => $.run(SaveTodo.make($.props.todo).pipe(Command.asNoop)) }), // `h.isRunning` is true from `ClickedSave` until the save ends. view: (h) => h.el( "li", h.el("button").on("click", TodoItemMessage.ClickedToggle()).children(h.props.todo.done ? "[x]" : "[ ]"), h.el("span", h.props.todo.title), h.el("button").on("click", TodoItemMessage.ClickedSave()).children("save"), h.isRunning(SaveTodo) ? " saving" : "" )})Composition
Provides services to a component and everything below it, like
Effect.provide.
When to use
Use to give a component its Command Layers and feature implementations where the context they need lives: the page, the feature or the app. A test provides fakes the same way.
Details
It returns the same component, with R changed to Exclude<R, ROut> | RIn.
A Layer passed as a value is built once per Env plus Layer identity,
reference-counted, and shared between the instances that resolve from it;
{ local: true } or a function of props builds once per instance, at mount.
A memoised Layer inside a shared one is built once per Env too: every
provide that resolves from that Env, or from an Env below it, gets the same
instance, and the last of them to unmount closes it. Provides in sibling
Envs build their own, so a service built for one never sees the other's
dependencies. As with nested Effect.provide, a provide reuses what an Env
above it built even where an Env between them provides a different
dependency; Layer.fresh builds it again. A stateful service belongs to
the component that owns its lifetime, usually the root: provide it there,
and the provides below that name it get that instance.
An array of Layers is merged once with Layer.mergeAll, so the elements
don't see each other. Nothing is rebuilt when props change: re-key instead.
Nested provides let the inner one win, and the inner one can use the outer
one's services.
A keyed provide, { key, layer }, selects the Layer again whenever the key
changes, and a key change remounts everything below the component. key
reads props and the Model, and layer gets only the key: anything the Layer
needs goes in the key. The key is read once per flush, before the view of an
instance whose Model or props changed, and compared with Equal.equals, so
an update that leaves it equal calls nothing and builds nothing. On a change
the component keeps its Model. Its in-flight Commands are interrupted, its
Subscriptions and queries restart, and its query results go back to their
initial value. The Commands issued in the flush that changed the key run
against the new services. The previous selection is released once the new
one has built, and a selection still building is interrupted.
By default, a key change leaves the query cache intact. Queries with unchanged
args can reuse results fetched under the previous selection. If query data
depends on the selection, include it in the query args or supply Query.layer()
through the keyed provide. With Query.layer(), a key change disposes the old
cache, interrupts its in-flight fetches, and gives the component and its
descendants a new, empty cache. During server rendering, queries use the
request's cache.
A failed build goes to onFailure or fails the instance, as at mount, with
no fallback to the previous selection. The Commands waiting for that build
are interrupted. A later key change builds again; an unchanged key doesn't
retry. Until then, a newly issued Command runs against the parent's
services, as after a failure at mount, so one that needs a selected service
fails the instance. Every Subscription and query on the instance waits for
the next selection, those that use only the parent's services included: work
that must keep running goes on a component above the provide.
A keyed provide builds per instance and turns off sharing for every provide
on the component: share between instances with a LayerMap. On the server
the key is read from init's Model; the client reads it from the Model it
hydrates or restores.
Builds run in the background: the component renders from init at once and
its Commands and Subscriptions wait for the Layer. onFailure is required
when a provided Layer can fail, and the curried form can't take it.
On the server, provided Layers are built under the render's budget. A Layer
that is always asynchronous there, such as a live connection, takes
{ server: false }: the server never builds it and renders the component
like one whose Layer missed the budget, and the client builds the instance
fresh.
Signature
declare const provide: { <Props, L extends Layer<never, never, any>>(layer: (props: Props) => L): <C extends Members<Props, any, any, never>>(component: C) => Provided<C, CommonSuccess<L>, AnyServices<L>>; <Props, Model, K, L extends Layer<never, never, any>>(keyed: ProvideKeyed<Props, Model, K, L>, options?: { readonly local?: never; readonly server?: false; }): <C extends Members<Props, any, any, never>>(component: C & KeyTakes<C, Model>) => Provided<C, CommonSuccess<L>, AnyServices<L>>; <L extends Any | readonly Array<Any>>(layer: L & CurriedCantFail<L>, options?: LocalOption): <C extends Any>(component: C) => Provided<C, Success<L>, Services<L>>; <C extends Any, L extends Layer<never, never, any>>(component: C, layer: (props: Props<C>) => L): Provided<C, CommonSuccess<L>, AnyServices<L>>; <C extends Any, L extends Layer<never, any, any>, M = never>(component: C & ErasedMessage<C, M>, layer: (props: Props<C>) => L, options: ProvideOptions<AnyError<L>, ProvideMessage<C, M>>): Provided<C, CommonSuccess<L>, AnyServices<L>>; <C extends Any, K, L extends Layer<never, any, any>, M = never>(component: C & ErasedMessage<C, M>, keyed: ProvideKeyed<Props<C>, Model<C>, K, L>, ...options: KeyedRest<AnyError<L>, ProvideMessage<C, M>>): Provided<C, CommonSuccess<L>, AnyServices<L>>; <C extends Any, L extends Any | readonly Array<Any>, M = never, F = unknown>(component: C & ErasedHandler<C, M, NoInfer<F>, Error<L>>, layer: L, ...options: ProvideRest<L, ProvideMessage<C, M>, F>): Provided<C, Success<L>, Services<L>>; <C extends Any, L extends Any | readonly Array<Any>>(component: C, layer: L & RequiresOnFailure<L>): Provided<C, Success<L>, Services<L>>;}Example Sharing Command Layers across rows, and a per-instance store
import { Command, Component, UiSchema } from "effect/ui"import { Context, Effect, Layer, Schema } from "effect"
const RowMessage = UiSchema.TaggedEnum({ ClickedSave: {} })
class SaveTodo extends Command.Service<SaveTodo>()( "todos/SaveTodo", { args: { id: Schema.String }, success: Schema.Void }) { static readonly layer = this.toLayer(() => Effect.void)}
class EditorStore extends Context.Service<EditorStore, { readonly draft: string }>()("EditorStore") { static readonly layer = Layer.succeed(EditorStore, { draft: "" })}
const Row = Component.define({ name: "Row", props: Schema.Struct({ id: Schema.String }), model: Schema.Struct({}), message: RowMessage}).make({ init: () => ({}), update: ($, message) => RowMessage.match(message, { ClickedSave: () => $.run(SaveTodo.make({ id: $.props.id }).pipe(Command.asNoop)) }), view: (h) => h.el("li", h.props.id)})
const RowLive = Component.provide(Row, [SaveTodo.layer]) // shared per Envconst Editor = Component.provide(Row, EditorStore.layer, { local: true }) // per instanceExample A room switcher selecting its services by a Model field
import { Command, Component, UiSchema } from "effect/ui"import { Context, Effect, Layer, LayerMap, Schema } from "effect"
class Chat extends Context.Service<Chat, { readonly room: string }>()("Chat") {}
class Rooms extends LayerMap.Service<Rooms>()("Rooms", { lookup: (room: string) => Layer.succeed(Chat, { room })}) {}
const RoomMessage = UiSchema.TaggedEnum({ SelectedRoom: { room: Schema.String }, CompletedJoinRoom: { room: Schema.String }})
class JoinRoom extends Command.Service<JoinRoom>()( "rooms/JoinRoom", { args: {}, success: RoomMessage }) { static readonly layer = this.toLayer( Chat.useSync((chat) => () => Effect.succeed(RoomMessage.CompletedJoinRoom({ room: chat.room }))) )}
const RoomView = Component.define({ name: "RoomView", model: Schema.Struct({ room: Schema.String, joined: Schema.String }), message: RoomMessage}).make({ init: ($) => $.set({ room: "lobby", joined: "" }).run(JoinRoom.make()), update: ($, message) => RoomMessage.match(message, { // Selects the new room's Layer: JoinRoom runs against it. SelectedRoom: ({ room }) => $.evolve({ room }).run(JoinRoom.make()), CompletedJoinRoom: ({ room }) => $.evolve({ joined: room }) }), view: (h, model) => h.el("p", model.joined)})
// Requires `Rooms`, provided above, so the rooms outlive a switch.const Room = Component.provide(RoomView, { key: (_, model) => model.room, layer: (room) => JoinRoom.layer.pipe(Layer.provideMerge(Rooms.get(room)))})Constructors
Binds one child to the component whose children returns it, under the
entry's name. Its view places it with h.children.name().
When to use
Use when a child's state must outlive the view leaving it out: a tab, a
wizard step or panel with background work. A child declared in the view
with Child(h, { ... }) unmounts once a render leaves it out, and its
Model goes with it. Declare every other child in the view.
Details
component is a component with a view, a Component.lazy or a feature
service. A headless component can't be bound. options are those of a
call in the view, key, props, onEmit and onFailure, typed
against the binding component's message. fallback and slots belong to
each placement: h.children.name({ fallback, slots }).
A bound child lives while its parent lives and its entry resolves to the
same component and key. Changing a keyed ancestor Layer also restarts it.
An entry that becomes undefined, null or false ends it, and one
with a changed key starts it over. Its props and onEmit are the entry's
latest, whether or not the view places it.
While no view places it, it keeps its Model, query results, Subscriptions and Commands in flight. Its view does not run, its host nodes are removed, and its view-scoped descendants unmount. Scroll position, focus and uncontrolled input text are lost; text stored in the Model survives. To retain host nodes, keep the child placed inside a hidden element. Hiding does not guarantee focus restoration.
Moving a placement in the same flush keeps its Model and reuses its nodes where the host supports the move. A move requiring a different HTML/SVG namespace rebuilds the affected nodes. On React Native, moving between native parents recreates the native subtree, losing focus, scroll position and uncontrolled input text. Reordering within the same native parent preserves its native views.
Placing one child twice in one render fails the parent. The child resolves
shared reads and Layers from its parent, not from where it's placed. A
lazy child starts loading when it's bound, and a feature child waits for
its Layer: until then a placement shows its fallback. Its requirements
join the parent's, since it runs whether or not the view places it.
Signature
declare const child: <C extends Bindable, Msg = never, Tags extends HandlerTag<Bind<C>["e"]> = never>(component: C, ...options: {} extends Bind<C>["p"] ? [options?: ChildOptions<Bind<C>["p"], Bind<C>["e"], Msg, Tags>] : [options: ChildOptions<Bind<C>["p"], Bind<C>["e"], Msg, Tags>]) => BoundOf<C, Msg>Example Keep a preview's Model while its view is absent
import { Component, UiSchema } from "effect/ui"import { Html } from "effect/ui/html"import { Schema } from "effect"
declare const Preview: Component.Mountable<{ readonly url: string }, { readonly _tag: "Closed" }>
const PageMessage = UiSchema.TaggedEnum({ ClickedToggle: {}, ClosedPreview: {} })
export const Page = Html.component({ name: "Page", model: Schema.Struct({ url: Schema.NullOr(Schema.String), shown: Schema.Boolean }), message: PageMessage, children: ($) => ({ preview: $.model.url !== null && Component.child(Preview, { props: { url: $.model.url }, onEmit: { Closed: () => PageMessage.ClosedPreview() } }) })}).make({ init: () => ({ url: null, shown: true }), update: { ClickedToggle: ($) => ({ ...$.model, shown: !$.model.shown }), ClosedPreview: ($) => ({ ...$.model, url: null }) }, view: (h, model) => h.div( h.button.on("click", PageMessage.ClickedToggle()).children("Toggle"), model.shown && h.children.preview({ fallback: () => h.p("Loadingโฆ") }) )})Binds a child at each of keys to the component whose children returns
it, under the entry's name. Its view places one with
h.children.name(key).
When to use
Use when a set of children must outlive the view leaving them out, such as the open documents of an editor's tabs, where only the active one is shown.
Details
Each key binds one child with the lifetime and placement rules of
Component.child. Removing a key ends its child; changing the component
starts it over. props, onEmit and onFailure get the child's key.
A placer called with a key that isn't bound returns null.
Signature
declare const childMany: <C extends Bindable, Msg = never, Tags extends HandlerTag<Bind<C>["e"]> = never>(component: C, options: ChildManyOptions<Bind<C>["p"], Bind<C>["e"], Msg, Tags>) => BoundManyOf<C, Msg>Example Editor tabs that keep each document's state
import { Component } from "effect/ui"
declare const NoteEditor: Component.Mountable<{ readonly note: string }, { readonly _tag: "Saved" }>declare const open: Readonly<Record<string, string>>
// In `children`:const editors = Component.childMany(NoteEditor, { keys: Object.keys(open), props: (key) => ({ note: open[key]! }), onEmit: (_event, key) => ({ _tag: "Saved" as const, id: key })})// In the view: h.children.editors(active, { fallback: () => h.p("Loadingโฆ") })Defines a component, in two steps. define takes the name, the Schemas,
queries and elements, and make on the definition it returns takes
init, update, view, subscriptions and head.
Details
The first step holds what nothing is inferred from, so update functions
and views written outside the component are typed against the definition.
Typing them against typeof the component would be circular, because the
component's requirements are read off what update returns. queries
types $.queries and h.queries, and elements the tags on h, so both
belong to the first step. A definition is named with a Def suffix and
usually stays unexported. A component written in one piece chains the two
steps.
init and update get $ first, a step holding the current Model and
props, and update the message after it. view gets h first, bound to
the component's message type and carrying the props, with the component's
element vocabulary mixed in, and the Model after it. A view that
reads only props takes h alone. The whole return type of init, update
and view is inferred and R is read off it, so R covers every branch,
including conditional views. Framework services such as Scope are never
part of R.
The component keeps what define returned as its definition, so the
name option is read back as Component.definition.name. Paths, messages
and the message log use it. A component is a function, so its own name
is the function's and doesn't carry it.
props and events are optional. subscriptions, head and a query's
args each get one object: { model, props, queries }. subscriptions
returns keyed Streams run while their key is listed, and falsy entries are
skipped. Two entries with one key fail the instance. elements supplies
an element vocabulary for this component; without it, h is host-neutral
(el and text). For HTML or OpenTUI components, prefer Html.component
or OpenTui.component.
queries declares the queries the component shows, by name. Each entry is
{ query: Q, args } for one query, a list of pages when Q is a
Query.InfiniteService, or { queryMany: Q, args } for one query at many
args. args gets the Model, the props and the other queries' results,
and returns the query's args, undefined to disable it, or for
queryMany an array of args. The runtime watches each query at those args
and keeps what it last returned as the query's result, beside the Model:
the Model plus the results is an instance's state. A result that changes
re-renders the instance. h.queries, $.queries in update, and
queries in head and subscriptions open the results, by
query name. Each query is added to R.
An entry's debounce delays a fetch for changed args by a
Duration.Input on the Clock. Only a fetch waits: the first args at
mount, the server render, args whose cache entry is fresh or already being
fetched, and a change to undefined go through at once. Args that change
again restart the wait. A queryMany query's new keys wait each on their
own.
When an entry's args change, the old args' fetch is interrupted unless
another watch, even one starting in the same update, a get or a prefetch
still needs it. A fetch in flight at unmount runs on and fills the cache.
When an enabled query entry's args change, it keeps the last Success
with waiting: true until the new args have a result, including during
debounce. $.queries, head and subscriptions see the same result.
A kept infinite list reports more: Loading. Without a stored Success,
the result is Initial, waiting. A disabled query is Initial, not
waiting. Set dropPrevious: true on the entry to show Initial instead
when old results would mislead.
An entry's onChange returns a message for update, or undefined to
skip dispatch without calling update or logging an Update. The callback
runs when a result is written, not when the args alone change. A query
entry's callback gets its result as h.queries opens it; a queryMany
entry's callback gets its entries
and the keys whose result changed. The result is written first, and the
message's update sees it in $.queries.
An entry's restore: false keeps its result out of history, for a large
result such as a table. On Back the query reads the cache or fetches, as on
a fresh mount, so its onChange runs again. Server page state still holds
the result, and so can history if the user leaves before hydration decodes it.
head returns the instance's head entries, typed by the component's
vocabulary: Head.title, Head.titleTemplate and Head.reduce on any
vocabulary, and HtmlHead's on Html. It's a pure function of the
Model, the props and the queries' results, like a view. On every flush that
changed a view, the runtime folds the head of the placed tree, a child's
fallback content included, with the root vocabulary's merge (see
Head). A Head.reduce or HtmlHead.reduce entry maps the folded
head of the instance and everything its view placed: a layout derives an
og:title from the title that won, say. The root's result is final.
update is a function over the whole message type, or a record with a
function for every _tag of the message, which gets a $ for that tag's
member and the member. The record has no default key, so a component that wants a
catch-all uses the function form. Def.update(tag, f) is a slice for one
tag, and Def.update(f) or Def.update(record) an update function over the
whole message type.
$.combine runs update functions one after another. Def.view(f) is a
view, and Def.fragment(f) a view fragment that takes h and any other
arguments, such as a row.
slots names the places a parent can fill with markup. The parent passes
slots: { name: content } when it declares the child, written with its own
h, and the view places each one with h.slots.<name>, once per render.
The content belongs to the parent: its handlers send the parent's
messages, its children's events and failures map to them, and it
resolves services where the parent declared the child. A parent's re-render patches only the content,
without running the child's view. Content the view doesn't place is not
mounted, and a slot placed again starts over. A definition with slots
finishes with view, not parts.
Gotchas
An instance whose model Schema, or a query's success, error or args
Schema, holds a Schema.Redacted anywhere never has its state written as
JSON. The server defers it and its subtree to the client, and logs a
warning once per component, and the Router keeps no history entry for it.
Keep a secret in a leaf component, or in a service, so the rest of the
page still hydrates and restores. When only history is the concern, clear
the field with restore instead: the server still sends it.
Signature
declare function define<Name extends string, Model, Msg, Props = {}, Events = never, S = {}, M = {}, L = QueryEntries<S, M>, V extends Elements = never, Tags extends string = never, Sl extends string = never, SR extends SharedReads = SharedReads, SO extends { [name: string]: "self" | Owner | Any;} = {}, SOpt = {}, SV = never, Rp = never, SA = SelfAbove<SV>, SK = never, Rc = Rp, Ch = {}>(options: DefineOptions<Name, Model, Msg, Props, Events, S, M, L, Tags, Sl, SR, SO, SOpt, SV, Rp, SA, SK, Rc, Ch> & { readonly elements?: Vocabulary<V>;}): Defined<Name, Props, Model, Msg, Events, V, L, Tags, Sl, SR, SV, Rp, SK, Ch>Example A counter
import { Component, UiSchema } from "effect/ui"import { Schema } from "effect"
const CounterMessage = UiSchema.TaggedEnum({ ClickedIncrement: {}, ClickedDecrement: {} })
const Counter = Component.define({ name: "Counter", props: Schema.Struct({ initial: Schema.Number }), model: Schema.Struct({ count: Schema.Number }), message: CounterMessage}).make({ init: ($) => ({ count: $.props.initial }), update: ($, message) => CounterMessage.match(message, { ClickedIncrement: () => ({ count: $.model.count + 1 }), ClickedDecrement: () => ({ count: $.model.count - 1 }) }), view: (h, model) => h.el( "div", h.el("button").on("click", CounterMessage.ClickedDecrement()).children("-"), h.el("span", String(model.count)), h.el("button").on("click", CounterMessage.ClickedIncrement()).children("+") )})Example A page that loads its user, and the user's team
import { Component, Query } from "effect/ui"import { Schema } from "effect"import { AsyncResult } from "effect/reactivity"
class GetUser extends Query.Service<GetUser>()("GetUser", { args: { id: Schema.String }, success: Schema.Struct({ name: Schema.String, teamId: Schema.String }), error: Schema.Never, staleTime: "1 minute"}) {}
class GetTeam extends Query.Service<GetTeam>()("GetTeam", { args: { id: Schema.String }, success: Schema.Struct({ title: Schema.String }), error: Schema.Never, staleTime: "1 minute"}) {}
const UserPage = Component.define({ name: "UserPage", props: Schema.Struct({ id: Schema.String }), model: Schema.Struct({}), message: Schema.Never, queries: { user: { query: GetUser, args: ({ props }) => ({ id: props.id }) }, // Disabled until the user has loaded. team: { query: GetTeam, args: ({ queries }) => AsyncResult.isSuccess(queries.user) ? { id: queries.user.value.teamId } : undefined } }}).make({ init: () => ({}), update: ($) => $.model, view: (h) => AsyncResult.match(h.queries.user, { onInitial: () => h.el("p", "Loadingโฆ"), onFailure: () => h.el("p", "No such user"), onSuccess: ({ value }) => h.el("p", value.name, AsyncResult.isSuccess(h.queries.team) ? ` of ${h.queries.team.value.title}` : "") })})Example A note page whose update is split into slices
import { Component, UiSchema } from "effect/ui"import { Schema } from "effect"
const NotePageMessage = UiSchema.TaggedEnum({ UpdatedBody: { body: Schema.String }, ClickedSave: {} })
const NotePageDef = Component.define({ name: "NotePage", model: Schema.Struct({ body: Schema.String, edits: Schema.Number, error: Schema.NullOr(Schema.String) }), message: NotePageMessage})
// Over the whole message type, so `$.combine` takes them.const touch = NotePageDef.update(($) => $.evolve({ edits: (edits) => edits + 1 }))const validate = NotePageDef.update(($) => $.evolve({ error: $.model.body === "" ? "Empty" : null }))
// `msg` is the UpdatedBody message.const handleUpdatedBody = NotePageDef.update("UpdatedBody", ($, msg) => $.combine(($) => $.evolve({ body: msg.body }), touch))
// `h` first, then any other arguments.const counter = NotePageDef.fragment((h, edits: number) => h.el("small", `${edits} edits`))
const noteView = NotePageDef.view((h, model) => h.el("div", h.el("p", model.body), counter(h, model.edits)))
export const NotePage = NotePageDef.make({ init: () => ({ body: "", edits: 0, error: null }), update: { UpdatedBody: handleUpdatedBody, ClickedSave: ($) => $.combine(validate) }, view: noteView})Example A card whose title and body its parent fills
import { Component } from "effect/ui"import { Schema } from "effect"
const Card = Component.define({ name: "Card", model: Schema.Boolean, message: Schema.Literal("ClickedToggle"), slots: ["title", "body"]}).make({ init: () => true, update: ($) => !$.model, view: (h, open) => h.el("section", h.el("h2", h.slots.title), h.el("button").on("click", "ClickedToggle"), open && h.slots.body)})
export const Page = Component.define({ name: "Page", model: Schema.Number, message: Schema.Literal("ClickedLike")}).make({ init: () => 0, update: ($) => $.model + 1, // The button is the page's, so a click sends the page's `ClickedLike`. view: (h, likes) => Card(h, { key: "card", slots: { title: "Likes", body: h.el("button").on("click", "ClickedLike").children(`${likes} likes`) } })})Declares a component whose module is loaded the first time one of its children is rendered, so a bundler such as Vite puts it in a chunk of its own.
When to use
Use when most visits never show a page or a panel, so its code, and the code only it imports, stays out of the initial load.
Details
load returns the component, usually from import(). The props,
events, slots, requirements and queries are read from its type, which
TypeScript erases, so the module is imported only when load runs. Nothing
else in the app may import the module statically, or the bundler keeps it in the
importing chunk.
name stands in for the component's name in its children's paths, since
the paths are needed before the module arrives. It's the name a Scene
error or a log entry shows for the child.
The first child rendered starts the load, which happens once per app. Until
it ends, the child shows its fallback, passed Initial, and the
parent's other content renders as usual. A child rendered after the module
loaded mounts at once, with no fallback. A load that fails shows the
fallback's Failure branch, and the next child that mounts loads again.
onFailure hears a failure of the child, not of the load. preload
starts the load without rendering, and TestHost.settle waits for a load
in flight.
A lazy component bound with Component.child or Component.childMany
starts loading when it's bound, whether or not the view places it. A
placement shows its fallback until the module has loaded.
Provide the services that only the loaded component uses with
Component.provide inside its module, so their Layers go into its chunk.
Its requirements that the module doesn't provide surface in the parent's.
Gotchas
loadmust resolve to a component that isn't headless. Any other value fails the load, as does aloadthat throws.- The server waits for the load and renders the component. During
hydration, a child the server rendered keeps its server nodes, with no
listeners yet, while the module loads, then adopts them without showing
the fallback.
root.adoptedwaits for the load. - A browser may keep a failed chunk request in its module map and fail
every later load of it without a request. Reloading the page recovers:
Vite reports such a failure with the
vite:preloadErrorevent.
Signature
declare const lazy: <C extends Mountable.Any>(name: string, load: () => Promise<C>) => Lazy<LazyProps<C>, Events<C>, Requirements<C>, Slots<C>, LazyQueries<C>>Example A page loaded on its first visit
import { Component } from "effect/ui"
const SettingsPage = Component.lazy( "SettingsPage", () => import("./pages/SettingsPage.ts").then((module) => module.SettingsPage))
// In the parent's view, called as the component would be:// SettingsPage(h, {// props: { user },// onEmit: { Saved: () => AppMessage.SavedSettings() },// fallback: (result) => h.p.children(result._tag === "Failure" ? "Couldn't load settings." : "Loadingโฆ")// })The message value that sends nothing.
When to use
Use as the result of a Command body, a Command.map mapper, a
Command.match branch or an onMount Effect when there's nothing to tell
the component, instead of adding a no-op variant to its Message. Command.asNoop is
shorthand for Command.as(Component.noop).
Details
A frozen object whose only property is its type id. The runtime recognises
it with Component.isNoop, by the type id and not by identity, so two
copies of effect in one bundle agree on it. When the final result of a
Command run, after every mapper, or of a mount is Component.noop, the
runtime sends nothing and logs no Update, and CommandEnded records the
run as silent. $.run takes a Command whose result is the Message,
Component.Noop or a union of the two, so a component whose Message is
Schema.Never can run one.
Gotchas
It's a message value, not a Command: $.run(Component.noop) doesn't
compile. Test for it with Component.isNoop, never ===: the runtime
doesn't compare by identity, and !== doesn't narrow a union. View
handlers keep undefined for "no message".
Signature
declare const noop: NoopExample Silent on success, a message on failure
import { Command, Component, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ FailedDeleteKey: { reason: Schema.String } })
const DeleteKey = Command.make("DeleteKey", { args: { key: Schema.String } }, ({ key }) => (key === "" ? Effect.fail("empty key") : Effect.void).pipe( Effect.as(Component.noop), Effect.catch((reason) => Effect.succeed(Message.FailedDeleteKey({ reason }))) ))withElements
unstableBinds an element vocabulary into a component constructor, as
Html.component and OpenTui.component do. Each call is
Component.define({ ...options, elements }).
Signature
declare function withElements<V extends Elements>(elements: Vocabulary<V>): Define<V>Example A host's component constructor
import { Component } from "effect/ui"import { Html } from "effect/ui/html"
export const component: Component.Define<Html.Elements> = Component.withElements(Html.vocabulary)Guards
isComponent
unstableReturns true if u is a component.
Signature
declare function isComponent(u: unknown): u is Mountable<any, any, any, never>isHeadless
unstableWhether a value is a headless component.
Signature
declare function isHeadless(u: unknown): u is AnyReturns true if u is a lazy component.
Signature
declare const isLazy: (u: unknown) => u is Lazy.AnyTells whether a value is Component.noop, by its type id.
When to use
Use to narrow a result typed A | Component.Noop, such as in a mapper over
a Command that can be silent. === Component.noop doesn't narrow the
other branch, and misses a copy of the value made by another copy of
effect.
Signature
declare const isNoop: (u: unknown) => u is NoopReturns true if u is a step.
Signature
declare function isStep(u: unknown): u is InitStep<unknown, unknown, unknown, unknown>Models
Any component.
Signature
type Any = Mountable<any, any, any>One child bound with Component.child: what an entry of children holds.
Msg is what its onEmit and onFailure send, R what it requires,
Sl its slots, and Result what a placement's fallback is passed.
Signature
interface Bound<out Msg, out R = never, in Sl extends string = never, out Result = AsyncResult.Failure<never, unknown>> { readonly "~Bound"?: Variance<Msg, R, Sl, Result>; readonly "~many": false;}Children bound with Component.childMany, one per key: what an entry of
children holds.
Signature
interface BoundMany<out Msg, out R = never, in Sl extends string = never, out Result = AsyncResult.Failure<never, unknown>> { readonly "~Bound"?: Variance<Msg, R, Sl, Result>; readonly "~many": true;}The options of childMany: the keys to bind, and the props, onEmit and
onFailure of each child, which get its key.
Signature
type ChildManyOptions<Props, Events, Msg, Tags extends string = never> = { readonly keys: Iterable<string>; readonly onEmit?: (event: Events, key: string) => Msg | undefined | BoundEmitHandlers<Events, Msg, Tags, [key: string]>; readonly onFailure?: (failure: AsyncResult.Failure<never, unknown>, key: string) => Msg | undefined;} & {} extends Props ? { readonly props?: (key: string) => Props;} : { readonly props: (key: string) => Props;}Options for Component.child. fallback and slots belong to each
placement instead.
Signature
type ChildOptions<Props, Events, Msg, Tags extends string = never> = { readonly key?: string; readonly onEmit?: (event: Events) => Msg | undefined | BoundEmitHandlers<Events, Msg, Tags, []>; readonly onFailure?: (failure: AsyncResult.Failure<never, unknown>) => Msg | undefined;} & {} extends Props ? { readonly props?: Props;} : { readonly props: Props;}A component definition.
Signature
interface Component<out Name extends string, in out Props, in out Model, in out Msg, out Events, out R = never, out V extends View.Elements = never, out L = {}, in Sl extends string = never> extends Members<Name, Props, Model, Msg, Events, R, V, L, Sl>, Call<Props, Events, R, Sl> { <Msg, RF = never, SC extends object = never>(h: HelperBase<Msg, unknown>, options: { readonly key?: string; readonly onEmit?: (events: Events) => NoInfer<Msg> | undefined | EmitHandlers<Events, NoInfer<Msg>>; readonly onFailure?: (failure: Failure<never, unknown>) => NoInfer<Msg> | undefined; } & {} extends Props ? { readonly props?: Props; } : { readonly props: Props; } & { readonly fallback?: (result: Failure) => Content<NoInfer<Msg>, RF>; } & SlotOptions<Sl, SC, NoInfer<Msg>> & 0 extends 1 & Props ? { readonly props: Props; } : {}): Child<Msg, R | NoInfer<RF> | SlotRequirements<SC>>;}What p.child returns: a headless child the component owns, with the
parts the consumer gets inside it. make unwraps it, so the component's
parts are Parts.
Signature
interface Composed<out Parts, out R = never, out Sh = never> { readonly "~effect/ui/Component/Composed": { readonly _Parts: Covariant<Parts>; readonly _R: Covariant<R>; readonly _Sh: Covariant<Sh>; };}What subscriptions, head and a query's args are asked with: the
current Model, props and query results of the instance. A query's args
gets the results of the other queries.
Signature
interface Current<out Model, out Props, out Queries> { readonly model: Model; readonly props: Props; readonly queries: Queries;}The call signature of a vocabulary-bound component constructor such as
Html.component or OpenTui.component, supplying vocabulary V
automatically to Component.define. Component.withElements makes one.
Signature
interface Define<V extends View.Elements> { <Name extends string, Props, Model, Msg, Events, R, L, Sl extends string, SR, HMsg = never, HModel = {}, Ch = {}>(logic: Logic<Name, Props, Model, Msg, Events, R, L, Sl, SR, Ch>, extra?: { readonly message?: Codec<HMsg, any, never, never>; readonly model?: Codec<HModel, any, never, never> & { readonly ast: Objects; readonly fields: Fields; } & NewFields<HModel, Model>; }): Hosted<Name, Props, [keyof HModel] extends [never] ? Model : Model & HModel, Msg | HMsg, Events, R, V, L, Sl, SR, HModel, HMsg, Ch>; <Name extends string, Model, Msg, Props = {}, Events = never, S = {}, M = {}, L = QueryEntries<S, M>, Tags extends string = never, Sl extends string = never, SR extends SharedReads = SharedReads, SO extends { [name: string]: "self" | Owner | Any; } = {}, SOpt = {}, SV = never, Rp = never, SA = SelfAbove<SV>, SK = never, Rc = Rp, Ch = {}>(options: DefineOptions<Name, Model, Msg, Props, Events, S, M, L, Tags, Sl, SR, SO, SOpt, SV, Rp, SA, SK, Rc, Ch>): Defined<Name, Props, Model, Msg, Events, V, L, Tags, Sl, SR, SV, Rp, SK, Ch>;}Options accepted by Component.define (minus elements) and by
vocabulary-bound component constructors typed with Define.
Signature
interface DefineOptions<Name extends string, Model, Msg, Props, Events, S, M, L, Tags extends TagOf<Msg>, Sl extends string, SR extends SharedReads, SO extends { [name: string]: "self" | Owner | Any;}, SOpt, SV, Rp, SA = SelfAbove<SV>, SK = never, Rc = Rp, Ch = {}> { readonly children?: ($: Current<Model, Props, QueryResults<NoInfer<L>>>) => Ch & { [K in string | number | symbol]: Entry<NoInfer<Msg>> }; readonly events?: Codec<Events, any, never, never>; readonly message: Codec<Msg, any>; readonly model: Codec<Model, any>; readonly name: Name; readonly props?: Codec<Props, any, never, never>; readonly queries?: { [K in string | number | symbol]: { readonly args: ($: Current<Model, Props, { [P in string | number | symbol]: QueryResultOf<NoInfer<...>[P]> }> & { readonly reads: SharesReads<NoInfer<SO>, NoInfer<SOpt>, NoInfer<SA>>; }) => ArgsFor<S[K], M[K & keyof M]>; readonly debounce?: Input; readonly dropPrevious?: DropPrevious<M[K & keyof M]>; readonly onChange?: OnChange<S[K], M[K & keyof M], NoInfer<Msg>>; readonly query?: S[K] & OneQuery<M[K & keyof M]>; readonly restore?: false; } } & { [K in string | number | symbol]: { readonly queryMany?: M[K] & ManyQuery<M[K]>; } }; readonly reads?: SR & { [K in string | number | symbol]: SOpt[K] & Owner | { readonly optional?: SOpt[K]; readonly owner: unknown; } } & { [K in string | number | symbol]: SharedEntry<SOpt[K & keyof SOpt], SO[K], Model, Props, NoInfer<Msg>, NoInfer<SV>, NoInfer<Rp>> } & NoInfer<OwnersOnly<SO>>; readonly restore?: false | (model: Model, props: Props) => NoInfer<Model>; readonly shares?: SharesValue<Model, Props, SO, SOpt, SA, SV, never> | { readonly collects?: { readonly onChange?: (collected: readonly Array<NoInfer<Rp>>) => NoInfer<Msg>; readonly schema: Codec<Rp, any>; }; readonly key?: SK & NoInfer<SharedKey<Name, SV, Extract<Msg, { readonly _tag: Tags; }>, Rp, Shared<Name>>>; readonly receives?: readonly Array<Tags>; readonly schema?: Codec<SV, any, never, never>; readonly value: SharesValue<Model, Props, SO, SOpt, SA, SV, Rc>; }; readonly slots?: readonly Array<Sl>;}What define returns: a component's name, Schemas, queries and
vocabulary. init, update, subscriptions, view and fragment
written in pieces are typed against it, and make finishes the component.
Details
update with a tag returns a slice for that tag. Without one, it takes a
function over the whole message type, or a record with a handler for every
_tag of a tagged message, and returns an update function over that type.
A slice or an update function fits the matching key of a record update,
and $.combine takes either where the message fits. A record key that
isn't a message tag is a type error. init, subscriptions, view and
fragment return the function they're given.
make takes init, update, view, subscriptions and head,
and reads R off what they return.
Signature
interface Definition<Name extends string, Props, Model, Msg, Events, V extends View.Elements, L, Rcv = never, Sl extends string = never, SR = {}, SV = never, Rp = never, K = never, Ch = {}> { readonly children: ($: Current<Model, Props, QueryResults<L>>) => Ch | undefined; readonly collects: SharesCollects<Msg, Rp> | undefined; readonly elements: Vocabulary<V> | undefined; readonly events: Codec<Events, any>; readonly message: Codec<Msg, any>; readonly model: Codec<Model, any>; readonly name: Name; readonly props: Codec<Props, any>; readonly queries: unknown; readonly reads: SR | undefined; readonly receives: Codec<Rcv, any>; readonly restore: false | (model: Model, props: Props) => Model | undefined; readonly sharedKey: Any | undefined; readonly shares: ($: { readonly model: Model; readonly props: Props; readonly reads: SharedValues<SR>; } & CollectedHelpers<Rp>) => SV | undefined; readonly sharesSchema: Codec<SV, any, never, never> | undefined; readonly slots: readonly Array<Sl>; fragment<Args extends readonly Array<unknown>, Out>(fragment: (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, ...args: Args) => Out): (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, ...args: Args) => Out; init<UI>(init: ($: Init<Model, Msg, Events, Props>) => UI): ($: Init<Model, Msg, Events, Props>) => UI; logic<UI = Model, U = Model, UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> } = { [T in string]: Model }, Sub extends Subscription<Msg, any> = never>(options: { readonly head?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<Entry>; readonly init: ($: Init<Model, Msg, Events, Props>) => UI; readonly subscriptions?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; readonly update: ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U | UpdateRecord<Model, Msg, Events, Props, L, SR, UR, Rp> & DispatchedByTag<Msg>; } & OwnersAreHeadless<SV>): Logic<Name, Props, Model, Msg, Events, Exclude<NamedRequirement<Exclude<RawStepRequirements<UI>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<U>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UR[keyof UR]>, OptionalTargets<SR>>>, FrameworkService> | Exclude<Requirements<Sub>, FrameworkService> | Exclude<QueryServices<L>, FrameworkService> | Exclude<SharedRequirements<SR>, FrameworkService> | Exclude<ChildRequirements<Ch>, FrameworkService>, L, Sl, SR, Ch>; make<Parts, UI = Model, U = Model, UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> } = { [T in string]: Model }, Sub extends Subscription<Msg, any> = never>(options: { readonly head?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<HeadEntry<V>>; readonly init: ($: Init<Model, Msg, Events, Props>) => UI; readonly parts: [Sl] extends [never] ? (p: PartsHelper<Msg, Props, V> & QueryHelpers<L> & SharedHelpers<SR> & CollectedHelpers<Rp>, model: Model) => Parts : never; readonly subscriptions?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; readonly update: ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U | UpdateRecord<Model, Msg, Events, Props, L, SR, UR, Rp>; } & SelfShares<SR, SV>): Headless<Props, Events, Parts<Parts>, Exclude<QueryServices<L>, FrameworkService> | Exclude<SharedRequirements<SR>, FrameworkService> | Exclude<ChildRequirements<Ch>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UI>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<U>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UR[keyof UR]>, OptionalTargets<SR>>>, FrameworkService> | Exclude<PartRequirements<Parts<Parts>[keyof Parts<Parts>]>, FrameworkService> | Exclude<Requirements<Parts>, FrameworkService> | Exclude<Requirements<Sub>, FrameworkService>, Rcv, [SV] extends [never] ? never : Shared<Name> | Shares<Parts>, SV, Rp, K, Model, Msg, L>; make<UI = Model, U = Model, UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> } = { [T in string]: Model }, Sub extends Subscription<Msg, any> = never>(options: { readonly head?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<HeadEntry<V>>; readonly init: ($: Init<Model, Msg, Events, Props>) => UI; readonly parts?: undefined; readonly subscriptions?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; readonly update: ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U | UpdateRecord<Model, Msg, Events, Props, L, SR, UR, Rp>; readonly view?: undefined; } & OnlyOwnersOmitParts<Sl, SV> & SelfShares<SR, SV>): Headless<Props, Events, {}, Exclude<QueryServices<L>, FrameworkService> | Exclude<SharedRequirements<SR>, FrameworkService> | Exclude<ChildRequirements<Ch>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UI>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<U>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UR[keyof UR]>, OptionalTargets<SR>>>, FrameworkService> | Exclude<Requirements<Sub>, FrameworkService>, Rcv, Shared<Name>, SV, Rp, K, Model, Msg, L>; make<UI = Model, U = Model, UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> } = { [T in string]: Model }, UV extends Content<Msg, any> = Node<Msg, never>, Sub extends Subscription<Msg, any> = never>(options: { readonly head?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<HeadEntry<V>>; readonly init: ($: Init<Model, Msg, Events, Props>) => UI; readonly subscriptions?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; readonly update: ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U | UpdateRecord<Model, Msg, Events, Props, L, SR, UR, Rp>; readonly view: (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, model: Model) => UV; } & OwnersAreHeadless<SV> & SelfShares<SR, SV>): Component<Name, Props, Model, Msg, Events, Exclude<QueryServices<L>, FrameworkService> | Exclude<SharedRequirements<SR>, FrameworkService> | Exclude<ChildRequirements<Ch>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UI>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<U>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UR[keyof UR]>, OptionalTargets<SR>>>, FrameworkService> | Exclude<Requirements<UV>, FrameworkService> | Exclude<Requirements<Sub>, FrameworkService>, V, L, Sl>; subscriptions<Sub extends Subscription<Msg, any>>(subscriptions: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>): ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; update<Tag extends string, U>(tag: Tag, update: ($: Update<Model, Msg, Events, Props, L, Extract<Msg, { readonly _tag: Tag; }>, SR, Rp>, msg: Extract<Msg, { readonly _tag: Tag; }>) => U): ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Extract<Msg, { readonly _tag: Tag; }>) => U; update<U>(update: ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U): ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => U; update<UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> }>(update: UpdateRecord<Model, Msg, Events, Props, L, SR, UR, Rp> & DispatchedByTag<Msg>): ($: Update<Model, Msg, Events, Props, L, Msg, SR, Rp>, msg: Msg) => UR[keyof UR]; view<UV extends Content<Msg, any>>(view: (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, model: Model) => UV): (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, model: Model) => UV;}A component with parts and no view. Whoever declares it, with
Listbox(h, { key, props, view }), writes its whole view from the parts.
Details
It keeps its own Model, update, Commands and Scope. It isn't a
Mountable, so it can't be a root, a page or a feature.
The view closure given to the call is the consumer's code. A child
declared in it, its onEmit and onFailure messages, and a fallback in
it all belong to the consumer. A closure that throws fails the headless
child, logged with the source content, and the child shows its fallback.
A part applied to an element adds a layer that the headless instance
owns. When the element's event fires, each layer's handler runs and its
message goes to its owner: the deepest headless owner first, and the
consumer last. A layer's preventDefault: true cancels the default only
when that layer's handler returned a message. preventDefault: "always"
from any layer wins, and two layers setting any other option of one event
fail the render that applies them. Handle keys on the part the user focuses, such as an
input or a trigger, rather than on a container around it.
A part's ref and mount belong to its owner: HtmlCommand.focus in the
headless update reaches its own ref, and the mount runs in a Scope of the
headless instance while the part stays applied to the element.
A headless component has no children of its own, except the ones its
parts declares with p.child to build on other headless components.
Those report to it and hold the consumer's closure
inside them: a Drawer built on a Dialog runs its consumer's closure at
Consumer/Drawer[]/Dialog[].
Parts need no runtime: Story.parts builds them from a Model and props
alone. p.id derives element ids from the instance's path, matching server
and client. When mounting the same root component twice in one document,
pass distinct key options to avoid collisions. Outside a mount, ids use
the component's own name.
Lists are data: a part reads its items from props, and takes an item as an argument where the consumer applies it. Richer row content stays in the consumer's closure, looked up by id.
A headless child renders again whenever its consumer does, since the
closure is part of the consumer's view, and its own update renders only
the closure. When the consumer renders often, wrap the headless child in a
small normal component of its own. Router.prefetch doesn't walk into
closures, so it never prefetches the queries of children declared there.
Signature
interface Headless<in out Props, out Events, out Parts, out R = never, in out Rcv = never, in Sh = never, in SV = never, in Rp = never, in K = never, out Model = unknown, out Msg = unknown, out L = {}> extends Pipeable { <Msg, RV = never, RF = never>(h: HelperBase<Msg, unknown>, options: { readonly key?: string; readonly onEmit?: (events: Events) => NoInfer<Msg> | undefined | EmitHandlers<Events, NoInfer<Msg>>; readonly onFailure?: (failure: Failure<never, unknown>) => NoInfer<Msg> | undefined; } & {} extends Props ? { readonly props?: Props; } : { readonly props: Props; } & { readonly fallback?: (result: Failure<never, unknown>) => Content<NoInfer<Msg>, RF>; readonly slots?: undefined; readonly view: (parts: Parts) => Content<NoInfer<Msg>, RV>; }): Child<Msg, R | Exclude<RV, Sh> | NoInfer<RF>>; readonly "~effect/ui/Component/Headless": { readonly _Events: Covariant<Events>; readonly _K: Contravariant<K>; readonly _Parts: Covariant<Parts>; readonly _Props: Invariant<Props>; readonly _R: Covariant<R>; readonly _Rcv: Invariant<Rcv>; readonly _Rp: Contravariant<Rp>; readonly _Sh: Contravariant<Sh>; readonly _SV: Contravariant<SV>; }; readonly "~L"?: L; readonly "~queries": unknown; readonly definition: Any; readonly elements: Vocabulary<any> | undefined; readonly events: Codec<Events, any>; readonly head: (model: any, props: Props, queries?: Results, shared?: SharedRecord | SharedLookup) => readonly Array<unknown> | undefined; readonly init: (props: Props) => Next<any, any, Events, R>; readonly message: Codec<Msg, any>; readonly model: Codec<Model, any>; readonly parts: (model: any, props: Props, context: PartsContext) => Parts | Composed<Parts, any, any>; readonly props: Codec<Props, any>; readonly receives: Codec<Rcv, any>; readonly subscriptions: (model: any, props: Props, queries?: Results, shared?: SharedRecord | SharedLookup) => readonly Array<Subscription<any, R>> | undefined; readonly update: (model: any, msg: never, props: Props, queries?: Results) => Next<any, any, Events, R>;}What a host's constructor returns for a Logic: make takes the host's
view, and what the host adds to the logic. Model and Msg are the
hosted component's, the logic's with the host's own fields and messages.
Details
update handles every host message and may handle shared messages after
the logic's handler, on the Model it returned. init returns only host Model
fields, and its Commands run after the logic's. subscriptions and head
are appended to the logic's. A message both Schemas accept goes to the
logic first. update is a function when a message has no _tag.
Signature
interface Hosted<Name extends string, Props, Model, Msg, Events, R, V extends View.Elements, L, Sl extends string, SR, HModel, HMsg, Ch = {}> { make<UI = HModel, U = Model, UR extends { [T in string]: Model | Step<Model, Msg, Events, any, L> } & { [T in string]: Model | Step<Model, Msg, Events, any, L> } = { [T in string]: Model } & { [T in string]: Model }, UV extends Content<Msg, any> = Content<Msg, any>, Sub extends Subscription<Msg, any> = never>(options: { readonly head?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<HeadEntry<V>>; readonly subscriptions?: ($: Current<Model, Props, QueryResults<L>>) => readonly Array<false | Sub | null | undefined>; readonly view: (h: ViewHelper<Props, Msg, V, L, Sl, SR, Ch>, model: Model) => UV; } & HostedOption<"init", [keyof HModel] extends [never] ? false : true, ($: Init<HModel, Msg, Events, Props>) => UI> & HostedOption<"update", [HMsg] extends [never] ? false : true, ($: UpdateBase<Model, Msg, Events, Props, L, Msg, SR>, msg: Msg) => U | UpdateRecord<Model, Msg, Events, Props, L, SR, UR, never> & DispatchedByTag<Msg>>): Component<Name, Props, Model, Msg, Events, R | Exclude<NamedRequirement<Exclude<RawStepRequirements<UI>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<U>, OptionalTargets<SR>>>, FrameworkService> | Exclude<NamedRequirement<Exclude<RawStepRequirements<UR[keyof UR]>, OptionalTargets<SR>>>, FrameworkService> | Exclude<Requirements<UV>, FrameworkService> | Exclude<Requirements<Sub>, FrameworkService>, V, L, Sl>;}An infinite query as h.queries opens it, inside its AsyncResult.
Details
items flattens the patched pages, keeping the first item for each
definition key. pages is the page array. more is Loading while a
load more runs or is queued, and Failed with the last load-more error.
Signature
interface InfiniteData<R extends Query.InfiniteQuery.Any> { readonly items: readonly Array<Item<R>>; readonly more: More<Error<R>>; readonly pages: readonly Array<Page<R>>;}$ in init: there's no Model yet, so set comes first.
Signature
interface Init<in out Model, in out Msg, in out Events, out Props> { readonly props: Props; set(model: Model): InitStep<Model, Msg, Events, never>;}What $.set in init returns: a step without loadMore and reset,
which init can't issue.
Signature
interface InitStep<in out Model, in out Msg, in out Events, out R = never> extends Pipeable { readonly "~effect/ui/Component/Step": "~effect/ui/Component/Step"; readonly commands: readonly Array<Command<Noop | Msg, R>>; readonly emitted: readonly Array<Events>; readonly model: Model; emit(...emitted: readonly Array<Events>): InitStep<Model, Msg, Events, R>; evolve(fields: EvolveFields<Model>): InitStep<Model, Msg, Events, R>; run<Self extends InitStep<Model, Msg, Events, unknown>, C extends readonly Array<Command<Noop | Msg, unknown>>>(this: Self, ...commands: C): InitStep<Model, Msg, Events, RawStepRequirements<Self> | Requirements<C[number]>>; set(model: Model): InitStep<Model, Msg, Events, R>;}One key of a queryMany query whose result changed, as its onChange
gets it.
Signature
interface KeyedChange<R extends Query.Query.Any> { readonly args: Args<R>; readonly result: AsyncResult<Success<R>, Error<R>>;}One entry of a queryMany query as h.queries opens it: the args from
the query, the opened result and whether the value includes an
unconfirmed patch.
Signature
interface KeyedEntry<R extends Query.Query.Any> { readonly args: Args<R>; readonly patched: boolean; readonly result: AsyncResult<Success<R>, Error<R>>;}A queryMany query as h.queries opens it: an entry per unique args the
query returns, in its order, and get to find one entry by its args.
Details
A key with no settled result opens as Initial, waiting. get is None
for args the query doesn't currently return. Entries carry no key: write
each row's .key(...) by hand.
Signature
interface KeyedResults<R extends Query.Query.Any> extends ReadonlyArray<KeyedEntry<R>> { [n: number]: KeyedEntry<R>; readonly get: (args: Args<R>) => Option<KeyedEntry<R>>;}A component whose module is loaded with a dynamic import(), as returned
by lazy. A parent declares it as it would the component: its props,
events, slots and requirements are the loaded component's. The first child
rendered starts loading the module. Its fallback is passed Initial
while the module loads, and Failure if the load or the child fails.
Details
L preserves the loaded component's queries for Router.page. It is
unknown when the component's type erases them.
Signature
interface Lazy<in out Props, out Events, out R = never, in Sl extends string = never, out L = unknown> extends Members<Props, Events, R, Sl, L>, Call<Props, Events, R, Sl, Lazy.Result> { <Msg, RF = never, SC extends object = never>(h: HelperBase<Msg, unknown>, options: { readonly key?: string; readonly onEmit?: (events: Events) => NoInfer<Msg> | undefined | EmitHandlers<Events, NoInfer<Msg>>; readonly onFailure?: (failure: Failure<never, unknown>) => NoInfer<Msg> | undefined; } & {} extends Props ? { readonly props?: Props; } : { readonly props: Props; } & { readonly fallback?: (result: Result) => Content<NoInfer<Msg>, RF>; } & SlotOptions<Sl, SC, NoInfer<Msg>> & 0 extends 1 & Props ? { readonly props: Props; } : {}): Child<Msg, R | NoInfer<RF> | SlotRequirements<SC>>;}A $.loadMore(name) or $.reset(name) an update issued, by query
name.
Signature
interface ListIssue { readonly name: string; readonly op: "loadMore" | "reset";}The local and server options of provide, for Layers that can't fail.
Signature
interface LocalOption { readonly local?: boolean; readonly server?: false;}A component with an empty view, returned by Definition.logic and testable
with Story. Add a host view with Html.component(logic),
Native.component(logic) or OpenTui.component(logic).
Signature
interface Logic<out Name extends string, in out Props, in out Model, in out Msg, out Events, out R = never, out L = {}, in Sl extends string = never, out SR = {}, out Ch = {}> extends Component<Name, Props, Model, Msg, Events, R, never, L, Sl> { <Msg, RF = never, SC extends object = never>(h: HelperBase<Msg, unknown>, options: { readonly key?: string; readonly onEmit?: (events: Events) => NoInfer<Msg> | undefined | EmitHandlers<Events, NoInfer<Msg>>; readonly onFailure?: (failure: Failure<never, unknown>) => NoInfer<Msg> | undefined; } & {} extends Props ? { readonly props?: Props; } : { readonly props: Props; } & { readonly fallback?: (result: Failure) => Content<NoInfer<Msg>, RF>; } & SlotOptions<Sl, SC, NoInfer<Msg>> & 0 extends 1 & Props ? { readonly props: Props; } : {}): Child<Msg, R | NoInfer<RF> | SlotRequirements<SC>>; readonly "~Ch"?: Ch; readonly "~logic": unknown; readonly "~SR"?: SR;}What a component has: a Component without its call signature.
Signature
interface Members<out Name extends string, in out Props, in out Model, in out Msg, out Events, out R = never, out V extends View.Elements = never, out L = {}, in Sl extends string = never> extends Members<Props, Events, R, Sl> { readonly "~L"?: L; readonly "~V"?: V; readonly definition: Of<Name>; readonly head: (model: Model, props: Props, queries?: Results, shared?: SharedRecord | SharedLookup) => readonly Array<HeadEntry<V>> | undefined; readonly init: (props: Props) => Next<Model, Msg, Events, R>; readonly layerFailure: (failure: Failure<never, any>) => Msg | undefined; readonly message: Codec<Msg, any>; readonly model: Codec<Model, any>; readonly subscriptions: (model: Model, props: Props, queries?: Results, shared?: SharedRecord | SharedLookup) => readonly Array<Subscription<Msg, R>> | undefined; readonly update: (model: Model, msg: Msg, props: Props, queries?: Results, shared?: SharedRecord, collected?: readonly Array<unknown>) => Next<Model, Msg, Events, R>; readonly view: (model: Model, props: Props, running?: (name: string, groupKey: string | undefined) => boolean, queries?: Results, path?: string, shared?: SharedLookup, lazy?: LazyStore) => Node<Msg, R>;}What a parent needs from a child: its props and events contract and its requirements. Model and message are the child's business and are erased.
Details
A component with message: Schema.Never is a valid child, because
update takes msg: never.
Signature
interface Mountable<in out Props, out Events, out R = never, in Sl extends string = never> extends Members<Props, Events, R, Sl>, Call<Props, Events, R, Sl> { <Msg, RF = never, SC extends object = never>(h: HelperBase<Msg, unknown>, options: { readonly key?: string; readonly onEmit?: (events: Events) => NoInfer<Msg> | undefined | EmitHandlers<Events, NoInfer<Msg>>; readonly onFailure?: (failure: Failure<never, unknown>) => NoInfer<Msg> | undefined; } & {} extends Props ? { readonly props?: Props; } : { readonly props: Props; } & { readonly fallback?: (result: Failure) => Content<NoInfer<Msg>, RF>; } & SlotOptions<Sl, SC, NoInfer<Msg>> & 0 extends 1 & Props ? { readonly props: Props; } : {}): Child<Msg, R | NoInfer<RF> | SlotRequirements<SC>>;}What the runtime reads after init or update: the next Model, the
Commands to run and what to emit to the parent.
Signature
interface Next<out Model, out Msg, out Events, out R = never> { readonly commands: readonly Array<Command<Noop | Msg, R>>; readonly events: readonly Array<Events>; readonly lists?: readonly Array<ListIssue>; readonly model: Model; readonly sends?: readonly Array<Send>; readonly viewTransition?: readonly Array<string>;}The type of Component.noop, the message value that sends nothing.
Details
An opaque interface rather than a unique symbol: TypeScript widens a
unique symbol to symbol when it's the inferred return type of a function,
so a Command body such as Effect.map(effect, () => Component.noop) would
be rejected. An interface doesn't widen.
Signature
interface Noop { readonly "~effect/ui/Component/Noop": "~effect/ui/Component/Noop";}The type of the Component.Noop Schema.
Details
A Command.Service whose success is Component.Noop, or omitted, is
silent and its body may return anything. A Schema built from it, such as
Schema.suspend(() => Component.Noop), isn't, so its body must return
Component.noop itself.
Signature
interface NoopSchema extends declare<Noop> { constructor(_: never); readonly "~effect/ui/Component/NoopSchema": "~effect/ui/Component/NoopSchema";}What a host of headless instances gives parts for one render: who owns
the layers, and the instance's path. Plain data, so a story builds it with
no runtime.
Signature
interface PartsContext { readonly collected?: readonly Array<unknown>; readonly owner: Owner; readonly queries?: Results; readonly running?: (name: string, groupKey: string | undefined) => boolean; readonly shared?: SharedLookup;}p in a headless component's parts: the props, the instance's ids, and
part, which declares a decorator for one tag.
Signature
interface PartsHelper<Msg, Props, V extends View.Elements> { readonly props: Props; child<P, E, Pt, R2, Rcv, Sh2, Out>(component: Headless<P, E, Pt, R2, Rcv, Sh2, never, never>, options: { readonly key?: string; readonly onEmit?: (events: E) => Msg | undefined | EmitHandlers<E, Msg>; readonly onFailure?: (failure: Failure<never, unknown>) => Msg | undefined; } & {} extends P ? { readonly props?: P; } : { readonly props: P; } & { readonly fallback?: undefined; readonly parts: (parts: Pt) => Out; readonly slots?: undefined; readonly view?: undefined; }): Composed<Parts<Out>, R2 | Requirements<Out>, Sh2 | Shares<Out>>; id(name: string, key?: string | number): string; isRunning<Args, G extends string>(command: Definition<Args, any, boolean, any, G>, ...group: GroupArg<Args, G>): boolean; part<K extends string, Args extends readonly Array<any>, R2 = never>(tag: K | readonly [K, K], decorate: (builder: PartBuilder<Tags<V, Msg>[K]>, ...args: Args) => ElementBuilder<Msg, R2, any, any, any>): Part<PartTag<Tags<V, Msg>[K]>, Args, R2>; part<Args extends readonly Array<any>, R2 = never>(decorate: (builder: ContainerBuilder<Msg>, ...args: Args) => ElementBuilder<Msg, R2, any, any, any>): Part<string, Args, R2>;}Placement options for h.children: fallback and slots. The binding
supplies the child's key, props and event handlers.
Signature
type PlaceOptions<Sl extends string, SC, Msg, Result, RF> = { readonly fallback?: (result: Result) => View.Content<Msg, RF>;} & SlotOptions<Sl, SC, Msg>What provide accepts: a Layer, an array of them, or a function of props
returning a Layer.
Signature
type ProvideInput = Layer.Any | ReadonlyArray<Layer.Any> | (props: any) => Layer.Any | ProvideKeyed<any, any, any, Layer.Any>The keyed form of provide: key picks a selection from props and the
Model, and layer turns it into the Layer to build. The Layer is built
again, in place, when the key changes by Equal.equals.
Details
While the new selection builds, the old view isn't kept. Each feature slot
below shows its fallback, passed AsyncResult.initial(true), as at
mount, and the log's LayerPending entry says Rebuilding. Once the
Layer is ready the feature mounts again. If the Layer fails, the slot shows
the failure branch of its fallback.
Signature
interface ProvideKeyed<in Props, in Model, K, out L> { readonly key: (props: Props, model: Model) => K; readonly layer: (key: K) => L;}The options of the keyed form of provide: onFailure and server. A
keyed provide always builds per instance, so local is rejected.
Signature
interface ProvideKeyedOptions<in E, out Msg> { readonly local?: undefined; readonly onFailure: (failure: Failure<never, E>) => Msg; readonly server?: false;}The options of provide.
Signature
interface ProvideOptions<in E, out Msg> { readonly local?: boolean; readonly onFailure: (failure: Failure<never, E>) => Msg; readonly server?: false;}A queryMany entry of queries, as the types see it: one query at many
args.
Signature
interface QueryMany<out R extends Query.Query.Any> { readonly _tag: "QueryMany"; readonly query: R;}A query entry of queries, as the types see it: one query, or a list
of pages when the query is a Query.InfiniteService.
Signature
interface QueryOne<out R extends Query.Query.Any> { readonly _tag: "QueryOne"; readonly query: R;}A component's queries, as the types see them: per name in queries, a
QueryOne or a QueryMany.
Signature
type QuerySpec = { [name: string]: QueryOne<any> | QueryMany<any>;}An instance's query results, by query name. Opaque: only the runtime and
Story build and read them.
Signature
type Results = { [name: string]: unknown;}A message issued by $.send, paired with its owner component or shared
key. The nearest matching owner above the sender receives it.
Signature
interface Send { readonly message: unknown; readonly owner: Owner;}An immutable builder for what init and update return.
Details
Every method returns a new step, so update stays pure and a story test can
read the result. set replaces the Model and doesn't merge. run collects
the Commands' requirements into R, one Command at a time, so two Commands
with different requirements give the union. Returning a bare Model from
update is also fine.
Signature
interface Step<in out Model, in out Msg, in out Events, out R = never, L = {}> extends InitStep<Model, Msg, Events, R> { readonly lists: readonly Array<ListIssue>; readonly sends: readonly Array<Send>; readonly viewTransitionTypes: readonly Array<string> | undefined; emit(...emitted: readonly Array<Events>): Step<Model, Msg, Events, R, L>; evolve(fields: EvolveFields<Model>): Step<Model, Msg, Events, R, L>; loadMore(name: InfiniteNames<L>): Step<Model, Msg, Events, R, L>; reset(name: InfiniteNames<L>): Step<Model, Msg, Events, R, L>; run<Self extends InitStep<Model, Msg, Events, unknown>, C extends readonly Array<Command<Noop | Msg, unknown>>>(this: Self, ...commands: C): Step<Model, Msg, Events, RawStepRequirements<Self> | Requirements<C[number]>, L>; send<O extends Owner>(owner: O, message: NoInfer<SendMessage<Receives<O>>>): Step<Model, Msg, Events, R | Of<O> & SendTarget<KeyOf<O>>, L>; set(model: Model): Step<Model, Msg, Events, R, L>; viewTransition(types?: readonly Array<string>): Step<Model, Msg, Events, R, L>;}$ in update: a step holding the current Model, plus the current props,
what the queries hold and the shared state the component reads.
Details
Cur is the message being handled: the whole message type in an update
function, and one tag's member in a slice for that tag. $.combine takes
functions over it. SR is what the component's reads lists, and Rp
what the readers of an owner whose shares has collects report.
$.props is what the Models above the instance give it now, whether or
not the flush that renders them has run: an ancestor waiting to render
renders before a message reaches the instance. One that no longer
renders the instance removes it then, and the message is dropped.
$.reads follows the same rule: each owner's value from its Model as
this update runs, which the reader's view may not have rendered yet. A
reader that sends to its owner still reads the old value in that
update, since the send applies after it returns. An onChange message
says a value changed, and $.reads holds the current one: when another
reader answers the owner within the same round, $.reads is already
newer than the onChange message being handled.
$.collected holds the reports from the last settled render pass. A
reader's change earlier in the same step is not available yet. An owner
that needs that change can receive it in the reader's message or react
through collects.onChange, whose update sees the new reports.
Signature
type Update<Model, Msg, Events, Props, L = {}, Cur = Msg, SR = {}, Rp = never> = UpdateBase<Model, Msg, Events, Props, L, Cur, SR, Rp> & CollectedHelpers<Rp>Other
Helper types for Bound.
Helper types for Composed.
Definition
unstableTypes for definitions: what a component keeps of the one it was made from.
Helper types for Headless.
Helper types for Lazy.
Helper types for Mountable.
ProvideInput
unstableHelper types for provide.
Schemas
Type Ids
ComposedTypeId
unstableThe type id of what p.child returns.
Signature
declare const ComposedTypeId: "~effect/ui/Component/Composed"The type id of what p.child returns.
Signature
type ComposedTypeId = typeof ComposedTypeIdHeadlessTypeId
unstableThe type id of a headless component.
Signature
declare const HeadlessTypeId: "~effect/ui/Component/Headless"The type id of a headless component.
Signature
type HeadlessTypeId = typeof HeadlessTypeIdLazyTypeId
unstableIdentifies a lazy component.
Signature
declare const LazyTypeId: "~effect/ui/Component/Lazy"Identifies a lazy component.
Signature
type LazyTypeId = typeof LazyTypeIdNoopSchemaTypeId
unstableIdentifies the Component.Noop Schema.
Signature
declare const NoopSchemaTypeId: "~effect/ui/Component/NoopSchema"Identifies the Component.Noop Schema.
Signature
type NoopSchemaTypeId = typeof NoopSchemaTypeIdNoopTypeId
unstableIdentifies Component.noop.
Signature
declare const NoopTypeId: "~effect/ui/Component/Noop"Identifies Component.noop.
Signature
type NoopTypeId = typeof NoopTypeIdStepTypeId
unstableIdentifies a step.
Signature
declare const StepTypeId: "~effect/ui/Component/Step"Identifies a step.
Signature
type StepTypeId = typeof StepTypeIdIdentifies a component.
Signature
declare const TypeId: "~effect/ui/Component"Identifies a component.
Signature
type TypeId = typeof TypeIdUtility Types
What a query's args returns: the args of a query entry's Query, or
undefined to disable it, and an array of args for a queryMany, empty
to watch nothing.
Signature
type ArgsFor<S, M> = M extends Query.Query.Any ? ReadonlyArray<Query.Query.Args<M>> : Query.Query.Args<S> | undefinedWhat h gains in view for a definition with children: h.children.<name>,
which places the child bound under that name.
Signature
type ChildHelpers<Ch, Msg> = [keyof Ch] extends [never] ? {} : { readonly children: Placers<Ch, Msg>;}What the children a definition binds require. They join the component's requirements, as they run whether or not its view places them.
Signature
type ChildRequirements<Ch> = { [K in keyof Ch]: Exclude<Ch[K], Unbound> extends Bound<any, infer R, never, any> | BoundMany<any, infer R, never, any> ? R : never }[keyof Ch]Adds collected to update, parts and shares.value for owners with
collects: the last settled reports, one per mounted reader, in no
promised order.
Signature
type CollectedHelpers<Rp> = [Rp] extends [never] ? {} : { readonly collected: ReadonlyArray<Rp>;}Passes unless the Layer can fail, because the curried form has no
onFailure.
Signature
type CurriedCantFail<L> = [ProvideInput.Error<L>] extends [never] ? unknown : { readonly "This Layer can fail, and the curried form has no onFailure. Use Component.provide(component, layer, { onFailure }) to handle": ProvideInput.Error<L>;}The events of a component.
Signature
type Events<C> = C extends Mountable.Members<infer _Props, infer E, infer _R> ? E : C extends Headless<infer _P, infer E, infer _Parts, infer _R, infer _Rcv, never> ? E : C extends Lazy.Members<infer _P, infer E, infer _R, infer _Sl, infer _L> ? E : neverh in the view of a definition, for a function that takes it without
Def.fragment.
Signature
type Helper<D> = D extends Definition<infer _N, infer P, infer _M, infer Msg, infer _E, infer V, infer L, infer _Rcv, infer Sl, infer SR, infer _SV, infer _Rp, infer _K, infer Ch> ? ViewHelper<P, Msg, V, L, Sl, SR, Ch> : neverExample A row fragment
import { Component } from "effect/ui"import { Schema } from "effect"
const Note = Schema.Struct({ id: Schema.String, title: Schema.String })
const NoteListDef = Component.define({ name: "NoteList", model: Schema.Struct({ notes: Schema.Array(Note) }), message: Schema.Never})
const noteRow = (h: Component.Helper<typeof NoteListDef>, note: typeof Note.Type) => h.el("li", note.title).key(note.id)
export const NoteList = NoteListDef.make({ init: () => ({ notes: [] }), update: ($) => $.model, view: (h, model) => h.el("ul", model.notes.map((note) => noteRow(h, note)))})The names of the infinite queries: $.loadMore and $.reset take one.
Signature
type InfiniteNames<L> = { [K in keyof L]: L[K] extends QueryOne<infer R> ? R extends Query.InfiniteQuery.Any ? K : never : never }[keyof L] & stringThe names of the queryMany queries.
Signature
type KeyedNames<L> = { [K in keyof L]: L[K] extends QueryMany<any> ? K : never }[keyof L] & stringThe message type of a component.
Signature
type Message<C> = C extends Members<infer _N, infer _P, infer _M, infer Msg, infer _E, infer _R, infer _V, infer _L> ? Msg : C extends Headless.Any ? C["message"]["Type"] : neverThe Model of a component.
Signature
type Model<C> = C extends Members<infer _N, infer _P, infer M, infer _Msg, infer _E, infer _R, infer _V, infer _L> ? M : C extends Headless.Any ? C["model"]["Type"] : neverA query's onChange: a query entry's gets its result as h.queries opens it,
and a queryMany's gets its entries and the keys whose result changed.
Return undefined to send no message.
Signature
type OnChange<S, M, Msg> = M extends Query.Query.Any ? (results: KeyedResults<M>, changes: ReadonlyArray<KeyedChange<M>>) => Msg | undefined : S extends Query.Query.Any ? (result: QueryResultOf<QueryOne<S>>) => Msg | undefined : neverThe chain type of a tag's root builder: what a part's decorate gets.
Signature
type PartBuilder<T> = T extends { readonly attr: (...args: any) => infer B;} ? B : neverThe tag a tag's builder declares, which a part checks: string for a
vocabulary that doesn't declare its tags.
Signature
type PartTag<T> = T extends { readonly "~Tag"?: infer Tag extends string | undefined;} ? Exclude<Tag, undefined> : neverh.children: one placer for each name children binds. A child entry
is placed with h.children.name(options?), a childMany entry with
h.children.name(key, options?).
Details
A placer returns null while its entry is unbound, so its result is
View.Child | null when the entry can be undefined, null or
false. A childMany placer also returns null for a key it isn't
bound to.
Signature
type Placers<Ch, Msg> = { [K in keyof Ch]: Placer<Ch[K], Msg> }The props of a component.
Signature
type Props<C> = C extends Mountable.Members<infer P, infer _Events, infer _R> ? P : C extends Headless<infer P, infer _E, infer _Parts, infer _R, infer _Rcv, never> ? P : C extends Lazy.Members<infer P, infer _E, infer _R, infer _Sl, infer _L> ? P : neverAccepts plain props or an Effect that produces them. Effects must satisfy
the error type E, even when Props is {}, object, any or unknown.
Signature
type PropsInput<Props, E = never, R = never> = PlainProps<Props> | Effect.Effect<Props, E, R>C with ROut provided and RIn required instead. Name, Model and message
are kept, so paths and story tests don't change.
Signature
type Provided<C, ROut, RIn> = C extends Component<infer N, infer P, infer M, infer Msg, infer E, infer _R, infer V, infer L, infer Sl> ? Component<N, P, M, Msg, E, Exclude<Requirements<C>, Exclude<ROut, RuntimeService>> | RIn, V, L, Sl> : Mountable<Props<C>, Events<C>, Exclude<Requirements<C>, Exclude<ROut, RuntimeService>> | RIn, Slots<C>>The options argument of provide. Optional when the Layer can't fail with a
typed error, and otherwise a required argument with onFailure. F
captures the handler as given, so provide can check it.
Signature
type ProvideRest<L, Msg, F = unknown> = [ProvideInput.Error<L>] extends [never] ? [options?: LocalOption & { readonly onFailure?: ProvideOptions<never, Msg>["onFailure"] & F;}] : [options_with_onFailure: ProvideOptions<ProvideInput.Error<L>, Msg> & { readonly onFailure: F;}]The queries of a component.
Signature
type Queries<C> = C extends { readonly "~L"?: infer L;} ? [L] extends [QuerySpec] ? L : {} : {}What h gains in view for a component with queries.
Details
queries holds each query's result, as $.queries does in update.
patched tells, per single or infinite query, whether the value includes an
optimistic patch the server hasn't confirmed. It is per entry, not per
instance. queryMany entries have no patched flag.
Signature
type QueryHelpers<L> = [keyof L] extends [never] ? {} : { readonly patched: { [K in SingleNames<L>]: boolean }; readonly queries: QueryResults<L>;}One query as h.queries, $.queries, and queries in head,
subscriptions and a query's args open it.
Details
A single query opens to an AsyncResult of its Query's success and error,
an infinite query to an AsyncResult of its InfiniteData, and a queryMany
query to its entries in the order of its args. An enabled single or infinite
query exposes the result for its current args. Until one is stored, it keeps
the last Success with waiting: true, unless dropPrevious is set.
Otherwise it returns Initial, waiting only while enabled.
Signature
type QueryResultOf<D> = D extends QueryMany<infer R> ? KeyedResults<R> : D extends QueryOne<infer R> ? R extends Query.InfiniteQuery.Any ? AsyncResult.AsyncResult<InfiniteData<R>, Query.Query.Error<R>> : AsyncResult.AsyncResult<Query.Query.Success<R>, Query.Query.Error<R>> : neverThe services a component's queries add to its requirements: the queries themselves, never what their fetchers use.
Signature
type QueryServices<L> = L extends unknown ? ServiceOf<L[keyof L]> : neverThe requirements of a component: the Commands and feature services it uses.
Signature
type Requirements<C> = C extends Mountable.Members<infer _Props, infer _Events, infer R> ? R : C extends Lazy.Members<infer _P, infer _E, infer R, infer _Sl, infer _L> ? R : neverPasses unless the Layer can fail; then names the error type in the compiler error.
Signature
type RequiresOnFailure<L> = [ProvideInput.Error<L>] extends [never] ? unknown : { readonly "This Layer can fail. Pass { onFailure } to handle": ProvideInput.Error<L>;}Services that provide cannot remove from a component's requirements because
the runtime owns them or reads them once at mount. Query.Cache is excluded:
Query.layer() can supply a cache to a component subtree.
Signature
type RuntimeService = Command.FrameworkService | typeof Query.Visibility | typeof Query.Connectivity | typeof Query.Problems | Shared.AnyThe names of single and infinite query entries, used as keys in h.patched.
Signature
type SingleNames<L> = { [K in keyof L]: L[K] extends QueryOne<any> ? K : never }[keyof L] & stringWhat h gains in view for a component with slots: h.slots.<name>,
the outlet that places what the parent passed for that slot.
Details
An outlet is opaque. It renders nothing when the parent passed nothing, and the view can't tell whether it did.
Signature
type SlotHelpers<Sl extends string> = [Sl] extends [never] ? {} : { readonly slots: { [K in Sl]: View.Outlet };}The names of the slots a component declares, never for one without slots.
Signature
type Slots<C> = C extends Mountable.Members<infer _Props, infer _Events, infer _R, infer Sl> ? Sl : C extends Lazy.Members<infer _P, infer _E, infer _R, infer Sl, infer _L> ? Sl : neverThe requirements of a step, or never for a bare Model.
Signature
type StepRequirements<U> = NamedRequirement<RawStepRequirements<U>>h in a component's view: the helpers of View.Helper, the tags of its
vocabulary, its queries, slots and shared state, and h.children for a
definition with children.
Signature
type ViewHelper<Props, Msg, V extends View.Elements, L, Sl extends string, SR, Ch = {}> = View.WithTags<Msg, Props, V> & QueryHelpers<L> & SlotHelpers<Sl> & SharedHelpers<SR> & ChildHelpers<Ch, Msg>