Renderer unstable
The renderer: mounts a component tree on a Host and keeps it in step with
each instance's Model.
Rendering is a virtual DOM bounded by components. A message re-runs only the view of the instance that received it, and the diff against its last view stops at a child: a child's nodes belong to the child, and the parent only places, moves or removes them. A child re-renders only when its props change, compared shallowly. Dirty instances render in one flush, parents before children.
One render comes before its flush: a message or a query result for an
instance renders the dirty instances above it first, so its update reads
current props. The instance's own view still waits for the flush.
The renderer only talks to a Host, which the Renderer service provides,
so switching target is a Layer swap. Host is public so third parties can
implement one.
Constructors
Mounts a component tree in container on the Renderer's host, for the
life of the current Scope.
Details
Every instance gets its own child Scope. Commands, Subscriptions and
provided Layers run in it, and closing the Scope unmounts the tree. Every
child is a failure boundary: a failed child shows its fallback until
its key changes. When the root itself fails, fallback is shown in its place
and the log records the root's Failed and Unmounted.
Mounting requires the root vocabulary's host marker, so mounting a root on the wrong host is a type error. Nested components are checked when they mount, and a mismatch fails that child.
props is the root's props or an Effect of them, such as
Router.props(AppRoute). An Effect is run once, before init, and its
requirements are added to the mount's. init still only sees plain props,
so a Story or a test can pass them directly.
It builds every node fresh. A server render is hydrated with
HtmlHydrate.hydrate.
onEmit receives the root's events in emission order, as a parent's
onEmit would; without it nothing is retained. init's events arrive
before mount returns and an update's inside send, both before the
container shows the new view, so don't read the container from the
callback. If the callback throws, the root fails in "onEmit" and the
transition's remaining events are dropped.
The mount owns the head: on every flush that changed a view it folds the
placed tree's head with the root vocabulary's merge, and gives it to the
host's head once every instance has adopted. Two siblings that set one
single slot, such as the title, are reported to Query.Problems as a
Head.Conflict. With head: false, for a mount embedded in a page
something else owns, the head is computed and the Router still reads its
title, but the host is never given it.
key changes the root's path from /<name> to /<name>[<key>].
Use distinct keys when mounting the same root component more than once
in one document to avoid generated element id collisions.
Gotchas
Any Effect passed as props is run, so a root's props can't themselves be
an Effect. Props decoded from a Schema never are.
Signature
declare const mount: <Name extends string, Props, Model, Msg, Events, R, V extends View.Elements, RF = never, RP = never>(component: Component.Members<Name, Props, Model, Msg, Events, R, V, any>, props: Component.PropsInput<Props, never, RP>, container: unknown, options?: { readonly fallback?: (failure: AsyncResult.Failure<never, unknown>, h: View.WithTags<never, {}, V>) => View.Content<never, RF>; readonly head?: boolean; readonly key?: string; readonly onEmit?: (event: Events) => void; readonly query?: QueryOptions;}) => Effect.Effect<Root<Model, Msg, Props>, never, R | RF | RP | HostOf<V> | Renderer | Scope.Scope>Runs a component tree the way a server renders it, and returns the tree to
serialise. Server renderers such as HtmlServer.renderToHtml build on it.
Details
The tree renders synchronously. Provided Layers are built, and data comes
from queries: a per-request cache fetches each key at most once, ignores
staleTime, and dispatches each watch when its entry settles, so a watch
message that changes a query's args fetches the next key in the same
render. No Command runs: init's are dropped silently, and one from
update is dropped, logged as CommandDropped with reason "server"
and reported as Command.ServerCommandIssued. Events are applied, so a
child can change its parent. Subscriptions other than query watches, and
onMount work, never run.
Rendering waits until nothing is in flight or budget (default 500 ms) is
spent, whichever comes first. Any fetch in flight holds it, a prefetch
nobody renders included. The budget limits waiting on Layers and fetches,
not the render itself. A Layer that missed it, or that a provide kept off
the server with { server: false }, defers its instance. A fetch that
missed it is interrupted and its entry isn't shipped, so the client fetches
it. A budget of 0 starts no fetch. The tree and the cache are serialised
once, in document order, and its Scopes are closed.
static: true is for HTML built at deploy or held in a CDN. It is written
into the state, and the client hydrates every entry with an unknown age: an
entry is stale, and refetches once, unless its query's staleTime is
"Infinity", and there is no fetch-free window.
elements lists the vocabularies the server renders, by name, as a host's
elements does.
Use distinct key options for repeated roots in one document. The key
sets the root's path to /<name>[<key>] and is saved in state for hydration.
includeProps: true adds the root's props to the state as ~props,
as HtmlServer.renderToHtml describes.
props may be an Effect, as with mount: it is run once, before init,
and its requirements are added to the render's. The client resolves its
own, so with Router.props both sides read the route from their Router.
Signature
declare const prerender: <Name extends string, Props, Model, Msg, Events, R, V extends View.Elements, RP = never>(component: Component.Members<Name, Props, Model, Msg, Events, R, V, any>, props: Component.PropsInput<Props, never, RP>, options?: { readonly budget?: Duration.Input; readonly elements?: ReadonlyArray<string> | "any"; readonly includeProps?: boolean; readonly key?: string; readonly static?: boolean;}) => Effect.Effect<Prerendered<Model, View.HeadValue<V>>, never, R | RP>Declares a ref. A vocabulary wraps this to type the node by tag.
Signature
declare function ref<Node = unknown>(name: string): Ref<Node>Inspection
Looks up a mounted component within root by the instance number in its
MessageLog entries. Returns a handle for inspection and dispatch, or
undefined if no mounted instance has that number.
Details
Without an enabled MessageLog, instances are unnumbered, so this returns
undefined.
Signature
declare function instance(root: Root<unknown, never, never>, number: number): ControlledInstance | undefinedinstanceAt
unstableReturns the instance of root that owns a host node, or undefined.
With root.session, its instance finds the instance's MessageLog
entries.
Details
Slot content belongs to the instance that passed it. An element with a
headless component's part belongs to that component, or the outermost owner
when parts are composed. Other rendered nodes belong to the instance whose
view wrote them. A node the renderer didn't create belongs to the owner of
its nearest rendered ancestor, found with Host.parentOf.
Returns undefined for the container, nodes outside it, nodes of a nested
root, nodes of unplaced bound children, removed nodes, and every node
once the root has closed. Without a MessageLog, instances are
unnumbered, so it always returns undefined.
Signature
declare function instanceAt(root: Root<unknown, never, never>, node: unknown): Instance | undefinedLayers
Provides a Host to mount on.
Signature
declare function layer<Node>(host: Host<Node>): Layer<Renderer>slowPhases
unstableReports each update, view or flush that takes longer than its budget, in
every tree mounted with this Layer.
Details
A phase without a budget isn't timed, one within its budget allocates
nothing, and one that throws isn't reported. Time comes from the Clock's
monotonic reading, so tests can script it. onSlow runs synchronously, and
an error it throws is logged with Effect.logError.
Gotchas
message is the raw message, not redacted. Send only what you need, such
as its _tag, to a remote service.
Signature
declare function slowPhases(options: { readonly flush?: Input; readonly onSlow: (slow: SlowPhase) => void; readonly update?: Input; readonly view?: Input;}): Layer<never>Example Reporting slow phases
import { Renderer } from "effect/ui"
const SlowPhases = Renderer.slowPhases({ update: "4 millis", view: "16 millis", flush: "16 millis", onSlow: (slow) => console.warn(slow.phase, slow.duration)})Models
A mounted component's metadata, message schema, and dispatch function.
Details
Running the effect returned by dispatch sends a message to this component
in its own step, waiting for a view transition that blocks the component.
The logged Update has source { _tag: "Dispatch" }, as with the root's
send. The effect returns the outcome described by Dispatched.
Dispatch does not decode the message. Tools accepting JSON must decode it
with the message schema first.
Signature
interface ControlledInstance extends Instance { readonly dispatch: (message: unknown) => Effect<Dispatched>; readonly message: Top;}How a host reports an event: the event's name, the handler it found on the innermost element with one, and the payload it built.
Details
The handler runs once, synchronously. When it produces a message,
onMessage runs before the message is sent, while the host's event is
still being handled, with the options the handler was set with, so the
host can act on them there, such as cancelling the event's default. Each
layer of an element that parts of headless components decorated runs it
with its own options. It doesn't run when the handler returns undefined
or fails, or when the instance is gone or not yet started. The result is
whether a handler produced a message.
Signature
type Dispatch = (event: string, handler: View.Handler<unknown, any>, payload: unknown, onMessage?: (options: View.EventOptions) => void) => booleanThe outcome of running a ControlledInstance.dispatch effect.
Details
Updated carries the seq of the logged Update entry. Failed carries
the seq of the Failed entry logged when update threw.
Ignored gives a reason: closed, waiting to adopt server nodes, or
frozen means update did not run. unchanged means update ran but
returned undefined.
Signature
type Dispatched = { readonly _tag: "Updated"; readonly seq: number;} | { readonly _tag: "Failed"; readonly seq: number;} | { readonly _tag: "Ignored"; readonly reason: "closed" | "waiting" | "frozen" | "unchanged";}An element's events as a host reads them: its handlers, the dispatch that runs them and their options.
Signature
interface Events { readonly dispatch: Dispatch; readonly handlers: Readonly<Record<string, View.Handler<unknown, any>>>; readonly options: Readonly<Record<string, View.EventOptions>>;}What a target must provide to show views: node operations plus a few capabilities.
Details
The renderer never inserts by index and never relies on comment nodes: a
child's node range is computed from its rendered tree. Property values are
unknown, so a host decides what a property means. Hosts own events: an
element's handlers are stored as data with setEvents, and the host turns
its own events into plain payloads and calls dispatch for the innermost
element with a handler, so re-rendering never touches listeners. The
element's EventOptions come with its handlers: a host with cancellable
events honours preventDefault: true in the options dispatch gives
onMessage, and preventDefault: "always" before it calls dispatch.
A handler value is opaque to the host. It may be a message, a function or
a value the renderer made, such as the one standing for every layer of an
element that parts of headless components decorated. The host stores it
as given and passes that same value back to dispatch, never calling or
copying it.
createElement gets props for construction options and an optional parent
for context such as namespaces. It must not change or keep the props record.
setProp sets each prop after the children are placed. Changing a prop
never rebuilds the node; give the element a new key to remount it.
elements lists the vocabularies the host shows, by name, or is "any".
controlled lists the properties re-applied after every patch, since the
user may have changed them; the host skips a no-op. A user edit the Model
didn't follow isn't patched, so the host puts it back once the event has
run. Its members must not change once the host renders. runsMounts: true
promises each mount the node its vocabulary types, a DOM element for
Html. A host that never runs onMount work, or shows a vocabulary on
other nodes, sets it to false. A function runs in place of each mount's
body, with the mount's lifecycle and log unchanged: send delivers a
result as the body would, and the Effect is interrupted when the element
goes. commit is called once at the end of each flush and after mounting,
for hosts that apply changes in a batch.
head receives the head the runtime folded, in the root vocabulary's form
(an HtmlHead for Html when HtmlHead is imported, else a title-only
Head), after the commit of every flush that changed
a view, once every instance has adopted. The host diffs it against what it
applied last. A mount with head: false never calls it. A host without a
document, such as a native one, leaves it out and the head is only
computed.
hydration lets the renderer read nodes a server rendered, so a
hydrating mount adopts them. A host without it builds every node fresh.
visible, if given, says whether the host shows node: false when it
or an ancestor is hidden, or it's off the host's tree. Key and paste
Subscriptions skip an instance whose first node it hides. A host without
it shows every placed node.
fits, if given, says whether node, made under another parent, can move
under parent as it is: false for an HTML element moving into an SVG
one. A bound child moved where its nodes don't fit is drawn again there,
keeping its Model. A host without it moves every node.
events, if given, has the host read an element's events from the
renderer when an event fires, so the host stores nothing per element and
setEvents is never called. A host without it gets setEvents.
removeChildren, if given, removes nodes, all children of parent, at
once, as remove on each would. The renderer may call it when a patch
removes every node of a list, so a host can clear a parent that holds
nothing else in one step. A host without it gets remove for each node.
unmounting, if given, is called once when a mount's Scope closes, before
its instances close or its nodes are removed, so a host such as a terminal
can keep the last frame. nodes are the mount's own top-level nodes in
container, in order and still attached, including the empty text node a
blank view leaves. If it throws, the mount still tears down and closing the
Scope dies with the error. The BrowserHost DOM path, and a mount whose
Scope closed before it placed anything, never call it.
viewTransition, if given, is called for a flush that renders an update
whose step called $.viewTransition, before it renders, with the rest of
the flush as update and the types the steps asked for. The host calls
update once, now or later, such as inside document.startViewTransition.
Until it does, the flush waits, and what arrives meanwhile renders in it,
without adding its types.
Once the root has closed, update does nothing. A host without it ignores
the request, and the flush runs as any other. The first mount never calls
it.
hot: true lets a hot-reload runtime swap the code of a component mounted
on the host without losing its state, as Vite's does in the browser. In
development, mount registers its root with the hook at
globalThis[Symbol.for("effect/ui/hot/swap")], which takes the first
and the next exports of a module and the names of its components, swaps
them in place and returns true, or returns false when the change
needs a reload. In production it does nothing.
Signature
interface Host<Node> { readonly commit?: () => void; readonly controlled: ReadonlySet<string>; readonly elements: readonly Array<string> | "any"; readonly events?: HostEvents<Node>; readonly fits?: (parent: Node, node: Node) => boolean; readonly head?: (head: any) => void; readonly hot?: boolean; readonly hydration?: Hydration<Node>; readonly normalizeAttrs?: (node: Node, attrs: Readonly<Record<string, string>>) => Readonly<Record<string, string>>; readonly removeChildren?: (parent: Node, nodes: readonly Array<Node>) => void; readonly runsMounts: boolean | (mount: HostMount<Node>, send: (result: unknown) => Effect<void>) => Effect<void>; readonly unmounting?: (container: Node, nodes: readonly Array<Node>) => void; readonly viewTransition?: (update: () => void, types: readonly Array<string>) => void; readonly visible?: (node: Node) => boolean; createElement(tag: string, props: Readonly<Record<string, unknown>>, parent?: Node): Node; createText(text: string): Node; insertBefore(parent: Node, node: Node, ref: Node | undefined): void; nextOf(node: Node): Node | undefined; parentOf(node: Node): Node | undefined; remove(node: Node): void; setAttr(node: Node, name: string, value: string | undefined, previous?: string): void; setEvents(node: Node, handlers: Readonly<Record<string, View.Handler<unknown, any>>>, dispatch: Dispatch, options: Readonly<Record<string, View.EventOptions>>): void; setProp(node: Node, name: string, value: unknown): void; setText(node: Node, text: string): void;}How a host reads its elements' events from the renderer when an event
fires, instead of storing them per element with setEvents.
Details
Each mount calls connect once with its lookup, and calls the function
it returns when the mount ends. A host may serve several mounts at once, so
it asks each mount's lookup. lookup takes an event's path, innermost node
first, as composedPath() gives it, and returns, at each index, the events
of that node if it is an element of the mount's tree. The renderer reads
them from the tree it rendered last, so a node that is no longer in the
tree gets no events. While a patch runs, the events it gave an element come
first: an event the patch causes, such as one a custom element's
connectedCallback fires, gets what setEvents would have given. The nodes of a
detached child are found from its container, for a host that dispatches
events there: a host listening on the document gets none from them.
listen is called where setEvents would be, with the handlers and
options of an element that has some, so the host can start listening for
the events they name. It may be called again with the same names.
Signature
interface HostEvents<Node> { connect(lookup: (path: readonly Array<Node>) => readonly Array<Events | undefined>): () => void; listen(handlers: Readonly<Record<string, View.Handler<unknown, any>>>, options: Readonly<Record<string, View.EventOptions>>): void;}A mount a host's runsMounts function stands in for: the instance's
path, the element's node, and the mount the view last rendered there.
Signature
interface HostMount<Node> { readonly mount: Any; readonly node: Node; readonly path: string;}How a host reads the nodes a server rendered, so hydration can adopt them.
Details
The server brackets an instance's nodes with two markers carrying its path,
<!--[path--> and <!--]path--> in HTML, except for a declared child whose
state is shipped, whose component provides no Layer, and whose view's root
is an element: that child is written as its element alone, and hydration
matches it by position when its path is in the state. Hydration still
accepts marker pairs for any child. inspect tells the renderer what a node
is: an element by tag, a text node, one of those markers, or anything else,
which never matches. Siblings are read with the host's nextOf. An element
whose content the host parses as text only, such as an HTML textarea, is
marked textOnly: the server writes only its text, and hydration adopts the
element but builds its children fresh.
adoptProp, if given, sets a property of an adopted element in place of
setProp, so the host can keep what the user changed in the server's
nodes before they adopted. A host without it gets setProp.
Signature
interface Hydration<Node> { readonly adoptProp?: (node: Node, name: string, value: unknown) => void; firstChild(node: Node): Node | undefined; getAttr(node: Node, name: string): string | undefined; inspect(node: Node): { readonly _tag: "Element"; readonly tag: string; readonly textOnly?: boolean; } | { readonly _tag: "Text"; readonly text: string; } | { readonly _tag: "Open"; readonly path: string; } | { readonly _tag: "Close"; readonly path: string; } | { readonly _tag: "Other"; };}An instance of a mounted root, as its MessageLog entries name it.
Signature
interface Instance { readonly component: string; readonly instance: number; readonly path: string;}The server render result, including state for hydration and reported failures.
Signature
interface Prerendered<out Model, out H = unknown> { readonly failures: readonly Array<ServerFailure>; readonly head: H; readonly model: Model | undefined; readonly nodes: readonly Array<ServerNode>; readonly state: State;}Cache-wide options for the query cache a mount owns. The app never
provides the cache, so they go through mount.
Signature
interface QueryOptions { readonly idleTimeToLive?: Input;}A name for an element, so a Command can reach its host node.
Details
Refs are declared at module level and typed by the node they reach, so a
vocabulary types them by tag. A ref resolves within the instance that issued
the Command, so two instances never collide. at derives a ref for one row
of a list.
Signature
interface Ref<in out Node> { readonly "~Node"?: (_: Node) => Node; readonly at: (key: string | number) => Ref<Node>; readonly key: string; readonly name: string;}A mounted tree.
Signature
interface Root<out Model, in Msg, in Props = never> { readonly adopted: Effect<void>; readonly model: () => Model | undefined; readonly path: string; readonly send: (message: Msg) => void; readonly session: string; readonly setProps: (props: Props) => void;}A server render failure, excluded from serialized state. path identifies
the failed instance; ~deferred may instead list an ancestor whose subtree
hydration rebuilds. Intentional deferrals do not produce failures.
Signature
interface ServerFailure { readonly cause: Cause<unknown>; readonly in: FailedIn; readonly path: string;}A node of a server-rendered tree. A Range is one instance's nodes, a
slot's content, or the fallback of a child, under its path. A declared
child whose state is shipped, whose component provides no Layer, and whose
view's root is an element is emitted as that Element without a wrapping
Range.
Signature
type ServerNode = { readonly _tag: "Element"; readonly attrs: Readonly<Record<string, string>>; readonly children: ReadonlyArray<ServerNode>; readonly props: Readonly<Record<string, unknown>>; readonly tag: string;} | { readonly _tag: "Text"; readonly text: string;} | { readonly _tag: "Range"; readonly children: ReadonlyArray<ServerNode>; readonly path: string;}One phase that took longer than its budget, from slowPhases.
Details
update: oneupdatecall, with its message.view: one view call, without its children's views, which run later.flush: one render pass, including every view, the host writes and thecommittedcallbacks. The first mount is one flush, from its firstinit. A flush held for a view transition is reported once it commits, without the time spent waiting for the browser.
A view's time also counts toward its flush. A view rendered before a
message's update runs outside any flush.
duration and budget are in milliseconds.
Signature
type SlowPhase = { readonly budget: number; readonly component: string; readonly duration: number; readonly message: unknown; readonly path: string; readonly phase: "update";} | { readonly budget: number; readonly component: string; readonly duration: number; readonly path: string; readonly phase: "view";} | { readonly budget: number; readonly duration: number; readonly phase: "flush";}What a server render hands the client: each instance's Schema-encoded Model and query results by path, the paths to build fresh, and the query entries the server's per-request cache settled.
Details
~deferred lists instances the client builds fresh instead of adopting:
a provided Layer kept off the server, and state that can't be shipped. A
deferred path covers its subtree.
~query holds every entry that settled on the server, a typed Failure
included, by query name and args key. The client's cache hydrates from it,
so a watch over a shipped entry doesn't fetch while the hydration window is
open. An entry still in flight at the budget isn't shipped, and the client
fetches it. ~static is set by a render with static: true, and ~key by
a render with key so hydration mounts at the same root path.
~props holds the root's props, encoded with its props Schema, from a
render with includeProps: true. Use HtmlHydrate.decodeProps to read them.
~reported holds, by path, an owner's reports from its readers, encoded
with its collects.schema, unless it has none. An owner that adopts its
Model starts from them, so its first render matches the server's and its
collects.onChange runs only if the client's reports differ, even with no
reader left to report. The comparison waits until nothing below the owner
is still building its Layer to adopt. An owner whose collects.schema holds
a Schema.Redacted can't ship them, so it's deferred with its subtree.
Gotchas
Query data is public: a query's success, error and args are in the state even when no view renders them.
An instance whose Model or query Schemas hold a Schema.Redacted is
never in the state: it's deferred, so the client builds it and its
subtree fresh, and the server logs a warning once per component.
The client decodes the state with its own Schemas, so it has to come from a
server on the same build. A path whose state doesn't decode isn't adopted:
the client runs init and builds it and its subtree fresh. Only ~query
hydrates the cache. Without it, every query fetches again, and instances
whose snapshots reference ~query are built fresh rather than adopted.
Signature
interface State { [path: string]: unknown; readonly "~deferred"?: readonly Array<string>; readonly "~key"?: string; readonly "~props"?: unknown; readonly "~query"?: unknown; readonly "~reported"?: { [path: string]: unknown; }; readonly "~static"?: boolean;}Schemas
The Schema of a ref in a Command's args: it encodes to the ref's key.
Details
The log shows a ref Command's args through it. Decoding a key gives a ref
with that key, named by the part before any at keys.
Gotchas
The name is read up to the first [, so a ref whose name contains [
decodes with a shorter name. Its key is still exact, and the runtime
resolves refs by key.
Signature
declare const Ref: decodeTo<declare<Ref<any>, Ref<any>>, String, never, never>Services
The Refs service.
Signature
declare const Refs: Service<Refs, Refs>How a Command reaches an element of the instance that issued it.
Details
lookup waits until the render the issuing update caused has been
committed, and returns Option.none() for a ref that isn't rendered. The
runtime gives every Command run one, so it's a framework service and never
part of a component's requirements.
Signature
interface Refs { readonly lookup: <Node>(ref: Ref<Node>) => Effect<Option<Node>>;}The Renderer service.
Signature
declare const Renderer: Service<Renderer, Renderer>The Renderer service: the Host a tree is mounted on.
Signature
interface Renderer { readonly host: Host<any>;}