@expressive/react 0.94.1 → 0.94.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,291 @@
1
+ # Expressive MVC - React
2
+
3
+ `@expressive/react` is the React host: a `Component` renders as a React component, `<Component for>` provides a Model to the tree, and function components read it with `Model.get()`.
4
+
5
+ - Core Model API (properties, reactivity, lifecycle, events): `../expressive-mvc/state/`.
6
+ - Instructions and reactive helpers (`get`, `set`, `ref`, `map`, `has`, `def`): `../expressive-mvc/field/*.md`.
7
+ - Examples and patterns: `patterns.md`.
8
+
9
+ ## Exports
10
+
11
+ `@expressive/react` exports nothing for app code - import it once, for its side effect, and take `Model`, `Component` and the instructions from `@expressive/mvc`. Subpaths: `@expressive/react/adapter` (`Runtime`, for writing a host) and `@expressive/react/vite` (the hot-reload plugin).
12
+
13
+ ## Quick Start
14
+
15
+ ```tsx
16
+ import { Model, Component, get, set, ref } from '@expressive/mvc';
17
+ import '@expressive/react'; // once, in the entry module
18
+
19
+ class Counter extends Component {
20
+ count = 0;
21
+ increment() {
22
+ this.count++;
23
+ }
24
+
25
+ render() {
26
+ return <button onClick={this.increment}>{this.count}</button>;
27
+ }
28
+ }
29
+
30
+ <Counter count={5} />;
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Effects run once committed
36
+
37
+ An effect declared during construction - in the constructor or `new()` - holds its first run until the owning component commits, client only. Timers, listeners, anything touching `window` go there; the cleanup it returns runs on destroy.
38
+
39
+ ```tsx
40
+ class Viewport extends Model {
41
+ width = 0;
42
+
43
+ protected new() {
44
+ this.get(() => {
45
+ const measure = () => (this.width = window.innerWidth);
46
+
47
+ measure();
48
+ window.addEventListener('resize', measure);
49
+ return () => window.removeEventListener('resize', measure);
50
+ });
51
+ }
52
+ }
53
+ ```
54
+
55
+ Commit is an **ownership** signal - it reaches an instance where a component creates and destroys it, never one a path merely reaches:
56
+
57
+ | Reaching an instance | Owns it | Effects wait for |
58
+ | ----------------------------- | ------- | --------------------- |
59
+ | `<Component />` | yes | its commit |
60
+ | `<Component for={Model}>` | yes | the provider's commit |
61
+ | `<Component for={instance}>` | no | nothing |
62
+ | `Model.get()` | no | nothing |
63
+ | `{instance}` | no | nothing |
64
+ | `Model.new()` | no host | its own settle |
65
+
66
+ `<Component for={Model}>` releases the instance it constructed with its own commit:
67
+
68
+ - Like any parent, it commits *after* its descendants (React commits bottom-up) - a descendant reacts to a provided instance by subscription, not by reading it imperatively in its own effect.
69
+ - Replacing `for` with another class destroys the previous instance and releases the new one at once - the provider is already placed, or, swapped before its first commit, treated as such.
70
+
71
+ The excluded paths are *many-to-one*: any number of components can `.get()` one instance or place it as `{instance}`, each for less time than the instance lives. To react to an instance a component does not own, subscribe with `Model.get()` or an event.
72
+
73
+ Nothing commits during server render, so these effects never run there. Children owned as fields follow their root ([expressive-mvc/state/lifecycle.md](../expressive-mvc/state/lifecycle.md#the-new-hook)).
74
+
75
+ The effect is tracked: a read of `$` subscribes, and each change re-runs it after its cleanup - a socket opened on `$.url` reopens per change. A one-shot resource reads `this`, which is untracked, and runs once.
76
+
77
+ | Seam | Phase | Runs | On the server |
78
+ | ----------------- | ------------ | --------------------------------------- | ------------- |
79
+ | `new()` body | construction | once, synchronously | yes |
80
+ | effect in `new()` | commit | once the host commits, then per change | no |
81
+
82
+ Setup accompanying the instance itself is the `new()` body; anything touching `window`, timers or subscriptions is an effect declared there.
83
+
84
+ React can discard a render before committing it - a suspended first mount, a dropped transition. Instances an owning path created there are already activated, so `new()` ran; the adapter destroys them once React releases the attempt, at garbage collection rather than promptly. Effects run only for the attempt that commits.
85
+
86
+ ## Server render (SSR / RSC)
87
+
88
+ Expressive components render on the server - `renderToString`, and the SSR pass of an RSC app (they are client components) - without touching the DOM. Nothing commits, so for a host-owned Component and the children it owns, effects declared in `new()` never run, `on({ ready })` never fires and `await state.get(() => {})` never resolves; the `new()` body does. Request-safety rules:
89
+
90
+ - **Request state goes in a `<Component for>`.** Each render builds its own context, so provided instances are isolated per request.
91
+ - **An instance held in `Context.root` is process-wide, *shared across requests* on the server** - fit for config, flags or a warmed cache. Keep per-request data out; provide it with `<Component for>`.
92
+ - **Resources belong in an effect or the request handler, never the `new()` body.** The body runs on the server but its returned teardown does not (no unmount), so a socket or handle opened there leaks. An effect is client-only; server-side resources are the framework's request scope to open and close.
93
+
94
+ To render a specific request's data (a path, a session), provide it per request: `<Component for={Session} …>`. Each render's `Router` is its own, so paths never bleed between requests; provide `<Component for={Router} path={…}>` to render a request's path.
95
+
96
+ ## React Native
97
+
98
+ Works with no configuration - the adapter imports only `react` and `react/jsx-runtime`, and Metro resolves it as published. Three boundaries:
99
+
100
+ - **Jest.** The build is ESM-only and `jest-expo` skips `node_modules`, so the import fails to parse until `@expressive` is added to `transformIgnorePatterns`:
101
+
102
+ ```js
103
+ transformIgnorePatterns: [
104
+ '/node_modules/(?!(.pnpm|@expressive|react-native|@react-native|expo|@expo))'
105
+ ]
106
+ ```
107
+
108
+ - **`BrowserRouter` is the browser binding** - it reads `window.location`, undefined in React Native. Use `Router`, whose path and history are in memory.
109
+ - **`Link` and `NavLinks` render DOM elements** (`<a>`, `<ul>`) with no native host yet. Drive navigation from `Router` directly and render your own `Pressable`.
110
+
111
+ ## Hot reload (Vite)
112
+
113
+ ```ts
114
+ // vite.config.ts
115
+ import react from '@vitejs/plugin-react';
116
+ import expressive from '@expressive/react/vite';
117
+
118
+ export default defineConfig({ plugins: [react(), expressive()] });
119
+ ```
120
+
121
+ Editing a `Model` or `Component` class patches it in place - instances keep their values and re-render with the new methods, getters, `render` and subcomponents. React Refresh keeps function components. A field, constructor or `new()` change reloads the page, as does any edit to a module declaring a class with `#` private members ([expressive-mvc/state/lifecycle.md](../expressive-mvc/state/lifecycle.md#hot-patching)). Dev server only.
122
+
123
+ A class must be top-level `class X` or `let X = class` - a `const` binding cannot be patched. `export default X;` exports a snapshot, so its importers are not checked for staleness - prefer `export default class X` or `export { X as default }`; likewise an anonymous `export default`.
124
+
125
+ ---
126
+
127
+ ## Model.get() - Context Hook
128
+
129
+ Fetches an instance from context (provided by a `Component` or `<Component for>`) and independently subscribes to accessed properties. Available on every Model.
130
+
131
+ ```tsx
132
+ function Profile() {
133
+ const app = AppState.get();
134
+ return <p>{app.user}</p>;
135
+ }
136
+ ```
137
+
138
+ ### Optional lookup
139
+
140
+ ```tsx
141
+ const app = AppState.get(false); // undefined if not in context
142
+ ```
143
+
144
+ ### Presence boundaries
145
+
146
+ Hold a value that may be unset as a Model field - the instance joins its owner's context. Destructure it and render conditionally; the child reads it with `.get()`:
147
+
148
+ ```tsx
149
+ const { draft } = Settings.get();
150
+ if (draft) return <Editor />;
151
+ return <Spinner />;
152
+ ```
153
+
154
+ The parent owns whether the child renders; the child's `Draft.get()` finds the instance wherever it renders - no fallback values threaded through its body, no Model values passed as props. A gated value with one view of its own is a `Component`, placed as `{draft}`:
155
+
156
+ ```tsx
157
+ function SettingsContent() {
158
+ const { draft } = SettingsState.get();
159
+
160
+ return (
161
+ <div className="settings-layout">
162
+ <LocationList />
163
+ {draft && <SettingsEditor />}
164
+ </div>
165
+ );
166
+ }
167
+
168
+ function SettingsEditor() {
169
+ const {
170
+ bankAccount,
171
+ categoryAccounts,
172
+ } = Draft.get();
173
+
174
+ const {
175
+ saveSettings,
176
+ saving,
177
+ } = SettingsState.get();
178
+ ...
179
+ }
180
+ ```
181
+
182
+ ### Derived values and effects
183
+
184
+ Derive from the snapshot in render, or declare a getter on the Model ([expressive-mvc/state/computed.md](../expressive-mvc/state/computed.md)); side effects belong in an instance effect (`state.get(effect)`), declared in `new()`.
185
+
186
+ ```tsx
187
+ function Greeting() {
188
+ const { user: { name } } = AppState.get();
189
+ return <p>Hello, {name.toUpperCase()}</p>;
190
+ }
191
+ ```
192
+
193
+ ### Custom lookup
194
+
195
+ A class overriding static `get` keeps context and render tracking - `User.get(id)` subscribes like `User.get()`. See [expressive-mvc/state/get.md](../expressive-mvc/state/get.md#static-get).
196
+
197
+ Bare `Context.get()` returns the render's context in a render, else root - safe anywhere. `state.get(Type)` runs no hooks and does not subscribe the component.
198
+
199
+ ### Reactive context
200
+
201
+ If the upstream instance is replaced in context (e.g. `<Component for>` given a new item), the hook resubscribes to the new instance and refreshes. An instance arriving after mount refreshes it too - `get(false)` included. Once the instance leaves, `get(false)` returns `undefined` and a required `get()` throws - unmount consumers before destroying their provider.
202
+
203
+ ---
204
+
205
+ ## Dependency Snapshots
206
+
207
+ Open every subscribing component by destructuring the exact reactive values it renders - nested levels included, optional objects defaulted in place:
208
+
209
+ ```tsx
210
+ function ReviewNotices() {
211
+ const {
212
+ blocking,
213
+ hasBlocking,
214
+ result: {
215
+ wssDownload: {
216
+ selectedLocationId,
217
+ usedLogin,
218
+ } = {},
219
+ },
220
+ } = ReviewStep.get();
221
+ ...
222
+ }
223
+ ```
224
+
225
+ An architectural norm, not formatting:
226
+
227
+ 1. The complete dependency surface is visible at the top.
228
+ 2. Trapped getters are traversed once, not re-walked (`review.result.wssDownload.usedLogin`) in every expression.
229
+ 3. Reads create subscriptions. A deep read inside a conditional branch subscribes only on renders where that branch runs (a **conditional subscription**), and reads inside event handlers never subscribe. Hoisting reads into the snapshot makes the dependency surface deterministic.
230
+
231
+ The same applies to `this` inside `Component.render()` and subcomponents - rendering shares the hooks' subscription plumbing.
232
+
233
+ ## Transparent Writes & `is`
234
+
235
+ Subscription proxies pass assignments through to the real instance. Three shapes cover every case:
236
+
237
+ ```tsx
238
+ const form = LoginForm.get(); // whole object is the only need
239
+ onChange={(e) => (form.username = e.target.value)}
240
+
241
+ const { transfer, confirmed } = ReviewStep.get(); // nested object from a snapshot -
242
+ onClick={() => (transfer.step = 'generate')} // writes are transparent
243
+
244
+ const { is: review, confirmed } = ReviewStep.get(); // root object + sibling values:
245
+ // only here does `is` earn its place
246
+ ```
247
+
248
+ Do not alias `is` merely because something will be written - writes never need the raw instance. Unwrapping nested objects through `is` is noise.
249
+
250
+ ---
251
+
252
+ ## Component Class
253
+
254
+ `Component` extends `Model` and renders as a React class component. The class contract - props, `render()`, subcomponents, `fallback`, `catch`, `pending()` - is [expressive-mvc/component.md](../expressive-mvc/component.md). Under React:
255
+
256
+ - `ref` receives the instance after mount and clears to `null` on unmount: `<ChatRoom ref={chatRef} />`. Use it for post-mount imperative access; `is` for construction time.
257
+ - The instance also carries React's class members (`state`, `context`, `setState`, `forceUpdate`).
258
+ - `fallback` is a React `Suspense` boundary; `catch()` an error boundary. `pending()` work runs through `startTransition`.
259
+ - Strict Mode: one instance despite double-mount.
260
+
261
+ ---
262
+
263
+ ## Providing state
264
+
265
+ `<Component for={AppState}>` provides one instance to its children, with no boundary unless `fallback` or `catch` is passed - contract in [expressive-mvc/state/context.md](../expressive-mvc/state/context.md#providing-with-component); commit timing in [Effects run once committed](#effects-run-once-committed). For a render-prop read, write an FC calling `AppState.get()`.
266
+
267
+ `Provider` was removed - replace `<Provider for={X}>` with `<Component for={X}>`.
268
+
269
+ ---
270
+
271
+ ## Internals: Runtime
272
+
273
+ Each adapter injects framework hooks into a shared `Runtime` object, so the same core logic works across React and Preact:
274
+
275
+ ```ts
276
+ Object.assign(Runtime, {
277
+ createElement,
278
+ createContext,
279
+ useContext,
280
+ useEffect,
281
+ useState,
282
+ useRef,
283
+ useSyncExternalStore, // optional: pre-commit revision validation
284
+ startTransition, // optional: for pending() work
285
+ Suspense,
286
+ idle, // true when certainly not rendering, undefined when it cannot tell
287
+ // plus adapter-specific: dedupe, ErrorBoundary, ignore
288
+ });
289
+ ```
290
+
291
+ `idle()` lets `Context.get()` skip its hook probe outside a render - React reads its dispatcher (`null`, or the between-render stub whose hooks all throw); Preact returns `undefined` and probes, which never logs. An unrecognised React returns `undefined` too.