@weftui/router 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -40,15 +40,28 @@ An unhandled failure re-raises to the **nearest enclosing** boundary; if none ca
40
40
 
41
41
  ### Post-mount failures with no enclosing boundary
42
42
 
43
- The routing above describes what happens while a node is being built. Once mounted, a reactive region (an attribute, child, or list stream, or a hydrated equivalent) keeps running for the lifetime of its scope. It can still fail later: a `Stream` backing a `Boundary.rpc` resource might raise `RouterNotFound` after a client-side navigation. If a `BoundaryContext` encloses the region, the failure routes to it exactly as above, and the boundary's fallback swaps in.
43
+ The routing above describes what happens while a node is being built. Once mounted, a reactive region keeps running for the lifetime of its scope: an attribute, a child, a list stream, or a hydrated equivalent. It can still fail later, e.g. a `Boundary.rpc` resource's refetch stream raising after a client-side navigation.
44
44
 
45
- If no boundary encloses it, there is nothing to swap to. Weft does not synthesize one. The region's DOM keeps its last rendered content, and a watcher fiber (forked into the same scope alongside the subscription itself) observes its exit directly.
45
+ If a boundary encloses the region, the failure routes to it exactly as above and its fallback swaps in. If none does, there is nothing to swap to. Weft does not synthesize one: the region's DOM keeps its last rendered content, and a watcher fiber (forked alongside the subscription itself) observes the exit instead.
46
46
 
