BrowserHost unstable
The browser host for effect/ui: mounts a component tree into an element of a
real document.
Events are delegated: the host keeps one listener per event name on the
document, and each element stores its handlers as data, so re-rendering
never touches listeners. An event goes to the innermost element with a
handler for it, and its handler gets a plain payload built from the DOM
event, never the event itself. The host cancels a form submission when
the form has a submit handler or uses the dialog method. Otherwise,
it leaves the browser default intact; the Router can intercept a
same-window GET whose URL the routes parse.
A dialog set with modal(true) is shown with showModal() at the commit
after it's in the document, and closed with close(). Dialogs shown in
the same commit open in document order, so one nested in another is on
top; one shown later is on top of those already open. The host cancels a
modal's cancel and sends it to the cancel handler, so the Model decides. When
the browser closes it anyway, as Chromium does after repeated cancelled
requests, the host shows it again on the next frame while the Model still
wants it, which moves focus to its first focusable element. Browsers
report each close a task later, so the host keeps one record per time it
showed the dialog, and each close event ends the oldest: it reaches
the close handler only for the latest showing, and not for a close the host made
itself. Before removing a dialog it showed that is still open, or an
element containing one, the host closes it, the latest shown first, so
focus goes back to where it was before each one opened, as it does when
the Model closes them. That close isn't the app's either.
A popover's popoverOpen is shown with showPopover() at the commit,
after the modal dialogs, since a modal opening closes the auto popovers
already showing, and hidden with hidePopover(). A "manual" popover is
applied at every commit, including when its component didn't render, since
a move in the document closes it without a toggle, and put back on the
frame after any other change;
an "auto" one is applied only when the Model's value or the mode
changes, and the browser's changes are left for the Model to follow.
Every toggle is sent, including a coalesced one whose states are equal,
since it may be the only report of a change.
Without showPopover() or hidePopover(), a popover is drawn in place,
with no top layer or light dismiss: the host drops its popover
attribute and shows it through a dialog's open or another element's
hidden.
Showing a modal dialog or a popover doesn't scroll the page. A browser
focuses something inside a <dialog> as it shows it and scrolls to it,
so the host puts the page's scroll position back after a showModal()
or a showPopover() that moved focus, which also stops a smooth scroll
the focus started.
A handler set with { preventDefault: true } cancels its event's default
when it produces a message, before the message is sent, and leaves the
event alone when it returns undefined. Nothing else is cancelled, and the
host never stops an event's propagation: the delegated listeners run on the
document in the capture phase, so stopping it there would hide the event
from the target and from every other listener. A cancelled click on a
routed link isn't followed by BrowserRouter. wheel, touchstart and
touchmove aren't in the vocabulary, since browsers make document listeners
for them passive.
The host does the drag and drop work a handler can't. On dragstart it puts
the innermost drag source's draggable data on the drag. While a drag is
over the app it works out the active drop target, the innermost element
whose dropTarget accepts the drag's types, on every dragenter and
dragover, cancels those events there so the browser allows the drop, and
sends the target's enter and leave when it changes, never for its
children. A drag that leaves the window, or is cancelled, leaves the
target: a dragleave from the latest dragenter's element with no enter
by the next task means the pointer left, whichever order the browser fires
them in. dragover is sent at most once per animation frame. A drop on a
target is always cancelled, and its strings and files are read then.
A pointerdown handler set with { capturePointer: true } captures the
pointer on its element when it produces a message. pointermove is
coalesced per animation frame, as Html.Events describes.
value, checked, selected and open are controlled. The host sets them
after the element's children exist, skips a no-op so the caret doesn't jump,
and puts the Model's value back after the user changes it and the Model
didn't follow, whether update rejected the change or nothing handled it.
A focused input or textarea keeps its selection when the host writes
its value. A rejected edit, typed or composed, puts back the selection
from before it, and if the Model takes the edit later, as when its update
runs late, the selection the user left comes back with it. A value
update changed, such as uppercased text or grouped digits, or one the
Model set, keeps each end of the selection with the unchanged text before
it, else after it, and a caret at the end stays at the end. When the text
changed on both sides of the caret, as when a character typed next to a
separator moves it, the caret keeps its offset.
A details the browser toggled isn't written until its toggle is sent:
browsers merge the toggles queued for an element, so a write in between
would hide the user's change from the Model.
A field's value isn't written while an input method composes text in it,
from compositionstart, or an input that says it's composing, to
compositionend, so a patch or a rejected input can't replace the text
being composed; it's put back after compositionend instead.
Under HtmlHydrate.hydrate, a server-rendered control the user changed
before its instance adopted keeps what it shows, and the host sends its state to the element's
input and change handlers as if the events had just fired, then puts the
Model's value back as above if update didn't take it. A control counts as
changed when it differs from both the server's HTML and the Model's value,
so a field the browser filled in, by autofill or by restoring a form, is
reported too, and so is one showing what the browser made of a value it
can't show, such as a range input clamped to its max. A focused text
field gets no change, as the browser sends it when focus leaves.
Example Mounting an app
import { BrowserHost, Html } from "effect/ui/html"import { Layer, Schema } from "effect"import { UiSchema } from "effect/ui"
const Message = UiSchema.TaggedEnum({ ClickedIncrement: {} })
const Counter = Html.component({ name: "Counter", model: Schema.Number, message: Message}).make({ init: () => 0, update: ($) => $.model + 1, view: (h, count) => h.button.on("click", Message.ClickedIncrement()).children(String(count))})
// The tree is mounted for as long as the Layer is built.const main = Layer.launch(BrowserHost.mount(Counter, {}, document.getElementById("app")!))Constructors
The element operations behind HtmlCommand.focus, blur,
scrollIntoView, measure, select, requestSubmit and showPicker,
on DOM elements.
Signature
declare const htmlHost: Context.Service.Shape<typeof Html.Host>Makes a browser host for document, plus dispose, which removes its
listeners.
Details
Most apps use layer or mount, which manage this for them. The host shows
the html vocabulary and host-neutral components. A component of another
vocabulary fails as a child when it mounts.
The host keeps the document head in sync with the tree's folded head: the
<title>, and when HtmlHead is imported the rest of the HtmlHead.
It owns only tags marked data-eui, plus <title> and
lang / dir on <html>, and restores the shell's value once no entry
sets one. Static titles, lang, classes and data-* on <html> and
<body> belong in the root component's head, not in the shell: HTML
keeps the first copy of a duplicated attribute, so the shell's copy would
hide the framework's. warn reports a shell that conflicts with the head
on the first sync, and defaults to console.warn. The check runs in every
build, as effect has no development switch; it looks at the shell once,
and warn: () => {} silences it. Every host on one document shares one
baseline of the shell's values, captured by the first, so a second mount
doesn't take the first one's title for the shell's.
Signature
declare function makeHost(document: Document, options?: { readonly warn?: (message: string) => void;}): Host<Node> & { readonly dispose: () => void;}mountEffect
unstableMounts a component tree into container for the life of the current
Scope, and returns its root.
When to use
Use when the caller needs the root: to read its Model, send it a message
or update its props with setProps. mount is the form that runs an app.
Details
It mounts and checks the root exactly as mount does.
Signature
declare function mountEffect<Name extends string, Props, Model, Msg, Events, R, V extends Elements, RF = never, RP = never>(component: Members<Name, Props, Model, Msg, Events, R, V, any, never> & HtmlRoot<V>, props: PropsInput<Props, never, RP>, container: Element, options?: MountOptions<V, RF, Events>): Effect<Root<Model, Msg, Props>, never, Scope | Exclude<R, Host> | Exclude<RF, Host> | Exclude<RP, Host>>Inspection
instanceAt
unstableReturns a node's owning instance in a mounted Controllable root, or
undefined if none exists. Uses the ownership rules of instancesAt.
Signature
declare function instanceAt(root: Controllable, node: Node): ControlledInstance | undefinedinstancesAt
unstableReturns the owning instance for each node in a mounted Controllable root,
in input order, or undefined for nodes with no owner in that root.
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 did not create uses the nearest rendered ancestor's owner.
Returns undefined for the root's container, nodes outside it, nodes
rendered by a nested root, nodes in pause's painted copy, and nodes of
unplaced bound children.
The lookup walks the root's render records when called. Nodes looked up together share an index of each sibling list.
Signature
declare function instancesAt(root: Controllable, nodes: Iterable<Node>): Array<ControlledInstance | undefined>Returns an instance's top-level rendered nodes that are connected to a document, in render order. Returns an empty array if the instance number is unknown or none of its nodes are connected.
Signature
declare function nodesOf(root: Controllable, instance: number): readonly Array<Node>Layers
defineElement
unstableA Layer that defines tag as a custom element rendering component
while the Layer is built. It provides no service.
When to use
Use to publish a component as a web component, for a page Effect UI
doesn't own or for another framework. Html.customElement does the
reverse: it uses a web component in a view.
Details
Each instance mounts its own root, with its own Scope and query cache, when it connects. The root replaces the element's children and never writes the document head. Instances share the Layer's services, and their generated element ids don't collide, even across tags.
Setting an attribute or property updates the props in place and keeps the
Model. The last write wins, and properties are never reflected to
attributes. An attribute is decoded by its Schema in attributes: a
rejected value is logged with console.error and leaves the prop as it
was, and removing the attribute restores the prop's value in props.
Properties set before the tag was defined are applied on connect, after
the attributes.
Each emission is dispatched on the element as a bubbling, composed
CustomEvent named by its lowercased _tag, with the emission as
detail, so TourBooked arrives as tourbooked.
Moving an element keeps its root, and removing it closes its Scope a
microtask later. Releasing the Layer closes every instance's Scope. The
tag stays defined, as customElements can't undefine it, but its elements
render nothing from then on. Building the Layer for a tag that is already
defined is a defect. DevTools can't pause an instance.
Signature
declare function defineElement<Name extends string, Props, Model, Msg, Events extends { readonly _tag: string;}, R, V extends Elements, RF = never>(tag: string, component: Members<Name, Props, Model, Msg, Events, R, V, any, never> & HtmlRoot<V>, options: DefineElementOptions<Props, V, RF>): Layer<never, never, Exclude<R, Host> | Exclude<RF, Host>>Example Publishing a form as a web component
import { BrowserHost, Html } from "effect/ui/html"import { Effect, Layer, Schema } from "effect"
const TourForm = Html.component({ name: "TourForm", props: Schema.Struct({ unitId: Schema.String }), model: Schema.Struct({}), message: Schema.Never}).make({ init: () => ({}), update: ($) => $.model, view: (h) => h.p(`Tour of ${h.props.unitId}`)})
// <unit-tour-form unit-id="u1"></unit-tour-form>const main = BrowserHost.defineElement("unit-tour-form", TourForm, { props: { unitId: "" }, attributes: { unitId: Schema.String }})
Effect.runFork(Layer.launch(main))Provides the browser host as the Renderer, Html.Host, the document's
Query.Visibility and Query.Connectivity (which also back
HtmlSubscription.onVisibility and HtmlSubscription.onConnectivity), its
events as HtmlSubscription.GlobalEvents, its window's frames as
HtmlSubscription.AnimationFrames, its window's media queries as
HtmlSubscription.MediaQueries, and an HtmlImages.Images and
HtmlFiles.Files over it, for the life of the Layer.
Details
document defaults to the global document. Closing the Layer removes the
host's listeners. Query.Visibility reads document.visibilityState and
Query.Connectivity reads defaultView.navigator.onLine. Every root and
Layer on a document shares these two signals, which listen only while
subscribed. Closing a Layer doesn't release another subscriber's listeners,
so a direct subscriber must unsubscribe. The signals,
HtmlSubscription.GlobalEvents, HtmlSubscription.AnimationFrames,
HtmlSubscription.MediaQueries, HtmlImages.Images and HtmlFiles.Files
use the document and its defaultView, never globals.
Signature
declare function layer(options?: { readonly document?: Document;}): Layer<Host | Renderer>A Layer that mounts a component tree into container for as long as the
Layer is built. It provides no service: launch it with Layer.launch, or
merge it into the app's Layer.
When to use
Use to run an app. Reach for mountEffect when the caller needs the root,
to send it messages or update its props.
Details
The root must render HTML (or be host-neutral): mounting a root of another
vocabulary is a type error. Nested components are checked when they mount,
and one of another vocabulary fails as a child. The tree's requirements
are the root's, minus Html.Host, which the host provides. When the root
itself fails, fallback is shown in its place.
props may be an Effect, such as Router.props(AppRoute). It runs once,
before init, and its requirements are added to the mount's, so a routed
app needs only this Layer and its Router's. A root's props therefore can't
themselves be an Effect.
Commands and Subscriptions run on HtmlScheduler, unless the caller
provides a Scheduler, and the render flush on a microtask. A navigation
Command runs in the flush its update caused, which renders the new route.
To adopt the HTML of HtmlServer.renderToHtml instead of building it, mount
with HtmlHydrate.hydrate.
The head. The mount owns the document head: <title> follows the
tree's folded head, and when HtmlHead is imported so do the marked head
tags and the <html> and <body> attributes. A mount embedded in a page that another mount, or the
server, owns passes head: false: it still computes its head, and its
Router announces the title, but it leaves the document alone. With two
mounts on one document, only the one that owns the head writes it.
For repeated mounts of the same component, also pass distinct key options
to avoid generated element id collisions.
Signature
declare function mount<Name extends string, Props, Model, Msg, Events, R, V extends Elements, RF = never, RP = never>(component: Members<Name, Props, Model, Msg, Events, R, V, any, never> & HtmlRoot<V>, props: PropsInput<Props, never, RP>, container: Element, options?: MountOptions<V, RF, Events>): Layer<never, never, Exclude<R, Host> | Exclude<RF, Host> | Exclude<RP, Host>>Example Launching an app
import { BrowserHost, Html } from "effect/ui/html"import { Effect, Layer, Schema } from "effect"
const App = Html.component({ name: "App", model: Schema.Struct({}), message: Schema.Never}).make({ init: () => ({}), update: ($) => $.model, view: (h) => h.h1("Hello")})
// In the browser entry module.Effect.runFork(Layer.launch(BrowserHost.mount(App, {}, document.getElementById("app")!)))Models
A root mounted with mount, mountEffect or HtmlHydrate.hydrate, offered to Controllables
so a tool such as DevTools can show the page as it was at an earlier state,
and send a message to any of its instances.
Details
instance finds an instance of the root by the instance number its
MessageLog entries carry, while it is mounted. See ControlledInstance.
pause hides the root's container and paints a frozen copy of the tree
next to it. The copy keeps its content inert while showing a not-allowed
cursor over its box and open dialogs and popovers, and drops the
container's tabindex, contenteditable, accesskey, draggable,
autofocus and event handler attributes. Each instance of the
copy adopts the state that state returns for its path, or starts from
init when state returns nothing. See Painted for what it returns.
The frozen copy runs nothing: no Command, init's included, no
Subscription, query watch or fetch, element mount or provided Layer, and
loads no lazy component, so a feature slot whose service comes from a
provided Layer, and a lazy component that hasn't loaded, show their
fallback. It logs no entries, leaves the document head alone, isn't seen
by the Router and takes no events. A modal dialog in the copy is shown as
a manual popover, and an auto popover as a manual one, so the copy never
makes the rest of the page inert, a tool's own UI included, and never
closes the live tree's popovers.
An element mount with a paint option, such as
Canvas.view's, calls it once to draw its node from the painted state.
The live root keeps running while it's hidden: its Commands,
Subscriptions and updates go on, and it renders into its hidden
container. While it's paused, its modal dialogs and auto popovers are
closed, without a toggle or close reaching the Model, and its document
and window listeners don't hear the user's mouse, pointer, touch and key
input. So a click on the copy doesn't reach the live tree or light-dismiss
its popovers, and nothing it shows blocks the rest of the page. Events
that aren't the user's input, and ones code dispatches, still reach it.
Pausing again replaces the painted copy. resume removes the copy, shows
the container again, with whatever happened meanwhile, and shows the modal
dialogs and popovers its Model has open. When a paint fails, pause
removes its copy and leaves the page as it was.
Gotchas
DOM state that isn't in a Model, such as what was typed into an uncontrolled input, scroll positions, focus and media, isn't painted. An element mount of the live root that measures reads zero while it's hidden. Elements of the copy have the same ids as the live ones.
Containers that cannot have a shadow root, such as form and ul, get
an inert copy without the cursor override. Dialog and popover cursor
covers require CSS anchor positioning. Without it, the pointer reaches
the page underneath those elements. The pointer also passes through
content painted outside the copy's box unless it is in the top layer.
Signature
interface Controllable { readonly instance: (instance: number) => ControlledInstance | undefined; readonly path: string; readonly pause: (state: (path: string) => Recorded | undefined) => Effect<Painted>; readonly resume: Effect<void>; readonly session: string;}A component within a Controllable root, with metadata and dispatch support.
See Renderer.ControlledInstance.
Signature
type ControlledInstance = Renderer.ControlledInstanceThe options of defineElement.
Details
props is every instance's starting props. Each key of props and
attributes becomes a property of the element. attributes maps a prop
to the Schema that decodes its kebab-case attribute, so unitId reads
unit-id. shadow mounts each instance in a shadow root, "open" by
default, that adopts styles. fallback and query are as for
mount. document defaults to the global one and also selects its
window's customElements.
Signature
interface DefineElementOptions<Props, V extends View.Elements, RF = never> { readonly attributes?: { [K in string | number | symbol]: Codec<Props[K], string, never, unknown> }; readonly document?: Document; readonly fallback?: (failure: Failure<never, unknown>, h: Helper<never, {}> & Tags<V, never>) => Content<never, RF>; readonly props: Props; readonly query?: QueryOptions; readonly shadow?: boolean | { readonly mode?: ShadowRootMode; readonly styles?: readonly Array<string>; };}The outcome of running a ControlledInstance.dispatch effect.
See Renderer.Dispatched.
Signature
type Dispatched = Renderer.DispatchedThe options of mount and mountEffect, and of HtmlHydrate.hydrate.
Signature
interface MountOptions<V extends View.Elements, RF = never, Events = unknown> { readonly fallback?: (failure: Failure<never, unknown>, h: Helper<never, {}> & Tags<V, never>) => Content<never, RF>; readonly head?: boolean; readonly key?: string; readonly onEmit?: (event: Events) => void; readonly query?: QueryOptions;}What Controllable.pause painted that differs from the page at that state.
Details
fellBack has the paths of the instances state returned nothing for,
which started from init. fallbacks has the path of each instance
whose view shows a feature slot's fallback, because the copy doesn't
build the provided Layer the feature's service comes from. skipped has
the path of each instance whose view puts an element mount on the copy
that has no paint, or whose paint threw, so its node may be blank.
All three may show something the page never showed at that state.
topLayer is true when the copy shows a dialog or popover. They open in
the top layer above what was already there, so a tool that keeps its own UI
in the top layer shows it again after such a paint.
Signature
interface Painted { readonly fallbacks: readonly Array<string>; readonly fellBack: readonly Array<string>; readonly skipped: readonly Array<string>; readonly topLayer: boolean;}An instance's state as a tool recorded it from the MessageLog: the
Model of a Mounted or Update entry, for a component with queries
its query results, and the props of its Mounted or latest
PropsChanged entry.
Details
Without props, the instance takes the props its parent's view passes it,
and the root its current props. With them, it takes those, so
a child shows the props it had at that entry, even when its parent's
Model at that entry would pass it newer ones or its parent wasn't
recorded.
Signature
interface Recorded { readonly model: unknown; readonly props?: unknown; readonly queries?: Results;}Services
Controllables
unstableThe Controllables service, read by mount, mountEffect and
HtmlHydrate.hydrate.
Signature
declare const Controllables: Reference<Controllables>Where mount, mountEffect and HtmlHydrate.hydrate offer their roots to be paused and sent
messages.
Details
register is called with each root as it mounts, and the function it
returns when the root unmounts. The default ignores every root, so a tool
that controls roots provides its own.
Signature
interface Controllables { readonly register: (root: Controllable) => () => void;}Utility Types
Passes when a root shows HTML or is host-neutral, and otherwise names the host its vocabulary needs.
Signature
type HtmlRoot<V> = [Renderer.HostOf<V>] extends [Html.Host] ? unknown : { readonly "BrowserHost.mount shows HTML elements. This root's vocabulary needs": Renderer.HostOf<V>;}