@weftui/router 0.27.1 → 0.29.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.
Files changed (38) hide show
  1. package/README.md +3 -3
  2. package/dist/client/index.d.ts +21 -21
  3. package/dist/client/index.js +15 -15
  4. package/dist/{compile-BJFIgBbE.d.ts → compile-Bb7AknG_.d.ts} +46 -62
  5. package/dist/{href-uvJ6b7zz.js → href-3swSSbn_.js} +7 -10
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +2 -2
  8. package/dist/{outlet-eoUQ-W0k.d.ts → outlet-2AnUWKQD.d.ts} +1 -2
  9. package/dist/{outlet-C9N4a4_F.js → outlet-BgJmsO_g.js} +38 -46
  10. package/dist/server/index.d.ts +9 -10
  11. package/dist/server/index.js +10 -10
  12. package/docs/explanation/boundaries-and-suspense.md +37 -18
  13. package/docs/explanation/combinator-api.md +14 -12
  14. package/docs/explanation/reactive-primitives.md +15 -15
  15. package/docs/explanation/rendering-model.md +20 -18
  16. package/docs/explanation/services-and-context.md +39 -29
  17. package/docs/how-to/add-routing.md +76 -52
  18. package/docs/how-to/author-components.md +46 -32
  19. package/docs/how-to/compose-behavior-and-markup.md +144 -0
  20. package/docs/how-to/handle-forms.md +6 -6
  21. package/docs/how-to/load-async-data.md +15 -13
  22. package/docs/how-to/load-data-with-rpc.md +34 -30
  23. package/docs/how-to/provide-services.md +54 -74
  24. package/docs/how-to/render-keyed-lists.md +10 -8
  25. package/docs/how-to/render-on-the-server.md +19 -14
  26. package/docs/how-to/show-navigation-progress.md +10 -8
  27. package/docs/how-to/split-routes-lazily.md +16 -14
  28. package/docs/how-to/style-reactively.md +13 -13
  29. package/docs/how-to/use-element-refs.md +10 -8
  30. package/docs/index.md +20 -18
  31. package/docs/reference/core.md +44 -40
  32. package/docs/reference/dom.md +395 -58
  33. package/docs/reference/router.md +71 -49
  34. package/docs/tutorial/01-your-first-app.md +10 -11
  35. package/docs/tutorial/02-reactivity.md +11 -8
  36. package/docs/tutorial/03-services-and-async.md +19 -13
  37. package/docs/tutorial/04-errors-and-server.md +17 -7
  38. package/package.json +10 -9
@@ -2,123 +2,103 @@
2
2
  title: Provide Services
3
3
  order: 12
4
4
  section: how-to
5
- description: Provide plain and scoped Layers to a mounted app the direct mount for value layers, mountScoped plus a shutdown signal for scoped layers, and a ManagedRuntime as an alternative.
5
+ description: "Provide plain and scoped Layers to a WeftApp: app layers for the common case, scoped layers that just work, memoMap sharing, and binding an app's lifetime to a scope."
6
6
  ---
7
7
 
8
8
  # Provide Services
9
9
 
10
- **Goal:** provide a `Layer` to the mounted app so its components can read services with `yield* Service`.
10
+ **Goal:** provide a `Layer` to a `WeftApp` so its components can read services with `yield* Service`.
11
11
 
