@tinkered/react 0.0.0-stage → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +314 -2
- package/dist/index.d.mts +202 -0
- package/dist/index.mjs +580 -0
- package/package.json +63 -4
- package/skills/react/SKILL.md +199 -0
package/README.md
CHANGED
|
@@ -1,3 +1,315 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tinkered/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React is a host adapter: it connects an app's Core graph to mounted views.
|
|
4
|
+
The app declares the graph; this package binds reads, actions, and view lifetime.
|
|
5
|
+
See the [package roles](../../docs/best-practices.md#give-the-package-a-job).
|
|
6
|
+
|
|
7
|
+
A thin React binding for [`@tinkered/core`](../core). It is **not a store** — core already owns
|
|
8
|
+
state, reactivity, lifetime, and observability. This package only _subscribes_ and _provides_: it
|
|
9
|
+
adds no store, no cache, no reducer, no query-key ([ADR 0030](../../docs/decisions/0030-react-is-a-thin-adapter-not-a-store.md)).
|
|
10
|
+
|
|
11
|
+
- **Reactive reads** → `useSyncExternalStore` over a cell's `watch`/`get`.
|
|
12
|
+
- **Scope provision** → the core `Handle` rides on React Context; the nearest one wins.
|
|
13
|
+
- **Async** → resources suspend (`use()` + `<Suspense>`); operations are imperative (a mutation).
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
On Bun, the main runtime:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
R=https://github.com/lagz0ne/tinkered/\
|
|
21
|
+
releases/download/v0.18.0
|
|
22
|
+
bun add $R/tinker-core-0.18.0.tgz \
|
|
23
|
+
$R/tinker-react-0.18.0.tgz
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
On Node 22.18 or later, with npm:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
R=https://github.com/lagz0ne/tinkered/\
|
|
30
|
+
releases/download/v0.18.0
|
|
31
|
+
npm install $R/tinker-core-0.18.0.tgz \
|
|
32
|
+
$R/tinker-react-0.18.0.tgz
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Each version's URLs are in the
|
|
36
|
+
[changelog](../../CHANGELOG.md).
|
|
37
|
+
|
|
38
|
+
## 60-second example
|
|
39
|
+
|
|
40
|
+
`examples/react/basic.tsx` is a cast-free example. The shape:
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
const count = data({ label: "count", initial: 0 });
|
|
44
|
+
const profile = resource({
|
|
45
|
+
label: "profile",
|
|
46
|
+
factory: () => Promise.resolve({ name: "Ada" }),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
function Counter() {
|
|
50
|
+
const value = useData(count);
|
|
51
|
+
const control = useController(count);
|
|
52
|
+
const increment = () => control.update((n) => n + 1);
|
|
53
|
+
return <button onClick={increment}>count {value}</button>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function ProfileCard() {
|
|
57
|
+
return <p>{useResource(profile).name}</p>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function App() {
|
|
61
|
+
return (
|
|
62
|
+
<ScopeProvider create={createScope}>
|
|
63
|
+
<Counter />
|
|
64
|
+
<Suspense fallback={<p>loading…</p>}>
|
|
65
|
+
<ProfileCard />
|
|
66
|
+
</Suspense>
|
|
67
|
+
</ScopeProvider>
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## The seam
|
|
73
|
+
|
|
74
|
+
- `ScopeProvider` supplies an app-owned scope with `scope={handle}`.
|
|
75
|
+
Its `create` form owns the scope and closes it on unmount.
|
|
76
|
+
- A root given `capsules` is a starting handle (Core ADR 0128).
|
|
77
|
+
The provider waits for its `ready` with React's `use`.
|
|
78
|
+
A `<Suspense>` above shows its fallback until start ends.
|
|
79
|
+
A failed start reaches the nearest error boundary.
|
|
80
|
+
In `create` form it renders nothing until start ends.
|
|
81
|
+
- `SessionProvider` opens a child session for its subtree.
|
|
82
|
+
Unmount force-closes that session.
|
|
83
|
+
Writes stay in the session.
|
|
84
|
+
- `useScope` returns the nearest Core handle.
|
|
85
|
+
Without a provider, it raises `NoProvider`.
|
|
86
|
+
- `useData(cell)` reads a cell and follows its changes.
|
|
87
|
+
A selector reads part of its value.
|
|
88
|
+
- `useData(cell, { writable: true })` returns the value and a setter.
|
|
89
|
+
- `useController` supplies writes without subscribing the component.
|
|
90
|
+
- `useResource` reads a built resource.
|
|
91
|
+
Async builds suspend; failures reach the error boundary.
|
|
92
|
+
- `useResource(handle, { suspense: false })` returns local query state.
|
|
93
|
+
It includes `status`, `data`, `error`, and `refetch`.
|
|
94
|
+
- `useRun` runs an operation and reports the latest result.
|
|
95
|
+
It supplies `run`, `runAsync`, `reset`, and result callbacks.
|
|
96
|
+
- `useRelease` resets a cell or releases a resource.
|
|
97
|
+
- `useSpans` reads the scope's span history when observation is on.
|
|
98
|
+
- `isError` checks errors from this package.
|
|
99
|
+
|
|
100
|
+
## Project keys and reset
|
|
101
|
+
|
|
102
|
+
Declare a namespace once and reuse its identity.
|
|
103
|
+
Use an explicit key when the scope belongs to the app:
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
const project42 = namespace();
|
|
107
|
+
const draft = data({ label: "draft", initial: "" });
|
|
108
|
+
const profile = resource({
|
|
109
|
+
label: "profile",
|
|
110
|
+
target: "namespace",
|
|
111
|
+
factory: () => ({ name: "Ada" }),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
function ProjectTools() {
|
|
115
|
+
const reset = useRelease(project42);
|
|
116
|
+
const resetField = () => reset(draft);
|
|
117
|
+
const query = useResource(profile, {
|
|
118
|
+
ns: project42,
|
|
119
|
+
suspense: false,
|
|
120
|
+
});
|
|
121
|
+
return (
|
|
122
|
+
<>
|
|
123
|
+
<button onClick={resetField}>Reset field</button>
|
|
124
|
+
<button onClick={query.refetch}>Refresh</button>
|
|
125
|
+
</>
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`useResource` accepts `ns` with either suspense mode.
|
|
131
|
+
The key selects both the read and its refetch.
|
|
132
|
+
Changing that option selects the new key on the next render.
|
|
133
|
+
`useRelease(key)` selects only the reset key.
|
|
134
|
+
An explicit key wins over an inherited session key.
|
|
135
|
+
|
|
136
|
+
Inside `SessionProvider`, omitted hook keys use its saved namespace head.
|
|
137
|
+
A child session inherits that key unless its own `options.ns` replaces it.
|
|
138
|
+
Reads still follow Core's full namespace chain.
|
|
139
|
+
Reset clears only the chain's first key.
|
|
140
|
+
A read may then expose a fallback value or reuse a fallback resource.
|
|
141
|
+
Refetch never clears fallback keys to force a new build.
|
|
142
|
+
|
|
143
|
+
A scope resource is shared across keys.
|
|
144
|
+
Reset and refetch still use Core's broad release for that resource.
|
|
145
|
+
With no known key, the hooks keep their existing broad release behavior.
|
|
146
|
+
Core handles do not expose their ambient namespace.
|
|
147
|
+
React cannot infer a key from an app-owned scope alone.
|
|
148
|
+
Use explicit hook keys or `SessionProvider` options in that case.
|
|
149
|
+
An independent `ScopeProvider` clears any outer React namespace key.
|
|
150
|
+
|
|
151
|
+
## Form and route lifetimes
|
|
152
|
+
|
|
153
|
+
A namespace is a reusable key.
|
|
154
|
+
Its session owns the temporary state and resources.
|
|
155
|
+
Use nested sessions for a route and its form:
|
|
156
|
+
|
|
157
|
+
```tsx
|
|
158
|
+
<ScopeProvider create={createScope}>
|
|
159
|
+
<SessionProvider key="42" options={{ ns: project42 }}>
|
|
160
|
+
<SessionProvider key="form:1">
|
|
161
|
+
<ProjectTools />
|
|
162
|
+
</SessionProvider>
|
|
163
|
+
</SessionProvider>
|
|
164
|
+
</ScopeProvider>
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Inside the form, `useRelease()` resets one field in its session.
|
|
168
|
+
Other fields and the form's session stay live.
|
|
169
|
+
Change the form key to discard all of that form's local state.
|
|
170
|
+
Unmount the route to close its form and route sessions.
|
|
171
|
+
Both actions stop owned work and clean session resources.
|
|
172
|
+
Returning with the same namespace key starts fresh session state.
|
|
173
|
+
Namespace resources remain owned by the root and can be reused.
|
|
174
|
+
|
|
175
|
+
Session options apply when the session is created.
|
|
176
|
+
Changing them for the same parent does not change a live session's reset key.
|
|
177
|
+
Remount the provider to apply new options.
|
|
178
|
+
Reset callbacks and cell controllers stay stable on ordinary renders.
|
|
179
|
+
An explicit resource controller is reused while scope, resource, and key stay the same.
|
|
180
|
+
|
|
181
|
+
## Testing
|
|
182
|
+
|
|
183
|
+
Behavior tests only, at the `src/index.ts` seam, in **vitest browser mode** (real chromium via
|
|
184
|
+
Playwright — [ADR 0033](../../docs/decisions/0033-react-tests-run-in-vitest-browser-mode.md)); no
|
|
185
|
+
mocks, no sleeps. Presets flow through `createScope({ presets })` in a `create`-mode provider — no
|
|
186
|
+
test-only API.
|
|
187
|
+
|
|
188
|
+
Tests import `@tinkered/core` from its **built** `dist`, so build core first. From the workspace root:
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
vp run core#build
|
|
192
|
+
vp run -r test
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Promises
|
|
196
|
+
|
|
197
|
+
This appendix states each behaviour the seam tests pin, one line per promise, grouped by hook.
|
|
198
|
+
`node tools/jev/promises.mjs react` is its check: every seam-test title names a line below.
|
|
199
|
+
|
|
200
|
+
### ScopeProvider
|
|
201
|
+
|
|
202
|
+
- The subtree uses the exact app-owned scope, which the provider never closes.
|
|
203
|
+
- Under StrictMode, create mode leaks no scope and never exposes a closed one.
|
|
204
|
+
|
|
205
|
+
### useScope
|
|
206
|
+
|
|
207
|
+
- A hook used with no provider raises NoProvider.
|
|
208
|
+
|
|
209
|
+
### useData
|
|
210
|
+
|
|
211
|
+
- A controller write re-renders a separate reader.
|
|
212
|
+
- A selector with an options object applies its isEqual.
|
|
213
|
+
- An isEqual of always-true never re-renders on cell updates.
|
|
214
|
+
- useData with only isEqual reads the raw value.
|
|
215
|
+
- The view re-renders only when the selected slice changes.
|
|
216
|
+
- A kept slice survives a raw change and two parent re-renders.
|
|
217
|
+
- A stable object selector without isEqual keeps its result identity across a parent re-render.
|
|
218
|
+
- A new inline selector after a parent re-render shows its output and still follows the cell.
|
|
219
|
+
- A swapped-in isEqual applies from the next render.
|
|
220
|
+
- A custom isEqual suppresses re-render for a new slice it treats as equal.
|
|
221
|
+
- The writable setter keeps its identity across a cell update.
|
|
222
|
+
- Reading through a new scope shows the new scope's value.
|
|
223
|
+
- Reads a cell and re-renders when it is set externally.
|
|
224
|
+
- An unchanged object value keeps its identity across a parent re-render.
|
|
225
|
+
- A write after unmount neither updates the removed subtree nor breaks the still-open scope.
|
|
226
|
+
|
|
227
|
+
### useResource
|
|
228
|
+
|
|
229
|
+
- A parent render keeps the local query handle when its state did not change.
|
|
230
|
+
|
|
231
|
+
- A rejected build is not rebuilt on the Suspense retry: the original error shows, one build.
|
|
232
|
+
- A re-render while pending reuses one build: the factory runs once and Suspense still resolves.
|
|
233
|
+
- resolve() hands back one stable promise per owner, while pending and after settle.
|
|
234
|
+
- A query reports its status through one flag at a time.
|
|
235
|
+
- An async query with no value leaves pending when it succeeds.
|
|
236
|
+
- suspense:false renders pending then success without a Suspense boundary.
|
|
237
|
+
- A synchronous build reports success at once with suspense:false.
|
|
238
|
+
- With suspense:false, a synchronous failure stays local and refetch can rebuild it.
|
|
239
|
+
- Reading through a new scope builds in the new scope.
|
|
240
|
+
- A synchronous build commits on the first flushed render with no suspend.
|
|
241
|
+
- The hook returns the exact instance core cached for the owner.
|
|
242
|
+
|
|
243
|
+
### Capsule components
|
|
244
|
+
|
|
245
|
+
- A component a capsule exports renders from the handle, bound to the capsule's own cells.
|
|
246
|
+
- The exported component keeps each session's data apart.
|
|
247
|
+
- The exported component raises CapsuleMissing through the exported cell it reads.
|
|
248
|
+
|
|
249
|
+
### useRun
|
|
250
|
+
|
|
251
|
+
- A parent render keeps the run handle when no run changed.
|
|
252
|
+
- StrictMode clears the run from its discarded effect mount.
|
|
253
|
+
- A cancelled run rejects with the caller's exact reason.
|
|
254
|
+
|
|
255
|
+
- Normal calls and omitted callbacks report no host error.
|
|
256
|
+
- runAsync keeps the operation value when onSuccess throws.
|
|
257
|
+
- run reports an onSuccess error through the global error event.
|
|
258
|
+
- Callback errors are reported and still allow onSettled to run.
|
|
259
|
+
runAsync keeps the operation value or failure.
|
|
260
|
+
|
|
261
|
+
- A failing operation stays in error state and does not throw to an error boundary.
|
|
262
|
+
- A handled operation panic stays in error state and the root closes successfully.
|
|
263
|
+
- Switching providers clears the previous run state.
|
|
264
|
+
- Switching providers drops late results and callbacks; the caller still gets its value.
|
|
265
|
+
- Switching operations drops late results and callbacks from the old operation.
|
|
266
|
+
- Reset from a success clears status, data, and error.
|
|
267
|
+
- Reset from an error clears status, data, and error.
|
|
268
|
+
- A run from before reset never overwrites a newer run that settled after it.
|
|
269
|
+
- Reset during operation startup keeps idle when the old run finishes.
|
|
270
|
+
- Reset during a pending run drops the late result: state stays idle.
|
|
271
|
+
- Switching the operation runs the new one, not the stale one.
|
|
272
|
+
- Switching the operation rebinds runAsync to the new one.
|
|
273
|
+
- A synchronous operation renders and commits success once without pending.
|
|
274
|
+
- runAsync returns the value or rejects with the failure while state tracks both.
|
|
275
|
+
- Only the latest run publishes: a stale earlier run that settles later is dropped.
|
|
276
|
+
- A run with only onSettled reports success without onSuccess.
|
|
277
|
+
- A run with only onSettled reports failure without onError.
|
|
278
|
+
- A run with empty options resolves runAsync without callbacks.
|
|
279
|
+
- onError and onSettled fire with the failure and the call.
|
|
280
|
+
|
|
281
|
+
### SessionProvider
|
|
282
|
+
|
|
283
|
+
- A data write under a session stays local and does not reach the parent scope.
|
|
284
|
+
- Switching the parent scope never exposes the old session, even if the old parent is closed.
|
|
285
|
+
- A session-target resource is one instance per SessionProvider; siblings are distinct.
|
|
286
|
+
- A scope-target resource is the same instance across sibling sessions.
|
|
287
|
+
|
|
288
|
+
### Namespace reset
|
|
289
|
+
|
|
290
|
+
- A session refetch keeps sibling and default namespace resources.
|
|
291
|
+
- An explicit field reset keeps sibling and default values at the same owner.
|
|
292
|
+
- Explicit resource reads and refetch follow the current key on an app-owned scope.
|
|
293
|
+
- A nested session inherits its parent's reset key.
|
|
294
|
+
- An inner session's explicit key replaces its parent's reset key.
|
|
295
|
+
- An explicit reset key overrides the React session's key.
|
|
296
|
+
- Changing session options without remounting keeps the live reset key.
|
|
297
|
+
- A chain refetch clears its head and reuses its fallback.
|
|
298
|
+
- A named session can still refetch a shared scope resource.
|
|
299
|
+
- An explicit reset key still releases a shared scope resource.
|
|
300
|
+
- An independent borrowed scope clears an outer session's reset key.
|
|
301
|
+
- An independent owned scope clears an outer session's reset key.
|
|
302
|
+
- A field reset keeps the form owner, other fields, and hook identities.
|
|
303
|
+
- A keyed form reset cancels its work and keeps the route alive.
|
|
304
|
+
- Leaving a route cleans its form and returning reuses the project key.
|
|
305
|
+
|
|
306
|
+
### isError
|
|
307
|
+
|
|
308
|
+
- isError matches a NoProvider error from this package.
|
|
309
|
+
- isError rejects a plain error without the asked kind.
|
|
310
|
+
- isError rejects values that are not errors.
|
|
311
|
+
|
|
312
|
+
## Decisions & vocabulary
|
|
313
|
+
|
|
314
|
+
[ADR 0030–0033, 0125](../../docs/decisions/) and the React section of the
|
|
315
|
+
[glossary](../../docs/glossary.md).
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { Data, Namespace, Observe, Operation, Resource, Scope } from "@tinkered/core";
|
|
2
|
+
import { ReactNode } from "react";
|
|
3
|
+
//#region src/errors.d.ts
|
|
4
|
+
/** Payload type for each adapter error. The registry is the only place this package throws. */
|
|
5
|
+
type Payloads = {
|
|
6
|
+
NoProvider: {
|
|
7
|
+
hook: string;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
declare namespace Errors {
|
|
11
|
+
type Name = keyof Payloads;
|
|
12
|
+
type Payload<N extends Name> = Payloads[N];
|
|
13
|
+
type Of<N extends Name = Name> = Error & {
|
|
14
|
+
readonly kind: N;
|
|
15
|
+
readonly payload: Payloads[N];
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Narrow an unknown error to one registry entry; callers rethrow on mismatch. */
|
|
19
|
+
export declare function isError<N extends Errors.Name>(value: unknown, kind: N): value is Errors.Of<N>;
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/index.d.ts
|
|
22
|
+
/** Props for {@link ScopeProvider}: either an app-owned `scope` (the app closes it), or a `create`
|
|
23
|
+
* factory the provider owns and closes on unmount. Exactly one. */
|
|
24
|
+
export type ScopeProviderProps = {
|
|
25
|
+
readonly scope: Scope.Handle | Scope.Starting;
|
|
26
|
+
readonly create?: never;
|
|
27
|
+
readonly children: ReactNode;
|
|
28
|
+
} | {
|
|
29
|
+
readonly create: () => Scope.Handle | Scope.Starting;
|
|
30
|
+
readonly scope?: never;
|
|
31
|
+
readonly children: ReactNode;
|
|
32
|
+
};
|
|
33
|
+
/** Put a `@tinkered/core` scope on React context for the subtree. Hooks resolve against the nearest
|
|
34
|
+
* provider's scope. This independent scope clears an outer React session's reset key. */
|
|
35
|
+
export declare function ScopeProvider(props: ScopeProviderProps): ReactNode;
|
|
36
|
+
/** Open a child session for a subtree: created on mount from the nearest scope, force-closed on
|
|
37
|
+
* unmount — a React subtree's mount lifetime IS a session lifetime (ADR 0031). Hooks under it resolve
|
|
38
|
+
* against the session (the nearest `Handle`), so a `data` write is shadowed and does not reach the
|
|
39
|
+
* parent. Created in an effect (StrictMode-safe, like {@link ScopeProvider}'s `create` mode): a
|
|
40
|
+
* discarded or replayed mount closes its own session and the next live mount opens a fresh one. The
|
|
41
|
+
* session is published paired with the parent it belongs to; if the nearest scope changes, the old
|
|
42
|
+
* session is never exposed for the new parent (render null until the effect opens a fresh one).
|
|
43
|
+
* The reset namespace head is saved with this session, including an inherited key.
|
|
44
|
+
* `options` apply when the session is created — changing them for the same parent has no effect until
|
|
45
|
+
* the provider remounts. */
|
|
46
|
+
export declare function SessionProvider(props: {
|
|
47
|
+
readonly children: ReactNode;
|
|
48
|
+
readonly options?: Scope.Options;
|
|
49
|
+
}): ReactNode;
|
|
50
|
+
/** Read the nearest scope `Handle`. Raises `NoProvider` when used outside a {@link ScopeProvider}. */
|
|
51
|
+
export declare function useScope(): Scope.Handle;
|
|
52
|
+
export declare namespace UseData {
|
|
53
|
+
/** Options for {@link useData}: `writable` returns `[value, set]` (a `useState`-like pair) instead
|
|
54
|
+
* of the bare value; `isEqual` compares selected slices (default `Object.is`). */
|
|
55
|
+
type Options<S> = {
|
|
56
|
+
readonly isEqual?: (a: S, b: S) => boolean;
|
|
57
|
+
readonly writable?: boolean;
|
|
58
|
+
};
|
|
59
|
+
/** The pair `useData(cell, { writable: true })` returns: the (selected) value and the cell's `set`. */
|
|
60
|
+
type Pair<T, S> = readonly [value: S, set: (value: T) => void];
|
|
61
|
+
}
|
|
62
|
+
/** Reactively read a `data` cell: returns its current value and re-renders when it changes. */
|
|
63
|
+
export declare function useData<T>(cell: Data.Cell<T>): T;
|
|
64
|
+
/** Reactively read a capsule's cell export (`talk.point`, ADR 0123). Read-only: no writable pair. */
|
|
65
|
+
export declare function useData<T>(view: Data.View<T>): T;
|
|
66
|
+
/** Reactively read one member or one part of a keyed cell, with the key given at each render:
|
|
67
|
+
* `useData(tasks.where({ project }))` (ADR 0136). It re-renders only when that part changes; a
|
|
68
|
+
* new key leaves the old part. Read-only: write through an op. */
|
|
69
|
+
export declare function useData<T>(read: Data.Read<T>): T;
|
|
70
|
+
/** Reactively read a slice of a capsule's cell export. */
|
|
71
|
+
export declare function useData<T, S>(view: Data.View<T>, selector: (value: T) => S, isEqual?: (a: S, b: S) => boolean): S;
|
|
72
|
+
/** Reactively read a slice of a `data` cell: returns `selector(value)` and re-renders only when the
|
|
73
|
+
* slice changes (`isEqual`, default `Object.is`). Lets a component subscribe to part of a cell. */
|
|
74
|
+
export declare function useData<T, S>(cell: Data.Cell<T>, selector: (value: T) => S, isEqual?: (a: S, b: S) => boolean): S;
|
|
75
|
+
export declare function useData<T>(cell: Data.Cell<T>, options: UseData.Options<T> & {
|
|
76
|
+
readonly writable: true;
|
|
77
|
+
}): UseData.Pair<T, T>;
|
|
78
|
+
/** Read a slice and write the whole cell: `[selector(value), set]`. */
|
|
79
|
+
export declare function useData<T, S>(cell: Data.Cell<T>, selector: (value: T) => S, options: UseData.Options<S> & {
|
|
80
|
+
readonly writable: true;
|
|
81
|
+
}): UseData.Pair<T, S>;
|
|
82
|
+
/** The nearest scope's read/write controller for a `data` cell (`get`/`set`/`update`/`watch`).
|
|
83
|
+
* For writes: a component that only holds a controller subscribes to nothing, so a write-only view
|
|
84
|
+
* never re-renders when the cell changes. Read reactively with {@link useData} instead. */
|
|
85
|
+
export declare function useController<T>(cell: Data.Cell<T>): Scope.DataController<T>;
|
|
86
|
+
export declare namespace Query {
|
|
87
|
+
/** `suspense: false` renders local query state. `ns` selects the same named bucket for reads
|
|
88
|
+
* and refetch. Without it, the scope's ambient namespace supplies reads and a React session
|
|
89
|
+
* supplies the reset key when known. */
|
|
90
|
+
type Options = {
|
|
91
|
+
readonly suspense?: boolean;
|
|
92
|
+
readonly ns?: Namespace;
|
|
93
|
+
};
|
|
94
|
+
/** The build state of a resource read with `{ suspense: false }`: a synchronous build is `success`
|
|
95
|
+
* at once; an async build is `pending` until it settles; a failed build stays `error` until
|
|
96
|
+
* `refetch` clears the selected bucket. The next read can build a fresh generation or reuse
|
|
97
|
+
* a fallback that remains in the namespace chain. */
|
|
98
|
+
type State<T> = {
|
|
99
|
+
readonly status: "pending";
|
|
100
|
+
readonly data: undefined;
|
|
101
|
+
readonly error: undefined;
|
|
102
|
+
} | {
|
|
103
|
+
readonly status: "success";
|
|
104
|
+
readonly data: T;
|
|
105
|
+
readonly error: undefined;
|
|
106
|
+
} | {
|
|
107
|
+
readonly status: "error";
|
|
108
|
+
readonly data: undefined;
|
|
109
|
+
readonly error: unknown;
|
|
110
|
+
};
|
|
111
|
+
type Handle<T> = State<T> & {
|
|
112
|
+
readonly isPending: boolean;
|
|
113
|
+
readonly isSuccess: boolean;
|
|
114
|
+
readonly isError: boolean;
|
|
115
|
+
readonly refetch: () => void;
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Read a resource's built value from the nearest scope. A synchronously-built resource returns its
|
|
119
|
+
* value directly (no promise). An async build suspends: the promise is handed to React's `use`, so a
|
|
120
|
+
* `<Suspense>` fallback shows while pending and the value renders once it settles. Core builds once
|
|
121
|
+
* per owner and returns the same promise on every resolve (including a rejected build, which stays
|
|
122
|
+
* until release), so a Suspense retry reuses that promise rather than rebuilding (ADR 0032).
|
|
123
|
+
* With `{ suspense: false }` nothing suspends or throws: the hook returns a react-query-like
|
|
124
|
+
* `{ status, data, error, isPending, isSuccess, isError, refetch }` for a local loading state.
|
|
125
|
+
* An explicit `ns` selects both reads and refetch; otherwise refetch uses the React session's
|
|
126
|
+
* saved head when known. Clearing a head leaves fallback buckets intact, so the next read may
|
|
127
|
+
* reuse a fallback. Shared scope resources retain their broad release (see {@link useRelease}). */
|
|
128
|
+
export declare function useResource<T>(handle: Resource.Handle<T>, options?: {
|
|
129
|
+
suspense?: true;
|
|
130
|
+
ns?: Namespace;
|
|
131
|
+
}): Awaited<T>;
|
|
132
|
+
export declare function useResource<T>(handle: Resource.Handle<T>, options: {
|
|
133
|
+
suspense: false;
|
|
134
|
+
ns?: Namespace;
|
|
135
|
+
}): Query.Handle<Awaited<T>>;
|
|
136
|
+
export declare namespace Run {
|
|
137
|
+
/** The call a run was made with: the first argument of {@link useRun}'s `run`. */
|
|
138
|
+
type Variables<I> = Scope.CallArgs<I>[0];
|
|
139
|
+
/** The settled state of the latest {@link useRun} run, shaped like a react-query mutation:
|
|
140
|
+
* `status` plus `data`/`error`/`variables` and one boolean per status. */
|
|
141
|
+
type State<T, I> = {
|
|
142
|
+
readonly status: "idle";
|
|
143
|
+
readonly data: undefined;
|
|
144
|
+
readonly error: undefined;
|
|
145
|
+
readonly variables: undefined;
|
|
146
|
+
} | {
|
|
147
|
+
readonly status: "pending";
|
|
148
|
+
readonly data: undefined;
|
|
149
|
+
readonly error: undefined;
|
|
150
|
+
readonly variables: Variables<I>;
|
|
151
|
+
} | {
|
|
152
|
+
readonly status: "success";
|
|
153
|
+
readonly data: T;
|
|
154
|
+
readonly error: undefined;
|
|
155
|
+
readonly variables: Variables<I>;
|
|
156
|
+
} | {
|
|
157
|
+
readonly status: "error";
|
|
158
|
+
readonly data: undefined;
|
|
159
|
+
readonly error: unknown;
|
|
160
|
+
readonly variables: Variables<I>;
|
|
161
|
+
};
|
|
162
|
+
/** Hook-level callbacks, fired for every run when it settles (success, failure, then either way). */
|
|
163
|
+
type Options<T, I> = {
|
|
164
|
+
readonly onSuccess?: (data: T, variables: Variables<I>) => void;
|
|
165
|
+
readonly onError?: (error: unknown, variables: Variables<I>) => void;
|
|
166
|
+
readonly onSettled?: (data: T | undefined, error: unknown, variables: Variables<I>) => void;
|
|
167
|
+
};
|
|
168
|
+
/** What {@link useRun} returns: the current {@link State}, one boolean per status, and the
|
|
169
|
+
* imperative `run` (fire-and-forget: the outcome lands in state), `runAsync` (returns the
|
|
170
|
+
* value, rejects with the failure — for callers that need the result in a handler) and `reset`. */
|
|
171
|
+
type Handle<T, I> = State<T, I> & {
|
|
172
|
+
readonly isIdle: boolean;
|
|
173
|
+
readonly isPending: boolean;
|
|
174
|
+
readonly isSuccess: boolean;
|
|
175
|
+
readonly isError: boolean;
|
|
176
|
+
readonly run: (...call: Scope.CallArgs<I>) => void;
|
|
177
|
+
readonly runAsync: (...call: Scope.CallArgs<I>) => Promise<T>;
|
|
178
|
+
readonly reset: () => void;
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/** Run an operation imperatively (a mutation): never suspends. Shaped like react-query's
|
|
182
|
+
* `useMutation`: `run(input)` fires and forgets (the outcome lands in `status`/`data`/`error`
|
|
183
|
+
* with `variables` = the call), `runAsync(input)` also returns the value or rejects, `reset()`
|
|
184
|
+
* returns to idle. A rejection never reaches an error boundary (that is {@link useResource}'s job).
|
|
185
|
+
* Only the latest run publishes state: a slower earlier run that settles after a newer one (or after
|
|
186
|
+
* `reset`) is dropped, though its `options` callbacks still fire. Changing the provider or operation
|
|
187
|
+
* clears the view and stops the old owner's state and callback writes; its caller still gets the result.
|
|
188
|
+
* Handled failures are received through Core's `settle`, so a panic does not fail the owner. */
|
|
189
|
+
export declare function useRun<T, I>(op: Operation.Handle<T, I>, options?: Run.Options<Awaited<T>, I>): Run.Handle<Awaited<T>, I>;
|
|
190
|
+
/** Reset a node in an explicit namespace, or the nearest React session's saved namespace head.
|
|
191
|
+
* Clearing a head can expose a fallback; fallback keys remain intact. Scope-target resources and
|
|
192
|
+
* calls with no known key retain Core's broad release. Opaque app-owned scope namespaces need an
|
|
193
|
+
* explicit key, since a Core handle does not expose its ambient namespace. */
|
|
194
|
+
export declare function useRelease(ns?: Namespace): (node: Data.Cell<unknown> | Resource.Handle<unknown>) => void;
|
|
195
|
+
/** Read the nearest scope's bounded span history (ADR 0030) for an inspector/devtools view — a
|
|
196
|
+
* snapshot taken on each render (an empty snapshot when observation is off). Core exposes no span
|
|
197
|
+
* subscription, so this is not push-reactive: a standalone inspector will not update on its own when
|
|
198
|
+
* sibling components do work — the caller arranges its re-renders (co-render with the work, or a
|
|
199
|
+
* manual refresh). */
|
|
200
|
+
export declare function useSpans(): readonly Observe.Span[];
|
|
201
|
+
//#endregion
|
|
202
|
+
export type { Errors };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import { isStarting } from "@tinkered/core";
|
|
2
|
+
import { createContext, createElement, use, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
3
|
+
//#region src/errors.ts
|
|
4
|
+
/** Throw a registry error. The only throw site in the package. */
|
|
5
|
+
function raise(kind, payload) {
|
|
6
|
+
const error = new Error(kind);
|
|
7
|
+
Object.assign(error, {
|
|
8
|
+
kind,
|
|
9
|
+
payload
|
|
10
|
+
});
|
|
11
|
+
throw error;
|
|
12
|
+
}
|
|
13
|
+
/** Narrow an unknown error to one registry entry; callers rethrow on mismatch. */
|
|
14
|
+
function isError(value, kind) {
|
|
15
|
+
return value instanceof Error && value.kind === kind;
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/index.ts
|
|
19
|
+
/** No DOM means a server render: one pass, no commit, no effects, no subscription. Like React's
|
|
20
|
+
* `useSyncExternalStore` server snapshot, a hook there reads once and keeps nothing. Hydration
|
|
21
|
+
* does not compare hook lists, so the server may call fewer hooks than the client. Trap: any
|
|
22
|
+
* renderer with no DOM that does commit takes this path too, and its views do not re-render on a
|
|
23
|
+
* change: React Native, a Web Worker renderer, Ink, react-test-renderer. */
|
|
24
|
+
const IS_SERVER = typeof document === "undefined";
|
|
25
|
+
const ScopeContext = createContext(void 0);
|
|
26
|
+
/** An independent scope clears an outer React session's reset key. */
|
|
27
|
+
const bind = (scope) => ({
|
|
28
|
+
scope,
|
|
29
|
+
ns: void 0
|
|
30
|
+
});
|
|
31
|
+
/** Start a scope's teardown without awaiting; a scope owns its own shutdown and never throws
|
|
32
|
+
* (ADR 0027), so the unmounting subtree does not wait on the result. */
|
|
33
|
+
function closeScope(scope) {
|
|
34
|
+
scope.close();
|
|
35
|
+
}
|
|
36
|
+
/** The stable no-selector fallback for {@link useData}: a module constant so the selector handed to
|
|
37
|
+
* the store keeps a stable identity across renders (a fresh closure would defeat its memoization). */
|
|
38
|
+
const identity = (value) => value;
|
|
39
|
+
/** A starting root (ADR 0128): wait for its `ready` with React's `use`, so a `<Suspense>` above
|
|
40
|
+
* shows its fallback, then provide the started handle. A failed start throws to the nearest
|
|
41
|
+
* error boundary. */
|
|
42
|
+
function StartedScopeProvider(props) {
|
|
43
|
+
const scope = use(props.scope.ready);
|
|
44
|
+
const value = useMemo(() => bind(scope), [scope]);
|
|
45
|
+
return createElement(ScopeContext.Provider, {
|
|
46
|
+
value,
|
|
47
|
+
children: props.children
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const WAITING = { kind: "waiting" };
|
|
51
|
+
/** Own a created scope for a subtree: create it in an effect (never during render, so a discarded
|
|
52
|
+
* or StrictMode-replayed render leaks nothing), publish it to children only once it exists, and
|
|
53
|
+
* close exactly that scope on unmount. StrictMode's mount→unmount→mount makes a fresh scope for
|
|
54
|
+
* each live mount and never leaves a closed scope on context for a consumer to touch (ADR 0031).
|
|
55
|
+
* A starting root (ADR 0128) is published once `ready` gives its started handle: nothing renders
|
|
56
|
+
* until then, and a failed start throws to the nearest error boundary. It does not suspend: a
|
|
57
|
+
* Suspense boundary above would hide and show this provider, and StrictMode then replays its
|
|
58
|
+
* effect, which would close the scope its children just subscribed to. */
|
|
59
|
+
function OwnedScopeProvider(props) {
|
|
60
|
+
const createRef = useRef(props.create);
|
|
61
|
+
createRef.current = props.create;
|
|
62
|
+
const [owned, setOwned] = useState(WAITING);
|
|
63
|
+
useEffect(() => {
|
|
64
|
+
const made = createRef.current();
|
|
65
|
+
let mounted = true;
|
|
66
|
+
const settle = (next) => {
|
|
67
|
+
if (mounted) setOwned(next);
|
|
68
|
+
};
|
|
69
|
+
if (isStarting(made)) made.ready.then((scope) => settle({
|
|
70
|
+
kind: "started",
|
|
71
|
+
bound: bind(scope)
|
|
72
|
+
}), (error) => settle({
|
|
73
|
+
kind: "failed",
|
|
74
|
+
error
|
|
75
|
+
}));
|
|
76
|
+
else settle({
|
|
77
|
+
kind: "started",
|
|
78
|
+
bound: bind(made)
|
|
79
|
+
});
|
|
80
|
+
return () => {
|
|
81
|
+
mounted = false;
|
|
82
|
+
setOwned(WAITING);
|
|
83
|
+
closeScope(made);
|
|
84
|
+
};
|
|
85
|
+
}, []);
|
|
86
|
+
if (owned.kind === "failed") throw owned.error;
|
|
87
|
+
if (owned.kind === "waiting") return null;
|
|
88
|
+
return createElement(ScopeContext.Provider, {
|
|
89
|
+
value: owned.bound,
|
|
90
|
+
children: props.children
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/** Put a `@tinkered/core` scope on React context for the subtree. Hooks resolve against the nearest
|
|
94
|
+
* provider's scope. This independent scope clears an outer React session's reset key. */
|
|
95
|
+
function ScopeProvider(props) {
|
|
96
|
+
const scope = props.scope;
|
|
97
|
+
const started = scope === void 0 || isStarting(scope) ? void 0 : scope;
|
|
98
|
+
const value = useMemo(() => started === void 0 ? void 0 : bind(started), [started]);
|
|
99
|
+
if (scope === void 0) return createElement(OwnedScopeProvider, {
|
|
100
|
+
create: props.create,
|
|
101
|
+
children: props.children
|
|
102
|
+
});
|
|
103
|
+
if (isStarting(scope)) return createElement(StartedScopeProvider, {
|
|
104
|
+
scope,
|
|
105
|
+
children: props.children
|
|
106
|
+
});
|
|
107
|
+
return createElement(ScopeContext.Provider, {
|
|
108
|
+
value,
|
|
109
|
+
children: props.children
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** Open a child session for a subtree: created on mount from the nearest scope, force-closed on
|
|
113
|
+
* unmount — a React subtree's mount lifetime IS a session lifetime (ADR 0031). Hooks under it resolve
|
|
114
|
+
* against the session (the nearest `Handle`), so a `data` write is shadowed and does not reach the
|
|
115
|
+
* parent. Created in an effect (StrictMode-safe, like {@link ScopeProvider}'s `create` mode): a
|
|
116
|
+
* discarded or replayed mount closes its own session and the next live mount opens a fresh one. The
|
|
117
|
+
* session is published paired with the parent it belongs to; if the nearest scope changes, the old
|
|
118
|
+
* session is never exposed for the new parent (render null until the effect opens a fresh one).
|
|
119
|
+
* The reset namespace head is saved with this session, including an inherited key.
|
|
120
|
+
* `options` apply when the session is created — changing them for the same parent has no effect until
|
|
121
|
+
* the provider remounts. */
|
|
122
|
+
function SessionProvider(props) {
|
|
123
|
+
const above = useBound("useScope");
|
|
124
|
+
const parent = above.scope;
|
|
125
|
+
const inherited = above.ns;
|
|
126
|
+
const optionsRef = useRef(props.options);
|
|
127
|
+
optionsRef.current = props.options;
|
|
128
|
+
const [owned, setOwned] = useState(void 0);
|
|
129
|
+
useEffect(() => {
|
|
130
|
+
const options = optionsRef.current;
|
|
131
|
+
const session = parent.createSession(options);
|
|
132
|
+
const ns = options?.ns;
|
|
133
|
+
const [head] = ns === void 0 ? [inherited] : "tags" in ns ? [ns] : ns;
|
|
134
|
+
setOwned({
|
|
135
|
+
parent,
|
|
136
|
+
bound: {
|
|
137
|
+
scope: session,
|
|
138
|
+
ns: head
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return () => {
|
|
142
|
+
setOwned(void 0);
|
|
143
|
+
closeScope(session);
|
|
144
|
+
};
|
|
145
|
+
}, [parent, inherited]);
|
|
146
|
+
if (owned === void 0 || owned.parent !== parent) return null;
|
|
147
|
+
return createElement(ScopeContext.Provider, {
|
|
148
|
+
value: owned.bound,
|
|
149
|
+
children: props.children
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** Read the nearest scope `Handle`. Raises `NoProvider` when used outside a {@link ScopeProvider}. */
|
|
153
|
+
function useScope() {
|
|
154
|
+
return useBound("useScope").scope;
|
|
155
|
+
}
|
|
156
|
+
/** The nearest provider's scope and saved namespace head, from one context read. */
|
|
157
|
+
function useBound(hook) {
|
|
158
|
+
const bound = useContext(ScopeContext);
|
|
159
|
+
if (!bound) raise("NoProvider", { hook });
|
|
160
|
+
return bound;
|
|
161
|
+
}
|
|
162
|
+
function useData(cell, a, b) {
|
|
163
|
+
return IS_SERVER ? readData(useScope(), cell, a, b) : useStoreData(cell, a, b);
|
|
164
|
+
}
|
|
165
|
+
function useStoreData(cell, a, b) {
|
|
166
|
+
const selector = typeof a === "function" ? a : void 0;
|
|
167
|
+
const options = typeof a === "function" ? typeof b === "function" ? void 0 : b : a;
|
|
168
|
+
const isEqual = typeof b === "function" ? b : options?.isEqual;
|
|
169
|
+
const writable = wantsPair(cell, options);
|
|
170
|
+
const store = useDataStore(cell, selector, isEqual);
|
|
171
|
+
const value = useSyncExternalStore(store.subscribe, store.read, store.read);
|
|
172
|
+
return writable ? [value, store.set] : value;
|
|
173
|
+
}
|
|
174
|
+
/** A server read: no controller and no store. `set` is built here and finds its controller only
|
|
175
|
+
* when called. */
|
|
176
|
+
function readData(scope, cell, a, b) {
|
|
177
|
+
if (isView(cell)) {
|
|
178
|
+
const value = readableOf(scope, cell).get();
|
|
179
|
+
return typeof a === "function" ? a(value) : value;
|
|
180
|
+
}
|
|
181
|
+
const raw = scope.resolve(cell);
|
|
182
|
+
const value = typeof a === "function" ? a(raw) : raw;
|
|
183
|
+
const options = typeof a === "function" ? b : a;
|
|
184
|
+
if (typeof options !== "object" || options.writable !== true) return value;
|
|
185
|
+
return [value, (next) => scope.controller(cell).set(next)];
|
|
186
|
+
}
|
|
187
|
+
function useDataStore(cell, selector, isEqual) {
|
|
188
|
+
const controller = readableOf(useScope(), cell);
|
|
189
|
+
const own = useRef(void 0);
|
|
190
|
+
if (selector === void 0 && isEqual === void 0) return controller[RAW] ?? createRawStore(controller);
|
|
191
|
+
const kept = own.current;
|
|
192
|
+
const store = kept !== void 0 && kept.controller === controller ? kept : own.current = createDataStore(controller);
|
|
193
|
+
store.select = selector ?? identity;
|
|
194
|
+
store.equal = isEqual ?? Object.is;
|
|
195
|
+
return store;
|
|
196
|
+
}
|
|
197
|
+
/** A capsule's cell export: a read edge (ADR 0123). */
|
|
198
|
+
const isView = (target) => target.kind !== void 0;
|
|
199
|
+
/** A writable pair only for a cell: a capsule's cell export answers the bare value. */
|
|
200
|
+
function wantsPair(cell, options) {
|
|
201
|
+
return options?.writable === true && !isView(cell);
|
|
202
|
+
}
|
|
203
|
+
function readableOf(scope, cell) {
|
|
204
|
+
if (!isView(cell)) return scope.controller(cell);
|
|
205
|
+
if (cell.kind === "reader") return scope.resolve(cell);
|
|
206
|
+
const keyed = scope.controller(cell.cell);
|
|
207
|
+
return cell.read === "of" ? keyed.of(cell.part) : keyed.where(cell.part);
|
|
208
|
+
}
|
|
209
|
+
/** The raw store rides on its controller: a property read, not a hash lookup. */
|
|
210
|
+
const RAW = Symbol("raw store");
|
|
211
|
+
/** Only a cache miss creates these closures. Core keeps each controller stable, and the
|
|
212
|
+
* store goes with its controller when the scope no longer retains it. */
|
|
213
|
+
function createRawStore(controller) {
|
|
214
|
+
const store = {
|
|
215
|
+
controller,
|
|
216
|
+
select: identity,
|
|
217
|
+
equal: Object.is,
|
|
218
|
+
subscribe: (notify) => controller.watch(notify),
|
|
219
|
+
read: () => controller.get(),
|
|
220
|
+
set: (value) => controller.set?.(value)
|
|
221
|
+
};
|
|
222
|
+
controller[RAW] = store;
|
|
223
|
+
return store;
|
|
224
|
+
}
|
|
225
|
+
function createDataStore(controller) {
|
|
226
|
+
let memo = void 0;
|
|
227
|
+
const store = {
|
|
228
|
+
controller,
|
|
229
|
+
select: identity,
|
|
230
|
+
equal: Object.is,
|
|
231
|
+
subscribe: (notify) => controller.watch(notify),
|
|
232
|
+
read: () => {
|
|
233
|
+
const raw = controller.get();
|
|
234
|
+
const prev = memo;
|
|
235
|
+
if (prev !== void 0 && prev.select === store.select && prev.equal === store.equal) {
|
|
236
|
+
if (Object.is(prev.raw, raw)) return prev.slice;
|
|
237
|
+
const slice = store.select(raw);
|
|
238
|
+
const kept = store.equal(prev.slice, slice) ? prev.slice : slice;
|
|
239
|
+
prev.raw = raw;
|
|
240
|
+
prev.slice = kept;
|
|
241
|
+
prev.select = store.select;
|
|
242
|
+
prev.equal = store.equal;
|
|
243
|
+
return kept;
|
|
244
|
+
}
|
|
245
|
+
const fresh = store.select(raw);
|
|
246
|
+
if (prev === void 0) memo = {
|
|
247
|
+
raw,
|
|
248
|
+
slice: fresh,
|
|
249
|
+
select: store.select,
|
|
250
|
+
equal: store.equal
|
|
251
|
+
};
|
|
252
|
+
else {
|
|
253
|
+
prev.raw = raw;
|
|
254
|
+
prev.slice = fresh;
|
|
255
|
+
prev.select = store.select;
|
|
256
|
+
prev.equal = store.equal;
|
|
257
|
+
}
|
|
258
|
+
return fresh;
|
|
259
|
+
},
|
|
260
|
+
set: (value) => controller.set?.(value)
|
|
261
|
+
};
|
|
262
|
+
return store;
|
|
263
|
+
}
|
|
264
|
+
/** The nearest scope's read/write controller for a `data` cell (`get`/`set`/`update`/`watch`).
|
|
265
|
+
* For writes: a component that only holds a controller subscribes to nothing, so a write-only view
|
|
266
|
+
* never re-renders when the cell changes. Read reactively with {@link useData} instead. */
|
|
267
|
+
function useController(cell) {
|
|
268
|
+
return useScope().controller(cell);
|
|
269
|
+
}
|
|
270
|
+
const QUERY_OPTIONS = {};
|
|
271
|
+
/** Query snapshots belong to one resource owner and stay unchanged until their visible state changes. */
|
|
272
|
+
var ResourceOwner = class {
|
|
273
|
+
scope;
|
|
274
|
+
handle;
|
|
275
|
+
ns;
|
|
276
|
+
force;
|
|
277
|
+
controller;
|
|
278
|
+
inherited = void 0;
|
|
279
|
+
pending = void 0;
|
|
280
|
+
settledKey = void 0;
|
|
281
|
+
settled = void 0;
|
|
282
|
+
cached = void 0;
|
|
283
|
+
constructor(scope, handle, ns, force) {
|
|
284
|
+
this.scope = scope;
|
|
285
|
+
this.handle = handle;
|
|
286
|
+
this.ns = ns;
|
|
287
|
+
this.force = force;
|
|
288
|
+
this.controller = scope.controller(handle, ns === void 0 ? void 0 : { ns });
|
|
289
|
+
}
|
|
290
|
+
refetch = () => {
|
|
291
|
+
const selected = this.ns ?? this.inherited;
|
|
292
|
+
if (selected === void 0 || this.handle.target === "scope") this.scope.release(this.handle);
|
|
293
|
+
else this.scope.releaseNs(this.handle, selected);
|
|
294
|
+
this.force();
|
|
295
|
+
};
|
|
296
|
+
effect = () => {
|
|
297
|
+
const pending = this.pending;
|
|
298
|
+
if (pending === void 0) return;
|
|
299
|
+
const observer = {
|
|
300
|
+
live: true,
|
|
301
|
+
work: void 0
|
|
302
|
+
};
|
|
303
|
+
observer.work = pending.then((data) => {
|
|
304
|
+
observer.work = void 0;
|
|
305
|
+
if (observer.live) this.publish(pending, {
|
|
306
|
+
status: "success",
|
|
307
|
+
data,
|
|
308
|
+
error: void 0
|
|
309
|
+
});
|
|
310
|
+
}, (error) => {
|
|
311
|
+
observer.work = void 0;
|
|
312
|
+
if (observer.live) this.publish(pending, {
|
|
313
|
+
status: "error",
|
|
314
|
+
data: void 0,
|
|
315
|
+
error
|
|
316
|
+
});
|
|
317
|
+
});
|
|
318
|
+
return () => {
|
|
319
|
+
observer.live = false;
|
|
320
|
+
observer.work = void 0;
|
|
321
|
+
};
|
|
322
|
+
};
|
|
323
|
+
publish(key, state) {
|
|
324
|
+
this.settledKey = key;
|
|
325
|
+
this.settled = state;
|
|
326
|
+
this.force();
|
|
327
|
+
}
|
|
328
|
+
query(failed, error, value, pending) {
|
|
329
|
+
if (failed) return this.snapshot("error", void 0, error);
|
|
330
|
+
if (pending === void 0) return this.snapshot("success", value, void 0);
|
|
331
|
+
const done = this.settledKey === pending ? this.settled : void 0;
|
|
332
|
+
if (done === void 0) return this.snapshot("pending", void 0, void 0);
|
|
333
|
+
return this.snapshot(done.status, done.data, done.error);
|
|
334
|
+
}
|
|
335
|
+
snapshot(status, data, err) {
|
|
336
|
+
const cached = this.cached;
|
|
337
|
+
if (cached !== void 0 && cached.status === status && Object.is(cached.data, data) && Object.is(cached.error, err)) return cached;
|
|
338
|
+
return this.cached = {
|
|
339
|
+
status,
|
|
340
|
+
data,
|
|
341
|
+
error: err,
|
|
342
|
+
isPending: status === "pending",
|
|
343
|
+
isSuccess: status === "success",
|
|
344
|
+
isError: status === "error",
|
|
345
|
+
refetch: this.refetch
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
function useResource(handle, options = QUERY_OPTIONS) {
|
|
350
|
+
const bound = useBound("useScope");
|
|
351
|
+
const scope = bound.scope;
|
|
352
|
+
if (IS_SERVER) return readServerResource(bound, handle, options);
|
|
353
|
+
const ns = options.ns;
|
|
354
|
+
const inherited = bound.ns;
|
|
355
|
+
const [, force] = useReducer(RunOwner.bump, 0);
|
|
356
|
+
const ref = useRef(void 0);
|
|
357
|
+
if (options.suspense !== false) return useSuspendedResource(scope, handle, ns);
|
|
358
|
+
let owner = ref.current;
|
|
359
|
+
if (owner === void 0 || owner.scope !== scope || owner.handle !== handle || owner.ns !== ns) owner = ref.current = new ResourceOwner(scope, handle, ns, force);
|
|
360
|
+
owner.inherited = inherited;
|
|
361
|
+
return useQueryResource(owner);
|
|
362
|
+
}
|
|
363
|
+
/** A server render never runs the effect that would observe a pending build, so the owner gets
|
|
364
|
+
* no `force` and the hooks of the client path are skipped. */
|
|
365
|
+
function readServerResource(bound, handle, options) {
|
|
366
|
+
if (options.suspense !== false) return readSuspended(bound.scope, handle, options.ns);
|
|
367
|
+
const owner = new ResourceOwner(bound.scope, handle, options.ns, noop);
|
|
368
|
+
owner.inherited = bound.ns;
|
|
369
|
+
return readQuery(owner);
|
|
370
|
+
}
|
|
371
|
+
/** A suspending read keeps no owner: it hands out no refetch and observes nothing. The hooks
|
|
372
|
+
* above and the effect here keep the hook order of the query path. */
|
|
373
|
+
function useSuspendedResource(scope, handle, ns) {
|
|
374
|
+
useEffect(noop, [scope, void 0]);
|
|
375
|
+
return readSuspended(scope, handle, ns);
|
|
376
|
+
}
|
|
377
|
+
function readSuspended(scope, handle, ns) {
|
|
378
|
+
const value = ns === void 0 ? scope.resolve(handle) : scope.resolve(handle, { ns });
|
|
379
|
+
return value instanceof Promise ? use(value) : value;
|
|
380
|
+
}
|
|
381
|
+
const noop = () => void 0;
|
|
382
|
+
function useQueryResource(owner) {
|
|
383
|
+
const query = readQuery(owner);
|
|
384
|
+
useSettled(owner);
|
|
385
|
+
return query;
|
|
386
|
+
}
|
|
387
|
+
function readQuery(owner) {
|
|
388
|
+
let value;
|
|
389
|
+
let error;
|
|
390
|
+
let failed = false;
|
|
391
|
+
try {
|
|
392
|
+
value = owner.controller.resolve();
|
|
393
|
+
} catch (caught) {
|
|
394
|
+
error = caught;
|
|
395
|
+
failed = true;
|
|
396
|
+
}
|
|
397
|
+
const pending = value instanceof Promise ? value : void 0;
|
|
398
|
+
owner.pending = pending;
|
|
399
|
+
return owner.query(failed, error, value, pending);
|
|
400
|
+
}
|
|
401
|
+
/** Detaching a resource owner or changing its promise stops the old observer from publishing. */
|
|
402
|
+
function useSettled(owner) {
|
|
403
|
+
useEffect(owner.effect, [owner, owner.pending]);
|
|
404
|
+
}
|
|
405
|
+
function settledState(outcome) {
|
|
406
|
+
return outcome.ok ? {
|
|
407
|
+
status: "success",
|
|
408
|
+
data: outcome.value,
|
|
409
|
+
error: void 0
|
|
410
|
+
} : {
|
|
411
|
+
status: "error",
|
|
412
|
+
data: void 0,
|
|
413
|
+
error: outcome.error
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
function readRunOutcome(result) {
|
|
417
|
+
return result.status === "success" ? {
|
|
418
|
+
ok: true,
|
|
419
|
+
value: result.value
|
|
420
|
+
} : {
|
|
421
|
+
ok: false,
|
|
422
|
+
error: result.status === "failed" ? result.error : result.reason
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
function notify(on, outcome, variables) {
|
|
426
|
+
if (!on) return;
|
|
427
|
+
try {
|
|
428
|
+
if (outcome.ok) on.onSuccess?.(outcome.value, variables);
|
|
429
|
+
else on.onError?.(outcome.error, variables);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
reportCallbackError(error);
|
|
432
|
+
}
|
|
433
|
+
try {
|
|
434
|
+
on.onSettled?.(outcome.value, outcome.error, variables);
|
|
435
|
+
} catch (error) {
|
|
436
|
+
reportCallbackError(error);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/** Callback failures belong to the host's error reporting, not the operation's outcome. */
|
|
440
|
+
function reportCallbackError(error) {
|
|
441
|
+
if (typeof reportError === "function") reportError(error);
|
|
442
|
+
else queueMicrotask(() => {
|
|
443
|
+
throw error;
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
/** Each committed hook owns its view; old calls keep their result but lose publication on detach. */
|
|
447
|
+
var RunOwner = class RunOwner {
|
|
448
|
+
static idle = {
|
|
449
|
+
status: "idle",
|
|
450
|
+
data: void 0,
|
|
451
|
+
error: void 0,
|
|
452
|
+
variables: void 0
|
|
453
|
+
};
|
|
454
|
+
static bump(n) {
|
|
455
|
+
return n + 1;
|
|
456
|
+
}
|
|
457
|
+
scope;
|
|
458
|
+
op;
|
|
459
|
+
/** Made on the first run: a server render, or a view never clicked, needs none. */
|
|
460
|
+
controller = void 0;
|
|
461
|
+
force;
|
|
462
|
+
live = false;
|
|
463
|
+
runId = 0;
|
|
464
|
+
options = void 0;
|
|
465
|
+
state = RunOwner.idle;
|
|
466
|
+
cached = void 0;
|
|
467
|
+
constructor(scope, op, force) {
|
|
468
|
+
this.scope = scope;
|
|
469
|
+
this.op = op;
|
|
470
|
+
this.force = force;
|
|
471
|
+
}
|
|
472
|
+
attach = () => {
|
|
473
|
+
this.live = true;
|
|
474
|
+
if (this.state !== RunOwner.idle) this.publish(RunOwner.idle);
|
|
475
|
+
return () => {
|
|
476
|
+
this.live = false;
|
|
477
|
+
};
|
|
478
|
+
};
|
|
479
|
+
run = (...call) => {
|
|
480
|
+
const outcome = this.invoke(call);
|
|
481
|
+
if (outcome instanceof Promise) outcome.catch(reportCallbackError);
|
|
482
|
+
};
|
|
483
|
+
runAsync = async (...call) => {
|
|
484
|
+
const running = this.invoke(call);
|
|
485
|
+
const outcome = running instanceof Promise ? await running : running;
|
|
486
|
+
if (outcome.ok) return outcome.value;
|
|
487
|
+
throw outcome.error;
|
|
488
|
+
};
|
|
489
|
+
reset = () => {
|
|
490
|
+
this.runId += 1;
|
|
491
|
+
if (this.live) this.publish(RunOwner.idle);
|
|
492
|
+
};
|
|
493
|
+
publish(state) {
|
|
494
|
+
this.state = state;
|
|
495
|
+
this.cached = void 0;
|
|
496
|
+
this.force();
|
|
497
|
+
}
|
|
498
|
+
finish(id, result, variables) {
|
|
499
|
+
const outcome = readRunOutcome(result);
|
|
500
|
+
if (this.live) {
|
|
501
|
+
if (this.runId === id) this.publish({
|
|
502
|
+
...settledState(outcome),
|
|
503
|
+
variables
|
|
504
|
+
});
|
|
505
|
+
notify(this.options, outcome, variables);
|
|
506
|
+
}
|
|
507
|
+
return outcome;
|
|
508
|
+
}
|
|
509
|
+
invoke(call) {
|
|
510
|
+
this.controller ??= this.scope.controller(this.op);
|
|
511
|
+
const id = this.runId += 1;
|
|
512
|
+
const [variables] = call;
|
|
513
|
+
const result = this.controller.settle(...call);
|
|
514
|
+
if (!(result instanceof Promise)) return this.finish(id, result, variables);
|
|
515
|
+
if (this.live && this.runId === id) this.publish({
|
|
516
|
+
status: "pending",
|
|
517
|
+
data: void 0,
|
|
518
|
+
error: void 0,
|
|
519
|
+
variables
|
|
520
|
+
});
|
|
521
|
+
return result.then((settled) => this.finish(id, settled, variables));
|
|
522
|
+
}
|
|
523
|
+
handle() {
|
|
524
|
+
const state = this.state;
|
|
525
|
+
return this.cached ??= {
|
|
526
|
+
status: state.status,
|
|
527
|
+
data: state.data,
|
|
528
|
+
error: state.error,
|
|
529
|
+
variables: state.variables,
|
|
530
|
+
isIdle: state.status === "idle",
|
|
531
|
+
isPending: state.status === "pending",
|
|
532
|
+
isSuccess: state.status === "success",
|
|
533
|
+
isError: state.status === "error",
|
|
534
|
+
run: this.run,
|
|
535
|
+
runAsync: this.runAsync,
|
|
536
|
+
reset: this.reset
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
/** Run an operation imperatively (a mutation): never suspends. Shaped like react-query's
|
|
541
|
+
* `useMutation`: `run(input)` fires and forgets (the outcome lands in `status`/`data`/`error`
|
|
542
|
+
* with `variables` = the call), `runAsync(input)` also returns the value or rejects, `reset()`
|
|
543
|
+
* returns to idle. A rejection never reaches an error boundary (that is {@link useResource}'s job).
|
|
544
|
+
* Only the latest run publishes state: a slower earlier run that settles after a newer one (or after
|
|
545
|
+
* `reset`) is dropped, though its `options` callbacks still fire. Changing the provider or operation
|
|
546
|
+
* clears the view and stops the old owner's state and callback writes; its caller still gets the result.
|
|
547
|
+
* Handled failures are received through Core's `settle`, so a panic does not fail the owner. */
|
|
548
|
+
function useRun(op, options) {
|
|
549
|
+
const scope = useScope();
|
|
550
|
+
if (IS_SERVER) return new RunOwner(scope, op, noop).handle();
|
|
551
|
+
const [, force] = useReducer(RunOwner.bump, 0);
|
|
552
|
+
const ref = useRef(void 0);
|
|
553
|
+
let owner = ref.current;
|
|
554
|
+
if (owner === void 0 || owner.scope !== scope || owner.op !== op) owner = ref.current = new RunOwner(scope, op, force);
|
|
555
|
+
owner.options = options;
|
|
556
|
+
useLayoutEffect(owner.attach, [owner]);
|
|
557
|
+
return owner.handle();
|
|
558
|
+
}
|
|
559
|
+
/** Reset a node in an explicit namespace, or the nearest React session's saved namespace head.
|
|
560
|
+
* Clearing a head can expose a fallback; fallback keys remain intact. Scope-target resources and
|
|
561
|
+
* calls with no known key retain Core's broad release. Opaque app-owned scope namespaces need an
|
|
562
|
+
* explicit key, since a Core handle does not expose its ambient namespace. */
|
|
563
|
+
function useRelease(ns) {
|
|
564
|
+
const { scope, ns: inherited } = useBound("useScope");
|
|
565
|
+
const selected = ns ?? inherited;
|
|
566
|
+
return useCallback((node) => {
|
|
567
|
+
if (selected === void 0 || "target" in node && node.target === "scope") scope.release(node);
|
|
568
|
+
else scope.releaseNs(node, selected);
|
|
569
|
+
}, [scope, selected]);
|
|
570
|
+
}
|
|
571
|
+
/** Read the nearest scope's bounded span history (ADR 0030) for an inspector/devtools view — a
|
|
572
|
+
* snapshot taken on each render (an empty snapshot when observation is off). Core exposes no span
|
|
573
|
+
* subscription, so this is not push-reactive: a standalone inspector will not update on its own when
|
|
574
|
+
* sibling components do work — the caller arranges its re-renders (co-render with the work, or a
|
|
575
|
+
* manual refresh). */
|
|
576
|
+
function useSpans() {
|
|
577
|
+
return useScope().spans();
|
|
578
|
+
}
|
|
579
|
+
//#endregion
|
|
580
|
+
export { ScopeProvider, SessionProvider, isError, useController, useData, useRelease, useResource, useRun, useScope, useSpans };
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tinkered/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.18.0",
|
|
4
|
+
"description": "Tinkered React: a thin React adapter over @tinkered/core.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"tanstack-intent"
|
|
7
|
+
],
|
|
8
|
+
"homepage": "https://github.com/author/library#readme",
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/author/library/issues"
|
|
11
|
+
},
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "Author Name <author.name@mail.com>",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/lagz0ne/tinkered.git",
|
|
17
|
+
"directory": "packages/react"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"skills"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./dist/index.mjs",
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@tinkered/core": "^0.18.0"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@stryker-mutator/core": "^10.0.0",
|
|
36
|
+
"@stryker-mutator/vitest-runner": "^10.0.0",
|
|
37
|
+
"@tinkered/core": "^0.18.0",
|
|
38
|
+
"@types/node": "^26.1.1",
|
|
39
|
+
"@types/react": "^19",
|
|
40
|
+
"@types/react-dom": "^19",
|
|
41
|
+
"@vitest/browser-playwright": "5.0.1",
|
|
42
|
+
"playwright": "1.55.0",
|
|
43
|
+
"react": "^19.3.0",
|
|
44
|
+
"react-dom": "^19.3.0",
|
|
45
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.0.0",
|
|
46
|
+
"vite-plus": "1.0.0",
|
|
47
|
+
"vitest": "5.0.1",
|
|
48
|
+
"vitest-browser-react": "^2.3.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"react": ">=19"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"bun": ">=1.4",
|
|
55
|
+
"node": ">=22.18.0"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "vp pack",
|
|
59
|
+
"size": "vp pack && node ../../scripts/check-size.mjs 10240",
|
|
60
|
+
"dev": "vp pack --watch",
|
|
61
|
+
"test": "vp test",
|
|
62
|
+
"mutate": "stryker run",
|
|
63
|
+
"check": "vp check"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: react
|
|
3
|
+
description: >
|
|
4
|
+
Use when you write or change a React page or
|
|
5
|
+
component in a Tinker app: read a cell, run
|
|
6
|
+
an operation from a button, show a pending or
|
|
7
|
+
failed call, or mount the app. Also when a
|
|
8
|
+
check prints tinker/react-state or
|
|
9
|
+
tinker/one-wire.
|
|
10
|
+
metadata:
|
|
11
|
+
purpose: >
|
|
12
|
+
How React reads cells and runs operations
|
|
13
|
+
through @tinkered/react, with no state and no
|
|
14
|
+
effect of its own.
|
|
15
|
+
type: framework
|
|
16
|
+
framework: react
|
|
17
|
+
library: '@tinkered/react'
|
|
18
|
+
library_version: '0.18.0'
|
|
19
|
+
requires:
|
|
20
|
+
- '@tinkered/core#core'
|
|
21
|
+
sources:
|
|
22
|
+
- 'lagz0ne/tinkered:packages/react/src/index.ts'
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
# Tinker React
|
|
26
|
+
|
|
27
|
+
Read the `@tinkered/core` skill `core` first. This
|
|
28
|
+
skill adds the React side only.
|
|
29
|
+
|
|
30
|
+
React is a thin host. It reads cells and runs
|
|
31
|
+
operations. State lives in a cell. An effect lives
|
|
32
|
+
in a resource.
|
|
33
|
+
|
|
34
|
+
## Setup
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
import { createScope, data, operation } from "@tinkered/core";
|
|
38
|
+
import {
|
|
39
|
+
ScopeProvider,
|
|
40
|
+
useData,
|
|
41
|
+
useRun,
|
|
42
|
+
} from "@tinkered/react";
|
|
43
|
+
import { createRoot } from "react-dom/client";
|
|
44
|
+
|
|
45
|
+
const count = data({ label: "count", initial: 0 });
|
|
46
|
+
|
|
47
|
+
const add = operation({
|
|
48
|
+
label: "count.add",
|
|
49
|
+
depends: { count: count.controller },
|
|
50
|
+
run: ({ count }) => count.update((n) => n + 1),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
function Counter() {
|
|
54
|
+
const value = useData(count);
|
|
55
|
+
const { run, isPending, error } = useRun(add);
|
|
56
|
+
return (
|
|
57
|
+
<button disabled={isPending} onClick={() => run()}>
|
|
58
|
+
{error ? "failed" : value}
|
|
59
|
+
</button>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const scope = createScope();
|
|
64
|
+
createRoot(document.body).render(
|
|
65
|
+
<ScopeProvider scope={scope}>
|
|
66
|
+
<Counter />
|
|
67
|
+
</ScopeProvider>,
|
|
68
|
+
);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
- `useData(cell)` renders again when that cell
|
|
72
|
+
changes.
|
|
73
|
+
- `useRun(op)` gives `run`, `runAsync`, `status`,
|
|
74
|
+
`data` and `error`. It has the shape of a React
|
|
75
|
+
Query mutation.
|
|
76
|
+
- With capsules, pass the scope that
|
|
77
|
+
`createScope({ capsules })` returns. The
|
|
78
|
+
provider waits for its start.
|
|
79
|
+
|
|
80
|
+
## Core patterns
|
|
81
|
+
|
|
82
|
+
### Read a part of a cell
|
|
83
|
+
|
|
84
|
+
```tsx
|
|
85
|
+
import { data } from "@tinkered/core";
|
|
86
|
+
import { useData } from "@tinkered/react";
|
|
87
|
+
|
|
88
|
+
const user = data({
|
|
89
|
+
label: "user",
|
|
90
|
+
initial: { name: "Ann", visits: 0 },
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
function Name() {
|
|
94
|
+
const name = useData(user, (u) => u.name);
|
|
95
|
+
return <b>{name}</b>;
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The component renders again only when `name`
|
|
100
|
+
changes.
|
|
101
|
+
|
|
102
|
+
### Read a keyed part
|
|
103
|
+
|
|
104
|
+
```tsx no-check
|
|
105
|
+
const list = useData(
|
|
106
|
+
sea.board.waves.where({ room }),
|
|
107
|
+
);
|
|
108
|
+
const one = useData(
|
|
109
|
+
sea.board.waves.of({ room, id }),
|
|
110
|
+
);
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### State for one subtree
|
|
114
|
+
|
|
115
|
+
`SessionProvider` opens a session for its
|
|
116
|
+
children. A write inside it stays inside it, and
|
|
117
|
+
ends when the subtree unmounts.
|
|
118
|
+
|
|
119
|
+
```tsx
|
|
120
|
+
import { data } from "@tinkered/core";
|
|
121
|
+
import {
|
|
122
|
+
SessionProvider,
|
|
123
|
+
useController,
|
|
124
|
+
useData,
|
|
125
|
+
} from "@tinkered/react";
|
|
126
|
+
|
|
127
|
+
const draft = data({ label: "form.draft", initial: "" });
|
|
128
|
+
|
|
129
|
+
function Field() {
|
|
130
|
+
const text = useData(draft);
|
|
131
|
+
const cell = useController(draft);
|
|
132
|
+
return (
|
|
133
|
+
<input
|
|
134
|
+
value={text}
|
|
135
|
+
onChange={(e) => cell.set(e.target.value)}
|
|
136
|
+
/>
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function Form() {
|
|
141
|
+
return (
|
|
142
|
+
<SessionProvider>
|
|
143
|
+
<Field />
|
|
144
|
+
</SessionProvider>
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Common mistakes
|
|
150
|
+
|
|
151
|
+
### HIGH: `useState` or `useReducer` [tinker/react-state]
|
|
152
|
+
|
|
153
|
+
Wrong:
|
|
154
|
+
|
|
155
|
+
```tsx no-check
|
|
156
|
+
const [open, setOpen] = useState(false);
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Right: a `data` cell, read with `useData`. For
|
|
160
|
+
state that must end with a subtree, put the
|
|
161
|
+
subtree in a `SessionProvider`.
|
|
162
|
+
|
|
163
|
+
### HIGH: `useEffect` [tinker/react-state]
|
|
164
|
+
|
|
165
|
+
Wrong:
|
|
166
|
+
|
|
167
|
+
```tsx no-check
|
|
168
|
+
useEffect(() => {
|
|
169
|
+
const id = setInterval(tick, 1000);
|
|
170
|
+
return () => clearInterval(id);
|
|
171
|
+
}, []);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Right: a `resource` holds the timer and its
|
|
175
|
+
cleanup. An operation or a capsule `start` hook
|
|
176
|
+
depends on it.
|
|
177
|
+
|
|
178
|
+
### HIGH: `fetch` in a component [tinker/one-wire]
|
|
179
|
+
|
|
180
|
+
The page talks to the server by rpc and remote
|
|
181
|
+
data only. Read the `@tinkered/core` skill
|
|
182
|
+
`core/rpc`.
|
|
183
|
+
|
|
184
|
+
### MEDIUM: a new object as the selected value
|
|
185
|
+
|
|
186
|
+
```tsx no-check
|
|
187
|
+
useData(user, (u) => ({ name: u.name }));
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
A new object on each read renders on each change.
|
|
191
|
+
Select a plain value, or pass `isEqual` as the
|
|
192
|
+
third argument.
|
|
193
|
+
|
|
194
|
+
## Completion
|
|
195
|
+
|
|
196
|
+
- The app's frontend check prints no
|
|
197
|
+
`tinker/react-state` and no `tinker/one-wire`.
|
|
198
|
+
- A browser test clicks the control and reads
|
|
199
|
+
the new text.
|