/** * Subscriptions are keyed Streams an instance runs while it asks for them. * * A component's `subscriptions: ({ model, props }) => [...]` is re-run on mount, * after each `update` and on a props change. The result is diffed by key: a * key that disappears has its Scope closed first, then a new key starts in a * child Scope of the instance. Each element the Stream emits is dispatched to * the instance as a message. A key runs one Stream, so a result that lists * one key twice fails the instance. * * Rule of thumb: if the lifetime is an event (an upload, one long poll), use a * Command. If you can say "while ...", use a Subscription. A Subscription's * source is a service or the clock, never a captured global, which is what * makes it testable. * * **Example** (A timer while running, and a room keyed on a prop) * * ```ts import.meta.vitest * import { Subscription, UiSchema } from "effect/ui" * import { Schema, Stream } from "effect" * * const Message = UiSchema.TaggedEnum({ Ticked: {}, Received: { text: Schema.String } }) * * const roomMessages = (roomId: string) => Stream.make(`hello from ${roomId}`) * * const subscriptions = ({ model, props }: { * readonly model: { readonly running: boolean } * readonly props: { readonly roomId: string } * }) => [ * model.running && Subscription.make("tick", Stream.tick("1 second").pipe(Stream.as(Message.Ticked()))), * Subscription.make("room", props.roomId, (roomId) => * roomMessages(roomId).pipe(Stream.map((text) => Message.Received({ text })))) * ] * ``` * * @stability unstable * @since 4.2.0 */ import type * as Cause from "../Cause.ts" import type * as Context from "../Context.ts" import * as Effect from "../Effect.ts" import * as Stream from "../Stream.ts" import * as services from "./internal/services.ts" import * as subscriptionRun from "./internal/subscriptionRun.ts" import * as subscriptions from "./internal/subscriptions.ts" subscriptions.load(subscriptionRun.sync) /** * Identifies a Subscription. * * @stability unstable * @category type ids * @since 4.2.0 */ export const TypeId = "~effect/ui/Subscription" as const /** * Identifies a Subscription. * * @stability unstable * @category type ids * @since 4.2.0 */ export type TypeId = typeof TypeId /** * A keyed Stream declaration. * * **Details** * * `key` identifies the Subscription across renders: the runtime diffs by it, * and two entries of one `subscriptions` result that share a key fail the * instance. `name` and `deps` are what `make` built the key from, kept apart * so a tool can group a component's `room` Subscriptions without parsing * keys. `name` is the string `make` was given, with no escaping. `deps` is * always an array, so a single dep and a one-element tuple, which share a * key, share their `deps` too. It's `undefined` for a Subscription with no * deps. * * `stream` has `E = never`: a defect fails the instance, and a Stream that * ends stays stopped until its key leaves and comes back. Reconnect logic * lives in the Stream. `R` joins the component's requirements. * * @stability unstable * @category models * @since 4.2.0 */ export interface Subscription { readonly [TypeId]: TypeId readonly key: string readonly name: string readonly deps?: ReadonlyArray | undefined readonly stream: Stream.Stream } /** * The primitives a Subscription may depend on. They're joined into the key. * * @stability unstable * @category models * @since 4.2.0 */ export type Dep = string | number | boolean | null /** * One dependency or a tuple of them. * * @stability unstable * @category models * @since 4.2.0 */ export type Deps = Dep | ReadonlyArray /** * The requirements of a Subscription, or of a union of them. * * @stability unstable * @category utility types * @since 4.2.0 */ export type Requirements = S extends Subscription ? R : never /** * The key of a Subscription: the name, and with deps a colon followed by the * deps joined with commas. * * **Details** * * Strings are JSON-quoted and other deps are their literal, so `1` and `"1"`, * `["a,b", "c"]` and `["a", "b,c"]`, `NaN` and `null`, or `0` and `-0`, never * share a key. * A colon in a name is doubled, so a name can't pass for a name with deps: * `keyOf("page:null")` is `page::null` and `keyOf("page", null)` is `page:null`. * A single dep and a one-element tuple share a key, as they mean the same. * * **Example** (Reading keys) * * ```ts import.meta.vitest * import { Subscription } from "effect/ui" * * Subscription.keyOf("tick") // => "tick" * Subscription.keyOf("room", "42") // => 'room:"42"' * Subscription.keyOf("cell", [1, true]) // => "cell:1,true" * Subscription.keyOf("page:null") // => "page::null" * ``` * * @stability unstable * @category constructors * @since 4.2.0 */ export const keyOf: (name: string, deps?: Deps) => string = subscriptions.keyOf /** * Declares a keyed Subscription. * * **When to use** * * Use to run a Stream for as long as the Model and props ask for it: a clock * tick while a timer runs, a chat room's messages while a room is shown. * * **Details** * * With deps, the builder sees only its deps, never the Model, so a Stream * can't hold stale Model values. The deps are joined into the key * (`room:"42"`, see `keyOf`), so `room:"1"` and `room:"2"` are never both * connected: the old key closes before the new one starts. The builder runs * when the Stream starts, not when `subscriptions` returns the Subscription, * so it never runs on the server. * * **Example** (Keying a Subscription on a prop) * * ```ts import.meta.vitest * import { Subscription, UiSchema } from "effect/ui" * import { Schema, Stream } from "effect" * * const Message = UiSchema.TaggedEnum({ Received: { text: Schema.String } }) * * const roomMessages = (roomId: string) => Stream.make(`hello from ${roomId}`) * * const room = Subscription.make("room", "42", (roomId) => * roomMessages(roomId).pipe(Stream.map((text) => Message.Received({ text })))) * * room.key // => 'room:"42"' * room.name // => "room" * room.deps // => ["42"] * ``` * * @stability unstable * @category constructors * @since 4.2.0 */ export const make: { ( name: string, stream: Stream.Stream ): Subscription ( name: string, deps: D, build: (deps: D) => Stream.Stream ): Subscription } = ( name: string, depsOrStream: any, build?: (deps: any) => Stream.Stream ): Subscription => build === undefined ? { [TypeId]: TypeId, key: keyOf(name), name, deps: undefined, stream: depsOrStream } : { [TypeId]: TypeId, key: keyOf(name, depsOrStream), name, deps: Array.isArray(depsOrStream) ? depsOrStream : [depsOrStream], stream: Stream.suspend(() => build(depsOrStream)) } const directState = Symbol.for("effect/ui/Subscription/directState") /** * The controls passed to a {@link direct} Subscription's attach callback. * * **Details** * * `enter` renders pending ancestors and calls `f` with the latest state * declared for this Subscription's key, unless the Subscription has stopped. * `emit` dispatches a message synchronously, calling `accepted` right before * dispatch so a host listener can cancel the event's default. `fail` fails * the subscribing instance with `cause`. `drawn` is `false` while the * instance, or a component above it, is a kept child that isn't drawn, so a * host's input source can skip it. * * @stability unstable * @category models * @since 4.2.0 */ export interface DirectControls { readonly emit: (message: Msg, accepted?: () => void) => void readonly fail: (cause: Cause.Cause) => void readonly enter: (f: (latest: State) => void) => void readonly drawn: () => boolean } /** * Declares a keyed Subscription that attaches synchronously to a host event * source instead of running a Stream. * * **When to use** * * Use when building a host package (such as a terminal or native host) where a * global listener must inspect the latest declaration and cancel an event's * default synchronously inside the host callback. * * **Details** * * `attach` runs when the Subscription starts and returns the function that * detaches it, or `{ close, start }`. `start` runs once the Subscription * has started, outside the render that started it, so a source can send its * current value before any change. `state` is updated on every * `subscriptions` run for the same key; read the current value inside * `controls.enter((latest) => ...)` so a listener never closes over stale * handlers or Model values. * * @stability unstable * @category constructors * @since 4.2.0 */ export const direct = ( name: string, deps: Deps | undefined, state: State, attach: ( context: Context.Context, controls: DirectControls ) => | (() => void) | { readonly close: () => void; readonly start: () => void } ): Subscription => { const connect: NonNullable = ( context, emit, fail, enter, drawn ) => { const attached = attach(context as Context.Context, { emit: (message, accepted) => emit(message, accepted ?? noop), fail, drawn, enter: (f) => enter((latest) => f( (latest as unknown as { readonly [directState]: State })[ directState ] ) ) }) return typeof attached === "function" ? { initial: Effect.void, close: attached } : { initial: Effect.sync(attached.start), close: attached.close } } return Object.assign( deps === undefined ? make(name, Stream.never) : make(name, deps, () => Stream.never), { [directState]: state, [services.direct]: connect } ) } const noop = () => {}