Skip to content
// EFFECT DAYS 2026

HtmlSubscription unstable

The Subscriptions to the page, as opposed to one element's events: onDocument for a game's arrow keys or a press outside a popup, shortcuts for a table of keyboard shortcuts, keySequences for one with multi-key rows such as g then l, onCustomEvent for a CustomEvent dispatched on the document, onWindow for the window's focus, scroll and resize, onAnimationFrame for animation, onMediaQuery for CSS media queries, onVisibility for tab visibility, and onConnectivity for network connectivity.

Details

Their sources are GlobalEvents, AnimationFrames, MediaQueries, Query.Visibility, and Query.Connectivity, which BrowserHost.layer provides. Nothing listens on the server. A test drives them with HtmlScene, with TestGlobalEvents, TestAnimationFrames and TestMediaQueries from effect/ui/html/testing, or with TestHost.setVisible and TestHost.setOnline (which TestHost.layer() always provides, starting true).

23 exports Since v4.2.0 Source

Events

CustomEventPayload

interface unstable
Since v4.2.0

The payload of onCustomEvent: the event's detail, which is null when the event has none.

Signature

interface CustomEventPayload {
readonly detail: unknown;
}

DocumentEvents

interface unstable
Since v4.2.0

The events onDocument listens for, with their payloads: the same ones an element's handler gets.

Details

pointerup and pointercancel get the pointer payload. Together they end every press, including one the browser cancels, such as a touch that turns into a scroll, which sends no mouseup.

Signature

interface DocumentEvents {
readonly click: PointerPayload;
readonly keydown: KeyPayload;
readonly keyup: KeyPayload;
readonly mousedown: PointerPayload;
readonly mouseup: PointerPayload;
readonly pointercancel: PointerPayload;
readonly pointerup: PointerPayload;
}

GlobalEventOptions

interface unstable
Since v4.2.0

The options of onDocument, onCustomEvent and onWindow: preventDefault, as on an element's handler, and capture, to listen in the capture phase, before any element sees the event, so a handler that stops it can't hide it.

Signature

interface GlobalEventOptions extends EventOptions {
readonly capture?: boolean;
}

GlobalPayload

type unstable
Since v4.2.0

The payload of a document or window listener: the event's payload, whether something already cancelled the event's default, the event's timeStamp in ms, and whether a modal is open in the document.

Details

In the bubble phase defaultPrevented includes every element handler set with preventDefault, since the host's own listeners run on the document in the capture phase. In the capture phase it depends on the order the listeners were added in, so don't read it there.

The test tools default timeStamp to 0, so a test sets it to move time between presses for keySequences.

modal is true while a dialog the host opened with showModal(), or an element given to holdModal, is in the document, wherever the event started. HtmlKeyboard.shortcuts skips rows without whileModal then.

Signature

type GlobalPayload<P> = P & {
readonly defaultPrevented: boolean;
readonly modal: boolean;
readonly timeStamp: number;
}

holdModal

unstable
Since v4.2.0

Marks element as a modal shown in its document, so document and window listeners there get modal: true until the returned function releases it.

When to use

Use when the host doesn't open a modal itself, as with a popover drawn as a modal layer, so the page's shortcuts stop matching behind it. A dialog written with h.dialog.modal(true) is held already.

Details

The hold counts only while element is in the document it was held in, so one left behind by a removed element doesn't keep the page's shortcuts off. A modal moved to another document needs a new hold there, and the old one released. Release it as the modal starts closing.

Signature

declare const holdModal: (element: Element) => () => void

KeySequenceOptions

interface unstable
Since v4.2.0

The options of keySequences: those of onDocument, and timeout, the longest gap allowed between two presses of a row.

Signature

interface KeySequenceOptions extends GlobalEventOptions {
readonly timeout?: Input;
}

ResizePayload

interface unstable
Since v4.2.0

The viewport's innerWidth and innerHeight when a window resize fires.

Signature

interface ResizePayload {
readonly height: number;
readonly width: number;
}

WindowEvents

interface unstable
Since v4.2.0

The events onWindow listens for, with their payloads.

Details

focus and blur don't bubble, so a listener in the bubble phase hears only the window's own: the window gaining and losing focus, not an element in it.

Page scroll events bubble from the document to the window; element scroll events don't bubble. With capture: true, the listener also receives element scrolls. In either phase, top and left are the page's window.scrollY and window.scrollX when the event fires.

Signature

