@shivaedev/react 0.49.2 → 0.50.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 +20 -0
- package/README.md +83 -116
- 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/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/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/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/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/noticeEntry.ts +5 -0
- package/src/noticeStore.ts +9 -4
- package/src/noticeTypes.ts +1 -2
- package/src/submission.ts +4 -6
- 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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.50.0 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `NoticeHost` takes `failure(unexpected)`, the application's one wording for a lost connection, a server outage, an `InternalServerError`, a defect or an untagged failure, called once per failed invocation. Without it the host shows `Could not reach the server. Check your connection and try again.`, the server's redacted message, or `Something went wrong. Try again.`, never a cause. Without `render`, notices render with `role="alert"` or `role="status"` and a Dismiss button. A `Notice` carries `kind`: `"success"`, `"rejection"` or `"failure"`.
|
|
8
|
+
- `QueryViewDefaults` in `client/QueryView.ts` sets the application's default `failure` and `loading` rendering for every `QueryView` below it.
|
|
9
|
+
- `useCreate` and `useEditor` take their form fields from the command's payload schema when `fields` is omitted, and `useEditor` fills its inputs by encoding each row with those fields when `values` is omitted. `fixed` supplies the payload fields the form does not edit, and every save sends `{ ...fixed, ...values }`. `fixed` and the form's fields must cover the payload exactly: a missing key, a key outside the payload or a value of the wrong type does not compile, and the error names the key. Passing a bound query where a command belongs reports `a bound query only reads: read it with useQuery, and pass a command here`.
|
|
10
|
+
|
|
11
|
+
### Breaking
|
|
12
|
+
|
|
13
|
+
- a bound command given to `useAction`, `usePendingCommand` or `useUndoableChange`, and the save of `useCreate` or `useEditor`, now show their failures without screen code. A shared rejection from `@shivaedev/errors/taxonomy.ts` publishes its server message through the mounted `NoticeHost`; a rejection whose `field` names a form field still lands on that field; `Unauthorized` still rechecks the session and now also shows its message; interrupted work publishes nothing. Delete screen-local alerts that only repeated the message, such as `{Option.isSome(editor.failure) && <p role="alert">{editor.failure.value.message}</p>}`.
|
|
14
|
+
- `notices.onFailure` and `rejectField` are removed in favour of one per-tag `failures` option. Before: `useAction(api.remove, { notices: { onFailure: () => ({ message: "Could not remove" }) } })`. After: `useAction(api.remove, { failures: { Conflict: couldNotRemove } })` with `function couldNotRemove() { return { message: "Could not remove" }; }` declared outside the component, or leave it out to show the server's message. Before: `useEditor(api.retitle, { query, fixed: { id }, rejectField: (error) => ({ field: "title", message: error.message }) })`. After: `useEditor(api.retitle, { query, fixed: { id }, failures: { SubtitleRejected: onTitle } })` with `function onTitle(error: SubtitleRejected) { return { field: "title" as const, message: error.message }; }` declared outside the component, because Biome's `noNestedComponentDefinitions` reads a one-parameter function under a PascalCase key inside a component as a component. A handler receives the error and the invocation's input and returns a notice descriptor, a field rejection (form hooks only) or `"silent"`; `"message"` shows the error's own message and `"silent"` shows nothing for that tag. `silent: true` shows nothing for any failure of the call.
|
|
15
|
+
- a command or save that can fail with a rejection the application declared for itself does not compile until `failures` names it; the error names the tag, for example `Property '"failures.SubtitleRejected"' is missing`. Add `failures: { SubtitleRejected: "message" }`, or a handler, to each such call.
|
|
16
|
+
- `QueryView`'s `loading` and `failure` are optional. Without them the view renders the application's `QueryViewDefaults`, or a `Loading…` status and the failure's message with a Retry button that calls `refresh`. A query that can fail with an application-declared rejection still requires `failure`. Remove `loading` and `failure` renderers that repeated the default.
|
|
17
|
+
- `useAction` takes the bound command instead of a runtime and its `run`. The plain action atom form `useAction(atom)` is unchanged. Before: `useAction(NotesClient.runtime, api.remove.run, { onSuccess })`. After: `useAction(api.remove, { onSuccess })`. For an Effect that is not a single bound command, pass `{ run, runtime }`: `useAction({ run: save, runtime: NotesClient.runtime })`.
|
|
18
|
+
- `useCreate` takes the operation first and its options second; the `create` and `runtime` options are gone, and `fields` is optional. Before: `useCreate({ fields: NoteFields, initialValues: { title: "" }, create: api.create.run, runtime: NotesClient.runtime })`. After: `useCreate(api.create, { initialValues: { title: "" } })`. Keep `fields` when an input holds another encoding than the payload, such as `Schema.NumberFromString` for a number typed as text.
|
|
19
|
+
- `useEditor` takes the operation first and its options second; the `save` and `runtime` options are gone, and `fields` and `values` are optional. Before: `useEditor({ query: api.get.query({ id }), fields: NoteFields, values: (note) => ({ title: note.title }), save: (values) => api.update.run({ id, ...values }), runtime: NotesClient.runtime })`. After: `useEditor(api.update, { query: api.get.query({ id }), fixed: { id } })`. Pass `values(row)` when the row's shape differs from the fields; a payload field the row lacks, such as an expected version, goes in `fixed`. A save that composes several Effects passes `{ run, runtime }` as the operation: `useEditor({ run: (values) => save(id, values), runtime }, { fields, query, values })`.
|
|
20
|
+
- `useUndoableChange` and `usePendingCommand` take the bound command itself, and `useUndoableChange` takes `update` in its options. Before: `useUndoableChange({ ...api.change, runtime: NotesClient.runtime, update }, { describe })` and `usePendingCommand({ ...api.toggle, runtime: ItemsClient.runtime }, { value, wanted })`. After: `useUndoableChange(api.change, { describe, update })` and `usePendingCommand(api.toggle, { value, wanted })`. The `VersionedChangeCommand` and `PendingCommand` types are removed; both hooks accept any `{ run, runtime }`.
|
|
21
|
+
- the `CreateConfig` and `EditorConfig` types are now `CreateOptions` and `EditorOptions`, without the operation's members.
|
|
22
|
+
|
|
3
23
|
## 0.49.2 - 2026-11-20
|
|
4
24
|
|
|
5
25
|
### Changed
|
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,7 +265,9 @@ 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
|
|
|
@@ -304,7 +295,7 @@ An action's `dispatch(input)` returns `void`. Read the atom's latest result from
|
|
|
304
295
|
|
|
305
296
|
#### An editor and a create form
|
|
306
297
|
|
|
307
|
-
The next module assumes a sibling `invoice-lines-client.ts` exports a contract-bound `api` with `get`, `save` and `create
|
|
298
|
+
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
299
|
|
|
309
300
|
```tsx
|
|
310
301
|
import { useCreate } from "@shivaedev/react/client/create.ts";
|
|
@@ -313,7 +304,7 @@ import { QueryView } from "@shivaedev/react/client/QueryView.ts";
|
|
|
313
304
|
import { useField } from "@shivaedev/form/adapters/react.ts";
|
|
314
305
|
import type { Form } from "@shivaedev/form/shape.ts";
|
|
315
306
|
import { Option, Schema } from "effect";
|
|
316
|
-
import { api
|
|
307
|
+
import { api } from "./invoice-lines-client.ts";
|
|
317
308
|
|
|
318
309
|
const InvoiceLineFields = Schema.Struct({
|
|
319
310
|
name: Schema.String,
|
|
@@ -341,25 +332,10 @@ function Inputs<A, E, ER>({ form }: { readonly form: Form<Fields, A, E, ER> }) {
|
|
|
341
332
|
}
|
|
342
333
|
|
|
343
334
|
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
|
-
});
|
|
335
|
+
const editor = useEditor(api.save, { query: api.get.query({ id }), fields: InvoiceLineFields, fixed: { id } });
|
|
351
336
|
return (
|
|
352
337
|
<QueryView
|
|
353
338
|
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
339
|
content={() =>
|
|
364
340
|
editor.form && (
|
|
365
341
|
<form
|
|
@@ -369,7 +345,6 @@ export function InvoiceLineEditor({ id }: { readonly id: number }) {
|
|
|
369
345
|
}}
|
|
370
346
|
>
|
|
371
347
|
<Inputs form={editor.form} />
|
|
372
|
-
{Option.isSome(editor.cause) && <p role="alert">Could not save</p>}
|
|
373
348
|
<button type="submit" disabled={editor.saving}>
|
|
374
349
|
Save
|
|
375
350
|
</button>
|
|
@@ -388,12 +363,7 @@ export function InvoiceLineEditor({ id }: { readonly id: number }) {
|
|
|
388
363
|
}
|
|
389
364
|
|
|
390
365
|
export function InvoiceLineCreate() {
|
|
391
|
-
const create = useCreate({
|
|
392
|
-
fields: InvoiceLineFields,
|
|
393
|
-
initialValues: { name: "", quantity: "" },
|
|
394
|
-
create: api.create.run,
|
|
395
|
-
runtime: InvoiceLinesClient.runtime,
|
|
396
|
-
});
|
|
366
|
+
const create = useCreate(api.create, { fields: InvoiceLineFields, initialValues: { name: "", quantity: "" } });
|
|
397
367
|
return (
|
|
398
368
|
<form
|
|
399
369
|
onSubmit={(event) => {
|
|
@@ -402,7 +372,6 @@ export function InvoiceLineCreate() {
|
|
|
402
372
|
}}
|
|
403
373
|
>
|
|
404
374
|
<Inputs form={create.form} />
|
|
405
|
-
{Option.isSome(create.cause) && <p role="alert">Could not create</p>}
|
|
406
375
|
<button type="submit" disabled={create.saving}>
|
|
407
376
|
Create
|
|
408
377
|
</button>
|
|
@@ -412,7 +381,13 @@ export function InvoiceLineCreate() {
|
|
|
412
381
|
}
|
|
413
382
|
```
|
|
414
383
|
|
|
415
|
-
|
|
384
|
+
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`.
|
|
385
|
+
|
|
386
|
+
`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`.
|
|
387
|
+
|
|
388
|
+
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.
|
|
389
|
+
|
|
390
|
+
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
391
|
|
|
417
392
|
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
393
|
|
|
@@ -422,7 +397,7 @@ A successful create replaces its form with one at `initialValues`, keeping field
|
|
|
422
397
|
|
|
423
398
|
#### One-shot create and edit
|
|
424
399
|
|
|
425
|
-
Use `useCreate` when the app already has the opening values and needs one submission.
|
|
400
|
+
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
401
|
|
|
427
402
|
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
403
|
|
|
@@ -440,16 +415,10 @@ type VersionedLine = {
|
|
|
440
415
|
|
|
441
416
|
export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedLine; readonly onSaved: (line: VersionedLine) => void }) {
|
|
442
417
|
const [original] = useState(opening);
|
|
443
|
-
const edit = useCreate({
|
|
418
|
+
const edit = useCreate(api.save, {
|
|
444
419
|
fields: InvoiceLineFields,
|
|
420
|
+
fixed: { id: original.id, expectedVersion: original.version },
|
|
445
421
|
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
422
|
});
|
|
454
423
|
useEffect(() => {
|
|
455
424
|
if (Option.isSome(edit.created)) onSaved(edit.created.value);
|
|
@@ -462,9 +431,6 @@ export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedL
|
|
|
462
431
|
}}
|
|
463
432
|
>
|
|
464
433
|
<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
434
|
<button type="submit" disabled={edit.saving}>
|
|
469
435
|
Save
|
|
470
436
|
</button>
|
|
@@ -473,37 +439,45 @@ export function OneShotEdit({ opening, onSaved }: { readonly opening: VersionedL
|
|
|
473
439
|
}
|
|
474
440
|
```
|
|
475
441
|
|
|
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
|
|
442
|
+
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
443
|
|
|
478
444
|
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
445
|
|
|
480
|
-
####
|
|
446
|
+
#### Failures of commands and saves
|
|
481
447
|
|
|
482
|
-
A
|
|
448
|
+
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
449
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
450
|
+
- 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.
|
|
451
|
+
- 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.
|
|
452
|
+
- 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.
|
|
453
|
+
- A rejection the app declared for itself has no default. The call does not compile until `failures` says what it shows.
|
|
454
|
+
- Interrupted work shows nothing.
|
|
455
|
+
|
|
456
|
+
`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.
|
|
457
|
+
|
|
458
|
+
```tsx
|
|
459
|
+
function onTitle(error: SubtitleRejected) {
|
|
460
|
+
return { field: "title" as const, message: error.message };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function Retitle({ id }: { readonly id: number }) {
|
|
464
|
+
const editor = useEditor(api.retitle, { query: api.get.query({ id }), fixed: { id }, failures: { SubtitleRejected: onTitle } });
|
|
465
|
+
return <TitleForm form={editor.form} save={editor.save} />;
|
|
466
|
+
}
|
|
495
467
|
```
|
|
496
468
|
|
|
497
|
-
Here `
|
|
469
|
+
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. Declare a handler that takes only the error outside the component, as `onTitle` is here, or give it the input as a second parameter: Biome's `noNestedComponentDefinitions` and `noComponentHookFactories`, which Quality's preset enables, read a function of at most one parameter under a PascalCase key inside a component or hook as a component definition. 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.
|
|
470
|
+
|
|
471
|
+
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
472
|
|
|
499
473
|
#### Query, command and form feedback
|
|
500
474
|
|
|
501
|
-
Use `useQuery` with `QueryView` for reads,
|
|
475
|
+
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
476
|
|
|
503
|
-
|
|
477
|
+
`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
478
|
|
|
505
479
|
```ts
|
|
506
|
-
const remove = useAction(
|
|
480
|
+
const remove = useAction(api.remove, {
|
|
507
481
|
concurrent: true,
|
|
508
482
|
notices: {
|
|
509
483
|
onSuccess: (removed, input) => ({
|
|
@@ -517,12 +491,11 @@ const remove = useAction(OrdersClient.runtime, api.remove.run, {
|
|
|
517
491
|
}),
|
|
518
492
|
},
|
|
519
493
|
}),
|
|
520
|
-
onFailure: () => ({ message: "Could not remove this order" }),
|
|
521
494
|
},
|
|
522
495
|
});
|
|
523
496
|
```
|
|
524
497
|
|
|
525
|
-
`
|
|
498
|
+
`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
499
|
|
|
527
500
|
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
501
|
|
|
@@ -534,16 +507,13 @@ const notes = useQuery(api.list.query(), {
|
|
|
534
507
|
message: refreshing ? "Refresh failed" : "Load failed",
|
|
535
508
|
}),
|
|
536
509
|
});
|
|
537
|
-
const save = useCreate({
|
|
538
|
-
fields: TitleFields,
|
|
510
|
+
const save = useCreate(api.save, {
|
|
539
511
|
initialValues: { title: "" },
|
|
540
|
-
create: api.save.run,
|
|
541
|
-
runtime: NotesClient.runtime,
|
|
542
512
|
notices: { onSuccess: (title) => ({ message: `Saved ${title}` }) },
|
|
543
513
|
});
|
|
544
514
|
```
|
|
545
515
|
|
|
546
|
-
Here `api
|
|
516
|
+
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
517
|
|
|
548
518
|
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
519
|
|
|
@@ -551,37 +521,36 @@ A descriptor has `message`, optional `expiresIn` as a native Duration, and optio
|
|
|
551
521
|
|
|
552
522
|
#### Completion inside each command invocation
|
|
553
523
|
|
|
554
|
-
Pass the
|
|
524
|
+
Pass the bound command to `useAction` when the screen needs feedback for each invocation:
|
|
555
525
|
|
|
556
526
|
```tsx
|
|
557
|
-
const rename = useAction(
|
|
527
|
+
const rename = useAction(api.rename, {
|
|
558
528
|
notices: {
|
|
559
529
|
onSuccess: (saved, input) => ({ message: `Renamed ${input.id} to ${saved.title}` }),
|
|
560
|
-
onFailure: (_error, input) => ({ message: `Could not rename ${input.id}` }),
|
|
561
530
|
},
|
|
562
531
|
});
|
|
563
532
|
```
|
|
564
533
|
|
|
565
|
-
`
|
|
534
|
+
`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
535
|
|
|
567
|
-
The command's identity is the native action atom, or the `run` function
|
|
536
|
+
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
537
|
|
|
569
538
|
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
539
|
|
|
571
540
|
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
541
|
|
|
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.
|
|
542
|
+
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
543
|
|
|
575
544
|
#### Remove with a version-guarded Undo
|
|
576
545
|
|
|
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`.
|
|
546
|
+
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
547
|
|
|
579
548
|
```tsx
|
|
580
549
|
import { Option } from "effect";
|
|
581
550
|
import { useUndoableChange } from "@shivaedev/react/client/adapters/useUndoableChange.ts";
|
|
582
551
|
|
|
583
552
|
function RemoveNote({ note }: { readonly note: { id: string; version: number } }) {
|
|
584
|
-
const change = useUndoableChange(
|
|
553
|
+
const change = useUndoableChange(api.change, { describe: (saved) => `Removed ${saved.id}`, update });
|
|
585
554
|
const notice = Option.getOrUndefined(change.notice);
|
|
586
555
|
return (
|
|
587
556
|
<>
|
|
@@ -604,34 +573,32 @@ function RemoveNote({ note }: { readonly note: { id: string; version: number } }
|
|
|
604
573
|
}
|
|
605
574
|
```
|
|
606
575
|
|
|
607
|
-
`api`,
|
|
576
|
+
`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
577
|
|
|
609
578
|
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
579
|
|
|
611
580
|
```tsx
|
|
612
|
-
const change = useUndoableChange(
|
|
613
|
-
|
|
614
|
-
{
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
},
|
|
618
|
-
);
|
|
581
|
+
const change = useUndoableChange(api.editEntries, {
|
|
582
|
+
describe: () => "Changed diary entries",
|
|
583
|
+
undoInput: (saved) => ({ _tag: "undo" as const, token: saved.undo }),
|
|
584
|
+
update,
|
|
585
|
+
});
|
|
619
586
|
change.remove({ _tag: "edit", rows: selectedVersions, scale: 0.5, copies: true });
|
|
620
587
|
```
|
|
621
588
|
|
|
622
|
-
`api.editEntries
|
|
589
|
+
`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
590
|
|
|
624
591
|
`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
592
|
|
|
626
593
|
#### Commands with a pending display value
|
|
627
594
|
|
|
628
|
-
Use `usePendingCommand` for a command acting on a query row, such as a list toggle. Pass the bound command
|
|
595
|
+
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
596
|
|
|
630
597
|
```tsx
|
|
631
598
|
import { usePendingCommand } from "@shivaedev/react/client/pendingCommand.ts";
|
|
632
599
|
|
|
633
600
|
function EnabledToggle({ row }: { readonly row: { readonly id: number; readonly enabled: boolean } }) {
|
|
634
|
-
const command = usePendingCommand(
|
|
601
|
+
const command = usePendingCommand(api.toggle, { value: row.enabled, wanted: (input) => input.enabled });
|
|
635
602
|
return (
|
|
636
603
|
<button
|
|
637
604
|
aria-pressed={command.value}
|
|
@@ -645,7 +612,7 @@ function EnabledToggle({ row }: { readonly row: { readonly id: number; readonly
|
|
|
645
612
|
}
|
|
646
613
|
```
|
|
647
614
|
|
|
648
|
-
The example assumes a bound `api.toggle`
|
|
615
|
+
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
616
|
|
|
650
617
|
`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
618
|
|
|
@@ -790,7 +757,7 @@ For a loader that coordinates more work, use `loadQuery(registry, atom, loaderCo
|
|
|
790
757
|
|
|
791
758
|
`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
759
|
|
|
793
|
-
`useLoaderQuery(atom, route.useLoaderData())` subscribes to the same atom and exposes `data` as its success type, with no `Option` or Initial result. Refetches keep the last value visible. `useQuery`, `useLoaderQuery` 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, pass the loader value as `useEditor({ ...
|
|
760
|
+
`useLoaderQuery(atom, route.useLoaderData())` subscribes to the same atom and exposes `data` as its success type, with no `Option` or Initial result. Refetches keep the last value visible. `useQuery`, `useLoaderQuery` 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, pass the loader value as `useEditor(api.save, { ...options, loaded: route.useLoaderData() })`; its form is defined on the first render and `editor.query.data` is the row directly.
|
|
794
761
|
|
|
795
762
|
`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
763
|
|
|
@@ -971,13 +938,13 @@ These rules apply to each component and test you write.
|
|
|
971
938
|
|
|
972
939
|
#### Hook configuration between renders
|
|
973
940
|
|
|
974
|
-
`useCreate`
|
|
941
|
+
`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
942
|
|
|
976
|
-
Changing the `fields` schema or `runtime`
|
|
943
|
+
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
944
|
|
|
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
|
|
945
|
+
`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
946
|
|
|
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
|
|
947
|
+
`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
948
|
|
|
982
949
|
#### Resume and refresh policy
|
|
983
950
|
|
|
@@ -1232,11 +1199,11 @@ const screen = screenDriver({ act, pending, root: view.container, tell: story.te
|
|
|
1232
1199
|
| `pending` | The native result is waiting. |
|
|
1233
1200
|
| `refreshing` | The result is waiting and successful data is available. |
|
|
1234
1201
|
|
|
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.
|
|
1202
|
+
`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
1203
|
|
|
1237
1204
|
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
1205
|
|
|
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.
|
|
1206
|
+
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
1207
|
|
|
1241
1208
|
### Install, setup and limits
|
|
1242
1209
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FailureHostContext.d.ts","sourceRoot":"","sources":["../../src/client/FailureHostContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEtE,eAAO,MAAM,kBAAkB,qCAA4B,iBAAiB,KAAK,IAAI,cAAyB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FailureHostContext.js","sourceRoot":"","sources":["../../src/client/FailureHostContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAGtC,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAqD,SAAS,CAAC,CAAC"}
|
|
@@ -3,6 +3,6 @@ export declare const NoticeContext: import("react").Context<{
|
|
|
3
3
|
active: boolean;
|
|
4
4
|
close: () => void;
|
|
5
5
|
entries: import("effect/reactivity/Atom").Writable<readonly import("../noticeEntry.ts").NoticeEntry<ReactNode>[], readonly import("../noticeEntry.ts").NoticeEntry<ReactNode>[]>;
|
|
6
|
-
publish: (descriptor: Pick<import("../noticeTypes.ts").NoticeDescriptor<never, ReactNode>, "expiresIn" | "message">, action?: import("../noticeEntry.ts").NoticeAction<ReactNode> | undefined) => void;
|
|
6
|
+
publish: (descriptor: Pick<import("../noticeTypes.ts").NoticeDescriptor<never, ReactNode>, "expiresIn" | "message">, kind: import("../noticeEntry.ts").NoticeKind, action?: import("../noticeEntry.ts").NoticeAction<ReactNode> | undefined) => void;
|
|
7
7
|
} | undefined>;
|
|
8
8
|
//# sourceMappingURL=NoticeContext.d.ts.map
|
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
+
import type { Unhandled } from "#client/failures.ts";
|
|
2
3
|
import type { QueryState } from "#client/resultState.ts";
|
|
3
|
-
export interface
|
|
4
|
+
export interface QueryViewRenderers {
|
|
5
|
+
readonly failure: (error: unknown, query: QueryState<unknown, unknown>) => ReactNode;
|
|
6
|
+
readonly loading: (query: QueryState<unknown, unknown>) => ReactNode;
|
|
7
|
+
}
|
|
8
|
+
export declare function queryFailureMessage(error: unknown): string;
|
|
9
|
+
export declare const defaultQueryViewRenderers: QueryViewRenderers;
|
|
10
|
+
export declare function QueryViewDefaults({ children, failure, loading }: Partial<QueryViewRenderers> & {
|
|
11
|
+
readonly children: ReactNode;
|
|
12
|
+
}): ReactNode;
|
|
13
|
+
type FailureRenderer<A, E> = (error: E, query: QueryState<A, E>) => ReactNode;
|
|
14
|
+
export type QueryViewProps<A, E> = {
|
|
4
15
|
readonly content: (data: A, query: QueryState<A, E>) => ReactNode;
|
|
5
|
-
readonly
|
|
6
|
-
readonly loading: (query: QueryState<A, E>) => ReactNode;
|
|
16
|
+
readonly loading?: ((query: QueryState<A, E>) => ReactNode) | undefined;
|
|
7
17
|
readonly query: QueryState<A, E>;
|
|
8
|
-
}
|
|
9
|
-
|
|
18
|
+
} & ([Unhandled<E>] extends [never] ? {
|
|
19
|
+
readonly failure?: FailureRenderer<A, E> | undefined;
|
|
20
|
+
} : {
|
|
21
|
+
readonly failure: FailureRenderer<A, E>;
|
|
22
|
+
});
|
|
23
|
+
export declare function QueryView<A, E>(props: QueryViewProps<A, E>): ReactNode;
|
|
24
|
+
export {};
|
|
10
25
|
//# sourceMappingURL=QueryView.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryView.d.ts","sourceRoot":"","sources":["../../src/client/QueryView.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"QueryView.d.ts","sourceRoot":"","sources":["../../src/client/QueryView.ts"],"names":[],"mappings":"AACA,OAAO,EAA0C,KAAK,SAAS,EAAc,MAAM,OAAO,CAAC;AAG3F,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,SAAS,CAAC;IACrF,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,SAAS,CAAC;CACrE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAI1D;AAED,eAAO,MAAM,yBAAyB,EAAE,kBAUvC,CAAC;AAKF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAA;CAAE,GAAG,SAAS,CAO3I;AAED,KAAK,eAAe,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;AAG9E,MAAM,MAAM,cAAc,CAAC,CAAC,EAAE,CAAC,IAAI;IAClC,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;IAClE,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,GAAG,SAAS,CAAC;IACxE,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CACjC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,SAAS,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;CAAE,CAAC,CAAC;AAE9I,wBAAgB,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,SAAS,CAgBtE"}
|