@shivaedev/react 0.49.2 → 0.51.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/CHANGELOG.md +37 -0
- package/README.md +188 -186
- package/dist/adapters/permissionGuard.d.ts +4 -3
- package/dist/adapters/permissionGuard.d.ts.map +1 -1
- package/dist/adapters/permissionGuard.js +3 -4
- package/dist/adapters/permissionGuard.js.map +1 -1
- package/dist/adapters/signInRedirect.d.ts +4 -0
- package/dist/adapters/signInRedirect.d.ts.map +1 -0
- package/dist/adapters/signInRedirect.js +6 -0
- package/dist/adapters/signInRedirect.js.map +1 -0
- package/dist/client/FailureHostContext.d.ts +3 -0
- package/dist/client/FailureHostContext.d.ts.map +1 -0
- package/dist/client/FailureHostContext.js +3 -0
- package/dist/client/FailureHostContext.js.map +1 -0
- package/dist/client/NoticeContext.d.ts +1 -1
- package/dist/client/QueryView.d.ts +20 -5
- package/dist/client/QueryView.d.ts.map +1 -1
- package/dist/client/QueryView.js +23 -3
- package/dist/client/QueryView.js.map +1 -1
- package/dist/client/actionCompletion.d.ts +6 -5
- package/dist/client/actionCompletion.d.ts.map +1 -1
- package/dist/client/actionCompletion.js +19 -18
- package/dist/client/actionCompletion.js.map +1 -1
- package/dist/client/adapters/formFields.d.ts +4 -0
- package/dist/client/adapters/formFields.d.ts.map +1 -0
- package/dist/client/adapters/formFields.js +30 -0
- package/dist/client/adapters/formFields.js.map +1 -0
- package/dist/client/adapters/operationHooks.d.ts +5 -0
- package/dist/client/adapters/operationHooks.d.ts.map +1 -0
- package/dist/client/adapters/operationHooks.js +7 -0
- package/dist/client/adapters/operationHooks.js.map +1 -0
- package/dist/{adapters → client/adapters}/queryRoute.d.ts +12 -5
- package/dist/client/adapters/queryRoute.d.ts.map +1 -0
- package/dist/{adapters → client/adapters}/queryRoute.js +14 -1
- package/dist/client/adapters/queryRoute.js.map +1 -0
- package/dist/client/adapters/rowValues.d.ts +7 -0
- package/dist/client/adapters/rowValues.d.ts.map +1 -0
- package/dist/client/adapters/rowValues.js +17 -0
- package/dist/client/adapters/rowValues.js.map +1 -0
- package/dist/client/adapters/useFeedback.d.ts +11 -0
- package/dist/client/adapters/useFeedback.d.ts.map +1 -0
- package/dist/client/adapters/useFeedback.js +38 -0
- package/dist/client/adapters/useFeedback.js.map +1 -0
- package/dist/client/adapters/useQueryNotice.js +1 -1
- package/dist/client/adapters/useQueryNotice.js.map +1 -1
- package/dist/client/adapters/useStableRun.js +1 -1
- package/dist/client/adapters/useStableRun.js.map +1 -1
- package/dist/client/adapters/useSubmissionCallbacks.d.ts +4 -5
- package/dist/client/adapters/useSubmissionCallbacks.d.ts.map +1 -1
- package/dist/client/adapters/useSubmissionCallbacks.js +37 -17
- package/dist/client/adapters/useSubmissionCallbacks.js.map +1 -1
- package/dist/client/adapters/useUndoableChange.d.ts +13 -12
- package/dist/client/adapters/useUndoableChange.d.ts.map +1 -1
- package/dist/client/adapters/useUndoableChange.js +16 -4
- package/dist/client/adapters/useUndoableChange.js.map +1 -1
- package/dist/client/boundOperation.d.ts +12 -0
- package/dist/client/boundOperation.d.ts.map +1 -0
- package/dist/client/boundOperation.js +2 -0
- package/dist/client/boundOperation.js.map +1 -0
- package/dist/client/create.d.ts +15 -11
- package/dist/client/create.d.ts.map +1 -1
- package/dist/client/create.js +12 -5
- package/dist/client/create.js.map +1 -1
- package/dist/client/editor.d.ts +25 -18
- package/dist/client/editor.d.ts.map +1 -1
- package/dist/client/editor.js +14 -8
- package/dist/client/editor.js.map +1 -1
- package/dist/client/failureDecision.d.ts +16 -0
- package/dist/client/failureDecision.d.ts.map +1 -0
- package/dist/client/failureDecision.js +49 -0
- package/dist/client/failureDecision.js.map +1 -0
- package/dist/client/failures.d.ts +45 -0
- package/dist/client/failures.d.ts.map +1 -0
- package/dist/client/failures.js +2 -0
- package/dist/client/failures.js.map +1 -0
- package/dist/client/notices.d.ts +9 -4
- package/dist/client/notices.d.ts.map +1 -1
- package/dist/client/notices.js +22 -3
- package/dist/client/notices.js.map +1 -1
- package/dist/client/operationForm.d.ts +40 -0
- package/dist/client/operationForm.d.ts.map +1 -0
- package/dist/client/operationForm.js +2 -0
- package/dist/client/operationForm.js.map +1 -0
- package/dist/client/pendingCommand.d.ts +6 -9
- package/dist/client/pendingCommand.d.ts.map +1 -1
- package/dist/client/pendingCommand.js +3 -3
- package/dist/client/pendingCommand.js.map +1 -1
- package/dist/client/resultState.d.ts +7 -4
- package/dist/client/resultState.d.ts.map +1 -1
- package/dist/client/resultState.js +6 -3
- package/dist/client/resultState.js.map +1 -1
- package/dist/client/unexpectedFailure.d.ts +8 -0
- package/dist/client/unexpectedFailure.d.ts.map +1 -0
- package/dist/client/unexpectedFailure.js +17 -0
- package/dist/client/unexpectedFailure.js.map +1 -0
- package/dist/client/useDebouncedValue.js +1 -1
- package/dist/client/useDebouncedValue.js.map +1 -1
- package/dist/client/useDelay.js +1 -1
- package/dist/client/useDelay.js.map +1 -1
- package/dist/noticeEntry.d.ts +3 -1
- package/dist/noticeEntry.d.ts.map +1 -1
- package/dist/noticeEntry.js +2 -1
- package/dist/noticeEntry.js.map +1 -1
- package/dist/noticeStore.d.ts +3 -3
- package/dist/noticeStore.d.ts.map +1 -1
- package/dist/noticeStore.js +4 -4
- package/dist/noticeStore.js.map +1 -1
- package/dist/noticeTypes.d.ts +1 -2
- package/dist/noticeTypes.d.ts.map +1 -1
- package/dist/submission.d.ts +2 -4
- package/dist/submission.d.ts.map +1 -1
- package/dist/submission.js +1 -3
- package/dist/submission.js.map +1 -1
- package/package.json +13 -13
- package/src/adapters/permissionGuard.ts +6 -5
- package/src/adapters/signInRedirect.ts +7 -0
- package/src/client/FailureHostContext.ts +4 -0
- package/src/client/QueryView.ts +50 -7
- package/src/client/actionCompletion.ts +33 -23
- package/src/client/adapters/formFields.ts +33 -0
- package/src/client/adapters/operationHooks.ts +14 -0
- package/src/{adapters → client/adapters}/queryRoute.ts +24 -9
- package/src/client/adapters/rowValues.ts +25 -0
- package/src/client/adapters/useFeedback.ts +50 -0
- package/src/client/adapters/useQueryNotice.ts +1 -1
- package/src/client/adapters/useStableRun.ts +1 -1
- package/src/client/adapters/useSubmissionCallbacks.ts +44 -21
- package/src/client/adapters/useUndoableChange.ts +66 -30
- package/src/client/boundOperation.ts +13 -0
- package/src/client/create.ts +50 -20
- package/src/client/editor.ts +98 -38
- package/src/client/failureDecision.ts +70 -0
- package/src/client/failures.ts +56 -0
- package/src/client/notices.ts +44 -6
- package/src/client/operationForm.ts +52 -0
- package/src/client/pendingCommand.ts +12 -14
- package/src/client/resultState.ts +20 -11
- package/src/client/unexpectedFailure.ts +24 -0
- package/src/client/useDebouncedValue.ts +1 -1
- package/src/client/useDelay.ts +1 -1
- package/src/noticeEntry.ts +5 -0
- package/src/noticeStore.ts +9 -4
- package/src/noticeTypes.ts +1 -2
- package/src/submission.ts +4 -6
- package/dist/adapters/queryRoute.d.ts.map +0 -1
- package/dist/adapters/queryRoute.js.map +0 -1
- package/dist/client/adapters/useNoticePublisher.d.ts +0 -4
- package/dist/client/adapters/useNoticePublisher.d.ts.map +0 -1
- package/dist/client/adapters/useNoticePublisher.js +0 -8
- package/dist/client/adapters/useNoticePublisher.js.map +0 -1
- package/src/client/adapters/useNoticePublisher.ts +0 -10
package/README.md
CHANGED
|
@@ -9,16 +9,10 @@ Live query screens and route loaders receive their first authorized result on th
|
|
|
9
9
|
A refresh should not blank a useful screen. A save response should not erase what someone typed while waiting. Signing in as someone else should not inherit the previous person's draft. These hooks and the session boundary handle those transitions around native atoms and forms:
|
|
10
10
|
|
|
11
11
|
```ts
|
|
12
|
-
const editor = useEditor({
|
|
13
|
-
query: api.get.query({ id }),
|
|
14
|
-
fields: InvoiceLineFields,
|
|
15
|
-
values: (line) => ({ name: line.name, quantity: String(line.quantity) }),
|
|
16
|
-
save: (values) => api.save.run({ id, ...values }),
|
|
17
|
-
runtime: InvoiceLinesClient.runtime,
|
|
18
|
-
});
|
|
12
|
+
const editor = useEditor(api.save, { query: api.get.query({ id }), fixed: { id } });
|
|
19
13
|
```
|
|
20
14
|
|
|
21
|
-
`api` is the application's
|
|
15
|
+
`api` is the application's contract binding: `api.save` is a command that carries its runtime and its payload schema, so the editor takes its fields from the payload, fills them from the loaded row and adds `id` to every save. The editor creates the form when the row arrives. A refresh updates untouched fields and keeps edited ones; a save receives the server's normalized result while keeping edits made during the request. The component renders the form and decides what its loading and error messages say.
|
|
22
16
|
|
|
23
17
|
## Using it
|
|
24
18
|
|
|
@@ -184,11 +178,12 @@ Each `useUpdateBlocker(update, true)` holds its own blocker until it becomes fal
|
|
|
184
178
|
|
|
185
179
|
#### Mount the notice host
|
|
186
180
|
|
|
187
|
-
Mount
|
|
181
|
+
Mount `NoticeHost` from `@shivaedev/react/client/notices.ts` once, inside `SessionBoundary` and above the screens. Every bound command and form save publishes the failures its screen does not handle there, so ordinary screens carry no failure wiring; [Failures of commands and saves](#failures-of-commands-and-saves) says which failure goes where. The host owns a native atom collection, dismissal, expiry and each notice action's native `AsyncResult`. Without `render`, a notice renders as a `div` whose `data-notice` is its kind, with `role="status"` for a success and `role="alert"` otherwise, its message in a paragraph, its action button and a Dismiss button. Supply `render(notice)` to choose markup, wording for action outcomes and labels. Render `notice.action.run` as a button handler and disable that control with `notice.action.pending`; `notice.dismiss` removes the entry. No command requires a host. Expiry sleeps on the `Clock` of the optional `runtime` prop, an atom runtime such as `client.runtime`; without it, the host uses Effect's default clock. A story can pass a runtime built with `Layer.succeed(Clock.Clock, clock)` and drive expiry with `TestClock.adjust`.
|
|
188
182
|
|
|
189
183
|
```tsx
|
|
190
184
|
import { Cause } from "effect";
|
|
191
185
|
import * as AsyncResult from "effect/reactivity/AsyncResult";
|
|
186
|
+
import type { UnexpectedFailure } from "@shivaedev/react/client/unexpectedFailure.ts";
|
|
192
187
|
import { NoticeHost, type Notice } from "@shivaedev/react/client/notices.ts";
|
|
193
188
|
|
|
194
189
|
function renderNotice(notice: Notice) {
|
|
@@ -208,16 +203,22 @@ function renderNotice(notice: Notice) {
|
|
|
208
203
|
);
|
|
209
204
|
}
|
|
210
205
|
|
|
206
|
+
function failureNotice(failure: UnexpectedFailure) {
|
|
207
|
+
return failure.kind === "connection" ? { message: "You are offline. Your changes were not sent." } : { message: failure.message };
|
|
208
|
+
}
|
|
209
|
+
|
|
211
210
|
function SessionScreens({ client }: { readonly client: AppClient }) {
|
|
212
211
|
return (
|
|
213
|
-
<NoticeHost render={renderNotice}>
|
|
212
|
+
<NoticeHost failure={failureNotice} render={renderNotice}>
|
|
214
213
|
<OrderScreens client={client} />
|
|
215
214
|
</NoticeHost>
|
|
216
215
|
);
|
|
217
216
|
}
|
|
218
217
|
```
|
|
219
218
|
|
|
220
|
-
`AppClient` and `OrderScreens` belong to the application; return `SessionScreens` from the session boundary's child function. The renderer receives `id`, `message`, `dismiss` and an optional action with `label`, `run`, `pending` and `result`.
|
|
219
|
+
`AppClient` and `OrderScreens` belong to the application; return `SessionScreens` from the session boundary's child function. The renderer receives `id`, `kind` (`"success"`, `"rejection"` for a rejection the server sent, `"failure"` for a failure the host worded), `message`, `dismiss` and an optional action with `label`, `run`, `pending` and `result`.
|
|
220
|
+
|
|
221
|
+
`failure(unexpected)` is the application's one place for the failures that belong to the framework rather than to a screen: a lost connection (`RpcClientError` or `WebSocketRequired`), a server outage (`ServiceUnavailable` or `AuthUnavailable`), an `InternalServerError`, a defect and any untagged failure. It receives `{ kind, message, cause }` with `kind` `"connection"`, `"unavailable"` or `"unexpected"`, and returns a descriptor without an action, or `"silent"`. The default shows `message`: `Could not reach the server. Check your connection and try again.` for a lost connection, the server's own message for an outage or an `InternalServerError`, which the server's handler edge has already redacted, and `Something went wrong. Try again.` for a defect or an untagged failure. It never shows a cause or a stack trace; `cause` is there for the application's diagnostics. One failed invocation publishes one notice, however many hooks hold the same operation. Without a mounted host nothing is published, and the failure stays in the hook's `cause`. Action results retain the native success value or failure cause as `unknown`; narrow domain errors in your renderer to choose their wording.
|
|
221
222
|
|
|
222
223
|
### 2. Once per feature
|
|
223
224
|
|
|
@@ -244,19 +245,7 @@ function Report() {
|
|
|
244
245
|
const action = useAction(rename);
|
|
245
246
|
return (
|
|
246
247
|
<section>
|
|
247
|
-
<QueryView
|
|
248
|
-
query={query}
|
|
249
|
-
content={(row) => <h1>{row.title}</h1>}
|
|
250
|
-
loading={(state) => <p>{state.refreshing ? "Refreshing…" : "Loading…"}</p>}
|
|
251
|
-
failure={(error, state) => (
|
|
252
|
-
<p role="alert">
|
|
253
|
-
{String(error)}{" "}
|
|
254
|
-
<button disabled={state.pending} onClick={state.refresh}>
|
|
255
|
-
Retry
|
|
256
|
-
</button>
|
|
257
|
-
</p>
|
|
258
|
-
)}
|
|
259
|
-
/>
|
|
248
|
+
<QueryView query={query} content={(row) => <h1>{row.title}</h1>} />
|
|
260
249
|
<button onClick={query.refresh}>Refresh</button>
|
|
261
250
|
<button disabled={action.pending} onClick={() => action.dispatch("Annual report")}>
|
|
262
251
|
Rename
|
|
@@ -276,35 +265,30 @@ export function App() {
|
|
|
276
265
|
}
|
|
277
266
|
```
|
|
278
267
|
|
|
279
|
-
`QueryView` from `client/QueryView.ts` is stateless presentation over `QueryState<A, E>`, including an editor's `query`. Supply `content(data, query)
|
|
268
|
+
`QueryView` from `client/QueryView.ts` is stateless presentation over `QueryState<A, E>`, including an editor's `query`. Supply `content(data, query)`; `loading(query)` and `failure(error, query)` are optional. Without them the view uses the application's defaults, or the package's own: a `role="status"` paragraph reading `Loading…` (`Refreshing…` while retained data shows), and a `role="alert"` paragraph with the failure's message and a Retry button that calls the query's `refresh`. While the retry reads, the loading paragraph shows beside the failure. The default failure shows the message of a shared request rejection or a server failure from `@shivaedev/errors/taxonomy.ts`, and `Could not load. Try again.` for anything else. A query that can fail with a rejection the app declared for itself requires `failure`: the call does not compile without it. Wrap the screens once in `QueryViewDefaults` from the same module, with `failure` or `loading` or both, to choose the application's rendering; a view's own renderer still wins.
|
|
269
|
+
|
|
270
|
+
The example's action is a native atom, so its failure stays in `cause` and nothing is published; a bound command reports its failures as [Failures of commands and saves](#failures-of-commands-and-saves) describes. Loading renders while pending, including refreshes, or before the first result; a settled initial rejection renders failure without loading. The failure renderer receives the typed rejection and can call the query's native `refresh` to retry. The component keeps successful content in the same React position through refresh, failure and recovery, preserving mounted inputs. Keep content component types and keys stable as usual.
|
|
280
271
|
|
|
281
272
|
The hook owns retained display data and the native atom owns execution and caching. `QueryView` creates neither. Expected query rejections stay in its failure renderer; defects are thrown to the application's error boundary. It leaves field and command failures with the editor, form or action that owns them. Native `useAtomSuspense` is unchanged and still throws failures.
|
|
282
273
|
|
|
283
274
|
For both queries and actions, a successful `undefined` is `Option.some(undefined)` in `data`, with `pending` and `refreshing` false. A defect or interruption is available as `Option.some(cause)` in `cause`; they do not request a session recheck, even when the defect has an `Unauthorized` tag.
|
|
284
275
|
|
|
285
|
-
The example's action returns a value; it does not persist the report or invalidate its query. In an application,
|
|
276
|
+
The example's action returns a value; it does not persist the report or invalidate its query. In an application, pass the bound query and command of a module's generated contract instead:
|
|
286
277
|
|
|
287
278
|
```ts
|
|
288
|
-
const notes = useQuery(
|
|
289
|
-
|
|
290
|
-
reactivityKeys: ["notes"],
|
|
291
|
-
}),
|
|
292
|
-
);
|
|
293
|
-
const create = useAction(NotesClient.mutation("CreateNote"));
|
|
279
|
+
const notes = useQuery(api.list.query());
|
|
280
|
+
const add = useAction(api.add);
|
|
294
281
|
|
|
295
|
-
|
|
296
|
-
payload: { title: "Morning walk" },
|
|
297
|
-
reactivityKeys: ["notes"],
|
|
298
|
-
});
|
|
282
|
+
add.dispatch({ title: "Morning walk" });
|
|
299
283
|
```
|
|
300
284
|
|
|
301
|
-
`
|
|
285
|
+
`api` comes from `makeClient` over the module's generated contract, as the [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#the-wire-and-the-browsers-contract) describes, with a `list` query and an `add` command that takes `{ title }`. The command's success refreshes the queries that read its keys.
|
|
302
286
|
|
|
303
287
|
An action's `dispatch(input)` returns `void`. Read the atom's latest result from `data`, `cause` or `result`. With the default `Atom.fn` action, a later dispatch interrupts the earlier work and the shared state reports the later result.
|
|
304
288
|
|
|
305
289
|
#### An editor and a create form
|
|
306
290
|
|
|
307
|
-
The next module assumes a sibling `invoice-lines-client.ts` exports a contract-bound `api` with `get`, `save` and `create
|
|
291
|
+
The next module assumes a sibling `invoice-lines-client.ts` exports a contract-bound `api` with `get`, `save` and `create`. `get` returns `{ id, name, quantity }`, `save` takes `{ id, name, quantity }`, `create` takes `{ name, quantity }`, and both commands return the saved row. The [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md) describes that binding.
|
|
308
292
|
|
|
309
293
|
```tsx
|
|
310
294
|
import { useCreate } from "@shivaedev/react/client/create.ts";
|
|
@@ -313,7 +297,7 @@ import { QueryView } from "@shivaedev/react/client/QueryView.ts";
|
|
|
313
297
|
import { useField } from "@shivaedev/form/adapters/react.ts";
|
|
314
298
|
import type { Form } from "@shivaedev/form/shape.ts";
|
|
315
299
|
import { Option, Schema } from "effect";
|
|
316
|
-
import { api
|
|
300
|
+
import { api } from "./invoice-lines-client.ts";
|
|
317
301
|
|
|
318
302
|
const InvoiceLineFields = Schema.Struct({
|
|
319
303
|
name: Schema.String,
|
|
@@ -341,25 +325,10 @@ function Inputs<A, E, ER>({ form }: { readonly form: Form<Fields, A, E, ER> }) {
|
|
|
341
325
|
}
|
|
342
326
|
|
|
343
327
|
export function InvoiceLineEditor({ id }: { readonly id: number }) {
|
|
344
|
-
const editor = useEditor({
|
|
345
|
-
query: api.get.query({ id }),
|
|
346
|
-
fields: InvoiceLineFields,
|
|
347
|
-
values: (line) => ({ name: line.name, quantity: String(line.quantity) }),
|
|
348
|
-
save: (values) => api.save.run({ id, ...values }),
|
|
349
|
-
runtime: InvoiceLinesClient.runtime,
|
|
350
|
-
});
|
|
328
|
+
const editor = useEditor(api.save, { query: api.get.query({ id }), fields: InvoiceLineFields, fixed: { id } });
|
|
351
329
|
return (
|
|
352
330
|
<QueryView
|
|
353
331
|
query={editor.query}
|
|
354
|
-
loading={(query) => <p>{query.refreshing ? "Refreshing…" : "Loading…"}</p>}
|
|
355
|
-
failure={(_error, query) => (
|
|
356
|
-
<p role="alert">
|
|
357
|
-
Could not load{" "}
|
|
358
|
-
<button disabled={query.pending} onClick={query.refresh}>
|
|
359
|
-
Retry
|
|
360
|
-
</button>
|
|
361
|
-
</p>
|
|
362
|
-
)}
|
|
363
332
|
content={() =>
|
|
364
333
|
editor.form && (
|
|
365
334
|
<form
|
|
@@ -369,7 +338,6 @@ export function InvoiceLineEditor({ id }: { readonly id: number }) {
|
|
|
369
338
|
}}
|
|
370
339
|
>
|
|
371
340
|
<Inputs form={editor.form} />
|
|
372
|
-
{Option.isSome(editor.cause) && <p role="alert">Could not save</p>}
|
|
373
341
|
<button type="submit" disabled={editor.saving}>
|
|
374
342
|
Save
|
|
375
343
|
</button>
|
|
@@ -388,12 +356,7 @@ export function InvoiceLineEditor({ id }: { readonly id: number }) {
|
|
|
388
356
|
}
|
|
389
357
|
|
|
390
358
|
export function InvoiceLineCreate() {
|
|
391
|
-
const create = useCreate({
|
|
392
|
-
fields: InvoiceLineFields,
|
|
393
|
-
initialValues: { name: "", quantity: "" },
|
|
394
|
-
create: api.create.run,
|
|
395
|
-
runtime: InvoiceLinesClient.runtime,
|
|
396
|
-
});
|
|
359
|
+
const create = useCreate(api.create, { fields: InvoiceLineFields, initialValues: { name: "", quantity: "" } });
|
|
397
360
|
return (
|
|
398
361
|
<form
|
|
399
362
|
onSubmit={(event) => {
|
|
@@ -402,7 +365,6 @@ export function InvoiceLineCreate() {
|
|
|
402
365
|
}}
|
|
403
366
|
>
|
|
404
367
|
<Inputs form={create.form} />
|
|
405
|
-
{Option.isSome(create.cause) && <p role="alert">Could not create</p>}
|
|
406
368
|
<button type="submit" disabled={create.saving}>
|
|
407
369
|
Create
|
|
408
370
|
</button>
|
|
@@ -412,7 +374,13 @@ export function InvoiceLineCreate() {
|
|
|
412
374
|
}
|
|
413
375
|
```
|
|
414
376
|
|
|
415
|
-
|
|
377
|
+
Both hooks take the bound command first. It carries the atom runtime that runs it and supplies the services of schema decoding, and its payload schema. Without `fields`, the form's fields are the payload's fields minus the keys in `fixed`. Pass `fields` when an input holds another encoding than the payload, as here: the inputs hold strings and `InvoiceLineFields` decodes `quantity` to a number before the command receives it. A command whose payload is not a struct needs `fields`.
|
|
378
|
+
|
|
379
|
+
`fixed` holds the payload fields the form does not edit, such as the record's `id` or an expected version; every save sends `{ ...fixed, ...values }`. `fixed` and the form's fields together must cover the payload exactly. A missing key, a key outside the payload and a value of the wrong type are compile errors that name the key: an editor for `{ id, title, expectedVersion }` given `fixed: { id }` reports `Property 'expectedVersion' is missing`, and `fixed: { owner: "ada" }` reports `Type '"ada"' is not assignable to type '"is not a field of the command's payload"'`. A query passed where a command belongs reports `a bound query only reads: read it with useQuery, and pass a command here`.
|
|
380
|
+
|
|
381
|
+
An editor fills its inputs by encoding each loaded or saved row with the form's field schemas, without rerunning their checks, because the row already passed its schema. Pass `values(row)` when the row's shape differs from the fields or a field's encoding needs services; the compiler requires it then. A payload field the row lacks must go in `fixed`. Put a payload field the user must not edit, such as `id`, in `fixed` even when the row has it, so it stays out of drafts.
|
|
382
|
+
|
|
383
|
+
For a save that is not a single bound command, pass `{ run, runtime }`: `run` takes the decoded values and returns the Effect, and `runtime` provides its services. Spread a bound command into it, `{ ...api.save, runtime }`, to run it on another runtime.
|
|
416
384
|
|
|
417
385
|
The editor's form is absent until its first row arrives. A different query atom creates a new form, so another record starts without the previous draft. Refresh results adopt untouched fields and leave edited fields alone. Saved rows supply server normalization while edits made during the save remain dirty. A refresh failure keeps the draft, and `query.refresh()` retries.
|
|
418
386
|
|
|
@@ -422,7 +390,7 @@ A successful create replaces its form with one at `initialValues`, keeping field
|
|
|
422
390
|
|
|
423
391
|
#### One-shot create and edit
|
|
424
392
|
|
|
425
|
-
Use `useCreate` when the app already has the opening values and needs one submission.
|
|
393
|
+
Use `useCreate` when the app already has the opening values and needs one submission. It accepts any command, including an update command; `created` holds the command's successful result. Creation above and the query-free edit below use the same form lifecycle. No upsert or new form hook is needed: creation and update remain separate domain commands with explicit payloads.
|
|
426
394
|
|
|
427
395
|
For this versioned example, the app's `save` command requires `{ id, expectedVersion, name, quantity }` and returns the row with its new `version`. It rejects a stale version with a tagged `Conflict` error. Reuse `InvoiceLineFields` and `Inputs` from above:
|
|
428
396
|
|
|
@@ -440,16 +408,10 @@ type VersionedLine = {
|
|
|
440
408
|
|
|
441
409
|
export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedLine; readonly onSaved: (line: VersionedLine) => void }) {
|
|
442
410
|
const [original] = useState(opening);
|
|
443
|
-
const edit = useCreate({
|
|
411
|
+
const edit = useCreate(api.save, {
|
|
444
412
|
fields: InvoiceLineFields,
|
|
413
|
+
fixed: { id: original.id, expectedVersion: original.version },
|
|
445
414
|
initialValues: { name: original.name, quantity: String(original.quantity) },
|
|
446
|
-
create: (values) =>
|
|
447
|
-
api.save.run({
|
|
448
|
-
id: original.id,
|
|
449
|
-
expectedVersion: original.version,
|
|
450
|
-
...values,
|
|
451
|
-
}),
|
|
452
|
-
runtime: InvoiceLinesClient.runtime,
|
|
453
415
|
});
|
|
454
416
|
useEffect(() => {
|
|
455
417
|
if (Option.isSome(edit.created)) onSaved(edit.created.value);
|
|
@@ -462,9 +424,6 @@ export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedL
|
|
|
462
424
|
}}
|
|
463
425
|
>
|
|
464
426
|
<Inputs form={edit.form} />
|
|
465
|
-
{Option.isSome(edit.failure) && (
|
|
466
|
-
<p role="alert">{edit.failure.value._tag === "Conflict" ? "This line changed. Reopen it to use the latest version." : "Could not save"}</p>
|
|
467
|
-
)}
|
|
468
427
|
<button type="submit" disabled={edit.saving}>
|
|
469
428
|
Save
|
|
470
429
|
</button>
|
|
@@ -473,37 +432,45 @@ export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedL
|
|
|
473
432
|
}
|
|
474
433
|
```
|
|
475
434
|
|
|
476
|
-
The app captures the opening record once. Pass a stable `onSaved` callback to close the dialog, navigate or record a completion message; mount a new form for another opening. Domain data, including expected versions and any Undo payload, stays in the app. A
|
|
435
|
+
The app captures the opening record once. Pass a stable `onSaved` callback to close the dialog, navigate or record a completion message; mount a new form for another opening. Domain data, including expected versions and any Undo payload, stays in the app. A `Conflict` shows the server's message through the notice host and keeps the input; the typed error is also in `failure`. Field rejections stay on the submitted form until corrected; stale-rejection matching belongs to form. Success uses `useCreate`'s normal reset to opening values while preserving input changed during submission, so `onSaved` owns what happens next rather than turning this into a continuing editor.
|
|
477
436
|
|
|
478
437
|
Use `useEditor` for a continuing editor that subscribes to a record, merges refreshes and receives saved rows as its new baseline. Its `loaded` option supplies the initial row, usually from a route loader; it still requires `query` because the query owns identity, refresh and invalidation. Supplying `loaded` does not make an editor query-free. In either pattern contract owns the command Effect and invalidation, form owns submission and field errors, and react exposes query state where a query exists.
|
|
479
438
|
|
|
480
|
-
####
|
|
439
|
+
#### Failures of commands and saves
|
|
481
440
|
|
|
482
|
-
A
|
|
441
|
+
A bound command given to `useAction`, `usePendingCommand` or `useUndoableChange`, and the save of `useCreate` or `useEditor`, decide what each failure shows from its class, so the ordinary screen writes no failure handling:
|
|
483
442
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
443
|
+
- A rejection whose `field` names one of the form's fields becomes that field's message (form saves only). `Conflict` and `BadRequest` from `@shivaedev/errors/taxonomy.ts` with a `field`, and a contract `fieldRejection` over the form's fields, land there.
|
|
444
|
+
- A shared request rejection from `@shivaedev/errors/taxonomy.ts` (`NotFound`, `Unauthorized`, `Forbidden`, `BadRequest`, `Conflict`, `PreconditionFailed` or `TooManyRequests`) publishes a notice with the error's `message`. `Unauthorized` also asks the session to recheck.
|
|
445
|
+
- A framework failure goes to the notice host's `failure` wording: `RpcClientError`, `ServiceUnavailable`, `AuthUnavailable`, `InternalServerError`, contract's `MissingReadPolicy`, `MissingReadPolicies`, `QueryReadDenied` and `WebSocketRequired`, a defect and any untagged failure.
|
|
446
|
+
- A rejection the app declared for itself has no default. The call does not compile until `failures` says what it shows.
|
|
447
|
+
- Interrupted work shows nothing.
|
|
448
|
+
|
|
449
|
+
`failureKind` from `@shivaedev/contract/failureKind.ts` holds that classification, `AppRejection<E>` names the app's own rejections in an error type, and `RequestRejection` and `ServerFailure` in `@shivaedev/errors/taxonomy.ts` name the shared ones.
|
|
450
|
+
|
|
451
|
+
```tsx
|
|
452
|
+
function Retitle({ id }: { readonly id: number }) {
|
|
453
|
+
const editor = useEditor(api.retitle, {
|
|
454
|
+
query: api.get.query({ id }),
|
|
455
|
+
fixed: { id },
|
|
456
|
+
failures: { SubtitleRejected: (error) => ({ field: "title", message: error.message }) },
|
|
457
|
+
});
|
|
458
|
+
return <TitleForm form={editor.form} save={editor.save} />;
|
|
459
|
+
}
|
|
495
460
|
```
|
|
496
461
|
|
|
497
|
-
Here `
|
|
462
|
+
Here `api.retitle` takes `{ id, title }` and can fail with the app's tagged `SubtitleRejected`, which refers to the server's `subtitle` while the form calls the input `title`; `api`, `SubtitleRejected` and `TitleForm` belong to the application. A handler is keyed by the failure's tag and receives the error and the invocation's input, which for a form is its decoded values. It returns a notice descriptor, a field rejection `{ field, message }` naming one of the form's fields (form hooks only), or `"silent"`. In place of a function, `"message"` shows the error's own message as a notice and `"silent"` shows nothing for that tag. A handler may also be given for a shared rejection to word it differently for that call. `silent: true` shows nothing for any failure of the call, which differs from leaving `failures` out: that uses the defaults. The typed failure stays in the hook's `failure` and `cause` in every case.
|
|
463
|
+
|
|
464
|
+
A missing handler is a compile error that names the tag. `useAction(api.retitle)` with no options reports `Property '"failures.SubtitleRejected"' is missing`, followed by `the operation can fail with SubtitleRejected, a rejection the app declared: say what it shows, for example failures: { SubtitleRejected: "message" }`. Options without `failures` report `Property 'failures' is missing` for a type `HandleAppRejections<"SubtitleRejected", …>`, `failures: {}` reports `Property 'SubtitleRejected' is missing`, and a key that is not a failure of the operation is an unknown property. A form's rejection whose `field` can only name a field the form lacks counts as the app's own and needs a handler.
|
|
498
465
|
|
|
499
466
|
#### Query, command and form feedback
|
|
500
467
|
|
|
501
|
-
Use `useQuery` with `QueryView` for reads,
|
|
468
|
+
Use `useQuery` with `QueryView` for reads, `useAction` with a bound command for commands, and `useCreate` or `useEditor` for form submissions. Give these owners success notice descriptors and mount one `NoticeHost` inside the session boundary; failures reach it as the previous section describes. contract still runs commands and invalidates queries; form still owns submission, fields and drafts. The app supplies wording, Undo payloads and expected versions.
|
|
502
469
|
|
|
503
|
-
|
|
470
|
+
`useAction` with a command accepts `notices.onSuccess(value, input)`, which returns a descriptor or `undefined`. Independent concurrent completions publish independently, preserving the invocation's input. `useCreate` and `useEditor` accept the same `notices` option around their existing save Effects. Use the descriptors instead of screen-local notice state, expiry timers or result-watching effects:
|
|
504
471
|
|
|
505
472
|
```ts
|
|
506
|
-
const remove = useAction(
|
|
473
|
+
const remove = useAction(api.remove, {
|
|
507
474
|
concurrent: true,
|
|
508
475
|
notices: {
|
|
509
476
|
onSuccess: (removed, input) => ({
|
|
@@ -517,12 +484,11 @@ const remove = useAction(OrdersClient.runtime, api.remove.run, {
|
|
|
517
484
|
}),
|
|
518
485
|
},
|
|
519
486
|
}),
|
|
520
|
-
onFailure: () => ({ message: "Could not remove this order" }),
|
|
521
487
|
},
|
|
522
488
|
});
|
|
523
489
|
```
|
|
524
490
|
|
|
525
|
-
`
|
|
491
|
+
`api`, the restore payload and its expected version belong to the application. The host runs the supplied Effect with the operation's native runtime, disables repeated dispatch while it is pending and exposes the outcome on that action. A failed Undo stays on its original notice; it does not become another operation failure notice. Command execution and invalidation remain with contract, and form submission remains with form.
|
|
526
492
|
|
|
527
493
|
For query failures, pass `useQuery(atom, { notice: ({ cause, refreshing }) => descriptor })`. `useEditor` accepts the same callback as `queryNotice` for its query. `refreshing` distinguishes a failure with retained data from an initial load failure. Each settled failed result publishes once per hook; a rerender does not replay it. Omit the callback or return `undefined` for operations that need no notice.
|
|
528
494
|
|
|
@@ -534,16 +500,13 @@ const notes = useQuery(api.list.query(), {
|
|
|
534
500
|
message: refreshing ? "Refresh failed" : "Load failed",
|
|
535
501
|
}),
|
|
536
502
|
});
|
|
537
|
-
const save = useCreate({
|
|
538
|
-
fields: TitleFields,
|
|
503
|
+
const save = useCreate(api.save, {
|
|
539
504
|
initialValues: { title: "" },
|
|
540
|
-
create: api.save.run,
|
|
541
|
-
runtime: NotesClient.runtime,
|
|
542
505
|
notices: { onSuccess: (title) => ({ message: `Saved ${title}` }) },
|
|
543
506
|
});
|
|
544
507
|
```
|
|
545
508
|
|
|
546
|
-
Here `api
|
|
509
|
+
Here `api` belongs to the app, and `api.save` takes `{ title }` and returns the saved title. Render `notes` through `QueryView`: its loading renderer shows pending work, its failure renderer offers `notes.refresh` as Retry, and its content renderer holds the form and command controls. Bind fields with form's `useField`, submit with `save.save()` and disable Save with `save.saving`. A tagged field rejection stays beside that input. A held save keeps newer edits when it completes and publishes its success notice before the invalidated query finishes. A failed refresh keeps the last content and the draft while publishing the refresh notice.
|
|
547
510
|
|
|
548
511
|
Replacing the session during a command or Undo disposes the outgoing registry: late completion callbacks and outcomes do not publish, and retained notice action and dismiss handlers cannot change the new host.
|
|
549
512
|
|
|
@@ -551,37 +514,36 @@ A descriptor has `message`, optional `expiresIn` as a native Duration, and optio
|
|
|
551
514
|
|
|
552
515
|
#### Completion inside each command invocation
|
|
553
516
|
|
|
554
|
-
Pass the
|
|
517
|
+
Pass the bound command to `useAction` when the screen needs feedback for each invocation:
|
|
555
518
|
|
|
556
519
|
```tsx
|
|
557
|
-
const rename = useAction(
|
|
520
|
+
const rename = useAction(api.rename, {
|
|
558
521
|
notices: {
|
|
559
522
|
onSuccess: (saved, input) => ({ message: `Renamed ${input.id} to ${saved.title}` }),
|
|
560
|
-
onFailure: (_error, input) => ({ message: `Could not rename ${input.id}` }),
|
|
561
523
|
},
|
|
562
524
|
});
|
|
563
525
|
```
|
|
564
526
|
|
|
565
|
-
`
|
|
527
|
+
`api` belongs to the application. Input, success, typed failure and runtime requirements are inferred from the command. Use `notices` for success notices and `failures` for the wording of a failure. The optional synchronous `onSuccess(value, input)` and `onFailure(error, input)` callbacks are also available for application completion work. They run inside each invocation using the latest committed callbacks and that invocation's input and outcome. Rerendering a result does not replay completion, and an abandoned render cannot replace the committed callback. A callback that throws becomes a native defect; it does not call `onFailure` as a domain rejection.
|
|
566
528
|
|
|
567
|
-
The command's identity is the native action atom, or the `run` function
|
|
529
|
+
The command's identity is the native action atom, or the operation's `run` function and `runtime`. A bound command such as `api.rename` keeps both; memoize a custom `run` in `{ run, runtime }` with `useCallback` or `useMemo`. A `run` written inline in the component is a new function on every render: its next render fails with an error that names `useAction`, says `run` must stay the same function and gives this fix, where React alone reports only `Too many re-renders`. Changing the command on a mounted control keeps `pending` true until its outgoing request settles. Its result, data and cause stay with the outgoing command: a refusal or success from Launch never appears on a replacement Resume control. Resume dispatches its own function and input. Completion callbacks for the outgoing runtime command stop when it is replaced; callbacks for the same command still use the latest committed props.
|
|
568
530
|
|
|
569
531
|
The hook calls the supplied Effect once. A bound contract command still owns invalidation, and completion does not wait for server query reruns and their pushed results. Undo payloads, expected versions and presentation text stay in the application.
|
|
570
532
|
|
|
571
533
|
A newer dispatch interrupts the earlier command by default. Interrupted work produces no completion feedback. Pass `{ concurrent: true, onSuccess, onFailure }` to let invocations overlap and report their own outcomes. `result`, `data`, `cause` and `pending` remain the native action atom's aggregate state, including its native result selection during concurrent execution; they do not identify an invocation. Use notice descriptors for per-invocation messages and completion callbacks for application work. Keep the runtime and concurrency policy stable for the same owner.
|
|
572
534
|
|
|
573
|
-
A typed `Unauthorized` failure asks the session owner to recheck once per failed invocation, even with concurrent commands. The hook does not sign out. Session replacement discards outgoing callbacks and rechecks, including when outgoing work cannot be interrupted.
|
|
535
|
+
A typed `Unauthorized` failure shows its message and asks the session owner to recheck once per failed invocation, even with concurrent commands. The hook does not sign out. Session replacement discards outgoing callbacks and rechecks, including when outgoing work cannot be interrupted.
|
|
574
536
|
|
|
575
537
|
#### Remove with a version-guarded Undo
|
|
576
538
|
|
|
577
|
-
Use `useUndoableChange` from `@shivaedev/react/client/adapters/useUndoableChange.ts` when a versioned command also performs its inverse. Its payload includes `expectedVersion: number`, and its success includes `version: number`.
|
|
539
|
+
Use `useUndoableChange` from `@shivaedev/react/client/adapters/useUndoableChange.ts` when a versioned command also performs its inverse. Its payload includes `expectedVersion: number`, and its success includes `version: number`. Pass the bound command, and the application's `deployUpdate` as the `update` option:
|
|
578
540
|
|
|
579
541
|
```tsx
|
|
580
542
|
import { Option } from "effect";
|
|
581
543
|
import { useUndoableChange } from "@shivaedev/react/client/adapters/useUndoableChange.ts";
|
|
582
544
|
|
|
583
545
|
function RemoveNote({ note }: { readonly note: { id: string; version: number } }) {
|
|
584
|
-
const change = useUndoableChange(
|
|
546
|
+
const change = useUndoableChange(api.change, { describe: (saved) => `Removed ${saved.id}`, update });
|
|
585
547
|
const notice = Option.getOrUndefined(change.notice);
|
|
586
548
|
return (
|
|
587
549
|
<>
|
|
@@ -604,34 +566,32 @@ function RemoveNote({ note }: { readonly note: { id: string; version: number } }
|
|
|
604
566
|
}
|
|
605
567
|
```
|
|
606
568
|
|
|
607
|
-
`api`,
|
|
569
|
+
`api`, the soft-removal payload and `update` belong to the application. `remove(input, inverse)` captures the inverse domain fields. `undo()` sends those fields through the same command with `expectedVersion` set to the successful removal's returned `version`. The server must enforce that version and declare its typed conflict; a later edit then refuses Undo without overwriting the row. `removeResult` and `undoResult` preserve the native `AsyncResult`, including typed failures. Successful Undo clears its notice; a failed Undo leaves it available.
|
|
608
570
|
|
|
609
571
|
For a batch command, supply `undoInput(value, input)` to build the complete inverse payload from its successful result and original input. This overload accepts any command payload and success shape and uses `remove(input)` with no second argument:
|
|
610
572
|
|
|
611
573
|
```tsx
|
|
612
|
-
const change = useUndoableChange(
|
|
613
|
-
|
|
614
|
-
{
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
},
|
|
618
|
-
);
|
|
574
|
+
const change = useUndoableChange(api.editEntries, {
|
|
575
|
+
describe: () => "Changed diary entries",
|
|
576
|
+
undoInput: (saved) => ({ _tag: "undo" as const, token: saved.undo }),
|
|
577
|
+
update,
|
|
578
|
+
});
|
|
619
579
|
change.remove({ _tag: "edit", rows: selectedVersions, scale: 0.5, copies: true });
|
|
620
580
|
```
|
|
621
581
|
|
|
622
|
-
`api.editEntries
|
|
582
|
+
`api.editEntries` and the payload shape belong to the application. The hook captures the inverse when the command succeeds and submits it unchanged through the same command on Undo. The result can carry a set of row versions with their previous values, or an opaque server-issued undo token; neither requires a top-level `expectedVersion` or `version`. The server owns the transaction: restore each changed row under its own returned version, remove rows the batch created under their own guards, and reject the whole inverse with a typed conflict if any guard is stale. React stories exercise portion scaling, copy removal and stale guards against PostgreSQL; the hook supplies no database undo engine.
|
|
623
583
|
|
|
624
584
|
`notice` is a native `Option` containing `message`, the submitted `input` and returned `value`. Only the most recently dispatched removal can publish it, even when replies arrive in reverse order. An older Undo cannot clear a newer notice. `removing` and `undoing` describe the two writes, and `pending` includes either. Each invocation holds `update.block` for its whole Effect lifetime, so overlapping writes hold deployment activation until all finish. The hook keeps UI wording and inverse domain data in the app; no `NoticeHost` is needed.
|
|
625
585
|
|
|
626
586
|
#### Commands with a pending display value
|
|
627
587
|
|
|
628
|
-
Use `usePendingCommand` for a command acting on a query row, such as a list toggle. Pass the bound command
|
|
588
|
+
Use `usePendingCommand` for a command acting on a query row, such as a list toggle. Pass the bound command, the row's current server value and the display value an input asks for:
|
|
629
589
|
|
|
630
590
|
```tsx
|
|
631
591
|
import { usePendingCommand } from "@shivaedev/react/client/pendingCommand.ts";
|
|
632
592
|
|
|
633
593
|
function EnabledToggle({ row }: { readonly row: { readonly id: number; readonly enabled: boolean } }) {
|
|
634
|
-
const command = usePendingCommand(
|
|
594
|
+
const command = usePendingCommand(api.toggle, { value: row.enabled, wanted: (input) => input.enabled });
|
|
635
595
|
return (
|
|
636
596
|
<button
|
|
637
597
|
aria-pressed={command.value}
|
|
@@ -645,7 +605,7 @@ function EnabledToggle({ row }: { readonly row: { readonly id: number; readonly
|
|
|
645
605
|
}
|
|
646
606
|
```
|
|
647
607
|
|
|
648
|
-
The example assumes a bound `api.toggle`
|
|
608
|
+
The example assumes a bound `api.toggle` that takes `{ id, enabled }`. Its `run` and `runtime` are the command's identity and must stay the same between renders, as for `useAction`. Each use of the hook owns its action state, so one row can fail while another keeps its requested display.
|
|
649
609
|
|
|
650
610
|
`command.value` changes on dispatch and holds the requested value until the command is [reflected](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#when-a-commands-change-is-on-the-screen): every live query open on the connection shows the server's state after it. A switch backed by a live query therefore does not fall back to the old server value between the command's reply and the server's update, and a command that changes nothing frees the switch without an update. `pending` covers that whole interval, and `result`, `data` and `cause` settle when it ends. After the hold ends, `value` follows the server again, even if it differs from the requested value. A command failure immediately returns to the server value and remains typed in `result` and `cause`, just as with `useAction`. This binding holds a display value; it applies no optimistic update and does not write to the query cache.
|
|
651
611
|
|
|
@@ -676,7 +636,7 @@ With native `RpcClient.layerProtocolHttp` and `FetchHttpClient.layer` as the bro
|
|
|
676
636
|
|
|
677
637
|
#### Route loaders with TanStack Router
|
|
678
638
|
|
|
679
|
-
TanStack Router owns routes, navigation, search validation, loader data and screen components.
|
|
639
|
+
TanStack Router owns routes, navigation, search validation, loader data and screen components. Declare a route's query once with `queryRoute(buildQuery)` from `@shivaedev/react/client/adapters/queryRoute.ts`, spread the result into `createRoute`, and call its `useQuery()` in the route's component. The spread derives loader dependencies from validated search and loads the contract query atom in the router context’s registry; `useQuery()` reads the same atom, so the component names neither the operation nor its arguments. A `NotFound` instance from `@shivaedev/errors/taxonomy.ts` or a `QueryReadDenied` refusal enters TanStack's not-found handling with the original rejection in the not-found component's `data` prop, preserving its message. One root `notFoundComponent` can show that message for all query routes; a route's own `notFoundComponent` takes precedence. Other typed failures reach `errorComponent` unchanged. The atom runs through its native RPC runtime and shares its execution with React. The factory receives `{ context, params, search }`: `context` is the loader’s router context, including parent `beforeLoad` contributions. Annotate it with `typeof root.types.allContext` (or the parent route’s `types.allContext`) to keep client and viewer access checked against the route’s declaration.
|
|
680
640
|
|
|
681
641
|
This example assumes an application-owned `api.get.query({ id, page })` returning `{ id, title }`, with declared `NotFound` and `NoteMissing` rejections:
|
|
682
642
|
|
|
@@ -688,8 +648,7 @@ import { Effect, Option, Predicate, Schema } from "effect";
|
|
|
688
648
|
import type { ReactNode } from "react";
|
|
689
649
|
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
690
650
|
import { NotFound } from "@shivaedev/errors/taxonomy.ts";
|
|
691
|
-
import { queryRoute } from "@shivaedev/react/adapters/queryRoute.ts";
|
|
692
|
-
import { useLoaderQuery } from "@shivaedev/react/client/useLoaderQuery.ts";
|
|
651
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
693
652
|
import { api } from "./notes-client.ts";
|
|
694
653
|
|
|
695
654
|
const registry = AtomRegistry.make();
|
|
@@ -737,7 +696,7 @@ function Shell({ children }: { readonly children: ReactNode }) {
|
|
|
737
696
|
);
|
|
738
697
|
}
|
|
739
698
|
function Note() {
|
|
740
|
-
const query =
|
|
699
|
+
const query = noteQuery.useQuery();
|
|
741
700
|
return <h1>{query.data.title}</h1>;
|
|
742
701
|
}
|
|
743
702
|
function Failure({ error }: ErrorComponentProps) {
|
|
@@ -769,28 +728,40 @@ export function App() {
|
|
|
769
728
|
|
|
770
729
|
Keep the result of `queryRoute` to call its `useRetry()` hook inside that route's error component. The returned callback refreshes the query using the current match's params, decoded search dependencies and context, then invalidates that match. A successful retry renders the route again without replacing the surrounding shell or its draft inputs.
|
|
771
730
|
|
|
772
|
-
|
|
731
|
+
State where a signed-out visitor goes once, as `redirects.signedOut` in the router's context. A query route whose query fails with the shared `Unauthorized` rejection redirects there, and `permissionGuard` takes the same callback. `signInRedirect(path)` from `@shivaedev/react/adapters/signInRedirect.ts` builds it: a TanStack redirect to `path` that carries the requested path, search and fragment in sign-in's `returnTo` search field. `redirects.refused` handles `Forbidden` and `QueryReadDenied` the same way, with a callback that returns TanStack's `redirect`. A route overrides either target for its own query with `queryRoute(buildQuery, { redirects })`, as `memberNote` does here:
|
|
773
732
|
|
|
774
733
|
```ts
|
|
775
|
-
import {
|
|
776
|
-
import
|
|
777
|
-
import {
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
734
|
+
import { createRootRouteWithContext, createRoute, createRouter } from "@tanstack/react-router";
|
|
735
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
736
|
+
import type { QueryRouteRedirects } from "@shivaedev/react/adapters/queryRouteFailure.ts";
|
|
737
|
+
import { signInRedirect } from "@shivaedev/react/adapters/signInRedirect.ts";
|
|
738
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
739
|
+
import { api } from "./notes-client.ts";
|
|
740
|
+
|
|
741
|
+
const registry = AtomRegistry.make();
|
|
742
|
+
const root = createRootRouteWithContext<{ registry: AtomRegistry.AtomRegistry; api: typeof api; redirects: QueryRouteRedirects }>()();
|
|
743
|
+
const memberNote = createRoute({
|
|
744
|
+
getParentRoute: () => root,
|
|
745
|
+
path: "/members/$id",
|
|
746
|
+
...queryRoute(
|
|
747
|
+
({ context, params }: { context: typeof root.types.allContext; params: { id: string }; search: object }) =>
|
|
748
|
+
context.api.get.query({ id: params.id, page: 1 }),
|
|
749
|
+
{ redirects: { signedOut: signInRedirect("/members/sign-in") } },
|
|
750
|
+
),
|
|
751
|
+
});
|
|
752
|
+
const router = createRouter({
|
|
753
|
+
context: { registry, api, redirects: { signedOut: signInRedirect("/sign-in") } },
|
|
754
|
+
routeTree: root.addChildren([memberNote]),
|
|
784
755
|
});
|
|
785
756
|
```
|
|
786
757
|
|
|
787
|
-
Without
|
|
758
|
+
Without a callback at either level, failures keep their normal error or not-found handling. `NotFound` continues to use the not-found screen even when refusal redirects are configured.
|
|
788
759
|
|
|
789
760
|
For a loader that coordinates more work, use `loadQuery(registry, atom, loaderContext)` from `@shivaedev/react/adapters/loadQuery.ts` directly. It reads the atom in the supplied registry and throws typed failures unchanged, including `NotFound`; the loader decides how to handle them.
|
|
790
761
|
|
|
791
762
|
`defaultPendingMs: Infinity` keeps the current route's data visible during navigation; the shell reads TanStack's `isLoading` to display pending state. The new route commits when its loader settles. This is TanStack's pending policy, separate from `useQuery`'s retained display. The loader hands its query over to the route's component: the first render has the loaded value, and the query handler runs once, for a live subscription and for a `live: false` query alike, even when the route mounts after the registry’s idle window.
|
|
792
763
|
|
|
793
|
-
`
|
|
764
|
+
`useQuery()` reads the current match's params, decoded search, context and loader value, and exposes `data` as the query's success type, with no `Option` or Initial result. It takes the options of `useQuery` from `@shivaedev/react/client/resultState.ts`. Call it inside the route's component or a component it renders. Refetches keep the last value visible. `useQuery`, a route's `useQuery()` and a loader-backed editor’s `query` expose `denied: true` for `QueryReadDenied`, alongside the typed `cause`. Use this state to replace retained content with the application’s not-found screen after access is revoked. Refused live queries stay refused through change notifications until their input or viewer changes. For a loader-backed editor, spread the route's `useLoaded()`, which returns its atom as `query` and the loader value as `loaded`: `useEditor(api.save, { ...noteQuery.useLoaded(), fixed: { id } })`. Its form is defined on the first render and `editor.query.data` is the row directly. A loader written with `loadQuery` reads its atom with `useLoaderQuery(atom, route.useLoaderData())` from `@shivaedev/react/client/useLoaderQuery.ts`, which `useQuery()` uses underneath.
|
|
794
765
|
|
|
795
766
|
`loadQuery` mounts its query while the loader runs and, once it succeeds, for a five-second hand-over window measured on the bound query's atom runtime `Clock`. A component that mounts within the window continues the loader's subscription and its first result instead of opening another. A route that is left or never mounts releases the query when the window passes; from then on the bound query uses the same retention policy as component reads, including its expiry, capacity and session ownership. A route that mounts after the window shows that kept value while a new subscription revalidates it. A returning route whose bound query still has a kept result renders it immediately as stale. Readers without data suspend until their active loader completes. Failed loaders also release execution; the route keeps its error visible and Retry starts a new load. Already mounted readers keep their data during refreshes.
|
|
796
767
|
|
|
@@ -800,9 +771,9 @@ For a loader that coordinates more work, use `loadQuery(registry, atom, loaderCo
|
|
|
800
771
|
|
|
801
772
|
Permissions come from the session payload's `user.permissions`, populated by `@shivaedev/access` through the server's role policy. `can(session, permission)` uses access's grant evaluator without making a request: names match exactly, and an `any` grant covers an `own` check for that name. An `own` grant does not cover an `any` check. `useCan()` supplies the same check from the nearest `PermissionBoundary` for component controls. A signed-out session has no grants. These checks control visibility; the server still authorizes every request.
|
|
802
773
|
|
|
803
|
-
Declare a route's requirement in TanStack's native `staticData`: `signedIn: true` admits any signed-in viewer, and `permission` requires a specific grant. Routes that declare neither stay public. Install `permissionGuard` once as the root route's `beforeLoad`; it checks all matched routes before their loaders run, including requirements on parents. Signed-out visitors go to the
|
|
774
|
+
Declare a route's requirement in TanStack's native `staticData`: `signedIn: true` admits any signed-in viewer, and `permission` requires a specific grant. Routes that declare neither stay public. Install `permissionGuard` once as the root route's `beforeLoad`; it checks all matched routes before their loaders run, including requirements on parents. Signed-out visitors go to the guard's `signedOut` redirect; pass it the router's `redirects.signedOut` so the guard and query routes share one target. A signed-in session without a required grant throws the shared `Forbidden` failure. A signed-in-only parent does not bypass a child's permission requirement.
|
|
804
775
|
|
|
805
|
-
Set `permissionGuard({ session,
|
|
776
|
+
Set `permissionGuard({ session, signedOut, hidden: true })` to hide refused routes from signed-in members. The guard throws TanStack's native not-found result, renders the app's `notFoundComponent` at the requested URL and prevents the route's loader from running. Signed-out visitors still go to sign-in with their return location; sessions with the required grant still enter the route.
|
|
806
777
|
|
|
807
778
|
```tsx
|
|
808
779
|
import { RegistryContext } from "@effect/atom-react";
|
|
@@ -812,17 +783,23 @@ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
|
812
783
|
import { permission } from "@shivaedev/access/permission.ts";
|
|
813
784
|
import { Forbidden } from "@shivaedev/react/adapters/Forbidden.ts";
|
|
814
785
|
import { PermissionBoundary, PermissionBoundaryError, useCan } from "@shivaedev/react/adapters/permissionBoundary.ts";
|
|
815
|
-
import { useLoaderQuery } from "@shivaedev/react/client/useLoaderQuery.ts";
|
|
816
786
|
import { permissionGuard } from "@shivaedev/react/adapters/permissionGuard.ts";
|
|
787
|
+
import type { QueryRouteRedirects } from "@shivaedev/react/adapters/queryRouteFailure.ts";
|
|
788
|
+
import { signInRedirect } from "@shivaedev/react/adapters/signInRedirect.ts";
|
|
817
789
|
import type { PermissionSession } from "@shivaedev/identity/PermissionSession.ts";
|
|
818
790
|
import { can } from "@shivaedev/react/can.ts";
|
|
819
|
-
import { queryRoute } from "@shivaedev/react/adapters/queryRoute.ts";
|
|
791
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
820
792
|
import { api, registry } from "./notes-client.ts";
|
|
821
793
|
import { auth, SignIn } from "./auth.tsx";
|
|
822
794
|
|
|
823
795
|
const ReadNotes = permission("notes.read");
|
|
824
|
-
const root = createRootRouteWithContext<{
|
|
825
|
-
|
|
796
|
+
const root = createRootRouteWithContext<{
|
|
797
|
+
registry: AtomRegistry.AtomRegistry;
|
|
798
|
+
api: typeof api;
|
|
799
|
+
redirects: Required<Pick<QueryRouteRedirects, "signedOut">>;
|
|
800
|
+
session: PermissionSession | undefined;
|
|
801
|
+
}>()({
|
|
802
|
+
beforeLoad: ({ context, ...route }) => permissionGuard({ session: () => context.session, signedOut: context.redirects.signedOut })(route),
|
|
826
803
|
});
|
|
827
804
|
const profile = createRoute({
|
|
828
805
|
getParentRoute: () => root,
|
|
@@ -830,15 +807,17 @@ const profile = createRoute({
|
|
|
830
807
|
staticData: { signedIn: true },
|
|
831
808
|
component: () => <h1>Profile</h1>,
|
|
832
809
|
});
|
|
810
|
+
const noteQuery = queryRoute(
|
|
811
|
+
({ context, params }: { context: typeof root.types.allContext; params: { id: string }; search: Record<string, never> }) =>
|
|
812
|
+
context.api.get.query({ id: params.id, page: 1 }),
|
|
813
|
+
);
|
|
833
814
|
const note = createRoute({
|
|
834
815
|
getParentRoute: () => root,
|
|
835
816
|
path: "/notes/$id",
|
|
836
817
|
staticData: { permission: ReadNotes },
|
|
837
|
-
...
|
|
838
|
-
context.api.get.query({ id: params.id, page: 1 }),
|
|
839
|
-
),
|
|
818
|
+
...noteQuery,
|
|
840
819
|
component: () => {
|
|
841
|
-
const query =
|
|
820
|
+
const query = noteQuery.useQuery();
|
|
842
821
|
return <h1>{query.data.title}</h1>;
|
|
843
822
|
},
|
|
844
823
|
});
|
|
@@ -854,7 +833,7 @@ const login = createRoute({
|
|
|
854
833
|
},
|
|
855
834
|
});
|
|
856
835
|
const router = createRouter({
|
|
857
|
-
context: { registry, api, session: auth.session },
|
|
836
|
+
context: { registry, api, redirects: { signedOut: signInRedirect("/login") }, session: auth.session },
|
|
858
837
|
InnerWrap: PermissionShell,
|
|
859
838
|
defaultErrorComponent: PermissionBoundaryError,
|
|
860
839
|
routeTree: root.addChildren([profile, note, login]),
|
|
@@ -866,7 +845,7 @@ function Controls() {
|
|
|
866
845
|
return can(ReadNotes) ? <button type="button">Read notes</button> : null;
|
|
867
846
|
}
|
|
868
847
|
|
|
869
|
-
function PermissionShell({ children }: { readonly children: ReactNode })
|
|
848
|
+
function PermissionShell({ children }: { readonly children: ReactNode }) {
|
|
870
849
|
const session = useRouter<typeof router>().options.context?.session;
|
|
871
850
|
return (
|
|
872
851
|
<PermissionBoundary session={session} fallback={<NoAccess />}>
|
|
@@ -898,7 +877,7 @@ const showNotes = can(auth.session, ReadNotes);
|
|
|
898
877
|
|
|
899
878
|
`auth` owns the current session and passes it to `App`; `SignIn` updates that session before invoking `onSignedIn`. Use the session's registry for router context and React, as with other query routes. Importing `permissionGuard` augments TanStack's `StaticDataRouteOption`; route options and their inference remain native. The guard returns `void` explicitly, so `beforeLoad` needs no return annotation, including when it reads the session from route context.
|
|
900
879
|
|
|
901
|
-
`InnerWrap` puts `PermissionBoundary` inside the router
|
|
880
|
+
`InnerWrap` puts `PermissionBoundary` inside the router, and the boundary's fallback can render `Link` and read route context. TanStack types `InnerWrap` as a component that returns an element, so `PermissionShell` leaves its return type to inference; annotated as returning `ReactNode`, it does not compile. Set `defaultErrorComponent: PermissionBoundaryError` so route and loader failures reach the boundary's fallback while TanStack keeps its navigation controller mounted. This lets a refused viewer follow the fallback link without reloading the page. Keep `disableGlobalCatchBoundary: true`; other errors propagate to an enclosing application boundary. A route-specific `errorComponent` owns any failures it consumes.
|
|
902
881
|
|
|
903
882
|
`Forbidden` from `@shivaedev/react/adapters/Forbidden.ts` supplies the no-access heading, explanation and a router link. Set `to` to a route the viewer may open. Optional `title`, `children`, `backLabel` and `className` let the application choose wording and layout. The default heading is “Permission denied” and the link says “Go back”.
|
|
904
883
|
|
|
@@ -963,7 +942,7 @@ For other Better Auth reads, `authQuery` from `@shivaedev/react/client/authQuery
|
|
|
963
942
|
|
|
964
943
|
Pass the auth owner’s sign-out atom to `SessionBoundary` as `signOut={signOut}`. The boundary mounts it in the auth owner’s registry and unmounts the signed-in tree while sign-out is pending, including the following session refetch. A successful action keeps the tree held until the session clears; a failed action releases the hold. Supply an atom for the sign-out request itself, and give `recheck` the auth owner’s session refresh. After the request succeeds, the boundary starts that check and retries failures while holding the tree. A failed session check never releases a successful sign-out’s hold.
|
|
965
944
|
|
|
966
|
-
For an explicit sign-out in a TanStack route, use `useSignOut(signOut, { signIn: "/sign-in" })` from `@shivaedev/react/client/adapters/useSignOut.ts` in place of `useAction`. It exposes the same state and a `dispatch()` handler. The hook records sign-out intent before the request and navigates to sign-in after success. A refused request clears that intent, including when the boundary remounts its route. Repeated clicks while pending share one request and follow-up. Unmounting the component or disposing its registry stops the follow-up navigation. If a session refresh replaces the component before the response, the replacement session’s route policy owns navigation to sign-in. `
|
|
945
|
+
For an explicit sign-out in a TanStack route, use `useSignOut(signOut, { signIn: "/sign-in" })` from `@shivaedev/react/client/adapters/useSignOut.ts` in place of `useAction`. It exposes the same state and a `dispatch()` handler. The hook records sign-out intent before the request and navigates to sign-in after success. A refused request clears that intent, including when the boundary remounts its route. Repeated clicks while pending share one request and follow-up. Unmounting the component or disposing its registry stops the follow-up navigation. If a session refresh replaces the component before the response, the replacement session’s route policy owns navigation to sign-in. `signInRedirect` and `signInSearch(location)` omit `returnTo` for that intent, including when the auth owner's session refresh reruns guards first. Use `signInSearch` for module sign-in links too; ordinary visits retain the full requested location. Applications do not need history markers or Better Auth completion timing hooks.
|
|
967
946
|
|
|
968
947
|
### 3. Every day
|
|
969
948
|
|
|
@@ -971,13 +950,13 @@ These rules apply to each component and test you write.
|
|
|
971
950
|
|
|
972
951
|
#### Hook configuration between renders
|
|
973
952
|
|
|
974
|
-
`useCreate`
|
|
953
|
+
`useCreate` and `useEditor` call the latest committed render's operation `run` with that render's `fixed` values. Both hooks use the latest `failures` handlers when a save fails, including when a handler is removed to restore the default field mapping. An inline `run` or callback may close over changing props or state without replacing the form or losing edits.
|
|
975
954
|
|
|
976
|
-
Changing the `fields` schema or `runtime`
|
|
955
|
+
Changing the `fields` schema or the operation's `runtime` replaces either hook's form and discards its in-memory draft and submission state. A changed editor `query` also starts a new form. Keep schemas, runtimes and query atoms outside components or memoize them; constructing a schema on every render continually replaces the form.
|
|
977
956
|
|
|
978
|
-
`useEditor`, `useCreate` and the lower-level `submission` accept form’s `requiredMessages`, `checks`, `debounce` and `arrayKeys`. Required wording and checks use encoded field names and values; check services come from the
|
|
957
|
+
`useEditor`, `useCreate` and the lower-level `submission` accept form’s `requiredMessages`, `checks`, `debounce` and `arrayKeys`. Required wording and checks use encoded field names and values; check services come from the operation's runtime, and array key selectors receive encoded elements. Form owns check scheduling, stale feedback and keyed rejection tracking.
|
|
979
958
|
|
|
980
|
-
`initialValues` (create), `values` (editor), `persistedDraft`, `requiredMessages`, `checks`, `debounce` and `arrayKeys` are setup options, captured when the hook first creates a form and again when
|
|
959
|
+
`initialValues` (create), `values` (editor), `persistedDraft`, `requiredMessages`, `checks`, `debounce` and `arrayKeys` are setup options, captured when the hook first creates a form and again when its fields, `runtime` or editor `query` changes. Successful creates reuse the captured setup options for the next entry. Changing setup options alone does not replace an existing form; remount the component with a different React `key` to apply them. An editor's `loaded` value remains a fallback for query data, as with `useLoaderQuery`.
|
|
981
960
|
|
|
982
961
|
#### Resume and refresh policy
|
|
983
962
|
|
|
@@ -1081,22 +1060,49 @@ These lines belong inside a component; `text` and `ClipboardDenied` belong to th
|
|
|
1081
1060
|
|
|
1082
1061
|
#### Render tests in happy-dom
|
|
1083
1062
|
|
|
1084
|
-
Use `@shivaedev/test-story/client/adapters/react.ts` with Vitest's `happy-dom` environment. Install contract and
|
|
1063
|
+
Use `@shivaedev/test-story/client/adapters/react.ts` with Vitest's `happy-dom` environment. Install changes, contract and identity for the module's keys, operations, middleware and client binding, and the testing peers and environment in your app's dev dependencies:
|
|
1085
1064
|
|
|
1086
1065
|
```sh
|
|
1087
|
-
pnpm add @shivaedev/changes @shivaedev/contract
|
|
1066
|
+
pnpm add @shivaedev/changes @shivaedev/contract @shivaedev/identity
|
|
1088
1067
|
pnpm add -D @shivaedev/test-story @effect/platform-node @effect/vitest vitest happy-dom react-dom @types/react-dom
|
|
1089
1068
|
```
|
|
1090
1069
|
|
|
1091
|
-
Configure Vitest with `test: { environment: "happy-dom" }`, or select that environment for your DOM test project.
|
|
1070
|
+
Configure Vitest with `test: { environment: "happy-dom" }`, or select that environment for your DOM test project. The screen below reads a defined `notes` module, whose operations yield a `NoteTitles` service and run behind identity's `Authenticated` middleware:
|
|
1071
|
+
|
|
1072
|
+
```ts
|
|
1073
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
1074
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
1075
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
1076
|
+
import { notesWire } from "#generated/modules/notes/Notes.ts";
|
|
1077
|
+
import { NoteTitle, notes } from "#modules/notes/model.ts";
|
|
1078
|
+
import { NoteTitles } from "#modules/notes/services.ts";
|
|
1079
|
+
|
|
1080
|
+
const List = query("list", {
|
|
1081
|
+
reads: () => [notes.list],
|
|
1082
|
+
*run() {
|
|
1083
|
+
return yield* (yield* NoteTitles).all;
|
|
1084
|
+
},
|
|
1085
|
+
});
|
|
1086
|
+
const Add = command("add", {
|
|
1087
|
+
invalidates: () => [notes.list],
|
|
1088
|
+
payload: NoteTitle,
|
|
1089
|
+
*run({ title }) {
|
|
1090
|
+
yield* (yield* NoteTitles).add(title);
|
|
1091
|
+
},
|
|
1092
|
+
});
|
|
1093
|
+
export const Notes = defineModule({ middleware: Authenticated, name: "notes", operations: [List, Add], wire: notesWire });
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
`model.ts` declares `notes` as `collection("notes", Schema.Number)` and `NoteTitle` as `Schema.Struct({ title: Schema.String })`, and `services.ts` declares `NoteTitles` with an `all` Effect of titles and an `add(title)` method. Keep the engine, rendering and verbs in a story kit under `src/test-support/notesScreen.tsx`. This kit serves the module's own handlers from `moduleHandlers` over native RPC, with an in-memory `NoteTitles` and a fake `Authenticated` that signs alice in, binds the generated contract and gives the screen driver the registry's pending signal:
|
|
1092
1097
|
|
|
1093
1098
|
```tsx
|
|
1094
|
-
import { Effect, Layer, Option, Ref
|
|
1099
|
+
import { Effect, Layer, Option, Ref } from "effect";
|
|
1095
1100
|
import { act, createElement } from "react";
|
|
1096
|
-
import { collection } from "@shivaedev/changes/keys.ts";
|
|
1097
1101
|
import { makeClient } from "@shivaedev/contract/bind.ts";
|
|
1098
|
-
import {
|
|
1099
|
-
import {
|
|
1102
|
+
import { moduleHandlers } from "@shivaedev/contract/moduleHandlers.ts";
|
|
1103
|
+
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
1104
|
+
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
1105
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
1100
1106
|
import { layerMemoryProtocol } from "@shivaedev/test-kits/contract/testing.ts";
|
|
1101
1107
|
import { screenPending } from "@shivaedev/react/adapters/screenPending.ts";
|
|
1102
1108
|
import { useAction, useQuery } from "@shivaedev/react/client/resultState.ts";
|
|
@@ -1104,33 +1110,29 @@ import { render } from "@shivaedev/test-story/client/adapters/react.ts";
|
|
|
1104
1110
|
import { screenDriver } from "@shivaedev/test-story/server/screenDriver.ts";
|
|
1105
1111
|
import { storyKit } from "@shivaedev/test-story/server/storyKit.ts";
|
|
1106
1112
|
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
const Add = command("add", { invalidates: () => [notes.list], payload: { title: Schema.String } });
|
|
1111
|
-
const Notes = contract("notes", { commands: [Add], queries: [List] });
|
|
1113
|
+
import { Notes } from "#generated/modules/notes/Notes.ts";
|
|
1114
|
+
import { Notes as NotesModule } from "#modules/notes/Notes.ts";
|
|
1115
|
+
import { NoteTitles } from "#modules/notes/services.ts";
|
|
1112
1116
|
|
|
1113
1117
|
export const notesScreen = storyKit({
|
|
1114
1118
|
*create() {
|
|
1115
|
-
const
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
});
|
|
1123
|
-
}),
|
|
1119
|
+
const stored = yield* Ref.make<readonly string[]>([]);
|
|
1120
|
+
const titles = Layer.succeed(NoteTitles, {
|
|
1121
|
+
add: (title) => Ref.update(stored, (all) => [...all, title]),
|
|
1122
|
+
all: Ref.get(stored),
|
|
1123
|
+
});
|
|
1124
|
+
const signedIn = Layer.succeed(Authenticated, (effect) =>
|
|
1125
|
+
effect.pipe(Effect.provideService(CurrentViewer, Option.some({ id: "alice" })), Effect.provideService(Identity, { id: "alice" })),
|
|
1124
1126
|
);
|
|
1125
|
-
const
|
|
1127
|
+
const handlers = moduleHandlers(NotesModule).pipe(Layer.provide(titles));
|
|
1128
|
+
const { api } = makeClient(Notes, {
|
|
1126
1129
|
live: false,
|
|
1127
|
-
protocol: layerMemoryProtocol(
|
|
1130
|
+
protocol: layerMemoryProtocol(NotesModule.application).pipe(Layer.provide([handlers, signedIn])),
|
|
1128
1131
|
url: "memory://notes",
|
|
1129
1132
|
});
|
|
1130
|
-
const add = Client.runtime.fn(api.add.run);
|
|
1131
1133
|
function NotesView() {
|
|
1132
1134
|
const list = useQuery(api.list.query());
|
|
1133
|
-
const
|
|
1135
|
+
const add = useAction(api.add);
|
|
1134
1136
|
return createElement(
|
|
1135
1137
|
"section",
|
|
1136
1138
|
null,
|
|
@@ -1138,8 +1140,8 @@ export const notesScreen = storyKit({
|
|
|
1138
1140
|
createElement(
|
|
1139
1141
|
"button",
|
|
1140
1142
|
{
|
|
1141
|
-
disabled: list.pending ||
|
|
1142
|
-
onClick: () =>
|
|
1143
|
+
disabled: list.pending || add.pending,
|
|
1144
|
+
onClick: () => add.dispatch({ title: "Morning walk" }),
|
|
1143
1145
|
type: "button",
|
|
1144
1146
|
},
|
|
1145
1147
|
"Add",
|
|
@@ -1193,7 +1195,7 @@ notesScreen.it("a command refetches the rendered notes through native RPC", [],
|
|
|
1193
1195
|
|
|
1194
1196
|
`render(node, options?)` returns the attached `container`, its fresh native `registry`, `render(nextNode)` to update the same root and registry, and `unmount()` to release the root, registry and container. The options are React's own `RootOptions`, passed to `createRoot`, including `onCaughtError`, `onUncaughtError` and `onRecoverableError`. Acquire the view with `Effect.acquireRelease` so its scope releases it on success, failure or interruption. The screen driver's `act` adapter keeps component interactions and settling inside React's `act`. `expectNoReactWarnings()` registers a Vitest hook that fails a test if it logged to `console.error`.
|
|
1195
1197
|
|
|
1196
|
-
The
|
|
1198
|
+
The kit runs the module's real operations, read policies included, and replaces only the service they yield and the session. `moduleHandlers` requires exactly the services the operations yield beyond the middleware, so the compiler names one the kit forgets. The fake middleware provides the viewer the default `signedIn` policy checks and the `Identity` the operations may yield; without a viewer, the list answers `QueryReadDenied`. The starter's [notes screen kit](https://github.com/ShivaeDev/platform/blob/main/examples/starter/src/modules/notes/test-support/client.ts) fakes its middleware the same way. A story about persistence or the real session runs the operations through the application host, as the starter's application kit does.
|
|
1197
1199
|
|
|
1198
1200
|
For a boundary fallback test, keep the warnings guard and declare the caught error inside the test. `expectCaughtError(predicate)` returns an `onCaughtError` handler that accepts matching errors without logging them. The guard fails if the handler receives any other error or the expected error never arrives. Other console errors and React warnings still fail the guard.
|
|
1199
1201
|
|
|
@@ -1232,11 +1234,11 @@ const screen = screenDriver({ act, pending, root: view.container, tell: story.te
|
|
|
1232
1234
|
| `pending` | The native result is waiting. |
|
|
1233
1235
|
| `refreshing` | The result is waiting and successful data is available. |
|
|
1234
1236
|
|
|
1235
|
-
`useQuery(atom, options?)` adds `refresh(): void`; `useAction` adds `dispatch(input): void`. `QueryOptions.notice` publishes a notice descriptor for a failed result. `QueryOptions.keepPreviousData` defaults to `false` and controls retention across query atom changes. Same-identity refresh retention is always enabled. `result` and `cause` describe the current native query even when `data` displays a previous atom's success. Success, input and typed failure types are inferred from the supplied atom.
|
|
1237
|
+
`useQuery(atom, options?)` adds `refresh(): void`; `useAction` adds `dispatch(input): void`. `QueryOptions.notice` publishes a notice descriptor for a failed result. `QueryOptions.keepPreviousData` defaults to `false` and controls retention across query atom changes. Same-identity refresh retention is always enabled. `result` and `cause` describe the current native query even when `data` displays a previous atom's success. Success, input and typed failure types are inferred from the supplied atom. `useAction(atom)` takes a native action atom and publishes nothing; its failures stay in `cause`. `useAction(operation, options)` takes a bound command or `{ run, runtime }`, and its options supply `concurrent`, `notices.onSuccess`, `failures`, `silent`, `onSuccess(value, input)` and `onFailure(error, input)`; the options may be left out when the operation has no rejection of the app's own. Its shared state also includes the runtime's typed failure.
|
|
1236
1238
|
|
|
1237
1239
|
Import the defining `.ts` module, such as `@shivaedev/react/client/editor.ts`. There is no root import. `useSessionRecheck()` from `client/sessionBoundary.ts` requests the boundary’s shared session check.
|
|
1238
1240
|
|
|
1239
|
-
Prefer `useEditor` and `useCreate` when binding a form to a command. The lower-level modules expose the same composition pieces: `submission` from `submission.ts` makes a form and its submission snapshot reader, `rejecting` from `@shivaedev/form/fieldRejection.ts` maps save failures through a submitter, and `useSaveState` from `client/saveState.ts` observes submission and invokes a success callback.
|
|
1241
|
+
Prefer `useEditor` and `useCreate` when binding a form to a command. The lower-level modules expose the same composition pieces: `submission` from `submission.ts` makes a form and its submission snapshot reader, `rejecting` from `@shivaedev/form/fieldRejection.ts` maps save failures through a submitter, and `useSaveState` from `client/saveState.ts` observes submission and invokes a success callback. `FieldRejection`, `RejectField` and `fieldRejectionOf` also belong to `@shivaedev/form/fieldRejection.ts`; `AtomServices` belongs to `AtomServices.ts`.
|
|
1240
1242
|
|
|
1241
1243
|
### Install, setup and limits
|
|
1242
1244
|
|
|
@@ -1250,7 +1252,7 @@ pnpm add @shivaedev/react @effect/atom-react effect react
|
|
|
1250
1252
|
pnpm add @shivaedev/form
|
|
1251
1253
|
```
|
|
1252
1254
|
|
|
1253
|
-
Add the optional router peer when using `queryRoute`, `loadQuery`, `permissionGuard`, `PermissionBoundary`, `PermissionBoundaryError`, `Forbidden` or `useSignOut`:
|
|
1255
|
+
Add the optional router peer when using `queryRoute`, `loadQuery`, `permissionGuard`, `signInRedirect`, `PermissionBoundary`, `PermissionBoundaryError`, `Forbidden` or `useSignOut`:
|
|
1254
1256
|
|
|
1255
1257
|
```sh
|
|
1256
1258
|
pnpm add @tanstack/react-router
|