interface WindowEvents {
readonly blur: {};
readonly focus: {};
readonly resize: ResizePayload;
readonly scroll: ScrollPayload;
}

References

Since v4.2.0

The source of animation frames. It defaults to one that never fires.

Signature

declare const AnimationFrames: Reference<AnimationFrames>
Since v4.2.0

The source of document and window events. It defaults to one that never fires.

Signature

declare const GlobalEvents: Reference<GlobalEvents>
Since v4.2.0

The source of CSS media query matches. It defaults to one that never fires and sends nothing.

Signature

declare const MediaQueries: Reference<MediaQueries>

Services

AnimationFrames

interface unstable
Since v4.2.0

The source of animation frames, which onAnimationFrame listens to.

Details

listen calls the listener once per frame with the frame's time in ms, until the function it returns is called. now is the current time on the same clock.

BrowserHost.layer provides the one over its document's window, with requestAnimationFrame and performance.now. The default never fires, so a host without a window, and a test that doesn't fire frames, need nothing. A test fires them with HtmlScene's frame, or with TestAnimationFrames from effect/ui/html/testing.

Signature

interface AnimationFrames {
readonly listen: (listener: (time: number) => void) => () => void;
readonly now: () => number;
}

GlobalEvents

interface unstable
Since v4.2.0

The source of document and window events, which onDocument, onCustomEvent and onWindow listen to.

Details

listen adds a listener to the host's document or its window and returns the function that removes it. The listener gets the plain payload, defaultPrevented and timeStamp included, and a function that cancels the event's default. With custom: true the payload is a CustomEventPayload, whatever the event's type.

BrowserHost.layer provides the one over its document and that document's defaultView, so an app in an iframe hears its own document. The default never fires, so a host without a document, and a test that doesn't fire events, need nothing. A test fires them with HtmlScene's fireDocument, fireCustomEvent and fireWindow, or with TestGlobalEvents from effect/ui/html/testing.

Signature

interface GlobalEvents {
readonly listen: (target: "document" | "window", event: string, options: {
readonly capture: boolean;
readonly custom?: boolean;
}, listener: (payload: unknown, preventDefault: () => void) => void) => () => void;
}

MediaQueries

interface unstable
Since v4.2.0

Supplies the current match and change notifications for onMediaQuery.

Details

matches returns whether query currently matches, or undefined when no source is available so onMediaQuery sends nothing on start. listen calls the listener on each change with the new matches value, until the function it returns is called.

BrowserHost.layer provides one over its document's defaultView.matchMedia. The default returns undefined and never notifies listeners. In tests, use HtmlScene.mediaQuery or TestMediaQueries from effect/ui/html/testing.

Signature

interface MediaQueries {
readonly listen: (query: string, listener: (matches: boolean) => void) => () => void;
readonly matches: (query: string) => boolean | undefined;
}

Subscriptions

Since v4.2.0

Listens on the host's document for single-key shortcuts and timed key sequences, such as g then l, and sends the matching row's message.

When to use

Use when rows take Vim- or GitHub-style key sequences. For single-key rows only, use shortcuts, which is smaller.

Details

A row is a HtmlKeyboard.Shortcut with one key, or a HtmlKeyboard.Sequence with keys. Each press is matched with the pending presses against the latest table. The first matching row wins: a complete match sends its message; a prefix waits for the next press. In development, keySequences throws if earlier rows make a later row unreachable, naming the blocked row and a blocking row.

A press more than timeout (1 second by default) after the last matched press starts over. Timing uses the events' timeStamp; no timer runs. A press that does not continue a row is retried as a first press. While a modal is open, only rows with whileModal match, prefixes included. Unmatched modifier-key presses and auto-repeats preserve an unexpired prefix without extending its timeout. A composing or defaultPrevented press clears the prefix, as does gating the subscription off.

preventDefault defaults to true, cancelling matched prefixes as well as completions. Both count as handled in tests. The key is that of onDocument: effect/ui/html/document:"keydown".

Signature

declare function keySequences<Rows extends readonly Array<Shortcut<unknown> | Sequence<unknown>>>(table: Rows, options?: KeySequenceOptions): Subscription<Rows[number]["message"]>

