@expressive/react 0.94.1 → 0.94.3

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,683 @@
1
+ # Expressive MVC — Patterns
2
+
3
+ ## Counter
4
+
5
+ ```tsx
6
+ import { Component } from '@expressive/mvc';
7
+
8
+ class Counter extends Component {
9
+ count = 0;
10
+ increment() {
11
+ this.count++;
12
+ }
13
+ decrement() {
14
+ this.count--;
15
+ }
16
+
17
+ render() {
18
+ return (
19
+ <div>
20
+ <button onClick={this.decrement}>-</button>
21
+ <span>{this.count}</span>
22
+ <button onClick={this.increment}>+</button>
23
+ </div>
24
+ );
25
+ }
26
+ }
27
+ ```
28
+
29
+ ## Form with Validation
30
+
31
+ ```tsx
32
+ import { Component } from '@expressive/mvc';
33
+
34
+ class LoginForm extends Component {
35
+ email = '';
36
+ password = '';
37
+
38
+ get valid() {
39
+ return this.email.includes('@') && this.password.length >= 8;
40
+ }
41
+
42
+ submit() {
43
+ if (this.valid) postLogin(this.email, this.password);
44
+ }
45
+
46
+ render() {
47
+ const { email, password, valid, submit } = this;
48
+
49
+ return (
50
+ <form
51
+ onSubmit={(e) => {
52
+ e.preventDefault();
53
+ submit();
54
+ }}>
55
+ <input
56
+ value={email}
57
+ onChange={(e) => (this.email = e.target.value)}
58
+ />
59
+ <input
60
+ type="password"
61
+ value={password}
62
+ onChange={(e) => (this.password = e.target.value)}
63
+ />
64
+ <button disabled={!valid}>Log In</button>
65
+ </form>
66
+ );
67
+ }
68
+ }
69
+ ```
70
+
71
+ ## Async Data Fetching
72
+
73
+ ```tsx
74
+ import { Component, set } from '@expressive/mvc';
75
+
76
+ class Profile extends Component {
77
+ fallback = (<p>Loading...</p>);
78
+ data = set(async () => {
79
+ const res = await fetch('/api/user');
80
+ return res.json();
81
+ });
82
+
83
+ render() {
84
+ return (
85
+ <div>
86
+ <h1>{this.data.name}</h1>
87
+ <p>{this.data.email}</p>
88
+ </div>
89
+ );
90
+ }
91
+ }
92
+ ```
93
+
94
+ Suspense fits load-once data the view cannot render without. Keep explicit `loading` / `error` fields when the fetch is user-initiated, stale content stays visible during refresh, or errors render inline - see `expressive-mvc/field/set.md`.
95
+
96
+ ## Domain Rows in a Pool
97
+
98
+ State about a collection entry lives on the entry's class, spawned thru a `has` pool - not id-keyed records or `(id, value)` methods on the page. The factory takes the API payload (DTO in); the page keeps fetch, the pool, and selection *policy*:
99
+
100
+ ```tsx
101
+ import { Model, Component, get, has, set } from '@expressive/mvc';
102
+
103
+ class Message extends Component {
104
+ info = set<MessageDto>(); // payload stays one subobject - not exploded per key
105
+ id = set<string>();
106
+ selected = false;
107
+ inbox = get(Inbox);
108
+
109
+ toggle(event: MouseEvent) {
110
+ this.inbox.select(this, event); // policy stays on the page
111
+ }
112
+
113
+ async archive() {
114
+ await api.archive(this.id);
115
+ this.inbox.messages.delete(this);
116
+ }
117
+
118
+ render() {
119
+ const {
120
+ selected,
121
+ info: {
122
+ sender,
123
+ subject,
124
+ },
125
+ } = this;
126
+
127
+ return (
128
+ <button className={selected ? 'row on' : 'row'} onClick={this.toggle}>
129
+ <b>{sender}</b> {subject}
130
+ </button>
131
+ );
132
+ }
133
+ }
134
+
135
+ class Inbox extends Component {
136
+ messages = has((dto: MessageDto) => new Message({ info: dto, id: dto.id }));
137
+
138
+ get selected() {
139
+ return this.messages.filter((m) => m.selected);
140
+ }
141
+
142
+ async refresh() {
143
+ const data = await api.list();
144
+ this.messages.clear();
145
+ for (const dto of data) this.messages.add(dto);
146
+ }
147
+
148
+ select(message: Message, event: MouseEvent) { /* shift/meta multi-select */ }
149
+ }
150
+
151
+ function MessageList({ list }: { list: Message[] }) {
152
+ return <div className="messages">{list}</div>;
153
+ }
154
+ ```
155
+
156
+ Activated Components are React elements: the pool `{inbox.messages}` and plain subsets `{list}` place directly, no `.map`. Each row paints from its own `render()` subscription - selecting one re-renders one row.
157
+
158
+ The factory earns its line by folding the payload to `info`. A seed already matching the class's init is just `has(Message)` - integration writes declared keys only, skips the rest; a clashing shared key is a TypeScript error.
159
+
160
+ A cross-cutting subset can be a second pool instead of a member flag - class-mode `add` admits ready-made members; `pool.has(value)` tracks that member only. Members evict on destroy, so refill clears the subset - use a durable key when selection must survive refresh:
161
+
162
+ ```tsx
163
+ class Inbox extends Component {
164
+ messages = has((dto: MessageDto) => new Message({ info: dto, id: dto.id }));
165
+ selected = has(Message); // holds members of `messages` as guests
166
+ }
167
+
168
+ // on the row
169
+ get selected() {
170
+ return this.inbox.selected.has(this);
171
+ }
172
+ ```
173
+
174
+ **Anti-pattern:** `void selected;` in an FC to force tracking of member fields. Consume the value in JSX, or move paint into the row's `render()`.
175
+
176
+ ## Form Chips in a Pool
177
+
178
+ Same shape for form entries with their own async lifecycle - an upload, a pending download, an applied filter. The chip owns that lifecycle: started in `new()`, handle in an unmanaged field, torn down on destroy. The form owns the pool and readiness, reading DTOs back out at the API boundary:
179
+
180
+ ```tsx
181
+ class Attachment extends Component {
182
+ file = set<File>();
183
+ job?: UploadJob;
184
+ composer = get(Composer);
185
+ _stop: (() => void) | null = null; // unmanaged - see state/state.md
186
+
187
+ get uploading() {
188
+ return !this.job?.done;
189
+ }
190
+
191
+ protected new() {
192
+ this._stop = api.upload(this.file, (job) => { this.job = job; });
193
+ return () => this._stop?.();
194
+ }
195
+
196
+ toApi(): AttachmentDto {
197
+ return { name: this.file.name, url: this.job!.url };
198
+ }
199
+
200
+ remove() {
201
+ this.composer.attachments.delete(this);
202
+ }
203
+
204
+ render() { /* chip: name, progress, remove */ }
205
+ }
206
+
207
+ class Composer extends Model {
208
+ subject = '';
209
+ attachments = has((file: File) => new Attachment({ file }));
210
+
211
+ get ready() {
212
+ return !this.attachments.any((a) => a.uploading);
213
+ }
214
+
215
+ get attachmentDtos() {
216
+ return this.attachments.map((a) => a.toApi());
217
+ }
218
+ }
219
+ ```
220
+
221
+ The owner coordinates readiness only. A method re-finding a chip by id to feed it progress belongs on the chip.
222
+
223
+ ## Region Controls
224
+
225
+ When a page control accumulates unrelated clusters - draft fields plus lookups plus request state plus navigation - split each into a region control owned as a field. Owned fields are Models; painting features mount in `render()` as JSX. Unplug test, build-time bias, forms table: [refactor.md](refactor.md) steps 3/5. Ownership provides implicitly; views bind the region directly:
226
+
227
+ ```tsx
228
+ class ComposePage extends Component {
229
+ composer = new Composer(); // owned field - provided with the page
230
+ busy = false;
231
+
232
+ get canSend() {
233
+ return this.composer.ready && !this.busy;
234
+ }
235
+
236
+ async send() { /* composer -> request -> thread */ }
237
+ }
238
+
239
+ // Form sections bind the region; the footer mixes both
240
+ function SubjectField() {
241
+ const { is: composer, subject } = Composer.get();
242
+ ...
243
+ }
244
+
245
+ function Footer() {
246
+ const { canSend, send } = ComposePage.get();
247
+ ...
248
+ }
249
+ ```
250
+
251
+ The page remains orchestrator - route identity, session, request dispatch, page-level errors. Split when the second cluster appears, not as late cleanup.
252
+
253
+ Name a control `Control`, or `<Feature>Control` once an app has several - two classes sharing a name make `@expressive/inspect` label lookups throw.
254
+
255
+ Children of a region `.get()` the region, never the page above it and back down. Facts they repeat become getters on the region; nested config they keep unpacking is forwarded once (`get config() { return this.page.sendOptions; }`), named for the local scope.
256
+
257
+ ## Bridging an Existing Router
258
+
259
+ Bridge, don't replace: a conversion keeps the app's router; adopting `@expressive/router` needs explicit go-ahead. An outer FC reads router hooks and passes props - fields take them - or a Component calls them at the top of `render()`, which runs as a function component:
260
+
261
+ ```tsx
262
+ function InboxRoute() {
263
+ const navigate = useNavigate();
264
+ const { folder } = useParams();
265
+
266
+ return (
267
+ <Inbox navigate={navigate} urlFolder={folder}>
268
+ <Toolbar />
269
+ <Messages />
270
+ </Inbox>
271
+ );
272
+ }
273
+ ```
274
+
275
+ Route params are props, not always working identity. When leaving a route must not clear the control, keep the working field separate and soft-sync with a reaction:
276
+
277
+ ```tsx
278
+ class ComposePage extends Component {
279
+ threadId?: string; // working identity - survives route changes
280
+ urlThreadId?: string; // route param - undefined off /t/:id
281
+
282
+ protected new() {
283
+ this.get(($) => {
284
+ void $.urlThreadId; // declare the trigger - legitimate in get() effects, never in renders
285
+ this.syncRoute();
286
+ });
287
+ }
288
+
289
+ async send() {
290
+ const tid = this.threadId ??= createId(); // working field leads
291
+ this.navigate(`/t/${tid}`, { replace: true }); // navigation confirms, never informs
292
+ ...
293
+ }
294
+ }
295
+ ```
296
+
297
+ Assign the working field the moment identity is created. Fresh ids threaded thru arguments, or a shadow field remembering the last route, mean the working field is still a mirror.
298
+
299
+ ## Host-Agnostic Domain Model, View Adapter
300
+
301
+ A class shared across environments (extension host + webview, server + client) stays fields-only - no `window`, DOM, or host APIs at module scope or in `new()`. The view-side module re-exports the class and registers `Model.on()` once; every instance constructed after that import gets the wiring; hosts never importing the adapter never run it:
302
+
303
+ ```ts
304
+ // domain/session.ts - loads anywhere
305
+ export class Session extends Model {
306
+ status = 'idle';
307
+ messages: MessageDto[] = [];
308
+ }
309
+
310
+ // webview/session.ts - the adapter; views import Session from here
311
+ export { Session } from '../domain/session';
312
+
313
+ Session.on({
314
+ setup() {
315
+ const onMessage = (event: MessageEvent<HostToView>) => {
316
+ if (event.data?.type === 'state')
317
+ this.set(event.data.values as Model.Assign<Session>);
318
+ };
319
+
320
+ window.addEventListener('message', onMessage);
321
+ signal('ready');
322
+ return () => window.removeEventListener('message', onMessage);
323
+ }
324
+ });
325
+ ```
326
+
327
+ Construction stays with the consumer - `session = new Session()` on the owning Component. No subclass (`class ViewSession extends Session`), no `Session.new()` in the adapter. Inbound snapshots land with `set(values)` - a superset payload is fine, extra keys drop (`expressive-mvc/state/set.md`).
328
+
329
+ ## Context Sharing
330
+
331
+ ```tsx
332
+ import { Model, Component, get } from '@expressive/mvc';
333
+
334
+ class Theme extends Model {
335
+ color = 'blue';
336
+ toggle() {
337
+ this.color = this.color === 'blue' ? 'red' : 'blue';
338
+ }
339
+ }
340
+
341
+ class ThemedWidget extends Component {
342
+ theme = get(Theme);
343
+ clicks = 0;
344
+
345
+ render() {
346
+ const {
347
+ clicks,
348
+ theme: {
349
+ color,
350
+ toggle,
351
+ },
352
+ } = this;
353
+
354
+ return (
355
+ <div style={{ color }}>
356
+ <button onClick={() => this.clicks++}>Clicked {clicks}</button>
357
+ <button onClick={toggle}>Toggle theme</button>
358
+ </div>
359
+ );
360
+ }
361
+ }
362
+
363
+ function App() {
364
+ return (
365
+ <Component for={Theme}>
366
+ <ThemedWidget />
367
+ </Component>
368
+ );
369
+ }
370
+ ```
371
+
372
+ `ThemedWidget` owns `clicks`; were `theme` its only member, an FC snapshotting `Theme.get()` replaces the class.
373
+
374
+ ## Contextual Children (No Prop Drilling)
375
+
376
+ Children of a provided instance declare their own dependencies with `.get()` - don't thread state values and callbacks through props:
377
+
378
+ ```tsx
379
+ // Before: parent unpacks state and drills it down
380
+ function Wizard() {
381
+ const { step, busy, canContinue, advance, retreat } = TransferState.get();
382
+ return <WizardActions step={step} busy={busy} canContinue={canContinue}
383
+ onNext={advance} onBack={retreat} />;
384
+ }
385
+
386
+ // After: the child is contextual - dependencies are local
387
+ function Wizard() {
388
+ return <WizardActions />;
389
+ }
390
+
391
+ function WizardActions() {
392
+ const {
393
+ busy,
394
+ canContinue,
395
+ advance,
396
+ retreat,
397
+ } = TransferState.get();
398
+
399
+ return (
400
+ <footer>
401
+ <button onClick={retreat} disabled={busy}>Back</button>
402
+ <button onClick={advance} disabled={!canContinue}>Continue</button>
403
+ </footer>
404
+ );
405
+ }
406
+ ```
407
+
408
+ Pure presentation components (a `Metric`, a badge) may still take plain props - context replaces drilled state, not every value.
409
+
410
+ ## Presence Boundary
411
+
412
+ The parent owns whether an optional child exists - it destructures the gated field and renders conditionally; the child reads the field's instance with `.get()`: `SettingsContent` / `SettingsEditor` in [react.md](react.md#presence-boundaries).
413
+
414
+ ```tsx
415
+ class SettingsState extends Model {
416
+ draft?: Draft = undefined;
417
+ saving = false;
418
+
419
+ async saveSettings() { ... }
420
+ }
421
+ ```
422
+
423
+ Default for a self-contained widget: the parent mounts `<UndoBar />` unconditionally; the bar reads `Outbox.get()` and falls thru when `pendingSend` is unset. The parent gate above fits when the parent reads the field for its own content.
424
+
425
+ ## Computed Values
426
+
427
+ ```tsx
428
+ import { Component } from '@expressive/mvc';
429
+
430
+ class Cart extends Component {
431
+ items: { name: string; price: number; qty: number }[] = [];
432
+
433
+ get total() {
434
+ return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
435
+ }
436
+
437
+ get count() {
438
+ return this.items.reduce((sum, i) => sum + i.qty, 0);
439
+ }
440
+
441
+ add(name: string, price: number) {
442
+ this.items = [...this.items, { name, price, qty: 1 }];
443
+ }
444
+
445
+ render() {
446
+ return (
447
+ <div>
448
+ <p>
449
+ {this.count} items - ${this.total}
450
+ </p>
451
+ </div>
452
+ );
453
+ }
454
+ }
455
+ ```
456
+
457
+ ## Debounced Search
458
+
459
+ ```ts
460
+ import { Model, set } from '@expressive/mvc';
461
+
462
+ class Search extends Model {
463
+ query = '';
464
+ results: string[] = [];
465
+
466
+ debouncedQuery = set('', (value) => {
467
+ const timer = setTimeout(() => this.performSearch(value), 300);
468
+ return () => clearTimeout(timer);
469
+ });
470
+
471
+ async performSearch(q: string) {
472
+ const res = await fetch(`/api/search?q=${q}`);
473
+ this.results = await res.json();
474
+ }
475
+ }
476
+ ```
477
+
478
+ ## Async Effect - One Request in Flight
479
+
480
+ ```ts
481
+ import { Model } from '@expressive/mvc';
482
+
483
+ class Search extends Model {
484
+ query = '';
485
+ results: string[] = [];
486
+
487
+ protected new() {
488
+ this.get(async ({ query }) => {
489
+ const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
490
+ this.results = await res.json();
491
+ });
492
+ }
493
+ }
494
+ ```
495
+
496
+ - A returned promise holds the effect: changes in flight queue one re-run with the latest values after it settles - no overlap, no stale `results`.
497
+ - Destructure the trigger; reads after `await` subscribe too.
498
+ - Needs per-keystroke timing control (delay, not just serialization)? Use Debounced Search above.
499
+
500
+ ## Await a Pending Value
501
+
502
+ ```ts
503
+ import { Model, set } from '@expressive/mvc';
504
+
505
+ class Invite extends Model {
506
+ link = set<string>();
507
+ status = 'Not sent';
508
+
509
+ async send() {
510
+ const link = await this.get(async ($) => $.link);
511
+ this.status = `Sent ${link}`;
512
+ }
513
+ }
514
+ ```
515
+
516
+ - Awaiting an effect's release stops it and yields the latest run - waits for a pending field, resolves at once when set.
517
+ - Async effect only; a sync effect's return is a cleanup, so awaiting one yields `undefined`.
518
+ - Several at once: `await Promise.all([a.get(async ($) => $.x), b.get(async ($) => $.y)])`.
519
+
520
+ ## Downstream Collection
521
+
522
+ ```tsx
523
+ import { Model, Component, get } from '@expressive/mvc';
524
+
525
+ class Tab extends Model {
526
+ label = '';
527
+ group = get(TabGroup);
528
+ }
529
+
530
+ class TabGroup extends Component {
531
+ tabs = get(Tab, true); // collects all Tab instances below
532
+ active = 0;
533
+
534
+ render() {
535
+ return (
536
+ <div>
537
+ {this.tabs.map((tab, i) => (
538
+ <button
539
+ key={tab.label}
540
+ onClick={() => (this.active = i)}
541
+ style={{ fontWeight: this.active === i ? 'bold' : 'normal' }}>
542
+ {tab.label}
543
+ </button>
544
+ ))}
545
+ </div>
546
+ );
547
+ }
548
+ }
549
+ ```
550
+
551
+ ## Owned Collection
552
+
553
+ Register what a Component constructs - rendered children, pool members - without a type, and release each when it is destroyed:
554
+
555
+ ```tsx
556
+ import { Model, Component } from '@expressive/mvc';
557
+
558
+ class Layer extends Component {}
559
+
560
+ class Canvas extends Component {
561
+ new() {
562
+ return this.get(Model, (layer) => {
563
+ const id = register(layer);
564
+ return () => unregister(id);
565
+ }, true);
566
+ }
567
+
568
+ render() {
569
+ return (
570
+ <section>
571
+ <Layer />
572
+ <Layer />
573
+ </section>
574
+ );
575
+ }
576
+ }
577
+ ```
578
+
579
+ Each rendered `Layer` is owned by the `Canvas` rendering it, so the callback runs as it mounts and the cleanup when it unmounts. Downstream `get(Layer, true)` would also find them, but through context - it needs the type, and would include Layers a nested Component owns. Ownership stays one level deep. The other direction, a reusable child finding whoever constructed it without naming the type, is `get(Model)` - see `expressive-mvc/state/context.md#ownership-vs-context`.
580
+
581
+ ## Refactoring Hooks Into a Class
582
+
583
+ Avoid a literal hook-for-field rewrite. Mutable inputs go in fields, derived values in getters, client setup/cleanup in an effect declared in `new()`, event handlers in methods.
584
+
585
+ ```tsx
586
+ // Before: width is source state, compact is derived state kept in sync.
587
+ function LayoutBadge() {
588
+ const [width, setWidth] = useState(window.innerWidth);
589
+ const [compact, setCompact] = useState(width < 720);
590
+
591
+ useEffect(() => {
592
+ const update = () => setWidth(window.innerWidth);
593
+ window.addEventListener('resize', update);
594
+ return () => window.removeEventListener('resize', update);
595
+ }, []);
596
+
597
+ useEffect(() => {
598
+ setCompact(width < 720);
599
+ }, [width]);
600
+
601
+ return <span>{compact ? 'Compact' : `Wide (${width}px)`}</span>;
602
+ }
603
+ ```
604
+
605
+ ```tsx
606
+ // After: width is the source field, compact is a getter, and resize belongs to the class.
607
+ import { Component } from '@expressive/mvc';
608
+
609
+ class LayoutBadge extends Component {
610
+ width = 0;
611
+
612
+ get compact() {
613
+ return this.width < 720;
614
+ }
615
+
616
+ protected new() {
617
+ this.get(() => {
618
+ const update = () => {
619
+ this.width = window.innerWidth;
620
+ };
621
+
622
+ update();
623
+ window.addEventListener('resize', update);
624
+ return () => window.removeEventListener('resize', update);
625
+ });
626
+ }
627
+
628
+ render() {
629
+ const { compact, width } = this;
630
+
631
+ return <span>{compact ? 'Compact' : `Wide (${width}px)`}</span>;
632
+ }
633
+ }
634
+ ```
635
+
636
+ ## Effects & Cleanup
637
+
638
+ ```ts
639
+ import { Model } from '@expressive/mvc';
640
+
641
+ class Timer extends Model {
642
+ elapsed = 0;
643
+
644
+ tick() {
645
+ this.elapsed++;
646
+ }
647
+
648
+ protected new() {
649
+ this.get(() => {
650
+ const id = setInterval(this.tick, 1000); // methods are auto-bound - no arrow wrapper
651
+ return () => clearInterval(id);
652
+ });
653
+ }
654
+ }
655
+ ```
656
+
657
+ ## Deriving from Model.get()
658
+
659
+ Destructure what renders and derive inline; move a reused derivation to a getter on the Model:
660
+
661
+ ```tsx
662
+ class Cart extends Model {
663
+ items = [] as Item[];
664
+
665
+ get total() {
666
+ return this.items.reduce((sum, item) => sum + item.price, 0);
667
+ }
668
+ }
669
+
670
+ function OrderSummary() {
671
+ const { items, total } = Cart.get();
672
+
673
+ if (items.length)
674
+ return (
675
+ <div>
676
+ <p>{items.length} items</p>
677
+ <p>Total: ${total}</p>
678
+ </div>
679
+ );
680
+
681
+ return <p>Cart is empty</p>;
682
+ }
683
+ ```