View unstable
Views are values: a tree of element, text and child nodes that a component's
view returns and a host renders.
The core h has only el and text. A child component is declared by
calling it with h, and a feature by its render. An element vocabulary
such as the HTML one adds element names and its own element class, supplied
through a vocabulary constructor such as Html.component or by passing
elements to Component.define.
An element is written as a chain: h.el("form").on("submit", msg).children(...).
children returns the builder, so the chain goes on, and a second call
adds after the first. h.el(tag, ...children) is shorthand for it. A
builder is itself a valid child or view, with the children it holds.
Arrays of children are flattened, and false, null and
undefined render nothing. Adjacent text merges into one text node when
the view is built, and empty text is dropped. Key an element when a
conditional sibling before it has the same tag; otherwise it can take
that sibling's node.
Example A host-neutral view
import type { View } from "effect/ui"import { UiSchema } from "effect/ui"import { Schema } from "effect"
const Message = UiSchema.TaggedEnum({ ClickedIncrement: {} })
const view = (count: number, h: View.Helper<typeof Message.Type, {}>) => h.el("div", h.el("button").on("click", Message.ClickedIncrement()).children("+"), String(count))Constructors
Builds the element node a builder describes: the children it holds, then
the given ones, normalised as children does.
When to use
Use when a finished node is needed, such as in a function declared to
return a View.Element. A view, a child and a fallback take the builder
as it is.
Signature
declare function build<Msg, R, C extends readonly Array<Input<Msg, any>>>(builder: ElementBuilder<Msg, R, any, any>, inputs: C): Element<Msg, R | Requirements<C[number]>>Normalises element children: holes are dropped, arrays are flattened, element builders become elements with no children, and adjacent text merges into one node with empty text dropped.
Details
The view value never holds two text nodes side by side, so server HTML hydrates without separator comments.
Signature
declare function children<Msg>(inputs: readonly Array<Input<Msg, any>>): Array<Node<Msg, any>>Builds a text node.
Signature
declare function text(text: string): TextTurns view content into a node: an element builder becomes its element, with the children it holds, and a node is returned as it is.
Signature
declare function toNode<Msg, R>(content: Content<Msg, R>): Node<Msg, R>withFields
unstableCopies a builder with some of its fields replaced, keeping its class. Every chain method is written with it, so a builder stays a value.
Signature
declare function withFields<B extends ElementBuilder<any, any, any, any, string>>(builder: B, fields: Partial<Pick<ElementBuilder<unknown>, "elementKey" | "elementAttrs" | "elementProps" | "handlers" | "eventOptions" | "refKey" | "mount" | "owned">>): BKeeps a part's requirements on a wrapper function returned from a headless
component's parts.
Details
Returns wrapper unchanged, preserving its parameters, generics and return
type. Use it when adapting a part to an options object or adding markup.
The wrapper must apply part; this only carries that part's requirements,
not requirements of any other parts or effects the wrapper uses.
Signature
declare function wrapPart<P extends { readonly "~R"?: (_: never) => unknown;}, F extends (...args: Array<any>) => any>(_part: P, wrapper: F): F & Pick<P, "~R">Example A part with an options object
import { View } from "effect/ui"
const withOptions = <R>(part: View.Part<"button", [], R>) => View.wrapPart(part, <B extends View.PartTarget<"button">>( { element }: { element: B } ): ReturnType<B["attr"]> => part(element))Guards
isElementBuilder
unstableWhether a value is an element builder.
Signature
declare function isElementBuilder(u: unknown): u is ElementBuilder<unknown, unknown, unknown, unknown, string>Models
A child component, declared by calling a component with the
parent's h, Editor(h, { key }), or with a feature's render,
Todos.render(h, { key, fallback }).
Details
The runtime gives each child its own instance, Model and Scope, at the path
Name[key] under its parent. Several instances of one component are
several children with different keys. The child reports up through
onEmit, checked against the parent's message type, and every child is a
failure boundary: a failed child shows fallback, or nothing, until its
key changes, and the parent's optional onFailure is also messaged.
A child dropped from the view unmounts, and its Model goes with it. A
child that must outlive the view leaving it out, such as a hidden tab, is
bound with children on Component.define instead, and placed with
h.children: see Component.child.
Gotchas
A child without a key has the empty key, at Name[], so it must be the only
child of its component where it is rendered: a second one fails the parent
with an error that asks for a key. Rows in a list always need a key. A
list of one unkeyed row renders, and a row that replaces it keeps its
instance and Model.
Two children at one path are one instance, whatever branch of the view
declared them: cond ? Listbox(h, { props: a }) : Listbox(h, { props: b })
keeps the Model when cond changes, and init doesn't run again. Key each
branch when the component's Model holds state that shouldn't carry over.
Signature
interface Child<out Msg, out R = never> { readonly _tag: "Child"; readonly "~R"?: (_: never) => R; readonly bound?: unknown; readonly component: Any | Any | Any; readonly fallback: (result: Failure<never, unknown> | Initial<never, unknown>) => Content<Msg, any> | undefined; readonly key: string; readonly onEmit: (events: any) => Msg | undefined; readonly onFailure: (failure: Failure<never, unknown>) => Msg | undefined | undefined; readonly owner?: Owner; readonly props: unknown; readonly slots: Readonly<Record<string, Input<any, any>>> | undefined; readonly view: (parts: any) => Content<Msg, any> | undefined;}ContainerBuilder
unstableThe builder of an element that takes children: what h.el returns.
Details
children returns the builder with the children added after the ones it
holds. So a function that takes a builder can add children of its own and
still return a builder, for its caller to add more.
Signature
declare class ContainerBuilder<out Msg, out R = never, in out Handlers = Record<string, unknown>, in out HostNode = unknown, out Tag extends string = string> extends ElementBuilder<Msg, R, Handlers, HostNode, Tag> { constructor<out Msg, out R = never, in out Handlers = Record<string, unknown>, in out HostNode = unknown, out Tag extends string = string>(tag: string); readonly "~With"?: ContainerBuilder<Msg, unknown, Handlers, HostNode, Tag>; children<This, C extends readonly Array<Input<Msg, unknown>>>(this: This, ...inputs: C): WithRequirements<This, Requirements<C[number]>>;}What a view, a child and a fallback may return: a node, or an element
builder with no children yet, such as h.br or h.input.value(draft).
Signature
type Content<Msg, R = never> = Node<Msg, R> | ElementBuilder<Msg, R, any, any>An element node, as data.
Details
attrs are strings set as attributes. props are typed values the host
decides the meaning of. handlers map an event name to its handler, so
re-rendering never touches listeners, and eventOptions holds the
EventOptions set with a handler. key keeps the element's node when
its siblings move. Unkeyed elements match by position, checking matching
siblings from the start and then the end. Use a key to distinguish
same-tag siblings when inserting, removing or reordering them.
refKey names the element for ref Commands, and mount is the work
started by onMount.
Signature
interface Element<out Msg, out R = never> { readonly _tag: "Element"; readonly attrs: Readonly<Record<string, string>>; readonly children: readonly Array<Node<Msg, R>>; readonly elementKey: string | undefined; readonly eventOptions: Readonly<Record<string, EventOptions>>; readonly handlers: Readonly<Record<string, Handler<Msg, any>>>; readonly mount: Mount<Msg> | undefined; readonly owned?: readonly Array<Owned>; readonly props: Readonly<Record<string, unknown>>; readonly refKey: string | undefined; readonly tag: string;}ElementBuilder
unstableThe element builder: h.el(tag) and a vocabulary's element names. It
holds attributes, properties, handlers, a key, a ref, a mount and the
children given so far.
Details
Every method returns a copy, so a view stays a value. Handlers maps an
event name to its payload; a vocabulary's element class fixes it and adds
its own helpers. The core builder leaves payloads untyped.
This base class has no children, so it's the shape of a void element.
ContainerBuilder adds it, and a vocabulary does the same for the tags
that take children. A builder is itself valid content: as a child or a
view it renders as its element with no children.
Signature
declare class ElementBuilder<out Msg, out R = never, in out Handlers = Record<string, unknown>, in out HostNode = unknown, out Tag extends string = string> implements Pipeable { constructor<out Msg, out R = never, in out Handlers = Record<string, unknown>, in out HostNode = unknown, out Tag extends string = string>(tag: string); readonly "~Add"?: unknown; readonly "~Handlers"?: Handlers; readonly "~HostNode"?: (_: HostNode) => HostNode; readonly "~R"?: (_: never) => R; readonly "~Tag"?: Tag; readonly "~With"?: ElementBuilder<Msg, unknown, Handlers, HostNode, Tag>; readonly content: readonly Array<Node<Msg, any>> | undefined; readonly elementAttrs: Readonly<Record<string, string>>; readonly elementKey: string | undefined; readonly elementProps: Readonly<Record<string, unknown>>; readonly eventOptions: Readonly<Record<string, EventOptions>>; readonly handlers: Readonly<Record<string, Handler<Msg, any>>>; readonly hooks: readonly Array<Forward> | undefined; readonly mount: Mount<Msg> | undefined; readonly owned: readonly Array<Owned>; readonly refKey: string | undefined; readonly removals: readonly Array<string> | undefined; readonly tag: string; pipe: Pipe<this>; attr(name: string, value: string | undefined): this; attrs(attributes: Readonly<Record<string, string | undefined>>): this; forward<This, R2 = never>(this: This, place: (node: WithRequirements<This, never>) => Element<Msg, R2> | ElementBuilder<Msg, R2, any, any, string>): WithRequirements<This, R2>; key(key: string): this; on<K extends string>(event: K, handler: Handler<Msg, Handlers[K]>, options?: EventOptions): this; onMount<This, R2>(this: This, mount: Issued<Noop | Msg, R2, HostNodeOf<This>, never>): WithRequirements<This, R2>; onMount<This>(this: This, mount: Issued<Noop | Msg | "onMount's mount ends with a message or Component.noop. Map its result with Mount.map, or end its body with Effect.as(Component.noop)", any, HostNodeOf<This>, never>): never; prop(name: string, value: unknown): this; props(properties: Readonly<Record<string, unknown>>): this; ref(ref: Ref<HostNode>): this;}A type-level function from a message type to a set of element constructors, which a vocabulary implements.
Details
Tags is read with Msg bound: (V & { Msg })["Tags"]. Host is the
service a host's Layer provides to say it can show these elements, which
mount requires for the root.
Head is the entry type a component's head returns, and HeadValue
the value the vocabulary's merge folds them into.
A vocabulary that declares neither has Head's host-neutral title
entries. Read them with HeadEntry and HeadValue.
Signature
interface Elements { readonly Head?: unknown; readonly HeadValue?: unknown; readonly Host: unknown; readonly Msg: unknown; readonly Tags: unknown;}How a host treats one event of an element, set with the handler by on.
Details
With preventDefault: true, the host cancels the event's default action
when the handler produces a message, after the handler runs and before the
message is sent. A handler that returns undefined leaves the event alone,
so one handler decides per event, such as Enter but not Shift+Enter. A
message value always prevents. With preventDefault: "always", the host
cancels the default whatever the handler returns. A host whose events have
no default ignores it.
Nothing stops an event's propagation. A host gives each event to the
innermost element with a handler for it, and only that one, even when the
handler returns undefined.
A vocabulary may extend these options for its own events, such as what a drop target accepts. They stay plain data on the element: hosts and tests read what they know and ignore the rest.
Signature
interface EventOptions { readonly preventDefault?: boolean | "always";}What a builder's forward stores: a function from the finished builder
to the element to render.
Signature
type Forward = (node: any) => Element<any, any> | ElementBuilder<any, any, any, any>What an event sends: a message value, or a function of the event's payload
that returns undefined to ignore the event.
Details
Payloads are plain data declared by the vocabulary and built by the host. No host event object reaches component code, so a test fires one with a literal.
Signature
type Handler<Msg, Payload> = Msg | (payload: Payload) => Msg | undefinedHow a vocabulary folds its head: merge folds a tree of entries into the
vocabulary's value, reporting conflicts, and title reads the title out of
that value for the Router's announcement.
Signature
interface HeadFold<E = any, H = any> { readonly merge: (tree: Tree<E>, options?: MergeOptions) => H; readonly title: (head: H) => string | undefined;}The view helper, h in view: bound to the component's message type and
carrying its props.
Details
The core helper has el and text. A vocabulary's element names
are mixed in by Component.define.
Signature
interface Helper<Msg, Props> extends HelperBase<Msg, Props> { text(text: string): Text;}The view helper without text: what every h has, including one whose
vocabulary declares its own text tag. A function that takes any h
types it with this.
Signature
interface HelperBase<Msg, Props> { readonly props: Props; el(tag: string): ContainerBuilder<Msg>; el<C extends readonly [Input<Msg, any>, Input<Msg, any>]>(tag: string, ...children: C): ContainerBuilder<Msg, Requirements<C[number]>>; id(name: string, key?: string | number): string; isRunning<Args, G extends string>(command: Definition<Args, any, boolean, any, G>, ...group: GroupArg<Args, G>): boolean; lazy<H, A extends readonly Array<unknown>, C extends Content<Msg, any>>(this: H, fn: (h: H, ...args: A) => C, ...args: A): Node<Msg, Requirements<C>>;}One child argument of an element: a node, an element builder, text, an
array of them, or a hole (false, null, undefined) that renders
nothing. R is what the child requires, as for Content.
When to use
Use to type the children a shared view helper passes on. Leaving R out
accepts only children that need no service, so a child that needs one
fails at the call site. To pass on whatever the children need, take them
with a generic Children constraint, as in the example: the element adds their
requirements to its own.
Gotchas
Input<Msg, any> as a parameter's type, outside a generic, erases what
the children require.
Signature
type Input<Msg, R = never> = Content<Msg, R> | string | false | null | undefined | Children<Msg, R>Example A view helper that keeps its children's requirements
import type { View } from "effect/ui"import type { Html } from "effect/ui/html"
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))Where a host keeps what h.lazy built between one instance's renders: an
object it keeps for the instance, with lazy undefined at first.
Signature
interface LazyStore { lazy: unknown;}What onMount stores: the issued mount, with its name, its args and the
map from its result to a message.
Details
It's data: a story reads name and args off it without running the
body. See Mount.make.
Signature
type Mount<Msg> = MountModule.Issued<Msg | Component.Noop, any, any, never>The text of the type error onMount gives for a mount that doesn't end
with a message or Component.noop, such as one whose body is an
Effect<void> or whose result hasn't been mapped.
Signature
type MountHint = "onMount's mount ends with a message or Component.noop. Map its result with Mount.map, or end its body with Effect.as(Component.noop)"A node of a view: an element, text, or a child component.
Details
Msg is the message type the view's handlers send. R collects the
requirements of the children declared by value, which surface in the
parent's requirements.
Signature
type Node<Msg, R = never> = Element<Msg, R> | Text | Child<Msg, R> | OutletWhere a component places what its parent passed for one of its slots:
h.slots.body.
Details
An outlet is opaque: the view that places it can't read the content. The content keeps its own nodes, so an element key in it can't clash with the outlet's siblings, and the outlet is keyed by its slot's name among them.
Signature
interface Outlet { readonly _tag: "Outlet"; readonly name: string;}What a part of a headless component added to an element: its handlers, their options, its ref and its mount, kept apart from the author's.
Details
tokens holds the part's token-list attributes, such as class and
aria-describedby. They're added to the element's own value, whether the
consumer set it before or after applying the part, and a token already
there isn't repeated. The part's other attributes are written over what
the consumer set before applying it.
Signature
interface Owned { readonly eventOptions: Readonly<Record<string, EventOptions>>; readonly handlers: Readonly<Record<string, Handler<any, any>>>; readonly mount: Mount<any> | undefined; readonly owner: Owner; readonly refKey: string | undefined; readonly tokens: Readonly<Record<string, string>>;}Who a layer of an element belongs to: one headless instance. The runtime makes one per instance, and a story one per expanded child.
Signature
interface Owner { readonly depth: number; readonly path: string;}A part of a headless component: it takes the builder of an element the consumer wrote and returns it with the part's attributes, properties and owned layer added.
Details
Tag is the tag, or the union of tags, the part is declared for, and
string for a part that takes any element. Args is what the part takes
after the builder, and R what its mount requires, which joins the
headless component's requirements.
A part is tied to tag names, the same check the runtime makes: a part
declared for "h2" takes h.h2 and rejects h.h3, although both
render an HTMLHeadingElement. A part that takes several tags lists them,
as p.part(["h2", "h3"], ...).
The result is the builder's chain type, never the callable root, so
menu.trigger(h.button)("Open") doesn't compile.
Signature
interface Part<in out Tag extends string, in Args extends ReadonlyArray<any>, out R = never> { <B extends PartTarget<Tag>>(builder: B, ...args: Args): ReturnType<B["attr"]>; readonly "~R"?: (_: never) => R;}What a part accepts: a builder whose declared tag is one of Tag, either
a tag's callable root or its chain type.
Details
It's structural on purpose. With ElementBuilder as the constraint, a
callable root such as h.dialog infers as the constraint and loses its
chain type. A builder whose tag isn't known, such as h.el("x-foo")'s,
only fits a part declared without a tag.
Signature
interface PartTarget<out Tag extends string> { readonly "~Tag"?: Tag; readonly attr: (...args: any) => any;}A root builder that is also callable: b(...inputs) is
b.children(...inputs). What a vocabulary puts on h for a tag that
takes children, such as h.button("Add").
Details
The chain methods and the call return the builder B, which isn't
callable: h.div(a).children(b) adds b, and h.div(a)(b) doesn't
compile. B's children must return WithRequirements of B too.
Calling a choice of roots, (cond ? h.h2 : h.h1)(title), doesn't compile,
as it would lose the children's requirements. Write
(cond ? h.h2 : h.h1).children(title).
Signature
type Shorthand<B extends { readonly children: (...inputs: any) => WithRequirements<B, any>;}> = Omit<B, never> & <C extends InputsOf<B>, _Root extends B = B>(...inputs: C) => WithRequirements<B, Requirements<C[number]>>A text node.
Signature
interface Text { readonly _tag: "Text"; readonly text: string;}tokenListAttributes
unstableThe attributes whose value is a space-separated list, which a part adds
its tokens to rather than replacing: class, rel and the ARIA
attributes that list ids.
Signature
declare const tokenListAttributes: ReadonlySet<string>The runtime half of a vocabulary: its root element builders, installed on
h and shared by every render.
Details
A tag that takes children is a shorthand builder, so h.span(title)
works; a void tag is a plain builder.
Signature
interface Vocabulary<out V extends Elements = Elements> { readonly Elements?: V; readonly head?: HeadFold<any, any>; readonly name: string; readonly tags: Readonly<Record<string, ElementBuilder<any, any, any, any>>>; readonly textParents?: readonly Array<string>;}Other
Queries
Every node of a view in document order, the root first. A child is followed by what its parent passed for its slots, in the order they were passed.
Signature
declare function nodes<Msg>(node: Node<Msg, any>): Generator<Node<Msg, any>>The text of a view, with the text of every element concatenated in order. A child contributes the text of what its parent passed for its slots, in the order they were passed, and nothing of its own view.
Signature
declare function textOf(node: Node<any, any>): stringUtility Types
A readonly array of children. Use C extends View.Children<Msg> for a
wrapper's children option to preserve each child's requirements, and pass
that option directly to .children(options.children) without spreading it.
The default requirement is any for generic constraints, not annotations:
annotating a value as Children<Msg> erases its requirements.
For optional children, use C extends View.Children<Msg> = [] so omitted
children contribute never instead of any to the caller's requirements.
Signature
type Children<Msg, R = any> = ReadonlyArray<Content<Msg, R> | string | false | null | undefined>The entries a component of vocabulary V may return from head: the
vocabulary's Head, or Head.Entry when V is never or declares none.
Signature
type HeadEntry<V> = [V] extends [never] ? Head.Entry : V extends { readonly Head: infer E;} ? E : Head.EntryThe folded head of vocabulary V: the vocabulary's HeadValue, or
Head.Head when V is never or declares none.
Signature
type HeadValue<V> = [V] extends [never] ? Head.Head : V extends { readonly HeadValue: infer H;} ? H : Head.HeadThe requirements of the parts in a headless component's parts record.
Signature
type PartRequirements<P> = P extends { readonly "~R"?: (_: never) => infer R;} ? R : neverThe requirements of a tuple of children, collected one at a time, so two
siblings with different needs give the union. Requirements<any> is
any.
Signature
type Requirements<T> = 0 extends 1 & T ? any : T extends string | false | null | undefined ? never : T extends Text | Outlet ? never : T extends ReadonlyArray<infer E> ? Requirements<E> : T extends Child<infer _Msg, infer R> ? R : T extends Element<infer _Msg, infer R> ? R : T extends ElementBuilder<infer _Msg, infer R, any, any> ? R : neverThe element names a vocabulary adds to h, bound to a component's message
type. Nothing when V is never.
Signature
type Tags<V, Msg> = [V] extends [never] ? {} : V extends Elements ? V & { readonly Msg: Msg;}["Tags"] : {}The builder B, of its own class, with R2 added to its requirements:
what children, onMount and forward return. A union gives a union,
and a Shorthand root gives its builder.
Signature
type WithRequirements<B, R2> = B extends unknown ? B extends { readonly attr: (...args: any) => infer Chain;} ? Chain : B & { readonly "~Add": R2;} extends { readonly "~With"?: infer With;} ? With : never : neverCombines Helper with a vocabulary's Tags. When the
vocabulary declares its own text tag (such as a terminal or native
vocabulary), the vocabulary's text replaces Helper.text.
Signature
type WithTags<Msg, Props, V> = "text" extends keyof Tags<V, Msg> ? HelperBase<Msg, Props> : Helper<Msg, Props> & Tags<V, Msg>Vocabularies
Makes a builder callable as Shorthand describes, for a vocabulary's
tags. Make one per tag, once: h shares it across renders.
Details
The result is a function with the builder's class and fields. Its chain
methods copy only the builder's fields, so the function's own name and
length never reach a node.
Signature
declare function shorthand<B extends ElementBuilder<any, any, any, any, string> & { readonly children: (...inputs: any) => WithRequirements<B, any>;}>(builder: B): Shorthand<B>withContent
unstableA copy of builder with inputs after the children it already holds,
normalised as children does. What a builder's children calls, with
its rest arguments: the array is reused for the first children.
Signature
declare function withContent<B extends ElementBuilder<any, any, any, any, string>>(builder: B, inputs: readonly Array<Input<any, any>>): BwithNoTextContent
unstableLike withContent, for a container element that cannot hold text
directly. Throws if any child is text and marks slot Outlet nodes so
the runtime rejects text passed through them. vocabulary is the
vocabulary of builder: the error names it, and its textParents as
where text goes.
Signature
declare function withNoTextContent<B extends ElementBuilder<any, any, any, any, string>>(builder: B, inputs: readonly Array<Input<any, any>>, vocabulary: Pick<Vocabulary, "name" | "textParents">): B