Example Go-to shortcuts

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ WentToList: {}, WentToBoard: {} })
const Nav = Html.component({
name: "Nav",
model: Schema.String,
message: Message
}).make({
init: () => "home",
update: { WentToList: () => "list", WentToBoard: () => "board" },
view: (h, page) => h.p(page),
subscriptions: () => [
HtmlSubscription.keySequences([
{ keys: ["g", "l"], message: Message.WentToList() },
{ keys: ["g", "b"], message: Message.WentToBoard() }
])
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Nav, {})
s.fireDocument("keydown", { key: "g", timeStamp: 0 })
.fireDocument("keydown", { key: "l", timeStamp: 400 })
.expect(Locator.text("list")).toExist()
// Too late: `b` starts over, and begins no row.
.fireDocument("keydown", { key: "g", timeStamp: 1000 })
.fireDocument("keydown", { key: "b", timeStamp: 2500 }).expectIgnored()
}).pipe(Effect.scoped, Effect.runSync)
Since v4.2.0

A Subscription that sends a message on every animation frame, with the time since the last one in ms.

When to use

Use to move a scene along with the screen's refresh, such as a game or a simulation drawn with Canvas. Gate the entry on the Model, so frames come only while it runs.

Details

handler is a message or a function of the delta. The source is AnimationFrames, and the runtime dispatches each frame's message as it fires, so the update, the render and a Canvas repaint all land in the frame that ticked.

The first delta counts from when the Subscription starts, so a pause and resume doesn't jump. A browser stops sending frames to a hidden tab, though, and the first one after it returns covers the whole time away. Cap the delta in update when it drives motion.

The key is effect/ui/html/animationFrame, and an instance has one.

Signature

declare function onAnimationFrame<Msg>(handler: Handler<Msg, number>): Subscription<Msg>

Example A clock that runs while the Model says so

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ TickedFrame: { delta: Schema.Number } })
const Stopwatch = Html.component({
name: "Stopwatch",
model: Schema.Struct({ running: Schema.Boolean, elapsed: Schema.Number }),
message: Message
}).make({
init: () => ({ running: true, elapsed: 0 }),
update: {
// A tab that comes back from the background sends one long frame.
TickedFrame: ($, { delta }) => $.evolve({ elapsed: $.model.elapsed + Math.min(delta, 100) })
},
view: (h, model) => h.p(`${Math.round(model.elapsed)} ms`),
subscriptions: ({ model }) => [
model.running && HtmlSubscription.onAnimationFrame((delta) => Message.TickedFrame({ delta }))
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Stopwatch, {})
s.frame(16).frame(5000)
.expect(Locator.text("116 ms")).toExist()
}).pipe(Effect.scoped, Effect.runSync)
Since v4.2.0

A Subscription that tracks whether the browser is online: it sends the current online value when it starts, then each change.

When to use

Use to show an offline banner, disable actions that require a network connection, or trigger UI state changes when connectivity returns.

Details

handler is a message or a function of online: boolean. The source is Query.Connectivity, which BrowserHost.layer provides from defaultView.navigator.onLine and the window's online and offline events. The server never runs Subscriptions, so init chooses the initial state and the first browser emission updates it after hydration. Without a host, Query.Connectivity defaults to always true, so it emits true once.

In tests, HtmlScene.connectivity drives the handler directly, and TestHost.setOnline drives the shared signal on TestHost and Play (starting true).

The key is effect/ui/html/connectivity, and an instance has one.

Signature

declare function onConnectivity<Msg>(handler: Handler<Msg, boolean>): Subscription<Msg>

Example Showing an offline banner

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ ChangedConnectivity: { online: Schema.Boolean } })
const Banner = Html.component({
name: "Banner",
model: Schema.Boolean,
message: Message
}).make({
init: () => true,
update: { ChangedConnectivity: (_, { online }) => online },
view: (h, online) => h.p(online ? "online" : "offline"),
subscriptions: () => [
HtmlSubscription.onConnectivity((online) => Message.ChangedConnectivity({ online }))
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Banner, {})
s.connectivity(false)
.expect(Locator.text("offline")).toExist()
}).pipe(Effect.scoped, Effect.runSync)
Since v4.2.0

A Subscription that listens for a CustomEvent on the host's document.

Details

It works as onDocument does, with the key effect/ui/html/document, for an event type outside DocumentEvents. The payload carries the event's detail (as unknown) and defaultPrevented. A test fires it with HtmlScene's fireCustomEvent or TestGlobalEvents.fireCustomEvent.

Signature

declare function onCustomEvent<Msg>(event: string, handler: Handler<Msg, GlobalPayload<CustomEventPayload>>, options?: GlobalEventOptions): Subscription<Msg>