47
- When that exit is a failure whose cause is not interruption-only, Weft reports it explicitly via `Effect.logError(exit.cause)`. The log is annotated with `weft.region` to identify the failing region by kind and identity (e.g. `attribute:class`, `child:stream-3`, `list:stream-2`, `hydrate:stream-1 (/products/42)`). This fires for typed failures and defects alike, in both dev and prod, exactly once per failing region, at the `"Error"` level. Interruption (the ordinary case of unmount tearing down the region's scope) is never reported; only genuine failures are.
47
+ An exit whose cause is not interruption-only publishes an `UnhandledError` (`cause`, `region`, `root`) to the app's unhandled-error hub, exposed as `WeftApp.errors(app)`. `region` names the failing spot: `attribute:class`, `child:stream-3`, or `boundary:outermost` for a failure that escapes even the outermost boundary. Subscribe to observe every occurrence yourself:
48
48
 
49
- This is deliberate. Rather than leave the failure to whatever the Effect runtime would do with an unobserved fiber exit, Weft observes and logs it itself. Visibility is therefore controlled by the same knobs any Effect program uses: `References.MinimumLogLevel` (provided via `Effect.provideService`) to filter it, or a custom `Logger` to route it elsewhere.
49
+ ```typescript
50
+ import { WeftApp } from "@weftui/dom/client";
51
+ import { Effect, Stream } from "effect";
52
+
53
+ Effect.runFork(
54
+ Stream.runForEach(WeftApp.errors(app), (error) =>
55
+ Effect.log(`unhandled in ${error.region}`, error.cause),
56
+ ),
57
+ );
58
+ ```
50
59
 
51
- A stream that can fail and has no enclosing boundary is a stream whose failures you've chosen not to route into the UI. The log is what tells you that decision has consequences at runtime.
60
+ With zero subscribers, each unhandled error instead runs a default `Effect.logError(cause)` annotated with `weft.region`, exactly once per occurrence, in dev and prod alike. Subscribing suppresses that fallback for as long as at least one subscriber stays attached.
61
+
62
+ This is deliberate: rather than leave an unobserved fiber exit to the runtime, Weft always surfaces it, either to your subscriber or to the log. Interruption (ordinary unmount teardown) is never published or logged; only genuine failures are.
63
+
64
+ A stream that can fail with no enclosing boundary is a stream whose failures you've chosen not to route into the UI. `WeftApp.errors` (and the log fallback) is what tells you that decision has consequences at runtime. Full contract: [`WeftApp.errors` / `UnhandledError`](https://weftui.dev/docs/reference/dom#weftapperrors).
52
65
 
53
66
  ## Suspense boundaries
54
67
 
@@ -100,11 +113,28 @@ Its channel behavior is also distinct. The rpc's typed `error` schema joins the
100
113
 
101
114
  The unifying idea: failure, async pending state, and server data are not three separate subsystems bolted onto the renderer. They are three **boundary nodes** in the one tree, each intercepting a different thing flowing through it. Each has channel behavior you can read off its type.
102
115
 
103
- That is why they nest freely. A `Boundary.catchTag` can wrap a `Boundary.rpc` to catch its typed failure. A `Boundary.suspend` can wrap async siblings that themselves contain rpc boundaries.
116
+ That is why they nest freely. A `Boundary.catchTag` can wrap a `Boundary.rpc` to catch its typed failure, and a `Boundary.suspend` can wrap async siblings that themselves contain rpc boundaries:
117
+
118
+ ```typescript
119
+ import { Boundary, h, Subscribable } from "@weftui/core";
120
+ import { Stream } from "effect";
121
+
122
+ Boundary.catchTag({ tag: "StockRpcError", fallback: () => h.p("Couldn't load stock.") }, [
123
+ Boundary.rpc(
124
+ GetStock,
125
+ () => ({ id: productId }),
126
+ (resource) =>
127
+ h.span([Stream.map(Subscribable.changes(resource.value), (s) => String(s.units))]),
128
+ ),
129
+ ]);
130
+ ```
131
+
132
+ Each layer only sees the channel its own kind produces: `catchTag` narrows `E`, `Boundary.rpc` widens it by the rpc's error schema. Neither cares how the other renders.
104
133
 
105
134
  ## See also
106
135
 
107
136
  - [The Rendering Model](https://weftui.dev/docs/explanation/rendering-model): why a boundary is just a node in a static tree
108
137
  - [`Boundary` API reference](https://weftui.dev/docs/reference/core#boundary-namespace): every variant's signature and channel algebra
138
+ - [`WeftApp.errors` / `UnhandledError`](https://weftui.dev/docs/reference/dom#weftapperrors): the unhandled-error hub for post-mount failures with no enclosing boundary
109
139
  - [Load Data with RPC](https://weftui.dev/docs/how-to/load-data-with-rpc): the full `Boundary.rpc` walkthrough and its four lifecycles
110
140
  - [Render on the Server](https://weftui.dev/docs/how-to/render-on-the-server): how suspense and rpc boundaries stream and hydrate
@@ -7,7 +7,14 @@ description: How h, h.fragment, and Component.gen / Component.make work; why Nod
7
7
 
8
8
  # The Combinator API
9
9
 
10
- Weft builds UI trees by calling builder functions. Because component return types stay as generic `Effect.Effect<ElementDescriptor, E, R>`, the error channel (`E`) and requirements channel (`R`) propagate through the entire tree: visible to the type checker, satisfiable at the mount boundary.
10
+ Weft builds UI trees by calling builder functions, not by writing markup. There is no JSX runtime and no `h(Component)` overload: a component is a plain function you call, and its result goes straight into the tree.
11
+
12
+ ```typescript
13
+ // No JSX, no deferred element. Header/Main/Footer already ran; these are Nodes.
14
+ const tree = h.div({ class: "app" }, [Header(), Main(), Footer()]);
15
+ ```
16
+
17
+ Because a component's return type stays a concrete `Effect.Effect<ElementDescriptor, E, R>`, its error channel (`E`) and requirement channel (`R`) propagate through the whole tree. Both are visible to the type checker and satisfiable exactly once, at the mount boundary.
11
18
 
12
19
  JSX collapses every component's return type to an opaque `JSX.Element`, erasing both channels. The combinator API exists specifically to keep them intact.
13
20
 
@@ -110,7 +117,7 @@ const TableRow = ({ user }: { user: User }) =>
110
117
 
111
118
  ## Custom components with `Component.gen` / `Component.make`
112
119
 
113
- Plain functions work fine for simple components, but the `Component` factories provide type-level wiring so the caller's reactive prop types contribute their `E`/`R` to the returned node. Pick `Component.make` for a plain-function body and `Component.gen` for a generator body (when you need `yield*` to set up local state or pull from services).
120
+ Plain functions work fine for simple components. The `Component` factories add type-level wiring: the caller's actual reactive prop types contribute their `E`/`R` to the node returned at that call site, not just the types you wrote in the signature. Pick `Component.make` for a plain-function body, `Component.gen` for a generator body (when you need `yield*` for local state or a service).
114
121
 
115
122
  ```typescript
116
123
  import { Component, h } from "@weftui/core";
@@ -132,30 +139,29 @@ declare const labelStream: Stream.Stream<string, never, I18nService>;
132
139
  const btn = Button({ label: labelStream });
133
140
  ```
134
141
 
135
- Components also accept an optional `children` argument, either as `readonly Renderable[]` or as a `(input) => readonly Renderable[]` function (render-prop pattern). `E`/`R` from children, including the array returned by a function-children call, accumulate on the resulting node.
142
+ Components also accept an optional `children` argument: either `readonly Renderable[]`, or a `(input) => readonly Renderable[]` function for the render-prop pattern. Either way, the children's `E`/`R` accumulate onto the resulting node, including the array a function-children call returns.
136
143
 
137
- Without `Component`, a plain function's return type is fixed at definition time and does not reflect the caller's reactive prop types.
144
+ A plain function without `Component` has its return type fixed at definition time. It reflects only the prop types you wrote, never a specific caller's reactive prop types.
138
145
 
139
- See [component-authoring.md](https://weftui.dev/docs/how-to/author-components) for a full walkthrough.
146
+ See [Author Components](https://weftui.dev/docs/how-to/author-components) for a full walkthrough.
140
147
 
141
- ## Suspense boundaries
148
+ ## Boundaries accumulate channels too
142
149
 
143
- `Boundary.suspend` wraps async children and shows a fallback until all of them have emitted their first value:
150
+ `Boundary.suspend`, `Boundary.catch`, and the rest of the `Boundary` namespace are Nodes, not a separate concept. A boundary wraps children and its own type is `Node<ChildrenE, ChildrenR>`, so the same accumulation rules apply:
144
151
 
145
152
  ```typescript
146
153
  import { Boundary, h } from "@weftui/core";
147
154
 
155
+ // Node<ChildrenE, ChildrenR>: transparent to E/R, like a plain h.* parent
148
156
  Boundary.suspend({ fallback: h.div({ class: "spinner" }, "Loading...") }, [
149
157
  AsyncCard({ id: 1 }),
150
158
  AsyncCard({ id: 2 }),
151
159
  ]);
152
160
  ```
153
161
 
154
- The fallback is replaced atomically: either all children are visible or none are. This prevents partial flicker when multiple async siblings resolve at different times. The boundary's node type is `Node<ChildrenE, ChildrenR>`: the children's `E`/`R` channels accumulate onto it, exactly as they would for a plain `h.*` parent.
155
-
156
- On the server, `renderToStreamHydratable` emits the fallback inline and appends patch scripts as children resolve. On the client, `hydrate` sees through `Boundary.suspend` boundaries and adopts the already-resolved DOM directly.
162
+ A boundary changes _when_ and _whether_ its children's output reaches the DOM, not what its type carries. `Boundary.catchTag` is the one exception: it removes the matched tag from `E`, since that's the failure it discharges.
157
163
 
158
- `Boundary.suspend` is one of the boundary combinators. See the [core reference](https://weftui.dev/docs/reference/core#boundarysuspend) for the full `Boundary.*` surface, including the failure-catch variants and `Boundary.rpc`.
164
+ See [Boundaries and Suspense](https://weftui.dev/docs/explanation/boundaries-and-suspense) for what each boundary variant does, and the [core reference](https://weftui.dev/docs/reference/core#boundary-namespace) for the full `Boundary.*` surface.
159
165
 
160
166
  ## See also
161
167
 
@@ -7,16 +7,14 @@ description: The Source<A, E, R> vocabulary; Stream, Effect, and Subscribable as
7
7
 
8
8
  # Reactive Primitives
9
9
 
10
- The unified `Source` vocabulary lets static values, Effects, Streams, and Subscribables be used interchangeably. Props, children, and style values all accept the same type.
10
+ Weft accepts a `Source` for any prop value, any child, and any style value: one vocabulary, four kinds, used interchangeably wherever reactivity is supported.
11
11
 
12
- Weft accepts a `Source` for prop values and children. Any of these is valid wherever reactivity is supported:
13
-
14
- - A plain static value (`string`, `number`, `boolean`, ...)
15
- - An `Effect.Effect<A, E, R>`: runs once and resolves to a value
16
- - A `Stream.Stream<A, E, R>`: each emission replaces the previous value
17
- - A `Subscribable<A, E, R>`: like a hot stream; already has a "current value"
18
-
19
- The `Source<A, E, R>` type captures this union:
12
+ | Kind | Behavior |
13
+ | --------------------------------------------------------- | ----------------------------------------- |
14
+ | a plain static value (`string`, `number`, `boolean`, ...) | set once, never updates |
15
+ | `Effect.Effect<A, E, R>` | runs once, resolves to a value |
16
+ | `Stream.Stream<A, E, R>` | each emission replaces the previous value |
17
+ | `Subscribable<A, E, R>` | a hot stream: already has a current value |
20
18
 
21
19
  ```typescript
22
20
  type Source<A, E, R> = A | Effect.Effect<A, E, R> | Stream.Stream<A, E, R> | Subscribable<A, E, R>;
@@ -139,13 +137,42 @@ h.div({
139
137
  });
140
138
  ```
141
139
 
140
+ ## Latest-value-wins conflation
141
+
142
+ Every reactive region and prop is drained by one shared commit scheduler, the
143
+ Loom (see [The Rendering Model](https://weftui.dev/docs/explanation/rendering-model#the-loom-one-scheduler-per-app-committing-asynchronously)).
144
+ When a source emits faster than the DOM commits, the Loom conflates the burst:
145
+ it keeps only the newest value per region and skips the intermediate ones.
146
+
147
+ ```typescript
148
+ const ticks = Stream.range(0, 999); // publishes far faster than the DOM commits
149
+
150
+ h.span([ticks]); // the span settles on 999; 0 through 998 may never render
151
+ ```
152
+
153
+ The final DOM state always reflects the newest value; nothing is lost
154
+ permanently. What is skipped are the values in between, by design: this is
155
+ what keeps a fast-publishing source from piling up unbounded DOM work.
156
+
157
+ Code that must observe every emission, not just the settled one (an audit
158
+ log, a counter that sums each tick), should consume the stream directly
159
+ instead of relying on what lands in the DOM:
160
+
161
+ ```typescript
162
+ yield * Stream.runForEach(ticks, (n) => Effect.sync(() => total.push(n)));
163
+ ```
164
+
142
165
  ## NoPropValue
143
166
 
144
- When a `Stream` prop ends before emitting, the renderer raises a `NoPropValue` tagged error. This carries an optional `key` field identifying which prop triggered it:
167
+ A finite `Stream` prop can end without ever emitting, e.g. `Stream.empty` or `Stream.take(0, stream)`. When it does, the renderer raises a `NoPropValue` tagged error carrying an optional `key` that identifies the prop:
168
+
169
+ ```typescript
170
+ h.span([Stream.empty]); // completes without emitting: raises NoPropValue
171
+ ```
172
+
173
+ `Effect.catchTag` matches by the string tag, so handling it at the mount boundary needs no `NoPropValue` import:
145
174
 
146
175
  ```typescript
147
- // Handle at the mount boundary if needed. `Effect.catchTag` matches the error
148
- // by its string tag, so no `NoPropValue` import is required here.
149
176
  pipe(
150
177
  WeftApp.mount(app, App(), root),
151
178
  Effect.catchTag("NoPropValue", (e) =>
@@ -154,7 +181,7 @@ pipe(
154
181
  );
155
182
  ```
156
183
 
157
- In practice you only encounter `NoPropValue` when a finite `Stream` prop ends before emitting (e.g., `Stream.empty` or `Stream.take(0, stream)`). Most usage with `SubscriptionRef.changes` or infinite streams never raises it.
184
+ `SubscriptionRef.changes` and other infinite streams always emit before completing, so most usage never raises it.
158
185
 
159
186
  ## See also
160
187
 
@@ -37,12 +37,22 @@ When a stream emits, only the DOM at _that_ point updates. Nothing above it re-r
37
37
 
38
38
  ## Streams drive all updates
39
39
 
40
- There is no `setState`, no render-triggering scheduler, no "re-render this component." A region of the DOM is live **if and only if** a stream is woven into it. To make something update, you thread a stream through it; to keep something static, you pass a plain value.
40
+ There is no `setState`, no "re-render this component," no vdom diff. A region of the DOM is live **if and only if** a stream is woven into it. To make something update, you thread a stream through it; to keep something static, you pass a plain value.
41
41
 
42
- The renderer subscribes to each woven stream and patches its target in place on every emission. It reuses the existing DOM node and patches text and attributes rather than recreating elements, so identity, focus, and typed input survive an update.
42
+ The renderer reuses the existing DOM node and patches text and attributes in place rather than recreating elements, so identity, focus, and typed input survive an update. Updates stay local: a stream woven at one point never touches an untouched sibling or re-runs a parent.
43
43
 
44
44
  This also fixes the update _shape_. Because the structure is fixed, an update is always "new value into a known hole," never "reconcile these two trees." Even list rendering, where the number of children genuinely varies, is expressed as a keyed region ([`List.each`](https://weftui.dev/docs/how-to/render-keyed-lists)). It reconciles by key rather than by structural diff.
45
45
 
46
+ ## The Loom: one scheduler per app, committing asynchronously
47
+
48
+ Every woven stream feeds one shared scheduler per `WeftApp`: the **Loom**. It keeps one latest-value slot per reactive region or prop and commits changes to the DOM in passes.
49
+
50
+ The name follows the metaphor: individual streams spin as fast as they like, like threads paid out from a bobbin. The loom only ever weaves the newest state of each thread into the fabric, one pass at a time. A region that receives several values before its next commit collapses to the last one: intermediate emissions are conflated, never committed. This bounds DOM work no matter how fast a source publishes.
51
+
52
+ Commits are asynchronous: they happen on the scheduler's own turn, not synchronously with the write. `RootHandle.awaitCommit` is the acknowledgement. It resolves once everything pending at call time has either committed or been discarded, returning the commit generation. See the [`RootHandle` reference](https://weftui.dev/docs/reference/dom#roothandle) for its exact semantics.
53
+
54
+ None of this changes what you write. You still thread a `Stream`, `Effect`, or `Subscribable` through a prop or child; the Loom is an implementation detail of how those emissions reach the DOM. Code that must observe every intermediate value, not just the settled one, should consume the stream directly instead of relying on what lands in the DOM (see [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives#latest-value-wins-conflation)).
55
+
46
56
  ## One tree, two sides, hydrate in place
47
57
 
48
58
  The same component tree renders on the server and the client:
@@ -56,6 +66,7 @@ Because the same `Node<E, R>` describes both passes, there is nothing to keep in
56
66
 
57
67
  - **No diff cost.** Updates are O(changed value), not O(tree). There is no reconciliation pass to pay for.
58
68
  - **Local reasoning.** A stream woven at one point cannot affect another. What is reactive is exactly what you made reactive.
69
+ - **Bounded commit work.** The Loom conflates bursts to one commit per region, so a fast-publishing source cannot outrun the DOM.
59
70
  - **Type-honest edges.** The app node's `E`/`R` is the whole app's error and dependency surface, checked at compile time and discharged once at the edge.
60
71
  - **Flash-free SSR by construction.** Hydration adopts rather than replaces, because the tree is identical on both sides.
61
72
 
@@ -65,3 +76,4 @@ Because the same `Node<E, R>` describes both passes, there is nothing to keep in
65
76
  - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives): the stream-shaped values you weave through the tree
66
77
  - [Boundaries and Suspense](https://weftui.dev/docs/explanation/boundaries-and-suspense): how failure and async are modeled as nodes in the same tree
67
78
  - [Render on the Server](https://weftui.dev/docs/how-to/render-on-the-server): the server/client split and `hydrate`
79
+ - [`@weftui/dom` reference](https://weftui.dev/docs/reference/dom#roothandle): `RootHandle.awaitCommit` and `commitGeneration`
@@ -329,10 +329,7 @@ import { RouterApp, RouterLive } from "@weftui/router/client";
329
329
  import { Effect } from "effect";
330
330
  import { App } from "./app";
331
331
 
332
- const root = document.getElementById("root");
333
- if (root === null) {
334
- throw new Error("#root not found");
335
- }
332
+ const root = document.getElementById("root")!;
336
333
 
337
334
  const app = WeftApp.make(RouterLive(App));
338
335
  void Effect.runPromise(WeftApp.mount(app, RouterApp(App), root));
@@ -485,10 +482,7 @@ import { RouterApp, RouterLive } from "@weftui/router/client";
485
482
  import { Effect } from "effect";
486
483
  import { App } from "./app";
487
484
 
488
- const root = document.getElementById("root");
489
- if (root === null) {
490
- throw new Error("#root not found");
491
- }
485
+ const root = document.getElementById("root")!;
492
486
 
493
487
  const app = WeftApp.make(RouterLive(App));
494
488
  void Effect.runPromise(WeftApp.hydrate(app, RouterApp(App), root));
@@ -7,11 +7,11 @@ description: Plain functions vs. Component.gen / Component.make, instance scope,
7
7
 
8
8
  # Component Authoring
9
9
 
10
- Weft components are plain TypeScript functions that return a `Node<E, R>`. This guide covers the two ways to define them and when to choose each.
10
+ **Goal:** write a Weft component, a plain function returning a `Node<E, R>`, and pick the right authoring style for its complexity.
11
11
 
12
12
  ## Plain functions
13
13
 
14
- The simplest component is just a function:
14
+ Static props, no internal state: write and call a plain function.
15
15
 
16
16
  ```typescript
17
17
  import { h } from "@weftui/core";
@@ -20,19 +20,18 @@ function Greeting({ name }: { name: string }) {
20
20
  return h.p(`Hello, ${name}!`);
21
21
  }
22
22
 
23
- // Call it like a function
24
- Greeting({ name: "World" });
23
+ Greeting({ name: "World" }); // called directly, no JSX, no deferred descriptor
25
24
  ```
26
25
 
27
- Use a plain function when:
26
+ Reach for this when:
28
27
 
29
- - Props are all static (strings, numbers, plain functions)
30
- - The component has no internal state
31
- - You don't need the caller's reactive prop types to propagate
28
+ - Props are all static (strings, numbers, plain functions).
29
+ - The component has no internal state.
30
+ - You don't need the caller's reactive prop types to propagate into the return type.
32
31
 
33
32
  ## Components with internal state
34
33
 
35
- When a component needs reactive state, use `Effect.gen` to set it up before building the tree. The component function still runs once. The setup happens at mount time:
34
+ Set up reactive state with `Effect.gen` before building the tree. The component function still runs once; the setup happens at mount time:
36
35
 
37
36
  ```typescript
38
37
  import { h } from "@weftui/core";
@@ -49,68 +48,16 @@ const Counter = () =>
49
48
  });
50
49
  ```
51
50
 
52
- The return type here is `Effect.Effect<Node, never, never>`, itself a valid `Node`, so it composes naturally with other tree-building calls.
51
+ `Effect.Effect<Node, never, never>` is itself a valid `Node`, so it composes with any other tree-building call.
53
52
 
54
- As soon as such a component is reused or takes props, wrap the same generator in [`Component.gen`](#componentgen--componentmake-for-reusable-components) (below). That way the caller's reactive prop and children channels flow into its node type.
53
+ Once a component like this is reused or takes props, wrap the same generator in `Component.gen` (below) so the caller's reactive prop and children channels flow into its node type.
55
54
 
56
- ## Component scope and background effects
55
+ ## `Component.gen` / `Component.make`
57
56
 
58
- Every component instance is rendered under its own **instance scope**, a child of the
59
- mount scope created fresh for that instance. Anything bound to the instance scope lives
60
- exactly as long as the component is mounted. It is torn down automatically when the
61
- component unmounts (or when its root unmounts via `RootHandle.unmount()`).
57
+ Both build a component whose returned `Node`'s `E`/`R` include the caller's reactive prop and children channels, not just the body's own:
62
58
 
63
- The renderer provides this scope as the ambient `Scope.Scope` while it evaluates the
64
- component body, so it is already in context when you need it.
65
-
66
- This matters the moment a component starts **background work**: a subscription, an
67
- observer of a `ref`, a polling timer, anything you `fork`. The rule:
68
-
69
- > Fork background work with **`Effect.forkScoped`**, never a bare `Effect.forkChild`.
70
-
71
- `Effect.forkScoped` attaches the fiber to the instance scope, so it keeps running for
72
- the component's lifetime and is interrupted on unmount. A bare `Effect.forkChild` instead
73
- attaches the fiber to the component-body fiber, the one that runs your `Effect.gen` to
74
- produce the tree. That fiber completes the instant the gen returns its node, so the
75
- forked work is cancelled almost immediately.
76
-
77
- Concretely, an observer that runs an effect when a `ref`'s element mounts:
78
-
79
- ```typescript
80
- import { h } from "@weftui/core";
81
- import { Effect, Option, pipe, Stream, SubscriptionRef } from "effect";
82
-
83
- const AutoFocusInput = () =>
84
- Effect.gen(function* () {
85
- const inputRef = yield* SubscriptionRef.make<Option.Option<HTMLInputElement>>(Option.none());
86
-
87
- yield* pipe(
88
- SubscriptionRef.changes(inputRef),
89
- Stream.filter(Option.isSome),
90
- Stream.take(1),
91
- Stream.runForEach((el) => Effect.sync(() => el.value.focus())),
92
- Effect.forkScoped, // ✅ tied to the instance scope: survives until unmount
93
- // Effect.forkChild, // ❌ tied to the body fiber: interrupted when the gen returns
94
- );
95
-
96
- return yield* h.input({ ref: inputRef, type: "text" });
97
- });
98
- ```
99
-
100
- You do not manage the scope yourself: you do not create it, close it, or pass it
101
- around. `forkScoped` reads it from context, and unmount closes it for you. If you ever
102
- fork outside a component body (rare), you must supply a `Scope.Scope` yourself. The
103
- type system will tell you, because `forkScoped` carries a `Scope.Scope` requirement.
104
-
105
- See `examples/element-ref` for the auto-focus, measure, and canvas recipes built on
106
- this pattern.
107
-
108
- ## `Component.gen` / `Component.make` for reusable components
109
-
110
- When you want the caller's reactive prop types to flow into the returned node's type, use one of the `Component` factories. Both have the same call semantics; pick the body style that fits:
111
-
112
- - **`Component.make`**: body is a plain function returning any `Effect` (typically a `Node`). Use for one-liners and pipe compositions.
113
- - **`Component.gen`**: body is a generator. Use when you need `yield*` to set up local state or pull from services.
59
+ - **`Component.make`**: body is a plain function returning any `Effect`. Use for one-liners and pipe compositions.
60
+ - **`Component.gen`**: body is a generator. Use when you need `yield*` for local state or services.
114
61
 
115
62
  ```typescript
116
63
  import { Component, h, Source } from "@weftui/core";
@@ -128,40 +75,28 @@ const Card = Component.make((props: CardProps) =>
128
75
  );
129
76
  ```
130
77
 
131
- `Source.Source<string>` is Weft's caller-facing prop vocabulary: a single type covering a static `string`, a `Stream<string>`, an `Effect<string>`, or a `Subscribable<string>`. You don't hand-write `string | Stream.Stream<string> | …` on every prop.
132
-
133
- Passing a `Source` straight to `h` (as above) is all you need when the value is just spliced into the tree. The renderer normalizes it.
134
-
135
- Now the caller's stream types are visible in the returned node:
136
-
137
78
  ```typescript
138
79
  declare const titleStream: Stream.Stream<string, never, I18nService>;
139
80
 
140
- // Node<never, I18nService>: I18nService requirement flows out
81
+ // Node<never, I18nService>: I18nService flows out from the prop the caller passed
141
82
  const card = Card({ title: titleStream });
142
83
  ```
143
84
 
144
- Without a `Component` factory, a plain function's return type is fixed at definition time and won't reflect the caller's reactive prop types.
85
+ Without a `Component` factory, a plain function's return type is fixed at definition time and can't reflect what the caller actually passes.
145
86
 
146
- ### Body `E`/`R` inference
147
-
148
- You don't declare the body's `E`/`R` channels explicitly. They're inferred from the returned (or yielded) effect:
149
-
150
- - The body's `E`/`R` come from whatever effects appear inside.
151
- - The caller's reactive prop channels and reactive children channels are unioned on top at the call site.
87
+ - The body's `E`/`R` come from whatever effects it yields or returns.
88
+ - Caller prop channels and children channels are unioned on top at the call site.
152
89
  - Static prop values (`string`, `number`, plain functions) contribute `never`.
153
90
 
154
91
  ### Children: array or function
155
92
 
156
- Both factories accept an optional second `children` argument, typed as:
157
-
158
93
  ```typescript
159
94
  type Component.Children<Input = never> =
160
95
  | readonly Renderable[]
161
96
  | ((input: Input) => readonly Renderable[]);
162
97
  ```
163
98
 
164
- The function form is the render-prop / slot pattern. The component invokes the function with whatever input it chooses, and the returned array's `E`/`R` propagate out:
99
+ The function form is the render-prop / slot pattern. The component calls it with whatever `input` it chooses, and the returned array's `E`/`R` propagate out:
165
100
 
166
101
  ```typescript
167
102
  const ItemList = Component.make(
@@ -172,9 +107,9 @@ const ItemList = Component.make(
172
107
  ItemList({ items: ["a", "b"] }, (item) => [h.li(item)]);
173
108
  ```
174
109
 
175
- ## Props typing
110
+ ## Props typing with `Source`
176
111
 
177
- For a prop that accepts both static and reactive values, type it as [`Source.Source<T>`](https://weftui.dev/docs/reference/core#source-namespace) rather than hand-writing the union. `Source.Source<T>` **is** that union: `T | Stream<T> | Effect<T> | Subscribable<T>`. The caller can pass a plain value or any reactive shape interchangeably, and you write it once:
112
+ Type a prop that accepts both static and reactive values as `Source.Source<T>` instead of hand-writing the union:
178
113
 
179
114
  ```typescript
180
115
  import { Source } from "@weftui/core";
@@ -186,11 +121,9 @@ interface ButtonProps {
186
121
  }
187
122
  ```
188
123
 
189
- When a caller passes a plain string, the component's node type has `never` for that prop's channels. When they pass a `Stream.Stream<string, never, SomeService>`, `SomeService` appears in the `R` channel. The extraction is exactly `Source.Success` / `Source.Error` / `Source.Context`.
190
-
191
- ### Reading a `Source` in the body
124
+ `Source.Source<T>` **is** the union `T | Stream<T> | Effect<T> | Subscribable<T>`. A plain string contributes `never` to the node's channels; a `Stream<string, never, SomeService>` contributes `SomeService` to `R`. The extraction is `Source.Success` / `Source.Error` / `Source.Context`.
192
125
 
193
- Splicing a `Source` straight into `h` (`[props.label]`) is enough when you only place it in the tree. When the body needs to **read or derive** from the value (combine two props, feed a stream operator, drive logic), normalize it first with [`Source.toSubscribable`](https://weftui.dev/docs/reference/core#sourcetosubscribablesource-key). It turns any `Source<A>` into an await-first, hot `Subscribable<A>`:
126
+ Splicing a `Source` straight into `h` (`[props.label]`) is enough when the body only places it in the tree. Reach for `Source.toSubscribable` when the body needs to **read or derive** from it:
194
127
 
195
128
  ```typescript
196
129
  import { Component, h, Source, Subscribable } from "@weftui/core";
@@ -198,19 +131,48 @@ import { Stream } from "effect";
198
131
 
199
132
  const LoudLabel = Component.gen(function* (props: { label: Source.Source<string> }) {
200
133
  const label = yield* Source.toSubscribable(props.label); // Subscribable<string>
201
- // Now derive from it like any Subscribable: static, Effect, and Stream inputs all work.
202
134
  return yield* h.strong([Stream.map(Subscribable.changes(label), (text) => text.toUpperCase())]);
203
135
  });
204
136
  ```
205
137
 
206
- `toSubscribable` is scoped:
207
-
208
- - A `Stream` prop is pumped by a fiber that terminates with the component's instance scope.
209
- - An `Effect` prop is memoized.
210
- - An existing `Subscribable` is threaded through by reference.
138
+ - An existing `Subscribable` prop is threaded through by reference, no new fiber.
139
+ - A `Stream` prop is pumped by a fiber scoped to the component's instance scope.
140
+ - An `Effect` prop is memoized, so it runs at most once.
211
141
  - A static value emits once.
212
142
 
213
- It is the same normalization the renderer applies to props internally. Reach for it whenever you need the value as a `Subscribable` instead of leaving it opaque.
143
+ ## Instance scope and background effects
144
+
145
+ Every component instance renders under its own **instance scope**, a child of the mount scope created fresh per instance. It closes on unmount (or when its root unmounts via `RootHandle.unmount()`). The renderer supplies it as the ambient `Scope.Scope` while your body runs, so it's already in context.
146
+
147
+ Fork background work (a subscription, a ref observer, a polling timer) with **`Effect.forkScoped`**, never a bare `Effect.forkChild`:
148
+
149
+ ```typescript
150
+ import { h } from "@weftui/core";
151
+ import { Effect, Option, pipe, Stream, SubscriptionRef } from "effect";
152
+
153
+ const AutoFocusInput = () =>
154
+ Effect.gen(function* () {
155
+ const inputRef = yield* SubscriptionRef.make<Option.Option<HTMLInputElement>>(Option.none());
156
+
157
+ yield* pipe(
158
+ SubscriptionRef.changes(inputRef),
159
+ Stream.filter(Option.isSome),
160
+ Stream.take(1),
161
+ Stream.runForEach((el) => Effect.sync(() => el.value.focus())),
162
+ Effect.forkScoped, // ✅ tied to the instance scope: survives until unmount
163
+ // Effect.forkChild, // ❌ tied to the body fiber: interrupted when the gen returns
164
+ );
165
+
166
+ return yield* h.input({ ref: inputRef, type: "text" });
167
+ });
168
+ ```
169
+
170
+ - `Effect.forkScoped` attaches the fiber to the instance scope, so it keeps running for the component's lifetime and is interrupted on unmount.
171
+ - `Effect.forkChild` attaches to the component-body fiber instead, the one that runs your generator to produce the tree. That fiber completes the instant the body returns its node, so a bare fork is cancelled almost immediately.
172
+
173
+ You never create, close, or pass the scope yourself: `forkScoped` reads it from context, and unmount closes it for you. Forking outside a component body (rare) requires supplying a `Scope.Scope`, and `forkScoped`'s own `Scope.Scope` requirement makes the type system tell you.
174
+
175
+ See [Use Element Refs](https://weftui.dev/docs/how-to/use-element-refs) for the auto-focus, measure, and canvas recipes built on this pattern.
214
176
 
215
177
  ## Composing components
216
178
 
@@ -228,11 +190,11 @@ function App() {
228
190
  }
229
191
  ```
230
192
 
231
- Children arrays accumulate `E`/`R` from all their members. The parent node's type reflects the union of all children's channels.
193
+ Children arrays accumulate `E`/`R` from all their members; the parent node's type reflects the union.
232
194
 
233
195
  ## Components that require services
234
196
 
235
- If a component's render function uses a service via `yield*`, that service appears in the component's `CompR` parameter:
197
+ A service read via `yield*` inside the body appears in the component's `R` channel, regardless of what the caller passes:
236
198
 
237
199
  ```typescript
238
200
  import { Component, h } from "@weftui/core";
@@ -243,11 +205,11 @@ const UserAvatar = Component.gen(function* (props: { userId: string }) {
243
205
  return yield* h.img({ src: user.avatarUrl, alt: user.name });
244
206
  });
245
207
 
246
- // Node<never, UserService>: regardless of what the caller passes
208
+ // Node<never, UserService>
247
209
  const avatar = UserAvatar({ userId: "123" });
248
210
  ```
249
211
 
250
- Give the service to the app layer:
212
+ Give the service to the app layer, not to the mount call:
251
213
 
252
214
  ```typescript
253
215
  import { WeftApp } from "@weftui/dom/client";
@@ -257,9 +219,11 @@ const app = WeftApp.make(UserServiceLive);
257
219
  void Effect.runPromise(WeftApp.mount(app, App(), document.getElementById("root")!));
258
220
  ```
259
221
 
222
+ See [Provide Services](https://weftui.dev/docs/how-to/provide-services) for scoped layers, `memoMap` sharing, and why wrapping `Effect.provide` around the mount call doesn't work.
223
+
260
224
  ## Returning fragments
261
225
 
262
- When a component needs to return multiple sibling elements without a wrapper, use `h.fragment`:
226
+ Return multiple sibling elements without a wrapper using `h.fragment`:
263
227
 
264
228
  ```typescript
265
229
  import { h } from "@weftui/core";
@@ -268,11 +232,13 @@ const TableCells = ({ row }: { row: Row }) =>
268
232
  h.fragment([h.td(row.name), h.td(row.value), h.td(row.status)]);
269
233
  ```
270
234
 
271
- `h.fragment` returns a `Node<E, R>` that accumulates channels from all its children.
235
+ `h.fragment` returns a `Node<E, R>` that accumulates channels from all its children, same as any other `h.*` call.
272
236
 
273
237
  ## See also
274
238
 
275
239
  - [The Combinator API](https://weftui.dev/docs/explanation/combinator-api): `h`, `h.fragment`, and how `E`/`R` accumulate
276
240
  - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives): the `Source` vocabulary props accept
241
+ - [Use Element Refs](https://weftui.dev/docs/how-to/use-element-refs): `ref` props and scoped mount observers
242
+ - [Provide Services](https://weftui.dev/docs/how-to/provide-services): app layers, scoped layers, and `memoMap`
277
243
  - [Add Routing](https://weftui.dev/docs/how-to/add-routing): route components are `Component` slots
278
244
  - [`@weftui/core` reference](https://weftui.dev/docs/reference/core): `Component`, `Source`, and the full surface