12
- Which recipe to reach for depends on whether the layer has anything to release. Both plain and scoped layers are built with `Layer.succeed` or `Layer.effect` — the distinction is whether the layer's effect acquires releasable resources (`acquireRelease`, or a scope finalizer added directly). A plain value layer (`Layer.succeed`, or `Layer.effect` whose effect has no `acquireRelease`) can be provided directly at the mount — there is nothing to leak. A **scoped** layer (`Layer.effect` whose effect is backed by `acquireRelease`) needs the mount to outlive the effect's own resolution — see [Layer lifetime at the mount](https://weftui.dev/docs/explanation/services-and-context#layer-lifetime-at-the-mount) for why.
12
+ ## Recipe 1: app layers
13
13
 
14
- ## Recipe 1 plain value layers with `mount`
15
-
16
- Provide the layer directly around `mount` and run with `runPromise`. This is the common case and needs nothing else.
14
+ Pass the layer to `WeftApp.make`. This is the common case and needs nothing else. The layer builds lazily on first mount, and every component, event handler, and stream subscription in every root mounted from `app` can read it.
17
15
 
18
16
  ```typescript
19
- import { mount } from "@weftui/dom/client";
20
- import { Effect, pipe } from "effect";
17
+ import { WeftApp } from "@weftui/dom/client";
18
+ import { Effect } from "effect";
21
19
  import { App } from "./app";
22
20
  import { ThemeServiceLive } from "./theme-service";
23
21
 
24
22
  const root = document.getElementById("root")!;
25
23
 
26
- const program = pipe(mount(App(), root), Effect.provide(ThemeServiceLive));
27
-
28
- Effect.runPromise(program);
24
+ const app = WeftApp.make(ThemeServiceLive);
25
+ void Effect.runPromise(WeftApp.mount(app, App(), root));
29
26
  ```
30
27
 
31
- ## Recipe 2 scoped layers with `mountScoped`
28
+ ## Recipe 2: scoped layers just work
32
29
 
33
- Provide the scoped layer **outside** a long-lived scoped region, mount inside that region with `mountScoped`, and keep the region open with `Effect.never` or `Deferred.await` on a shutdown signal. Drive the whole thing with `runFork`, not `runPromise` the program never settles on its own.
30
+ A **scoped** layer (`Layer.effect` backed by `acquireRelease`, or anything else that owns a subscription, listener, or registry) needs nothing different from Recipe 1. The app owns one lazy `ManagedRuntime`. The layer builds on first mount and releases only at `WeftApp.dispose(app)`, not when any individual mount's render effect resolves.
34
31
 
35
- ```typescript
36
- import { mountScoped } from "@weftui/dom/client";
37
- import { Deferred, Effect, Fiber, pipe } from "effect";
38
- import { App } from "./app";
39
- import { AppLive } from "./app-live";
32
+ There is no `mountScoped`, no `Effect.never`, no manual scope threading.
40
33
 
41
- const root = document.getElementById("root")!;
34
+ `AtomRegistry.layer` (from `effect/unstable/reactivity`) is a real scoped layer. Its atom subscriptions are fibers forked for the app's whole lifetime:
42
35
 
43
- const program = pipe(
44
- Effect.scoped(
45
- Effect.gen(function* () {
46
- yield* mountScoped(App(), root);
47
- yield* Effect.never; // keeps the region — and AppLive — alive
48
- }),
49
- ),
50
- Effect.provide(AppLive), // OUTSIDE the scoped region: outlives initial render
51
- );
52
-
53
- const fiber = Effect.runFork(program);
36
+ ```typescript
37
+ import { WeftApp } from "@weftui/dom/client";
38
+ import { Effect } from "effect";
39
+ import { AtomRegistry } from "effect/unstable/reactivity";
40
+ import { App } from "./app";
54
41
 
55
- // later, e.g. on a "sign out" action or test teardown:
56
- // await Effect.runPromise(Fiber.interrupt(fiber));
42
+ const app = WeftApp.make(AtomRegistry.layer);
43
+ void Effect.runPromise(WeftApp.mount(app, App(), document.getElementById("root")!));
57
44
  ```
58
45
 
59
- Interrupting `fiber` closes the inner scope first running `mountScoped`'s finalizer, which calls `unmount` — and only then releases `AppLive`. Swap `Effect.never` for `Deferred.await(shutdown)` when something in the app should be able to request shutdown itself:
46
+ `RouterLive` (from `@weftui/router/client`) is another. It owns the `popstate` listener and the same-origin link-click interceptor for as long as the app runs:
60
47
 
61
48
  ```typescript
62
- const shutdown = await Effect.runPromise(Deferred.make<void>());
63
-
64
- const program = pipe(
65
- Effect.scoped(
66
- Effect.gen(function* () {
67
- yield* mountScoped(App(), root);
68
- yield* Deferred.await(shutdown); // resolves when shutdown is signalled
69
- }),
70
- ),
71
- Effect.provide(AppLive),
72
- );
73
- Effect.runFork(program);
74
-
75
- // elsewhere, to request shutdown:
76
- // await Effect.runPromise(Deferred.succeed(shutdown, undefined));
49
+ const app = WeftApp.make(RouterLive(App, { rpc: { group: StockRpcs } }));
50
+ void Effect.runPromise(WeftApp.hydrate(app, RouterApp(App), root));
77
51
  ```
78
52
 
79
- `hydrateScoped` is the SSR counterpart same composition, swap `mountScoped` for `hydrateScoped`.
53
+ Both examples are runnable in full at [examples/effect-atom](https://github.com/stefvw93/weft/tree/main/examples/effect-atom) and [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr).
80
54
 
81
- ## Recipe 3 `ManagedRuntime` with plain `mount`
55
+ ## Recipe 3: sharing layer memoization with `memoMap`
82
56
 
83
- Build a `ManagedRuntime` from the scoped layer and mount with plain `mount`, running through the runtime instead of `Effect.runPromise` directly. The layer lives until `runtime.dispose()` an explicit call, rather than a scope closing.
57
+ `WeftApp.make(layer, { memoMap })` accepts an explicit `Layer.MemoMap`, so multiple `WeftApp` instances can share layer construction. For example, build one app per test case while reusing an expensive shared dependency's memoized build across them:
84
58
 
85
59
  ```typescript
86
- import { mount } from "@weftui/dom/client";
87
- import { ManagedRuntime } from "effect";
88
- import { App } from "./app";
89
- import { AppLive } from "./app-live";
90
-
91
- const root = document.getElementById("root")!;
92
- const runtime = ManagedRuntime.make(AppLive);
60
+ import { WeftApp } from "@weftui/dom/client";
61
+ import { Layer } from "effect";
93
62
 
94
- await runtime.runPromise(mount(App(), root));
63
+ const memoMap = Layer.makeMemoMap();
95
64
 
96
- // later:
97
- // await runtime.dispose();
65
+ const appA = WeftApp.make(SharedLive, { memoMap });
66
+ const appB = WeftApp.make(SharedLive, { memoMap });
98
67
  ```
99
68
 
100
- This reads closer to Recipe 1 at the call site and is a good fit when the surrounding app (a framework integration, a test harness) already manages a runtime's lifecycle for you.
69
+ Most apps have exactly one `WeftApp` and never need this option.
101
70
 
102
- ## Anti-patterns
71
+ ## Recipe 4: binding an app's lifetime to a scope
103
72
 
104
- Both of these compile and both dispose the scoped layer while the app is still running the mounted tree keeps its subscriptions and handlers, but they now read from a released service.
73
+ There is deliberately no `makeScoped`. To tie an app's disposal to a `Scope` you already manage (a framework integration or a test harness that owns one), compose it yourself with `Effect.acquireRelease`:
105
74
 
106
75
  ```typescript
107
- // plain mount: the layer releases the instant runPromise settles
108
- Effect.runPromise(mount(App(), root).pipe(Effect.provide(SomeScopedLayer)));
76
+ import { Effect } from "effect";
77
+ import { WeftApp } from "@weftui/dom/client";
78
+ import { AppLive } from "./app-live";
79
+
80
+ const acquireApp = Effect.acquireRelease(
81
+ Effect.sync(() => WeftApp.make(AppLive)),
82
+ (app) => WeftApp.dispose(app),
83
+ );
109
84
  ```
110
85
 
86
+ `acquireApp` yields a `WeftApp` and registers `WeftApp.dispose` as a finalizer on whatever scope the surrounding effect runs in. Closing that scope tears the app down the same way `WeftApp.dispose` normally would (roots, then layers, then the error hub).
87
+
88
+ ## Anti-pattern: `Effect.provide` around the mount call
89
+
111
90
  ```typescript
112
- // ❌ mountScoped, but the scoped region closes as soon as the mount effect
113
- // resolves nothing keeps it open, so this is no better than plain mount
114
- Effect.runPromise(mountScoped(App(), root).pipe(Effect.provide(SomeScopedLayer), Effect.scoped));
91
+ // ❌ does nothing useful: WeftApp.mount's R is always `never`, and services
92
+ // come exclusively from the app layer: a wrapped Effect.provide never
93
+ // reaches components, handlers, or stream subscriptions
94
+ Effect.runPromise(pipe(WeftApp.mount(app, App(), root), Effect.provide(SomeLayer)));
115
95
  ```
116
96
 
117
- In both cases the tell is the same: nothing in the composition keeps a scope open past the point where the mount Effect itself resolves. Recipe 2's `Effect.never` (or `Deferred.await`) is doing the one piece of work these anti-patterns are missing.
97
+ `WeftApp.mount`/`WeftApp.hydrate` return an effect whose requirement channel is always `never`, so there is no `R` left for `Effect.provide` to discharge. Any service a component needs must be in the layer passed to `WeftApp.make`.
118
98
 
119
99
  ## See also
120
100
 
121
- - [Layer lifetime at the mount](https://weftui.dev/docs/explanation/services-and-context#layer-lifetime-at-the-mount) why the mount effect resolving early matters for scoped layers
122
- - [Services and Context](https://weftui.dev/docs/explanation/services-and-context) how `R` accumulates and discharges at the mount
123
- - [`mountScoped` / `hydrateScoped` reference](https://weftui.dev/docs/reference/dom#mountscoped) signatures and error unions
124
- - [examples/effect-atom](https://github.com/stefvw93/weft/tree/main/examples/effect-atom) a real scoped layer (`AtomRegistry.layer` from `effect/unstable/reactivity`) mounted with this composition
101
+ - [Services and Context](https://weftui.dev/docs/explanation/services-and-context): how `R` accumulates and discharges at `WeftApp.make`, and why scoped layers no longer need special handling
102
+ - [`WeftApp` reference](https://weftui.dev/docs/reference/dom): full signatures for `make`, `mount`, `hydrate`, `dispose`
103
+ - [examples/effect-atom](https://github.com/stefvw93/weft/tree/main/examples/effect-atom): a real scoped layer (`AtomRegistry.layer`)
104
+ - [examples/shared-state-islands](https://github.com/stefvw93/weft/tree/main/examples/shared-state-islands): one app layer shared by reference across multiple mounted roots
@@ -9,7 +9,7 @@ description: Render a reactive collection with List.each so reordering, insertin
9
9
 
10
10
  **Goal:** render a list whose items reorder, insert, or remove over time, without rebuilding the whole region (which would lose focus, scroll, and input state in the surviving rows).
11
11
 
12
- Use [`List.each`](https://weftui.dev/docs/reference/core#listeach), the keyed-list combinator. It renders each item **once per key** and reconciles across emissions a reorder _moves_ existing DOM nodes, an insert adds one, a remove drops one, and untouched rows are left entirely alone.
12
+ Use [`List.each`](https://weftui.dev/docs/reference/core#listeach), the keyed-list combinator. It renders each item **once per key** and reconciles across emissions. A reorder _moves_ existing DOM nodes, an insert adds one, a remove drops one, and untouched rows are left entirely alone.
13
13
 
14
14
  ```typescript
15
15
  import { h, List } from "@weftui/core";
@@ -25,16 +25,18 @@ h.ul([
25
25
  ]);
26
26
  ```
27
27
 
28
- - **`of`** the list source: any `Stream`, `Effect`, or `Subscribable` of an `Iterable`. Each emission is materialized to an array to fix order, then reconciled by key.
29
- - **`by`** projects each item to its reconciliation key, compared via Effect's `Equal`/`Hash`. Omit it and the item itself is the key (structural for `Data`, by reference otherwise).
28
+ - **`of`** is the list source: any `Stream`, `Effect`, or `Subscribable` of an `Iterable`. Each emission is materialized to an array to fix order, then reconciled by key.
29
+ - **`by`** projects each item to its reconciliation key, compared via Effect's `Equal`/`Hash`. Omit it and the item itself is the key (structural for `Data`, by reference otherwise).
30
30
 
31
31
  ## Why not `map`?
32
32
 
33
- Mapping items by hand `Stream.map(rows.changes, (rs) => rs.map(r => h.li(r.name)))` produces a **new children array on every emission**, so the renderer rebuilds the whole region: every row's DOM node is recreated even if only one item moved. `List.each` reconciles by key instead, so DOM identity (and the focus/scroll/typed-input state attached to it) survives across updates.
33
+ Mapping items by hand (`Stream.map(rows.changes, (rs) => rs.map(r => h.li(r.name)))`) produces a **new children array on every emission**. The renderer then rebuilds the whole region: every row's DOM node is recreated even if only one item moved.
34
+
35
+ `List.each` reconciles by key instead, so DOM identity (and the focus/scroll/typed-input state attached to it) survives across updates.
34
36
 
35
37
  ## Refresh a row's content
36
38
 
37
- Because `render` runs **exactly once per key**, reconciliation never re-runs it for a kept row so it never refreshes that row's content on its own. To make a row's content reactive, thread a `Stream` **inside** the row rather than expecting a re-render:
39
+ Because `render` runs **exactly once per key**, reconciliation never re-runs it for a kept row, so it never refreshes that row's content on its own. To make a row's content reactive, thread a `Stream` **inside** the row rather than expecting a re-render:
38
40
 
39
41
  ```typescript
40
42
  List.each({ of: rows.changes, by: (row) => row.id }, (row) =>
@@ -46,6 +48,6 @@ List.each({ of: rows.changes, by: (row) => row.id }, (row) =>
46
48
 
47
49
  ## See also
48
50
 
49
- - [`List.each` API reference](https://weftui.dev/docs/reference/core#listeach) full signature, `List.Options`, and the descriptor shape
50
- - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives) the stream-shaped sources `of` accepts
51
- - [examples/keyed-list](https://github.com/stefvw93/weft/tree/main/examples/keyed-list) a runnable keyed list with reordering and a browser test
51
+ - [`List.each` API reference](https://weftui.dev/docs/reference/core#listeach): full signature, `List.Options`, and the descriptor shape
52
+ - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives): the stream-shaped sources `of` accepts
53
+ - [examples/keyed-list](https://github.com/stefvw93/weft/tree/main/examples/keyed-list): a runnable keyed list with reordering and a browser test
@@ -7,12 +7,14 @@ description: renderToString / renderToStringHydratable / streaming variants, hyd
7
7
 
8
8
  # Server-Side Rendering
9
9
 
10
- Weft renders on the server and **hydrates** on the client: the server produces HTML (plus inline data), and the browser adopts that existing DOM in place rather than re-creating it. [`Boundary.rpc`](https://weftui.dev/docs/reference/core#boundaryrpc) extends this to **rpc-backed server data** — resolve an rpc on the server, serialize its result into the HTML, replay it on the client without a second request, and then keep the region live for refetch.
10
+ Weft renders on the server and **hydrates** on the client. The server produces HTML plus inline data, and the browser adopts that existing DOM in place rather than re-creating it.
11
+
12
+ [`Boundary.rpc`](https://weftui.dev/docs/reference/core#boundaryrpc) extends this to **rpc-backed server data**: resolve an rpc on the server, serialize its result into the HTML, and replay it on the client without a second request. The region then stays live for refetch.
11
13
 
12
14
  ## The two halves
13
15
 
14
- - **Server** `@weftui/dom/server` renders an app node to an HTML string (or stream). The _hydratable_ variants additionally emit the inline data each reactive region and `Boundary.rpc` needs to resume on the client.
15
- - **Client** `@weftui/dom/client`'s `hydrate` walks the server DOM, adopts it, wires up reactivity and event handlers, and resumes from the inline data. It does **not** re-render from scratch.
16
+ - **Server**: `@weftui/dom/server` renders an app node to an HTML string (or stream). The _hydratable_ variants also emit the inline data each reactive region and `Boundary.rpc` needs to resume on the client.
17
+ - **Client**: `@weftui/dom/client`'s `WeftApp.hydrate` walks the server DOM, adopts it, wires up reactivity and event handlers, and resumes from the inline data. It does **not** re-render from scratch.
16
18
 
17
19
  ```typescript
18
20
  // server entry
@@ -25,15 +27,16 @@ export const render = (): Promise<string> => Effect.runPromise(renderToStringHyd
25
27
 
26
28
  ```typescript
27
29
  // client entry
28
- import { hydrate } from "@weftui/dom/client";
30
+ import { WeftApp } from "@weftui/dom/client";
29
31
  import { Effect } from "effect";
30
32
  import { App } from "./app";
31
33
 
32
34
  const root = document.getElementById("root")!;
33
- void Effect.runPromise(hydrate(App(), root));
35
+ const app = WeftApp.make();
36
+ void Effect.runPromise(WeftApp.hydrate(app, App(), root));
34
37
  ```
35
38
 
36
- The same side-effect-free `App` is imported by both entries — splice the server HTML into your template's outlet, ship it, and let the client entry hydrate it.
39
+ Both entries import the same side-effect-free `App`. Splice the server HTML into your template's outlet, ship it, and let the client entry hydrate it.
37
40
 
38
41
  `@weftui/dom/server` exports four renderers:
39
42
 
@@ -46,7 +49,9 @@ Use a hydratable renderer whenever the client will call `hydrate`. The plain ren
46
49
 
47
50
  ## Loading server data with `Boundary.rpc`
48
51
 
49
- SSR's natural companion is `Boundary.rpc`: it resolves an rpc **on the server**, serializes the result into the same HTML this page produces, and replays it on the client during `hydrate` no second request, no fallback flash then keeps the region live for `refetch`. It is the data half of the same server/client split described above: the rpc **contract** (pure Schema) is shared, while its **handler** lives in a server-only Layer the client never imports.
52
+ `Boundary.rpc` resolves an rpc **on the server**, serializes the result into the same HTML this page produces, and replays it on the client during `hydrate`. There is no second request and no fallback flash, and the region stays live for `refetch`.
53
+
54
+ It follows the same server/client split: the rpc **contract** (pure Schema) is shared, while its **handler** lives in a server-only Layer the client never imports.
50
55
 
51
56
  ```typescript
52
57
  import { Boundary, h } from "@weftui/core";
@@ -67,20 +72,20 @@ const StockPanel = (productId: number) =>
67
72
  );
68
73
  ```
69
74
 
70
- Under SSR the server resolves the rpc in-process, `successSchema`-encodes the result inline as `<script type="application/json">`, and renders in place; `hydrate` reads that payload positionally, seeds the `Resource`, and adopts the DOM **without re-calling the rpc** (replay, never retry). The full model — the contract/handler split, router wiring, the four lifecycles, the `Resource` handle, and typed-failure replay — lives in one place: the [RPC Data Boundaries guide](https://weftui.dev/docs/how-to/load-data-with-rpc). This page does not repeat it.
75
+ Under SSR the server resolves the rpc in-process, `successSchema`-encodes the result inline as `<script type="application/json">`, and renders in place; `hydrate` reads that payload positionally, seeds the `Resource`, and adopts the DOM **without re-calling the rpc** (replay, never retry). The full model lives in one place, the [RPC Data Boundaries guide](https://weftui.dev/docs/how-to/load-data-with-rpc): the contract/handler split, router wiring, the four lifecycles, the `Resource` handle, and typed-failure replay. This page does not repeat it.
71
76
 
72
77
  > **Note.** `Boundary.rpc` resolves through the ambient [`AppRpcClientTag`](https://weftui.dev/docs/reference/core#apprpcclienttag) seam, which `@weftui/router` provides on both sides. In a router-less mount there is no seam, so the boundary resolves to a descriptive "needs router/rpc" error (not a defect).
73
78
 
74
79
  ## When to use
75
80
 
76
- - **`Boundary.rpc`** data that must be resolved on the server (behind a server-only service, credential, or private network) and rendered into the initial HTML, then **refreshable** on the client (refetch / client-first SPA mount) over the same rpc.
77
- - **`Boundary.suspend`** async data that loads on the client (or streams the shell then fills); see the [Boundary API](https://weftui.dev/docs/reference/core#boundarysuspend).
81
+ - **`Boundary.rpc`**: data that must be resolved on the server (behind a server-only service, credential, or private network) and rendered into the initial HTML, then **refreshable** on the client (refetch / client-first SPA mount) over the same rpc.
82
+ - **`Boundary.suspend`**: async data that loads on the client (or streams the shell then fills); see the [Boundary API](https://weftui.dev/docs/reference/core#boundarysuspend).
78
83
 
79
84
  ## See also
80
85
 
81
- - [rpc data boundaries guide](https://weftui.dev/docs/how-to/load-data-with-rpc) the full `Boundary.rpc` walkthrough: contract/handler split, router wiring, the four lifecycles, and typed-failure replay
82
- - [Routing](https://weftui.dev/docs/how-to/add-routing) `@weftui/router` builds on this SSR + hydration model for full-page nested routing
86
+ - [rpc data boundaries guide](https://weftui.dev/docs/how-to/load-data-with-rpc): the full `Boundary.rpc` walkthrough, covering the contract/handler split, router wiring, the four lifecycles, and typed-failure replay
87
+ - [Routing](https://weftui.dev/docs/how-to/add-routing): `@weftui/router` builds on this SSR + hydration model for full-page nested routing
83
88
  - [`Boundary.rpc` API reference](https://weftui.dev/docs/reference/core#boundaryrpc)
84
89
  - [`ServerTag` API reference](https://weftui.dev/docs/reference/core#servertag)
85
- - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr) a runnable shop with an SSR-replayed, refetchable live-stock `Boundary.rpc`
86
- - [examples/ssr-hydration](https://github.com/stefvw93/weft/tree/main/examples/ssr-hydration) SSR + hydration without server data loading
90
+ - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr): a runnable shop with an SSR-replayed, refetchable live-stock `Boundary.rpc`
91
+ - [examples/ssr-hydration](https://github.com/stefvw93/weft/tree/main/examples/ssr-hydration): SSR + hydration without server data loading
@@ -9,7 +9,9 @@ description: Render a pending indicator (e.g. a top progress bar) during a defer
9
9
 
10
10
  **Goal:** show a progress indicator while a [lazy route](https://weftui.dev/docs/how-to/split-routes-lazily) resolves its chunk and data, so a slow network is visible instead of feeling frozen.
11
11
 
12
- When you navigate to a route, the router is **deferred-commit**: it resolves the target branch's chunk (if the component is `Router.lazy`) **and the matched leaf's own component effect** including any data the leaf awaits in its body _before_ swapping the URL, keeping the previous page mounted for the whole window. That resolve window is exposed as a reactive signal, [`Router.navigating`](https://weftui.dev/docs/reference/router#routernavigating), that you read to render pending UI.
12
+ When you navigate to a route, the router is **deferred-commit**. It resolves the target branch's chunk (if the component is `Router.lazy`) **and the matched leaf's own component effect**, including any data the leaf awaits in its body. Only then does it swap the URL, keeping the previous page mounted for the whole window.
13
+
14
+ That resolve window is exposed as a reactive signal, [`Router.navigating`](https://weftui.dev/docs/reference/router#routernavigating), that you read to render pending UI.
13
15
 
14
16
  ```typescript
15
17
  import { Component, h } from "@weftui/core";
@@ -32,7 +34,7 @@ const Shell = Component.gen(function* () {
32
34
  });
33
35
  ```
34
36
 
35
- Thread the signal into a persistent layout (the outermost `Shell` is ideal, since it never re-renders across navigations), and style the pending class however you like a top bar, a cursor change, a dimmed outlet.
37
+ Thread the signal into a persistent layout (the outermost `Shell` is ideal, since it never re-renders across navigations), and style the pending class however you like: a top bar, a cursor change, a dimmed outlet.
36
38
 
37
39
  ## The signal
38
40
 
@@ -44,22 +46,22 @@ type NavState = { readonly _tag: "Idle" } | { readonly _tag: "Navigating"; reado
44
46
 
45
47
  Read it two ways, mirroring `Router.params` / `Router.paramsStream`:
46
48
 
47
- - `Router.navigating` the `Subscribable<NavState>` on the `Router` service.
48
- - `Router.navigatingStream` an `Effect` resolving that `Subscribable`, for use in a `Component.gen` body (as above).
49
+ - `Router.navigating`: the `Subscribable<NavState>` on the `Router` service.
50
+ - `Router.navigatingStream`: an `Effect` resolving that `Subscribable`, for use in a `Component.gen` body (as above).
49
51
 
50
52
  The `to` field on `Navigating` is the target URL, if you want to label _where_ the app is going.
51
53
 
52
54
  ## Behavior to expect
53
55
 
54
- - **Only navigations with real async work flip it.** A branch with no `Router.lazy` node and a leaf whose effect resolves synchronously (no async work, or a memoized revisit) commits in the same tick, and `navigating` stays `Idle` an entirely eager app never sees `Navigating`, and adding the reader costs nothing.
56
+ - **Only navigations with real async work flip it.** A branch with no `Router.lazy` node and a leaf whose effect resolves synchronously (no async work, or a memoized revisit) commits in the same tick, and `navigating` stays `Idle`. An entirely eager app never sees `Navigating`, and adding the reader costs nothing.
55
57
  - **Latest-wins.** Rapid successive navigations commit only the newest; a superseded navigation never resets the signal (the newer one owns it).
56
58
  - **Back/forward.** `popstate` into a route with async work also resolves before committing, so the indicator shows for browser back/forward too.
57
59
  - **Failure resets it.** A rejected chunk load or a failing leaf pre-run (a typed error such as `notFound()`, or a defect) resets `navigating` to `Idle` (it never sticks on), then surfaces through normal error/defect handling.
58
60
  - **Server renders `Idle`.** Server render is buffered, so `navigating` is a client-only concern; the server supplies a constant `Idle` so the same `Shell` type-checks and renders on both sides.
59
- - **No built-in anti-flash delay.** The signal flips as soon as an async window opens, so a borderline-fast navigation can flash the indicator briefly. If you want to only show it past a threshold, delay the reveal in CSS rather than in the signal e.g. `transition-delay: 200ms` on `.is-navigating` so genuinely fast navigations never flicker.
61
+ - **No built-in anti-flash delay.** The signal flips as soon as an async window opens, so a borderline-fast navigation can flash the indicator briefly. If you want to only show it past a threshold, delay the reveal in CSS rather than in the signal (e.g. `transition-delay: 200ms` on `.is-navigating`), so genuinely fast navigations never flicker.
60
62
 
61
63
  ## See also
62
64
 
63
65
  - [`Router.navigating` API reference](https://weftui.dev/docs/reference/router#routernavigating)
64
- - [Split Routes Lazily](https://weftui.dev/docs/how-to/split-routes-lazily) the `Router.lazy` deferred-commit navigation this reports on
65
- - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr) wires this exact progress bar in its `Shell` (`components/shell.ts`), with a `pending-navigation.browser.test.ts`
66
+ - [Split Routes Lazily](https://weftui.dev/docs/how-to/split-routes-lazily): the `Router.lazy` deferred-commit navigation this reports on
67
+ - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr): wires this exact progress bar in its `Shell` (`components/shell.ts`), with a `pending-navigation.browser.test.ts`
@@ -9,7 +9,7 @@ description: Code-split a route's component into its own chunk with Router.lazy,
9
9
 
10
10
  **Goal:** keep a heavy page's render code (and its dependencies) out of the initial bundle, loading it only when its route is actually rendered.
11
11
 
12
- Wrap the route's `component` in [`Router.lazy`](https://weftui.dev/docs/reference/router#routerlazy). The route **descriptor** (its segment and param schemas) stays eager so the matcher, `href`, and the server's dispatch API still see it statically only the component body is split into its own chunk.
12
+ Wrap the route's `component` in [`Router.lazy`](https://weftui.dev/docs/reference/router#routerlazy). The route **descriptor** (its segment and param schemas) stays eager, so the matcher, `href`, and the server's dispatch API still see it statically. Only the component body is split into its own chunk.
13
13
 
14
14
  ```typescript
15
15
  import { Router } from "@weftui/router";
@@ -21,42 +21,44 @@ Router.route("docs/:category/:slug", {
21
21
  });
22
22
  ```
23
23
 
24
- The chunk loads on the server during render and on the client on navigation; only the **matched branch's** chunks are ever fetched. `E`/`R` are preserved — a lazy route has the exact same channels as the same component declared eagerly, so an unmet service requirement is still a compile error at `Router.router(...)`.
24
+ The chunk loads on the server during render and on the client on navigation. Only the **matched branch's** chunks are ever fetched.
25
+
26
+ `E`/`R` are preserved: a lazy route has the exact same channels as the same component declared eagerly. An unmet service requirement is still a compile error at `Router.router(...)`.
25
27
 
26
28
  ## Make the split real
27
29
 
28
- `Router.lazy` only splits if the dynamic `import()` is the **only eager path** to the heavy module. Keep the `Router.route(…)` descriptor in an eagerly-imported file, and move the component implementation (and its heavy deps) into a separate module referenced _only_ through `Router.lazy(() => import("./impl"))`:
30
+ `Router.lazy` only splits if the dynamic `import()` is the **only eager path** to the heavy module. Keep the `Router.route(…)` descriptor in an eagerly-imported file. Move the component implementation (and its heavy deps) into a separate module referenced _only_ through `Router.lazy(() => import("./impl"))`:
29
31
 
30
32
  ```typescript
31
- // routes.ts eager, tiny: just the descriptor
33
+ // routes.ts: eager and tiny, just the descriptor
32
34
  export const docsRoute = Router.route("docs/:category/:slug", {
33
35
  path: { category: Schema.String, slug: Schema.String },
34
36
  component: Router.lazy(() => import("./doc-page-impl").then((m) => m.DocsPage)),
35
37
  });
36
38
 
37
- // doc-page-impl.ts heavy: pulled into its own chunk, never in the initial graph
39
+ // doc-page-impl.ts: heavy, pulled into its own chunk, never in the initial graph
38
40
  export const DocsPage = Component.gen(function* () {
39
41
  /* renderHast, code highlighting, … */
40
42
  });
41
43
  ```
42
44
 
43
- A descriptor file that still `import`s the impl statically gains nothing the bundler keeps it in the initial graph.
45
+ A descriptor file that still `import`s the impl statically gains nothing: the bundler keeps it in the initial graph.
44
46
 
45
47
  ## What you get for free
46
48
 
47
- - **Flash-free hydration.** On a directly-loaded lazy route, the client re-invokes the same slot, awaits the chunk, and adopts the server DOM in place the first production matches, so nothing is mutated.
48
- - **Blank-free navigation.** Client navigation is **deferred-commit**: the router resolves the target branch's chunk **and the matched leaf's own component effect** _before_ committing the URL, so the previous page stays mounted through both the fetch and any data the leaf awaits, and the swap is a single tick. See [Show Navigation Progress](https://weftui.dev/docs/how-to/show-navigation-progress) for the `Router.navigating` signal this exposes.
49
+ - **Flash-free hydration.** On a directly-loaded lazy route, the client re-invokes the same slot, awaits the chunk, and adopts the server DOM in place. The first production matches, so nothing is mutated.
50
+ - **Blank-free navigation.** Client navigation is **deferred-commit**: the router resolves the target branch's chunk **and the matched leaf's own component effect** _before_ committing the URL. The previous page stays mounted through the fetch and any data the leaf awaits, and the swap is a single tick. See [Show Navigation Progress](https://weftui.dev/docs/how-to/show-navigation-progress) for the `Router.navigating` signal this exposes.
49
51
  - **Synchronous revisits.** `Router.lazy` memoizes its load per slot, so a second visit to a loaded route commits immediately.
50
52
 
51
53
  ## Edge cases
52
54
 
53
- - **Lazy layouts.** A `Router.layout({ component: Router.lazy(...) })` splits too each lazy node in the matched branch is awaited; nodes outside it never load.
54
- - **Chunk-load failure is a defect.** If the `import()` rejects (offline, or a stale client requesting a chunk a new deploy removed), it dies as a defect and surfaces through normal defect handling it never hangs or silently 404s. The rejection is memoized, so the route keeps failing until a reload (the deploy-skew case).
55
- - **Not a lazy _subtree_.** Only the component is lazy; you cannot defer a whole `RouteNode` behind an `import()`, because the matcher needs every leaf's segment and param schema before anything loads.
55
+ - **Lazy layouts.** A `Router.layout({ component: Router.lazy(...) })` splits too. Each lazy node in the matched branch is awaited; nodes outside it never load.
56
+ - **Chunk-load failure is a defect.** If the `import()` rejects (offline, or a stale client requesting a chunk a new deploy removed), it dies as a defect and surfaces through normal defect handling. It never hangs or silently 404s. The rejection is memoized, so the route keeps failing until a reload (the deploy-skew case).
57
+ - **Not a lazy _subtree_.** Only the component is lazy. You cannot defer a whole `RouteNode` behind an `import()`; the matcher needs every leaf's segment and param schema before anything loads.
56
58
 
57
59
  ## See also
58
60
 
59
61
  - [`Router.lazy` API reference](https://weftui.dev/docs/reference/router#routerlazy)
60
- - [Show Navigation Progress](https://weftui.dev/docs/how-to/show-navigation-progress) the deferred-commit `Router.navigating` signal
61
- - [Add Routing](https://weftui.dev/docs/how-to/add-routing) authoring the route tree `Router.lazy` plugs into
62
- - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr) includes a `Router.lazy` page (`lazy-page.ts`) with a browser test
62
+ - [Show Navigation Progress](https://weftui.dev/docs/how-to/show-navigation-progress): the deferred-commit `Router.navigating` signal
63
+ - [Add Routing](https://weftui.dev/docs/how-to/add-routing): authoring the route tree `Router.lazy` plugs into
64
+ - [examples/router-ssr](https://github.com/stefvw93/weft/tree/main/examples/router-ssr): includes a `Router.lazy` page (`lazy-page.ts`) with a browser test
@@ -2,14 +2,14 @@
2
2
  title: Style Reactively
3
3
  order: 10
4
4
  section: how-to
5
- description: Drive inline styles from streams a single property, or a whole style object so the DOM updates in place with CSS transitions.
5
+ description: Drive inline styles from streams (a single property, or a whole style object) so the DOM updates in place with CSS transitions.
6
6
  ---
7
7
 
8
8
  # Style Reactively
9
9
 
10
- **Goal:** animate or react to state in an element's inline style without re-rendering a single CSS property, or a whole style object, driven by a stream.
10
+ **Goal:** animate or react to state in an element's inline style without re-rendering. Drive a single CSS property, or a whole style object, from a stream.
11
11
 
12
- The `style` prop accepts the [`Source`](https://weftui.dev/docs/explanation/reactive-primitives) vocabulary at any level: a property value can be a stream, and you can spread a stream of style objects. CSS `transition` composes naturally, because the renderer mutates the existing node in place.
12
+ The `style` prop accepts the [`Source`](https://weftui.dev/docs/explanation/reactive-primitives) vocabulary at any level. A property value can be a stream, and you can spread a stream of style objects. CSS `transition` composes naturally, because the renderer mutates the existing node in place.
13
13
 
14
14
  ```typescript
15
15
  import { h } from "@weftui/core";
@@ -36,9 +36,9 @@ const AnimatedHue = () => {
36
36
 
37
37
  ## Three modes
38
38
 
39
- 1. **A single property as a stream** as above: one key's value is a `Stream`, the others are static strings. Each stream property is subscribed independently.
40
- 2. **A static object** an ordinary `style: { backgroundColor: "#667eea" }` with no streams; nothing updates.
41
- 3. **A whole style object as a stream** spread a stream that emits complete style objects, merged with static props:
39
+ 1. **A single property as a stream.** As above: one key's value is a `Stream`, the others are static strings. Each stream property is subscribed independently.
40
+ 2. **A static object.** An ordinary `style: { backgroundColor: "#667eea" }` with no streams; nothing updates.
41
+ 3. **A whole style object as a stream.** Spread a stream that emits complete style objects, merged with static props:
42
42
 
43
43
  ```typescript
44
44
  const pulse = Stream.make(1, 0.5).pipe(
@@ -49,15 +49,15 @@ const pulse = Stream.make(1, 0.5).pipe(
49
49
  h.div({ style: { ...pulse, transition: "opacity 0.4s ease-in-out" } }, "Pulse");
50
50
  ```
51
51
 
52
- Each emitted object is merged with the static properties on the element.
53
-
54
52
  ## Notes
55
53
 
56
- - **Property names are camelCase** (`backgroundColor`, `boxShadow`) the same keys as the DOM `style` object.
57
- - **CSS transitions just work.** Because a stream emission patches the DOM node directly (no re-render), the browser applies the `transition` as it would for any style mutation.
58
- - **Pace with `Schedule`.** `Stream.iterate`/`Stream.make` paced by `Stream.schedule(Schedule.spaced(…))` and looped with `Stream.forever` is the idiom for time-based style animation; combine with any Effect timing you like.
54
+ - **Property names are camelCase** (`backgroundColor`, `boxShadow`), the same keys as the DOM `style` object.
55
+ - **CSS transitions just work.** A stream emission patches the DOM node directly (no re-render), so the browser applies the `transition` as it would for any style mutation.
56
+ - **Pace with `Schedule`.** The idiom for time-based style animation: `Stream.iterate`/`Stream.make` paced by `Stream.schedule(Schedule.spaced(…))` and looped with `Stream.forever`. Combine with any Effect timing you like.
57
+ - **Classes have a reactive builder too.** `Props.cx` builds a class string from strings, falsy values, nested arrays, and `{ className: condition }` records, where a condition may be a stream. Merging two bags that both carry `class` concatenates them. See [Compose Behavior and Markup](https://weftui.dev/docs/how-to/compose-behavior-and-markup).
59
58
 
60
59
  ## See also
61
60
 
62
- - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives) reactive style props and the `Source` vocabulary
63
- - [examples/reactive-styles](https://github.com/stefvw93/weft/tree/main/examples/reactive-styles) per-property and whole-object stream styles with CSS transitions
61
+ - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives): reactive style props and the `Source` vocabulary
62
+ - [Compose Behavior and Markup](https://weftui.dev/docs/how-to/compose-behavior-and-markup): `Props.cx` and merging `class` across two prop bags
63
+ - [examples/reactive-styles](https://github.com/stefvw93/weft/tree/main/examples/reactive-styles): per-property and whole-object stream styles with CSS transitions
@@ -7,9 +7,9 @@ description: Capture a DOM element with the ref prop into a SubscriptionRef<Opti
7
7
 
8
8
  # Use Element Refs
9
9
 
10
- **Goal:** get a handle to a real DOM element to focus it, measure it, or call an imperative browser API on it.
10
+ **Goal:** get a handle to a real DOM element, to focus it, measure it, or call an imperative browser API on it.
11
11
 
12
- Declare a `SubscriptionRef<Option<HTMLElement>>`, attach it with the `ref` prop, and either **react** to the element appearing (a scoped observer on `SubscriptionRef.changes(ref)`) or **read** it later inside a handler.
12
+ Declare a `SubscriptionRef<Option<HTMLElement>>` and attach it with the `ref` prop. Then either **react** to the element appearing (a scoped observer on `SubscriptionRef.changes(ref)`) or **read** it later inside a handler.
13
13
 
14
14
  ```typescript
15
15
  import { h } from "@weftui/core";
@@ -34,9 +34,9 @@ const AutoFocusInput = () =>
34
34
 
35
35
  ## How it works
36
36
 
37
- - **The `ref` prop** takes a `SubscriptionRef<Option<T>>`. The renderer sets it to `Option.some(element)` **once**, when the element is created so the ref is an `Option`: `None` until mount, `Some(el)` after.
38
- - **React to mount** by observing `SubscriptionRef.changes(ref)`: `Stream.filter(Option.isSome)` waits for the element, `Stream.take(1)` takes just the first appearance, and `Stream.runForEach` does the imperative work. This is the equivalent of a mount effect.
39
- - **Use `Effect.forkScoped`, not `Effect.forkChild`.** `forkScoped` ties the observer fiber to the component's **instance scope** (the ambient `Scope` the renderer provides), so it lives as long as the component is mounted. A bare `Effect.forkChild` binds to the transient component-body fiber and is interrupted the instant the generator returns the observer would never fire.
37
+ - **The `ref` prop** takes a `SubscriptionRef<Option<T>>`. The renderer sets it to `Option.some(element)` **once**, when the element is created. The ref is therefore an `Option`: `None` until mount, `Some(el)` after.
38
+ - **React to mount** by observing `SubscriptionRef.changes(ref)`. `Stream.filter(Option.isSome)` waits for the element, `Stream.take(1)` takes just the first appearance, and `Stream.runForEach` does the imperative work. This is the equivalent of a mount effect.
39
+ - **Use `Effect.forkScoped`, not `Effect.forkChild`.** `forkScoped` ties the observer fiber to the component's **instance scope** (the ambient `Scope` the renderer provides). It lives as long as the component is mounted. A bare `Effect.forkChild` binds to the transient component-body fiber and is interrupted the instant the generator returns, so the observer would never fire.
40
40
 
41
41
  ## Read a ref imperatively
42
42
 
@@ -54,10 +54,12 @@ const scroll = () =>
54
54
 
55
55
  - A plain `Ref` suffices if you **only** read the element imperatively; use `SubscriptionRef` when you need to **react** to it becoming available.
56
56
  - Refs are set once at element creation and are not cleared on unmount.
57
+ - **Several refs can share one element.** `ref` also accepts an array, and every entry receives the element: `h.div({ ref: [measure, focus] })`. `Props.merge` produces such an array when both bags carry a `ref`, so a shared behavior's ref and your own can coexist. See [Compose Behavior and Markup](https://weftui.dev/docs/how-to/compose-behavior-and-markup).
57
58
  - Coming from React: `SubscriptionRef.make<Option<T>>(Option.none())` ↔ `useRef<T>(null)`; the `Stream.filter(Option.isSome)` observer ↔ a `useEffect` mount guard.
58
59
 
59
60
  ## See also
60
61
 
61
- - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives) `SubscriptionRef` and `SubscriptionRef.changes`
62
- - [Author Components](https://weftui.dev/docs/how-to/author-components) instance scope and `Effect.forkScoped`
63
- - [examples/element-ref](https://github.com/stefvw93/weft/tree/main/examples/element-ref) auto-focus, element measurement, and imperative scroll via refs
62
+ - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives): `SubscriptionRef` and `SubscriptionRef.changes`
63
+ - [Author Components](https://weftui.dev/docs/how-to/author-components): instance scope and `Effect.forkScoped`
64
+ - [Compose Behavior and Markup](https://weftui.dev/docs/how-to/compose-behavior-and-markup): merging a shared behavior's `ref` with your own
65
+ - [examples/element-ref](https://github.com/stefvw93/weft/tree/main/examples/element-ref): auto-focus, element measurement, and imperative scroll via refs