Example Listening for a custom document event

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ Received: { text: Schema.String } })
const Banner = Html.component({
name: "Banner",
model: Schema.String,
message: Message
}).make({
init: () => "",
update: { Received: (_, { text }) => text },
view: (h, text) => h.p(text),
subscriptions: () => [
HtmlSubscription.onCustomEvent("app:notice", ({ detail }) =>
typeof detail === "string" ? Message.Received({ text: detail }) : undefined
)
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Banner, {})
s.fireCustomEvent("app:notice", { detail: "saved" })
.expect(Locator.text("saved")).toExist()
}).pipe(Effect.scoped, Effect.runSync)

onDocument

unstable
Since v4.2.0

A Subscription that listens for an event on the host's document.

When to use

Use when the input is one no element of the component hears: a keyboard shortcut, a game's arrow keys, a press outside a popup. Gate the entry on the Model, so the listener exists only while it's wanted. For a table of single-key shortcuts, use shortcuts.

Details

handler is a message or a function of the payload, as on an element, and the payload is plain data with defaultPrevented added. With preventDefault: true the default is cancelled only when the handler returns a message, and with "always" whatever it returns. capture: true listens in the capture phase.

The listener calls the handler of the latest subscriptions result, so a handler that reads the Model sees the current one. The source is GlobalEvents, which BrowserHost.layer provides, so nothing listens on the server and a test fires the event without a document.

The key is effect/ui/html/document with the event as its dep, and "capture" after it for a capture listener: effect/ui/html/document:"keydown". An instance has one listener per event and phase. Listing a second fails the instance as a duplicate key, so put both cases in one handler.

Signature

declare function onDocument<K extends keyof DocumentEvents, Msg>(event: K, handler: Handler<Msg, GlobalPayload<DocumentEvents[K]>>, options?: GlobalEventOptions): Subscription<Msg>

Example Steering with the arrow keys while the game runs

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Direction = Schema.Literals(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"])
const Message = UiSchema.TaggedEnum({ PressedArrow: { key: Direction } })
const Snake = Html.component({
name: "Snake",
model: Schema.Struct({ running: Schema.Boolean, heading: Direction }),
message: Message
}).make({
init: () => ({ running: true, heading: "ArrowRight" as const }),
update: { PressedArrow: ($, { key }) => $.evolve({ heading: key }) },
view: (h, model) => h.p(model.heading),
subscriptions: ({ model }) => [
model.running && HtmlSubscription.onDocument(
"keydown",
// The page doesn't scroll on an arrow key, and other keys keep their default.
({ key }) => Schema.is(Direction)(key) ? Message.PressedArrow({ key }) : undefined,
{ preventDefault: true }
)
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Snake, {})
s.fireDocument("keydown", { key: "ArrowUp" })
.expectDefaultPrevented()
.expect(Locator.text("ArrowUp")).toExist()
}).pipe(Effect.scoped, Effect.runSync)
Since v4.2.0

A Subscription that tracks a CSS media query: it sends the current matches value when it starts, then each change.

When to use

Use to react to viewport breakpoints, color-scheme preferences, or reduced-motion settings in component state.

Details

handler is a message or a function of matches: boolean. The source is MediaQueries, which BrowserHost.layer provides over defaultView.matchMedia. The server never runs Subscriptions, so init chooses the initial state. The first browser emission updates that state.

The key is effect/ui/html/mediaQuery with query as its dep, e.g. effect/ui/html/mediaQuery:"(prefers-color-scheme: dark)", so different queries run side by side.

Signature

declare function onMediaQuery<Msg>(query: string, handler: Handler<Msg, boolean>): Subscription<Msg>

Example Following the user's color scheme

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ ChangedScheme: { dark: Schema.Boolean } })
const Theme = Html.component({
name: "Theme",
model: Schema.Boolean,
message: Message
}).make({
init: () => false,
update: { ChangedScheme: (_, { dark }) => dark },
view: (h, dark) => h.p(dark ? "dark" : "light"),
subscriptions: () => [
HtmlSubscription.onMediaQuery(
"(prefers-color-scheme: dark)",
(dark) => Message.ChangedScheme({ dark })
)
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Theme, {})
s.mediaQuery("(prefers-color-scheme: dark)", true)
.expect(Locator.text("dark")).toExist()
}).pipe(Effect.scoped, Effect.runSync)
Since v4.2.0

A Subscription that tracks whether the tab is visible: it sends the current visible value when it starts, then each change.

When to use

Use to pause timers, media playback, or animations while the tab is hidden, or to react when the user returns to the tab.

Details

