@weftui/dom 0.26.0 → 0.26.2

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.
@@ -0,0 +1,124 @@
1
+ ---
2
+ title: Provide Services
3
+ order: 12
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.
6
+ ---
7
+
8
+ # Provide Services
9
+
10
+ **Goal:** provide a `Layer` to the mounted app so its components can read services with `yield* Service`.
11
+
12
+ Which recipe to reach for depends on whether the layer has anything to release. A plain value layer (`Layer.succeed`, `Layer.effect` with no `acquireRelease`) can be provided directly at the mount — there is nothing to leak. A **scoped** layer (`Layer.scoped`, anything 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.
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.
17
+
18
+ ```typescript
19
+ import { mount } from "@weftui/dom/client";
20
+ import { Effect, pipe } from "effect";
21
+ import { App } from "./app";
22
+ import { ThemeServiceLive } from "./theme-service";
23
+
24
+ const root = document.getElementById("root")!;
25
+
26
+ const program = pipe(mount(App(), root), Effect.provide(ThemeServiceLive));
27
+
28
+ Effect.runPromise(program);
29
+ ```
30
+
31
+ ## Recipe 2 — scoped layers with `mountScoped`
32
+
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.
34
+
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";
40
+
41
+ const root = document.getElementById("root")!;
42
+
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);
54
+
55
+ // later, e.g. on a "sign out" action or test teardown:
56
+ // await Effect.runPromise(Fiber.interrupt(fiber));
57
+ ```
58
+
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:
60
+
61
+ ```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));
77
+ ```
78
+
79
+ `hydrateScoped` is the SSR counterpart — same composition, swap `mountScoped` for `hydrateScoped`.
80
+
81
+ ## Recipe 3 — `ManagedRuntime` with plain `mount`
82
+
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.
84
+
85
+ ```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);
93
+
94
+ await runtime.runPromise(mount(App(), root));
95
+
96
+ // later:
97
+ // await runtime.dispose();
98
+ ```
99
+
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.
101
+
102
+ ## Anti-patterns
103
+
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.
105
+
106
+ ```typescript
107
+ // ❌ plain mount: the layer releases the instant runPromise settles
108
+ Effect.runPromise(mount(App(), root).pipe(Effect.provide(SomeScopedLayer)));
109
+ ```
110
+
111
+ ```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));
115
+ ```
116
+
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.
118
+
119
+ ## See also
120
+
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 (`Registry.layer`) mounted with this composition
@@ -0,0 +1,51 @@
1
+ ---
2
+ title: Render Keyed Lists
3
+ order: 5
4
+ section: how-to
5
+ description: Render a reactive collection with List.each so reordering, inserting, and removing items reuses and moves existing DOM instead of rebuilding the region.
6
+ ---
7
+
8
+ # Render Keyed Lists
9
+
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
+
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
+
14
+ ```typescript
15
+ import { h, List } from "@weftui/core";
16
+ import { Stream } from "effect";
17
+
18
+ declare const rows: Subscribable.Subscribable<ReadonlyArray<{ id: number; name: string }>>;
19
+
20
+ h.ul([
21
+ List.each(
22
+ { of: rows.changes, by: (row) => row.id }, // key by stable identity
23
+ (row) => h.li(row.name),
24
+ ),
25
+ ]);
26
+ ```
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).
30
+
31
+ ## Why not `map`?
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.
34
+
35
+ ## Refresh a row's content
36
+
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:
38
+
39
+ ```typescript
40
+ List.each({ of: rows.changes, by: (row) => row.id }, (row) =>
41
+ h.li([h.span([Stream.map(row.status.changes, (s) => s)])]),
42
+ );
43
+ ```
44
+
45
+ > **⚠️ Index-key footgun.** Keying by index (`by: (_, i) => i`) reuses rows positionally, so after a reorder each position keeps its old content and you see stale rows. Prefer a stable identity key (`by: (item) => item.id`).
46
+
47
+ ## See also
48
+
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
@@ -0,0 +1,86 @@
1
+ ---
2
+ title: Server-Side Rendering
3
+ order: 2
4
+ section: how-to
5
+ description: renderToString / renderToStringHydratable / streaming variants, hydrate, and the server/client split.
6
+ ---
7
+
8
+ # Server-Side Rendering
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.
11
+
12
+ ## The two halves
13
+
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
+
17
+ ```typescript
18
+ // server entry
19
+ import { renderToStringHydratable } from "@weftui/dom/server";
20
+ import { Effect } from "effect";
21
+ import { App } from "./app";
22
+
23
+ export const render = (): Promise<string> => Effect.runPromise(renderToStringHydratable(App()));
24
+ ```
25
+
26
+ ```typescript
27
+ // client entry
28
+ import { hydrate } from "@weftui/dom/client";
29
+ import { Effect } from "effect";
30
+ import { App } from "./app";
31
+
32
+ const root = document.getElementById("root")!;
33
+ void Effect.runPromise(hydrate(App(), root));
34
+ ```
35
+
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.
37
+
38
+ `@weftui/dom/server` exports four renderers:
39
+
40
+ | | String | Stream |
41
+ | -------------------------------------- | -------------------------- | -------------------------- |
42
+ | **Plain** (no JS / no hydration) | `renderToString` | `renderToStream` |
43
+ | **Hydratable** (emits inline payloads) | `renderToStringHydratable` | `renderToStreamHydratable` |
44
+
45
+ Use a hydratable renderer whenever the client will call `hydrate`. The plain renderers produce complete, JS-free HTML with no payload scripts.
46
+
47
+ ## Loading server data with `Boundary.rpc`
48
+
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.
50
+
51
+ ```typescript
52
+ import { Boundary, h } from "@weftui/core";
53
+ import { Stream } from "effect";
54
+ import { GetStock } from "./data/inventory";
55
+
56
+ const StockPanel = (productId: number) =>
57
+ Boundary.rpc(
58
+ GetStock,
59
+ () => ({ id: productId }), // a fresh typed payload per call (SSR / refetch / mount)
60
+ (resource) =>
61
+ h.p([
62
+ "in stock: ",
63
+ h.span([Stream.map(resource.value.changes, (stock) => String(stock.units))]),
64
+ h.button({ type: "button", onclick: () => resource.refetch }, "Refresh"),
65
+ ]),
66
+ { fallback: h.p("loading stock…") }, // shown only on a client-first SPA mount
67
+ );
68
+ ```
69
+
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.
71
+
72
+ > **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
+
74
+ ## When to use
75
+
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).
78
+
79
+ ## See also
80
+
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
83
+ - [`Boundary.rpc` API reference](https://weftui.dev/docs/reference/core#boundaryrpc)
84
+ - [`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
@@ -0,0 +1,65 @@
1
+ ---
2
+ title: Show Navigation Progress
3
+ order: 7
4
+ section: how-to
5
+ description: Render a pending indicator (e.g. a top progress bar) during a deferred-commit navigation by reading the router's Router.navigating signal.
6
+ ---
7
+
8
+ # Show Navigation Progress
9
+
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
+
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.
13
+
14
+ ```typescript
15
+ import { Component, h } from "@weftui/core";
16
+ import { Router } from "@weftui/router";
17
+ import { Stream } from "effect";
18
+
19
+ const Shell = Component.gen(function* () {
20
+ const outlet = yield* Router.Outlet;
21
+ const nav = yield* Router.navigatingStream;
22
+ return yield* h.div({ id: "app" }, [
23
+ h.div({
24
+ id: "nav-progress",
25
+ "aria-hidden": "true",
26
+ class: Stream.map(nav.changes, (s) =>
27
+ s._tag === "Navigating" ? "nav-progress is-navigating" : "nav-progress",
28
+ ),
29
+ }),
30
+ h.main([outlet]),
31
+ ]);
32
+ });
33
+ ```
34
+
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.
36
+
37
+ ## The signal
38
+
39
+ `NavState` is a two-state machine:
40
+
41
+ ```typescript
42
+ type NavState = { readonly _tag: "Idle" } | { readonly _tag: "Navigating"; readonly to: string };
43
+ ```
44
+
45
+ Read it two ways, mirroring `Router.params` / `Router.paramsStream`:
46
+
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
+
50
+ The `to` field on `Navigating` is the target URL, if you want to label _where_ the app is going.
51
+
52
+ ## Behavior to expect
53
+
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.
55
+ - **Latest-wins.** Rapid successive navigations commit only the newest; a superseded navigation never resets the signal (the newer one owns it).
56
+ - **Back/forward.** `popstate` into a route with async work also resolves before committing, so the indicator shows for browser back/forward too.
57
+ - **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
+ - **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.
60
+
61
+ ## See also
62
+
63
+ - [`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`
@@ -0,0 +1,62 @@
1
+ ---
2
+ title: Split Routes Lazily
3
+ order: 6
4
+ section: how-to
5
+ description: Code-split a route's component into its own chunk with Router.lazy, keeping the descriptor eager so matching, href, and SSR stay unchanged.
6
+ ---
7
+
8
+ # Split Routes Lazily
9
+
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
+
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
+
14
+ ```typescript
15
+ import { Router } from "@weftui/router";
16
+ import { Schema } from "effect";
17
+
18
+ Router.route("docs/:category/:slug", {
19
+ path: { category: Schema.String, slug: Schema.String },
20
+ component: Router.lazy(() => import("./doc-page").then((m) => m.DocPage)),
21
+ });
22
+ ```
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(...)`.
25
+
26
+ ## Make the split real
27
+
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"))`:
29
+
30
+ ```typescript
31
+ // routes.ts — eager, tiny: just the descriptor
32
+ export const docsRoute = Router.route("docs/:category/:slug", {
33
+ path: { category: Schema.String, slug: Schema.String },
34
+ component: Router.lazy(() => import("./doc-page-impl").then((m) => m.DocsPage)),
35
+ });
36
+
37
+ // doc-page-impl.ts — heavy: pulled into its own chunk, never in the initial graph
38
+ export const DocsPage = Component.gen(function* () {
39
+ /* renderHast, code highlighting, … */
40
+ });
41
+ ```
42
+
43
+ A descriptor file that still `import`s the impl statically gains nothing — the bundler keeps it in the initial graph.
44
+
45
+ ## What you get for free
46
+
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
+ - **Synchronous revisits.** `Router.lazy` memoizes its load per slot, so a second visit to a loaded route commits immediately.
50
+
51
+ ## Edge cases
52
+
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.
56
+
57
+ ## See also
58
+
59
+ - [`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
@@ -0,0 +1,63 @@
1
+ ---
2
+ title: Style Reactively
3
+ order: 10
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.
6
+ ---
7
+
8
+ # Style Reactively
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.
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.
13
+
14
+ ```typescript
15
+ import { h } from "@weftui/core";
16
+ import { Schedule, Stream } from "effect";
17
+
18
+ const AnimatedHue = () => {
19
+ const hue = Stream.iterate(0, (h) => (h + 2) % 360).pipe(
20
+ Stream.schedule(Schedule.spaced("50 millis")),
21
+ );
22
+
23
+ return h.div(
24
+ {
25
+ class: "demo-box",
26
+ style: {
27
+ // one property is reactive; the rest are static
28
+ backgroundColor: Stream.map(hue, (h) => `hsl(${h}, 70%, 60%)`),
29
+ transition: "background-color 0.05s",
30
+ },
31
+ },
32
+ "Hue",
33
+ );
34
+ };
35
+ ```
36
+
37
+ ## Three modes
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:
42
+
43
+ ```typescript
44
+ const pulse = Stream.make(1, 0.5).pipe(
45
+ Stream.schedule(Schedule.spaced("800 millis")),
46
+ Stream.forever,
47
+ );
48
+
49
+ h.div({ style: { ...pulse, transition: "opacity 0.4s ease-in-out" } }, "Pulse");
50
+ ```
51
+
52
+ Each emitted object is merged with the static properties on the element.
53
+
54
+ ## Notes
55
+
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.
59
+
60
+ ## See also
61
+
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
@@ -0,0 +1,63 @@
1
+ ---
2
+ title: Use Element Refs
3
+ order: 11
4
+ section: how-to
5
+ description: Capture a DOM element with the ref prop into a SubscriptionRef<Option<HTMLElement>>, then react to its mount with a scoped observer or read it imperatively.
6
+ ---
7
+
8
+ # Use Element Refs
9
+
10
+ **Goal:** get a handle to a real DOM element — to focus it, measure it, or call an imperative browser API on it.
11
+
12
+ Declare a `SubscriptionRef<Option<HTMLElement>>`, attach it with the `ref` prop, and either **react** to the element appearing (a scoped observer on `.changes`) or **read** it later inside a handler.
13
+
14
+ ```typescript
15
+ import { h } from "@weftui/core";
16
+ import { Effect, Option, pipe, Stream, SubscriptionRef } from "effect";
17
+
18
+ const AutoFocusInput = () =>
19
+ Effect.gen(function* () {
20
+ const inputRef = yield* SubscriptionRef.make<Option.Option<HTMLInputElement>>(Option.none());
21
+
22
+ // Observe the element becoming available, once, and focus it.
23
+ yield* pipe(
24
+ inputRef.changes,
25
+ Stream.filter(Option.isSome),
26
+ Stream.take(1),
27
+ Stream.runForEach((el) => Effect.sync(() => el.value.focus())),
28
+ Effect.forkScoped, // ← ties the observer to the component's instance scope
29
+ );
30
+
31
+ return yield* h.input({ ref: inputRef, type: "text", placeholder: "I'm focused!" });
32
+ });
33
+ ```
34
+
35
+ ## How it works
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 `ref.changes`: `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.fork`.** `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.fork` binds to the transient component-body fiber and is interrupted the instant the generator returns — the observer would never fire.
40
+
41
+ ## Read a ref imperatively
42
+
43
+ When you only need the element later (e.g. in a click handler), skip the observer and read the ref on demand:
44
+
45
+ ```typescript
46
+ const scroll = () =>
47
+ Effect.gen(function* () {
48
+ const el = yield* SubscriptionRef.get(targetRef);
49
+ if (Option.isSome(el)) el.value.scrollIntoView({ behavior: "smooth" });
50
+ });
51
+ ```
52
+
53
+ ## Notes
54
+
55
+ - A plain `Ref` suffices if you **only** read the element imperatively; use `SubscriptionRef` when you need to **react** to it becoming available.
56
+ - Refs are set once at element creation and are not cleared on unmount.
57
+ - Coming from React: `SubscriptionRef.make<Option<T>>(Option.none())` ↔ `useRef<T>(null)`; the `Stream.filter(Option.isSome)` observer ↔ a `useEffect` mount guard.
58
+
59
+ ## See also
60
+
61
+ - [Reactive Primitives](https://weftui.dev/docs/explanation/reactive-primitives) — `SubscriptionRef` and `.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
package/docs/index.md ADDED
@@ -0,0 +1,59 @@
1
+ # Weft Documentation
2
+
3
+ **Reactive UI, woven from Effect.**
4
+
5
+ Weft is an Effect-native reactive DOM library — in the browser and on the server. `Node<E, R>` is `Effect.Effect<ElementDescriptor, E, R>`: every element is an Effect, so error and requirement channels accumulate through the tree, all Effect combinators apply to nodes directly, and services flow from mount through the whole app. Streams drive every update — there is no virtual DOM — and the same tree renders to HTML on the server and `hydrate()`s in place on the client, flash-free. No JSX.
6
+
7
+ The docs follow the [Diátaxis](https://diataxis.fr) model. Pick your entry point by what you are trying to do:
8
+
9
+ ## Start here
10
+
11
+ **[→ Tutorial](https://weftui.dev/docs/tutorial/01-your-first-app)** — a four-step guided path from a static component to a server-rendered, error-handled app. Start here if you are new to Weft:
12
+
13
+ 1. [Your First App](https://weftui.dev/docs/tutorial/01-your-first-app) — `h` and `mount`
14
+ 2. [Reactivity](https://weftui.dev/docs/tutorial/02-reactivity) — `SubscriptionRef` and streams
15
+ 3. [Services and Async](https://weftui.dev/docs/tutorial/03-services-and-async) — handlers, services, async loading
16
+ 4. [Errors and Server Rendering](https://weftui.dev/docs/tutorial/04-errors-and-server) — boundaries and SSR
17
+
18
+ ## The four quadrants
19
+
20
+ | | |
21
+ | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | **[Tutorial](https://weftui.dev/docs/tutorial/01-your-first-app)** | Learning-oriented. One guided path, start to finish. |
23
+ | **[How-to guides](https://weftui.dev/docs/how-to/author-components)** | Task-oriented. Author components, render on the server, load data with rpc, add routing — plus recipes for forms, async data, keyed lists, reactive styles, refs, and lazy routing. |
24
+ | **[Explanation](https://weftui.dev/docs/explanation/rendering-model)** | Understanding-oriented. The rendering model, the combinator API, reactive primitives, boundaries, and services & context. |
25
+ | **[Reference](https://weftui.dev/docs/reference/core)** | Information-oriented. Full API: [`@weftui/core`](https://weftui.dev/docs/reference/core), [`@weftui/dom`](https://weftui.dev/docs/reference/dom), [`@weftui/router`](https://weftui.dev/docs/reference/router). |
26
+
27
+ New to the model itself? Read [The Rendering Model](https://weftui.dev/docs/explanation/rendering-model) — why there is no virtual DOM, and what "streams are the weft" means.
28
+
29
+ ## Packages
30
+
31
+ Three published packages make up Weft's public API, plus one build-time plugin:
32
+
33
+ - **`@weftui/core`** — element builders (`h`), components, sources/streams, and boundaries. Start here.
34
+ - **`@weftui/dom`** — the renderer: `./client` (`mount`/`hydrate`) and `./server` (`renderToString*`).
35
+ - **`@weftui/router`** — universal nested routing, `Router.lazy`, and the rpc seam.
36
+ - **`@weftui/vite`** — a build-time Vite plugin (tooling, not a runtime API).
37
+
38
+ `@weftui/base` is an internal, currently-empty stub — it has no public primitives; ignore it.
39
+
40
+ ## Examples
41
+
42
+ The [`examples/`](https://github.com/stefvw93/weft/tree/main/examples) directory contains standalone runnable apps. Each covers a specific pattern and ships with a browser test:
43
+
44
+ | Example | What it shows |
45
+ | ---------------------------- | ------------------------------------------------------------------------------------ |
46
+ | `async-data-loading` | Loading states, retry, error boundaries with Stream and Effect |
47
+ | `declarative-event-handlers` | Plain, Effect-returning, service-aware, and reactive handlers |
48
+ | `element-ref` | DOM refs with `SubscriptionRef<Option<HTMLElement>>` |
49
+ | `error-boundary` | All six failure-catch `Boundary.*` variants |
50
+ | `form-handling` | Reactive inputs, Schema validation, Effect submit handlers |
51
+ | `keyed-list` | Keyed list rendering with `List.each` |
52
+ | `list-rendering` | Static and stream-based lists, fragments, nested iterables |
53
+ | `reactive-styles` | Per-property and whole-object stream styles, CSS transitions |
54
+ | `router-ssr` | Universal nested routing with SSR, hydration, layouts, `Boundary.rpc`, `Router.lazy` |
55
+ | `server-boundary` | `Boundary.rpc` client-first mount + refetch, router-less |
56
+ | `ssr-hydration` | SSR + hydration without server data loading |
57
+ | `subscription-ref` | Local state, derived streams, coordinating multiple refs |
58
+ | `suspense` | Suspense boundaries for streaming SSR and client coordination |
59
+ | `type-augmentation` | Typed custom elements on `h` via the `CustomElements` interface |