@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,569 @@
|
|
|
1
|
+
# Refactoring React to Expressive MVC - The Golden Path
|
|
2
|
+
|
|
3
|
+
Read in full before converting hook-based React code. The common failure is translating hooks one-for-one - setter methods, drilled props, over-promoted getters mirroring the old architecture. Ownership first, translation second; the checklist at the end audits the result.
|
|
4
|
+
|
|
5
|
+
Examples follow the conventions in [expressive-mvc/style.md](../expressive-mvc/style.md).
|
|
6
|
+
|
|
7
|
+
**Large apps:** convert route/page controls and their domain pools first; leave mature leaf widgets (inputs, menus) on hooks until the parent domain is stable. Coexistence is fine mid-migration.
|
|
8
|
+
|
|
9
|
+
## Ambiguity defaults
|
|
10
|
+
|
|
11
|
+
A one-shot conversion cannot ask. Proceed on these defaults, declare deviations in the deliverable; ask only when an assumption would destroy something unrecoverable - a feature, a public API.
|
|
12
|
+
|
|
13
|
+
| Ambiguity | Default |
|
|
14
|
+
|---|---|
|
|
15
|
+
| "No redesigns" / parity scope | Observable behavior and public contracts; internal structure is the task |
|
|
16
|
+
| Does leaving a route clear its control? | Keep control alive; soft-sync working identity from params |
|
|
17
|
+
| Selection across refetch | Durable key + re-find getter; member references only in pools stable between fetches |
|
|
18
|
+
| Loading UX for user-initiated ops | Explicit loading/error fields; suspense for load-once data |
|
|
19
|
+
| File layout | Colocate feature folder once a route has `Model` classes; existing convention wins |
|
|
20
|
+
| Verification gate | Currently-green checks only - a check broken at base is not yours to fix; report what was exercised |
|
|
21
|
+
| Bug or dead branch found at base | Preserve behavior and note it; drop only provably dead code, and say so |
|
|
22
|
+
| Routing | Bridge the existing router (step 7); adopting `@expressive/router` needs explicit go-ahead, never part of a conversion |
|
|
23
|
+
| Deliverable | Ownership map, assumptions taken, behavior deltas, filled checklist - in the PR or ledger |
|
|
24
|
+
|
|
25
|
+
## 1. Identify owners before touching hooks
|
|
26
|
+
|
|
27
|
+
List the stateful *concerns*, not the hooks: a multi-step workflow, a settings draft, a preview toggle, a network resource. Each gets exactly one owner. Touch no hook until the owner list is stable.
|
|
28
|
+
|
|
29
|
+
## 2. Separate headless workflow from display-intrinsic state
|
|
30
|
+
|
|
31
|
+
Headless - would exist without this UI: network operations, domain rules, cross-view coordination. Display-intrinsic: preview modes, confirmation checkboxes, selections driving one subtree. They go in different classes even when adjacent `useState` calls held them.
|
|
32
|
+
|
|
33
|
+
## 3. Choose `Model`, `Component`, or a plain FC
|
|
34
|
+
|
|
35
|
+
- Headless workflow -> `Model`, provided via context.
|
|
36
|
+
- Display-intrinsic state -> `Component` owning that subtree, acquiring the workflow through an instruction.
|
|
37
|
+
- Simple presentation -> plain function component.
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
export class TransferState extends Model {
|
|
41
|
+
step: WizardStep = 'location';
|
|
42
|
+
busy = false;
|
|
43
|
+
result: GenerateResponse | null = null;
|
|
44
|
+
|
|
45
|
+
get selectedLocation() {
|
|
46
|
+
return this.locations.find((l) => l.site === this.selectedSite);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async generate() { /* network + coordination */ }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class ReviewStep extends Component {
|
|
53
|
+
transfer = get(TransferState);
|
|
54
|
+
previewMode: 'table' | 'raw' = 'table';
|
|
55
|
+
confirmed = false;
|
|
56
|
+
|
|
57
|
+
render() {
|
|
58
|
+
return (
|
|
59
|
+
<article className="panel review">
|
|
60
|
+
<ReviewSummary />
|
|
61
|
+
<ReviewNotices />
|
|
62
|
+
<ReviewActions />
|
|
63
|
+
</article>
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**Anti-pattern - the reflexive split.** `ReviewState` plus a `ReviewView` FC because the old code had hooks. Fields supporting one rendered surface belong on the `Component` rendering it.
|
|
70
|
+
|
|
71
|
+
**Anti-pattern - the pass-through Component.** A class whose only members are `foo = get(Foo)` and `render()` is an FC wearing an instance - snapshot `Foo.get()` instead. Component earns the class when the instance owns fields, a pool, or a boundary no Component below it can carry - lifecycle counts only when it manages owned state; a ref plus a DOM-sync reaction over context is still an FC. Same triage for shells: a singleton feature with no state of its own is an FC mounting its children (`<Sidebar /> <MessageList />`). Inversely, a leaf widget still on `useState`/`useEffect` whose inputs are its identity is a Component - `<Thumbnail src size />` writes the fields, an effect in `new()` reacts to them.
|
|
72
|
+
|
|
73
|
+
**House style: the app entry is an FC** - pure composition, chrome like any shell owning nothing. Its last-resort boundary is `fallback`/`catch` on the top Component it mounts, not a class wrapping it:
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
export default function App() {
|
|
77
|
+
return (
|
|
78
|
+
<Layout fallback={null}>
|
|
79
|
+
<Inbox />
|
|
80
|
+
</Layout>
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
A `class App extends Component` whose only members are `fallback` and a `render()` returning that tree is a pass-through. Inspect reads the live tree, so it adds no introspection surface. App-wide state is Models owned by a render-less `Global` Component the app entry mounts at the top - it provides them to everything below. A Component entry is not wrong - the FC is convention, not rule.
|
|
86
|
+
|
|
87
|
+
The forms, by role:
|
|
88
|
+
|
|
89
|
+
| Thing | Form |
|
|
90
|
+
|---|---|
|
|
91
|
+
| App entry | FC (house style) - `catch`/`fallback` on the top Component it mounts |
|
|
92
|
+
| App-wide logic | Model owned by a render-less `Global` Component the entry mounts at the top |
|
|
93
|
+
| Headless region (query, pool, policy) | `Model` field on the Component owning the feature |
|
|
94
|
+
| Feature that paints | mounted `<Composer />` - never `new Composer()` on a parent |
|
|
95
|
+
| Mount-only ancestor (scroll pin, focus trap) | `Component` without `render()` |
|
|
96
|
+
| Chrome / token frame / zero-state strip | FC that `.get()`s |
|
|
97
|
+
|
|
98
|
+
`new X()` on a parent is for Models and pool members. A nested `new Component()` that is not a pool member or hot-swap either paints - mount it - or is a Model's job wearing paint. Don't wrap a consumer under a provider Component with nothing to paint; hold the instance as a field on the control that already exists and let sibling views `.get()` it.
|
|
99
|
+
|
|
100
|
+
**Anti-pattern - subcomponent overuse.** The sections in `render()` above are freestanding FCs, not PascalCase methods. Subcomponents (`<this.Header />`) are extension points for subclasses. Test: **would a subclass reasonably replace or wrap this renderer?** For ordinary scopes no - a freestanding FC calling `ReviewStep.get()` is clearer. See [expressive-mvc/component.md](../expressive-mvc/component.md).
|
|
101
|
+
|
|
102
|
+
## 4. Give repeated UI entries their own class
|
|
103
|
+
|
|
104
|
+
A property or action *about* an entry in a collection lives on that entry's class - not the page. The tells are syntactic:
|
|
105
|
+
|
|
106
|
+
- a field keyed by id: `Record<Id, T>`, `Map<Id, unknown>`, or parallel structures - `items` plus `selectedIds`; a second pool of the members, `selected = has(Item)`, is the honest shape
|
|
107
|
+
- a method taking `(id, value)`: `setItemWeight(id, w)`, `toggle(id)`
|
|
108
|
+
- a page method re-finding a member by id `pool.get((x) => x.id === id)` - that is the member's method; behavior moves with state
|
|
109
|
+
- reassigning a collection to update one entry: `this.items = this.items.map(...)`, `this.jobs = { ...this.jobs, [id]: job }`
|
|
110
|
+
|
|
111
|
+
Each tell is a missing class. Declare a `has` pool - class mode when the seed matches the member's init, a factory only when it must transform - and move state and actions onto the member:
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
// Wrong: item state flattened onto the page
|
|
115
|
+
class Inbox extends Component {
|
|
116
|
+
messages: MessageDto[] = [];
|
|
117
|
+
selectedIds = new Set<string>();
|
|
118
|
+
uploads: Record<string, UploadJob> = {};
|
|
119
|
+
|
|
120
|
+
setLabel(id: string, label: string) {
|
|
121
|
+
this.messages = this.messages.map((m) => m.id === id ? { ...m, label } : m);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Right: the entry is a class; the page keeps fetch, the pool, and policy
|
|
126
|
+
class Message extends Component {
|
|
127
|
+
id = set<string>();
|
|
128
|
+
subject = '';
|
|
129
|
+
label = '';
|
|
130
|
+
selected = false; // UI - not on the seed, never written by it
|
|
131
|
+
inbox = get(Inbox);
|
|
132
|
+
|
|
133
|
+
render() { /* the row paints itself */ }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
class Inbox extends Component {
|
|
137
|
+
messages = has(Message); // add({ id, subject, label }) - the seed is the init
|
|
138
|
+
|
|
139
|
+
get selected() {
|
|
140
|
+
return this.messages.filter((m) => m.selected);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Class mode writes only keys the class declares - leftover seed keys are skipped; a key on both with a clashing type is a TypeScript error, so check it, don't pre-empt it with a factory.
|
|
146
|
+
|
|
147
|
+
Selection flags, per-row status, row actions live on the member (`message.selected`, `message.archive()`); the page keeps fetch, pool lifecycle, multi-select *policy*. Rows owning `render()` place directly - `{inbox.messages}` or subset `{list}` - no `.map`. Two views computing the same expression over an entry -> a getter on the entry's class.
|
|
148
|
+
|
|
149
|
+
A row earns a pool with any one of: mutable UI state (selection, expanded), async lifecycle (upload, watch, progress), actions (remove, retry). Demoting it to a plain DTO is not economy: status reads thru lookups, and a method call on a raw instance creates no subscription - progress rendered only thru `page.importFor(id)` never repaints. Tracked reads reach the member thru the pool or its own `render()`.
|
|
150
|
+
|
|
151
|
+
A factory earns its line only when the seed must transform: fat payload folded to one field (`has((dto: MessageDto) => new Message({ info: dto, id: dto.id }))`), a rename, a colliding key dropped, multi-argument construction (`has((file: File) => new Attachment({ file }))`). Keep members small: promote a payload key to reactive field only when views render it or it changes independently; the rest stays whole as `info`. Normalize API `null` to `undefined` here so presence fields stay optional. See [expressive-mvc/field/has.md](../expressive-mvc/field/has.md) for pool surface, [patterns.md](patterns.md) for worked recipes.
|
|
152
|
+
|
|
153
|
+
Behavior parity does not exempt this step - parity constrains observable behavior, not code shape ("no redesigns" means UI and public contracts). Entry ownership is an invariant, not a style option.
|
|
154
|
+
|
|
155
|
+
## 5. Split regions out of fat orchestrators
|
|
156
|
+
|
|
157
|
+
When a page control still accumulates unrelated clusters after pools - draft fields, lookups, request state, navigation - each becomes a region control owned as a field. Ownership provides implicitly; views bind the region directly:
|
|
158
|
+
|
|
159
|
+
```tsx
|
|
160
|
+
class Composer extends Model { // headless region
|
|
161
|
+
page = get(ComposePage);
|
|
162
|
+
subject = '';
|
|
163
|
+
attachments = has((file: File) => new Attachment({ file }));
|
|
164
|
+
|
|
165
|
+
get ready() { ... }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class ComposePage extends Component { // orchestrator: route, session, request
|
|
169
|
+
composer = new Composer();
|
|
170
|
+
busy = false;
|
|
171
|
+
|
|
172
|
+
get canSend() {
|
|
173
|
+
return this.composer.ready && !this.busy;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async send() { /* composer -> request -> thread */ }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Form sections bind the region; the footer mixes both
|
|
180
|
+
const { is: composer, subject } = Composer.get();
|
|
181
|
+
const { canSend, send } = ComposePage.get();
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
An owned region needs no cross-control sync - the parent holds and reads the instance. Split when the second cluster appears, not as late cleanup.
|
|
185
|
+
|
|
186
|
+
A feature region is unpluggable: it owns its pool, display state, and chrome - don't leave the pool or query on the page because the page syncs it. Test each pane, strip, or panel the page mounts: delete its import - does the feature leave whole, pool included? Judge clusters by interaction, not product framing - clusters that never read each other are unrelated even when the product calls them one surface; a shared wire or replica decides sync, not view ownership. Sibling features read each other thru optional context (`get(Other, false)`); siblings don't see each other's context, so the consumer mounts beneath the provider in JSX. Extraction moves concerns off the class, not ownership off the tree: regions stay fields on the page Component. Only a shell owning nothing - chrome between page and features - demotes to an FC (step 3).
|
|
187
|
+
|
|
188
|
+
Same rule while building: a second concern appearing on a class is the moment it leaves. Bias one concern per Model/Component; barrels are deliberate - the page after extraction, a pool owner, a shell that only mounts. Chrome counts: a resize handle's `height`/`resizing`/`beginDrag` parked on Composer fails like a stranded pool. Compose the add-on as a mounted wrapper - the sized thing reads the sizer:
|
|
189
|
+
|
|
190
|
+
```tsx
|
|
191
|
+
<Resize> {/* owns height, drag, the handle */}
|
|
192
|
+
<div className="compose-box">
|
|
193
|
+
<Draft />
|
|
194
|
+
</div>
|
|
195
|
+
</Resize>
|
|
196
|
+
|
|
197
|
+
function Draft() {
|
|
198
|
+
const { parts } = Composer.get();
|
|
199
|
+
const { height } = Resize.get(); // the only other reader
|
|
200
|
+
...
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Unplug is dropping the `<Resize>` wrap and the height read. `class Composer extends Resizable` is not this: extension puts drag fields on every `Composer.get()` snapshot. Extend for *is a kind of* (a `Nav` that is a `Link`); wrap for an add-on you take off.
|
|
205
|
+
|
|
206
|
+
## 6. Provide classes directly
|
|
207
|
+
|
|
208
|
+
```tsx
|
|
209
|
+
// Wrong: instance created only to be provided
|
|
210
|
+
function App() {
|
|
211
|
+
const [transfer] = useState(() => TransferState.new());
|
|
212
|
+
return (
|
|
213
|
+
<Component for={transfer}>
|
|
214
|
+
<TransferPage />
|
|
215
|
+
</Component>
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Right: the class is the `for` target
|
|
220
|
+
function App() {
|
|
221
|
+
return (
|
|
222
|
+
<Component for={TransferState}>
|
|
223
|
+
<TransferPage />
|
|
224
|
+
</Component>
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Provide an instance only when preconfiguration or external ownership requires it. A page Component needs neither: owned fields provide implicitly, so `<Inbox />` mounts bare - a `<Component for>` plus `Session.new()` in bootstrap hides the construction graph.
|
|
230
|
+
|
|
231
|
+
## 7. Move source state and behavior; do not translate setters
|
|
232
|
+
|
|
233
|
+
Once ownership is settled:
|
|
234
|
+
|
|
235
|
+
- Values written by user input, browser events, timers, or network callbacks -> mutable class fields.
|
|
236
|
+
- `useMemo` values and effects that only sync state -> class getters.
|
|
237
|
+
- `useEffect` setup/teardown -> `protected new()` returning cleanup; browser-only resources -> an effect declared in `new()`, which waits for commit.
|
|
238
|
+
- Chains of `useEffect`s reacting to each other -> tracked reactions (`this.get($ => ...)`) registered in `new()`; updates batch, one re-run per flush however many trigger fields changed.
|
|
239
|
+
- `useCallback` handlers -> auto-bound class methods - pass directly to timers and listeners: `setInterval(this.tick, 1000)`, not `() => this.tick()`.
|
|
240
|
+
- `useRef` handles - unsubscribe functions, snapshots, timer ids -> unmanaged fields ([expressive-mvc/state/state.md](../expressive-mvc/state/state.md#unmanaged-instance-data)) - never reactive, never `#private`.
|
|
241
|
+
- Repeated `postMessage`-style calls over a typed union -> one signal helper (`signal('setLabel', { id })`). The union is the API - no per-message facade methods.
|
|
242
|
+
- Inbound host snapshots -> `this.set(values)` - unknown keys are ignored, missing keys stay; no `apply()`/`pick` facade ([expressive-mvc/state/set.md](../expressive-mvc/state/set.md)).
|
|
243
|
+
- Route params -> props on the page owner. Working identity (session, selection) is a separate field a reaction soft-syncs - never the URL param itself. Fusing them shows as stale-prop workarounds: fresh ids threaded thru arguments to outrun the route, shadow fields remembering the last route. Router recipe in [patterns.md](patterns.md).
|
|
244
|
+
|
|
245
|
+
```tsx
|
|
246
|
+
// Wrong: the URL param is the working identity - fresh ids outrun the route
|
|
247
|
+
class Workspace extends Component {
|
|
248
|
+
sessionId?: string; // route prop
|
|
249
|
+
|
|
250
|
+
async send() {
|
|
251
|
+
let sid = this.sessionId;
|
|
252
|
+
if (!sid) {
|
|
253
|
+
sid = createId(); // threaded through locals; the control
|
|
254
|
+
this.navigate(`/s/${sid}`); // learns its own id via prop round-trip
|
|
255
|
+
}
|
|
256
|
+
await api.send(sid, this.body);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Right: the working field leads; navigation confirms, never informs
|
|
261
|
+
class Workspace extends Component {
|
|
262
|
+
sessionId?: string; // working identity
|
|
263
|
+
urlSessionId?: string; // route prop
|
|
264
|
+
|
|
265
|
+
protected new() {
|
|
266
|
+
this.get(($) => {
|
|
267
|
+
void $.urlSessionId;
|
|
268
|
+
this.syncRoute(); // adopt or keep per policy - not 1:1
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async send() {
|
|
273
|
+
const sid = this.sessionId ??= createId();
|
|
274
|
+
this.navigate(`/s/${sid}`, { replace: true });
|
|
275
|
+
await api.send(sid, this.body);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
Reactive fields are assigned directly - do not manufacture setters:
|
|
281
|
+
|
|
282
|
+
```tsx
|
|
283
|
+
// Wrong: hook setters mechanically translated
|
|
284
|
+
class TransferState extends Model {
|
|
285
|
+
username = '';
|
|
286
|
+
|
|
287
|
+
setUsername(value: string) {
|
|
288
|
+
this.username = value;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Right: assignment is the API
|
|
293
|
+
onChange={(event) => (transfer.username = event.target.value)}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Keep a method when the write enforces policy - validation, normalization, coordinating fields, triggering behavior:
|
|
297
|
+
|
|
298
|
+
```tsx
|
|
299
|
+
setStartDate(startDate: string) {
|
|
300
|
+
this.range = {
|
|
301
|
+
startDate,
|
|
302
|
+
endDate: this.range.endDate && this.range.endDate < startDate
|
|
303
|
+
? startDate
|
|
304
|
+
: this.range.endDate,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Audit rule: **delete any method whose body is only `this.field = value`** - vocabulary without policy.
|
|
310
|
+
|
|
311
|
+
## 8. Getters: shared and semantic only
|
|
312
|
+
|
|
313
|
+
A derived value earns a getter on shared state when it has multiple consumers, domain or workflow meaning, cost enough to merit memoized tracking, a place in the instance's deliberate API, or introspection value (debugging, devtools):
|
|
314
|
+
|
|
315
|
+
```tsx
|
|
316
|
+
get hasBlocking() { // read by notices, actions, and header
|
|
317
|
+
return this.blocking > 0;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
get hasSavedWssAccess() { // domain meaning, multiple consumers
|
|
321
|
+
...
|
|
322
|
+
}
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
A calculation feeding a single view belongs in that view, next to its snapshot:
|
|
326
|
+
|
|
327
|
+
```tsx
|
|
328
|
+
// Wrong: display-only value promoted to shared state
|
|
329
|
+
class TransferState extends Model {
|
|
330
|
+
get selectedStepIndex() {
|
|
331
|
+
return STEPS.indexOf(this.step);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Right: the one consumer derives it locally
|
|
336
|
+
function StepIndicator() {
|
|
337
|
+
const { step } = TransferState.get();
|
|
338
|
+
const index = STEPS.indexOf(step);
|
|
339
|
+
...
|
|
340
|
+
}
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Judge meaning, not reference counts. A getter with one JSX consumer may still earn its place as a domain capability or introspectable surface - a locality finding needs a semantic argument ("this is JSX formatting, not workflow meaning"), never a count alone.
|
|
344
|
+
|
|
345
|
+
## 9. Kill prop drilling
|
|
346
|
+
|
|
347
|
+
Contextual children declare their own dependencies with `.get()` - drop the prop contracts the hooks needed:
|
|
348
|
+
|
|
349
|
+
```tsx
|
|
350
|
+
// Wrong: converted, but still carries the old plumbing
|
|
351
|
+
function ReviewActions({
|
|
352
|
+
confirmed,
|
|
353
|
+
hasBlocking,
|
|
354
|
+
busy,
|
|
355
|
+
onConfirm,
|
|
356
|
+
onDownload,
|
|
357
|
+
onBack,
|
|
358
|
+
}: ReviewActionsProps) { ... }
|
|
359
|
+
|
|
360
|
+
// Right: dependencies are local
|
|
361
|
+
function ReviewActions() {
|
|
362
|
+
const {
|
|
363
|
+
confirmed,
|
|
364
|
+
hasBlocking,
|
|
365
|
+
downloadIif,
|
|
366
|
+
transfer,
|
|
367
|
+
} = ReviewStep.get();
|
|
368
|
+
...
|
|
369
|
+
}
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
Pure presentation components (a `Metric`, a `StatusCallout`) may still take plain props - context replaces drilled *state*, not every value.
|
|
373
|
+
|
|
374
|
+
`.get()` the nearest real parent. When Composer owns the form, its inputs call `Composer.get()` - reaching over to `ComposePage.get()` and back down is drilling with extra steps. Facts repeated across those children (`status === 'sending'`) become parent getters (`get sending()`); nested config they keep unpacking is forwarded once (`get config() { return this.page.sendOptions; }`), named for the local scope - `config`, not `sendOptions`. Only the parent holds `get(ComposePage)`. The root is not exempt: token and frame chrome reads its own snapshot (`Frame` `.get()`s `theme`) - don't snapshot `this` at the root only to drill `style`.
|
|
375
|
+
|
|
376
|
+
## 10. Destructure an exact dependency snapshot
|
|
377
|
+
|
|
378
|
+
Every `.get()` and `render()` opens with the exact reactive values it renders, nested levels included, optional objects defaulted in place. Static `.get()` is a React hook: top of component or `render()`, unconditionally - in a branch, handler, or loop they build green and crash at runtime.
|
|
379
|
+
|
|
380
|
+
```tsx
|
|
381
|
+
// Wrong: deep reads scattered through JSX, one hidden in a branch
|
|
382
|
+
function JournalOverview() {
|
|
383
|
+
const review = ReviewStep.get();
|
|
384
|
+
|
|
385
|
+
return (
|
|
386
|
+
<section>
|
|
387
|
+
<dd>{review.result.artifact.config.accountFile}</dd>
|
|
388
|
+
<dd>{new Date(review.result.artifact.generatedAt).toLocaleString()}</dd>
|
|
389
|
+
{review.showRaw && <pre>{review.result.iif}</pre>}
|
|
390
|
+
</section>
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Right: the full dependency surface, declared once at the top
|
|
395
|
+
function JournalOverview() {
|
|
396
|
+
const {
|
|
397
|
+
showRaw,
|
|
398
|
+
result: {
|
|
399
|
+
iif,
|
|
400
|
+
artifact: {
|
|
401
|
+
generatedAt,
|
|
402
|
+
config: {
|
|
403
|
+
accountFile,
|
|
404
|
+
},
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
} = ReviewStep.get();
|
|
408
|
+
...
|
|
409
|
+
}
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Why:
|
|
413
|
+
|
|
414
|
+
1. A reviewer sees the complete dependency surface at the top.
|
|
415
|
+
2. Trapped getters are traversed once, not re-walked per expression.
|
|
416
|
+
3. Reads create subscriptions - a deep read in a branch subscribes only on renders where the branch runs (a **conditional subscription**); reads in event handlers never subscribe. The snapshot makes the surface deterministic.
|
|
417
|
+
|
|
418
|
+
Same for `this` in `Component.render()` and subcomponents - destructure at the top; rendering shares the hooks' subscription plumbing. Injected parents (`inbox = get(Inbox)`) are part of that snapshot - `Inbox.get()` in a render whose class already holds the field is a second subscription to the same instance. Static `.get()` is for freestanding FCs.
|
|
419
|
+
|
|
420
|
+
## 11. Write through the proxy; use `is` sparingly
|
|
421
|
+
|
|
422
|
+
Subscription proxies pass assignments through to the real instance. Three shapes cover every case:
|
|
423
|
+
|
|
424
|
+
```tsx
|
|
425
|
+
const transfer = TransferState.get(); // whole object is the only need
|
|
426
|
+
|
|
427
|
+
const { transfer, confirmed } = ReviewStep.get(); // nested object from a snapshot -
|
|
428
|
+
onClick={() => (transfer.step = 'generate')} // writes are transparent
|
|
429
|
+
|
|
430
|
+
const { is: review, confirmed } = ReviewStep.get(); // root object + sibling values:
|
|
431
|
+
// only here does `is` earn its place
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
**Anti-pattern:** aliasing `is` whenever anything will be written. Writes don't need the raw instance - unwrapping nested objects through `is` is noise.
|
|
435
|
+
|
|
436
|
+
## 12. Widgets own their gates
|
|
437
|
+
|
|
438
|
+
Default: a self-contained widget mounts unconditionally and gates itself - the parent writes `<UndoBar />`; the bar reads `Outbox.get()` and falls thru when `pendingSend` is unset ([expressive-mvc/style.md](../expressive-mvc/style.md) render fallthrough). A parent read existing only to gate belongs in the widget.
|
|
439
|
+
|
|
440
|
+
This is for a widget the parent has no reason to mention. A piece split out of a Component's own `render()` (step 13) is the other way round: the parent writes `cond && <Slot />` and the slot paints unconditionally, never opening with `if (!cond) return`.
|
|
441
|
+
|
|
442
|
+
Parent gate over a Model field the child reads with `.get()` is the secondary shape - right when the parent reads the field for its own content, or composition genuinely varies. Either way presence is a contract; the half-measure fails audit - `get()` plus an internal null-guard mid-snapshot:
|
|
443
|
+
|
|
444
|
+
```tsx
|
|
445
|
+
// Wrong: no contract either way
|
|
446
|
+
function SettingsEditor() {
|
|
447
|
+
const { draft, saving } = SettingsState.get();
|
|
448
|
+
if (!draft) return null;
|
|
449
|
+
...
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Right (parent reads draft for its own content): draft is a Model field, child gets it
|
|
453
|
+
function SettingsContent() {
|
|
454
|
+
const { draft } = SettingsState.get();
|
|
455
|
+
|
|
456
|
+
return (
|
|
457
|
+
<div className="settings-layout">
|
|
458
|
+
<LocationList />
|
|
459
|
+
{draft && <SettingsEditor />}
|
|
460
|
+
</div>
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function SettingsEditor() {
|
|
465
|
+
const {
|
|
466
|
+
bankAccount,
|
|
467
|
+
categoryAccounts,
|
|
468
|
+
} = Draft.get();
|
|
469
|
+
|
|
470
|
+
const {
|
|
471
|
+
saveSettings,
|
|
472
|
+
saving,
|
|
473
|
+
} = SettingsState.get();
|
|
474
|
+
...
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
## 13. Extract, then consolidate
|
|
479
|
+
|
|
480
|
+
A conditional JSX branch above ~10 lines or five component levels signals its own named scope - a heuristic, not a mandate. Then the inverse: **recombine scopes that share dependencies, read locally, and contain no nested decision logic.** Splitting every fragment adds navigation without clarifying ownership.
|
|
481
|
+
|
|
482
|
+
```tsx
|
|
483
|
+
// Consolidated: both branches read the same ReviewStep context,
|
|
484
|
+
// neither contains nested logic - one scope, not three
|
|
485
|
+
function Exceptions() {
|
|
486
|
+
const {
|
|
487
|
+
exceptions,
|
|
488
|
+
feeExceptions,
|
|
489
|
+
hasBlocking,
|
|
490
|
+
} = ReviewStep.get();
|
|
491
|
+
|
|
492
|
+
if (hasBlocking) {
|
|
493
|
+
return <section className="exceptions">...</section>;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
if (feeExceptions.length) {
|
|
497
|
+
return <section className="fees">...</section>;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
An early return skipping most of a declared snapshot signals the gated content wants its own component.
|
|
503
|
+
|
|
504
|
+
A `render()` past ~50 lines usually stopped composing. Conditionals and ternaries are the cut points when the branch is a widget - deleted or moved as a unit, with its own moving parts. Then the branch becomes a local FC that `.get()`s the parent - the `cond &&` stays at the call site and the FC always paints; `a ? <Foo /> : <Bar />` may instead become one FC picking its branch inside; an FC whose first statement is a gate is not a unit. A one-op stays in the parent: a single gated button, empty-state copy or formatted scalar is lines in `render()`, not a component - the extra name makes deleting or moving the feature touch two places. Look for a gated chunk, independent siblings sharing no snapshot, or a replaceable slice (that one a subcomponent). Not a hard fail - a dense one-concern tree stays; a hop just to get under 50 is worse than reading the paint in place.
|
|
505
|
+
|
|
506
|
+
A split needs a name meaningful without the parent (`UndoBar`, `AttachmentTray`). When the only honest name is parent plus "Body"/"Label" *and* the call site is children, it is not a concern. Two shapes stay valid even small: a child passed as a named slot prop (`label={<SenderBadge />}`, `detail`, `icon`) - the hop keeps the parent composing, not painting; and an early-return body whose branches *are* its job. A slot earns an FC only when it paints - `detail={String(unread || '')}` is a formatted scalar, inline.
|
|
507
|
+
|
|
508
|
+
A slot FC reads its own context: `UnreadBadge` calls `Folder.get()` and paints its pill instead of taking a prop unpacked from `this`, so the parent writes `detail={<UnreadBadge />}` without snapshotting for it. "Just presentation props" does not exempt a slot whose value came off `this` - the step 9 carve-out is for values with no contextual owner:
|
|
509
|
+
|
|
510
|
+
```tsx
|
|
511
|
+
// Wrong: parent snapshots files only to feed its own slot
|
|
512
|
+
render() {
|
|
513
|
+
const { open, files } = this;
|
|
514
|
+
return <Section open={open} detail={<SizeTally files={files} />} ... />;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// Right: the slot reads the parent; render() composes without it
|
|
518
|
+
function SizeTally() {
|
|
519
|
+
const { files } = Outbox.get();
|
|
520
|
+
...
|
|
521
|
+
}
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
Same when section chrome wraps one Component - `open`/`onToggle` read from the parent by `.get()`, not drilled back thru a generic wrapper. A shared wrapper earns its props per caller: other callers varying does not license this one - a caller with constant slots gets its own chrome reading the parent.
|
|
525
|
+
|
|
526
|
+
Independent siblings that never interact (recipient field, attachment picker) split into local FCs in the same module, each snapshotting what it needs - independent *features* split; one-op chrome like a lone send button stays. A layout-only row with no state inlines into `render()`.
|
|
527
|
+
|
|
528
|
+
The line/depth threshold alone is never grounds for a finding. To fail a branch, name the concrete cost: a conditional subscription, multiple independent decisions in one branch, independent inputs funneled thru one snapshot, mixed ownership, a duplicated dependency snapshot, or navigation a well-named scope would materially improve. "A separate component would be slightly nicer" is polish, not a defect.
|
|
529
|
+
|
|
530
|
+
## 14. Audit with this checklist
|
|
531
|
+
|
|
532
|
+
Classify every finding by severity:
|
|
533
|
+
|
|
534
|
+
- **Invariant** - fail unless a real constraint is documented.
|
|
535
|
+
- **Default** - follow unless the alternative has clearer ownership or API value.
|
|
536
|
+
- **Heuristic** - investigate, but never fail on the numerical signal alone; the finding must name a concrete cost.
|
|
537
|
+
- **Style** - apply by default per [expressive-mvc/style.md](../expressive-mvc/style.md); report separately from architectural correctness.
|
|
538
|
+
|
|
539
|
+
The checklist:
|
|
540
|
+
|
|
541
|
+
- Is each state field owned at the narrowest useful scope? *(invariant)*
|
|
542
|
+
- Does state about a collection entry live on the entry's class - no id-keyed records, no `(id, value)` methods, no reassign-to-update-one-entry? *(invariant)*
|
|
543
|
+
- Is every `has((x) => new Foo({...}))` factory doing work `has(Foo)` wouldn't - transform, rename, multi-argument? *(default)*
|
|
544
|
+
- Are opaque handles (unsubscribe fns, timers, snapshots) unmanaged rather than reactive fields? *(invariant)*
|
|
545
|
+
- Does every subscription consume what it declares - no `void x` reads to force tracking in a render? *(invariant)*
|
|
546
|
+
- Does each class name one concern or a declared barrel (page orchestrator, pool owner, mounting shell) - unrelated clusters split into region controls, each rendered feature unplugging by one import? *(default)*
|
|
547
|
+
- Does every Component earn its instance (owned fields, pool, boundary - not a ref plus a DOM-sync reaction) - pass-throughs demoted to FCs, stateless shells mounted not held? *(default)*
|
|
548
|
+
- Is the app entry an FC (house style), with last-resort `catch`/`fallback` on the top Component it mounts - no class holding only `fallback` around the tree? *(default)*
|
|
549
|
+
- Is every `new Component()` on a parent a pool member or hot-swap - painting features mounted as JSX, region controls held as fields? *(invariant)*
|
|
550
|
+
- Does every Component without chrome omit `render()` - no `return this.props.children`? *(default)*
|
|
551
|
+
- Is working identity (session, selection) a separate field from URL params, soft-synced by a reaction? *(default)*
|
|
552
|
+
- Does every method do more than assign one field? *(invariant)*
|
|
553
|
+
- Are contextual values still being drilled through props - including slot FCs and section chrome fed values the parent unpacked from `this`? *(invariant)*
|
|
554
|
+
- Does every `.get()` and `render()` show the exact nested dependency surface? *(invariant)*
|
|
555
|
+
- Are any reactive deep reads hidden in conditional branches or handlers? *(invariant)*
|
|
556
|
+
- Does a Component holding `foo = get(Foo)` read it thru `this` - never a second `Foo.get()` in `render()`? *(invariant)*
|
|
557
|
+
- Is `is` used only where the root object must be retained alongside sibling destructuring? *(invariant)*
|
|
558
|
+
- Is presence a contract - a standalone widget owns its gate and falls thru by default; a split of `render()` is gated at the call site and always paints; parent gate over a Model field the child reads with `.get()` where the parent reads the field for its own content; no Model values as props; never `get()` plus an internal null-guard? *(invariant)*
|
|
559
|
+
- Are Component subcomponents genuine extension points? *(invariant)*
|
|
560
|
+
- Does every getter on shared state earn its place - multiple consumers, domain meaning, expensive computation, deliberate API, or introspection value? *(default - judge meaning, not reference counts)*
|
|
561
|
+
- Are large JSX branches and ~50-line renders split at conditionals into honestly-named scopes - units that delete or move as one place, never one-op conditionals or formatted scalars? *(heuristic - name the cost)*
|
|
562
|
+
- Are nested destructures placed after direct properties, with `is` first when retained? *(style)*
|
|
563
|
+
- Are modules near ~400 lines split at feature seams, without peeling thin wrappers? *(style)*
|
|
564
|
+
|
|
565
|
+
Auditing notes:
|
|
566
|
+
|
|
567
|
+
- Compare ownership, dependency surfaces, and write behavior - never filenames, file counts, or similarity to a reference implementation. File size and consolidation follow [expressive-mvc/style.md](../expressive-mvc/style.md) layout unless the project overrides - style lane, scored separately.
|
|
568
|
+
- Report two verdicts - architectural conformance and style adherence - so a formatting miss cannot obscure correct structure, or vice versa.
|
|
569
|
+
- Deliver the filled checklist with the change (PR description or ledger), not only a verdict.
|