handler is a message or a function of visible: boolean. The source is Query.Visibility, which BrowserHost.layer provides from document.visibilityState and visibilitychange. The server never runs Subscriptions, so init chooses the initial state and the first browser emission updates it after hydration. Without a host, Query.Visibility defaults to always true, so it emits true once.

In tests, HtmlScene.visibility drives the handler directly, and TestHost.setVisible drives the shared signal on TestHost and Play (starting true).

The key is effect/ui/html/visibility, and an instance has one.

Signature

declare function onVisibility<Msg>(handler: Handler<Msg, boolean>): Subscription<Msg>

Example Pausing while the tab is hidden

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ ChangedVisibility: { visible: Schema.Boolean } })
const Player = Html.component({
name: "Player",
model: Schema.Boolean,
message: Message
}).make({
init: () => true,
update: { ChangedVisibility: (_, { visible }) => visible },
view: (h, visible) => h.p(visible ? "playing" : "paused"),
subscriptions: () => [
HtmlSubscription.onVisibility((visible) => Message.ChangedVisibility({ visible }))
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Player, {})
s.visibility(false)
.expect(Locator.text("paused")).toExist()
}).pipe(Effect.scoped, Effect.runSync)

onWindow

unstable
Since v4.2.0

A Subscription that listens for an event on the host's window.

Details

Accepts the same handler forms and options as onDocument, with the key effect/ui/html/window. See WindowEvents for the events and payloads.

scroll and resize emit only when an event fires, not on mount. To read initial page offsets or viewport dimensions, use a Mount on an element; this also runs when hydration adopts the element.

Signature

declare function onWindow<K extends keyof WindowEvents, Msg>(event: K, handler: Handler<Msg, GlobalPayload<WindowEvents[K]>>, options?: GlobalEventOptions): Subscription<Msg>

Example Following the window's focus

import { UiSchema } from "effect/ui"
import { HtmlSubscription } from "effect/ui/html"
const Message = UiSchema.TaggedEnum({ FocusedWindow: {}, BlurredWindow: {} })
const subscriptions = () => [
HtmlSubscription.onWindow("focus", Message.FocusedWindow()),
HtmlSubscription.onWindow("blur", Message.BlurredWindow())
]
subscriptions().map((subscription) => subscription.key) // => ['effect/ui/html/window:"focus"', 'effect/ui/html/window:"blur"']

shortcuts

unstable
Since v4.2.0

A Subscription that listens for a table of single-key shortcuts on the host's document: onDocument on "keydown" with the handler of HtmlKeyboard.shortcuts.

When to use

Use when an instance's document shortcuts fit in a table. An instance has one keydown listener per phase, so to combine a table with other keydown logic, or to listen on "keyup", call HtmlKeyboard.shortcuts inside onDocument instead. For rows of several keys, such as g then l, use keySequences.

Details

preventDefault defaults to true, so the browser's default is cancelled for a key a row matches and kept for every other key. The rows match as HtmlKeyboard.shortcuts describes, and the key is that of onDocument: effect/ui/html/document:"keydown".

Signature

declare function shortcuts<Rows extends readonly Array<Shortcut<unknown>>>(table: Rows, options?: GlobalEventOptions): Subscription<Rows[number]["message"]>

Example Document shortcuts from a table

import { UiSchema } from "effect/ui"
import { Html, HtmlSubscription } from "effect/ui/html"
import { HtmlScene } from "effect/ui/html/testing"
import { Locator } from "effect/ui/testing"
import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ OpenedHelp: {}, ClosedHelp: {} })
const Shortcuts = Html.component({
name: "Shortcuts",
model: Schema.Boolean,
message: Message
}).make({
init: () => false,
update: { OpenedHelp: () => true, ClosedHelp: () => false },
view: (h, open) => h.p(open ? "help open" : "help closed"),
subscriptions: () => [
HtmlSubscription.shortcuts([
{ key: "?", message: Message.OpenedHelp() },
{ key: "Escape", message: Message.ClosedHelp(), whileTyping: true }
])
]
})
Effect.gen(function*() {
const s = yield* HtmlScene.make(Shortcuts, {})
s.fireDocument("keydown", { key: "?", editable: true }).expectIgnored()
.fireDocument("keydown", { key: "?" }).expectDefaultPrevented().expect(Locator.text("help open")).toExist()
.fireDocument("keydown", { key: "Escape", editable: true }).expect(Locator.text("help closed")).toExist()
}).pipe(Effect.scoped, Effect.runSync)