@runic-artifex/react 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -26
- package/dist/index.d.ts +120 -6
- package/dist/index.js +151 -10
- package/dist/suspense.d.ts +8 -1
- package/dist/suspense.js +8 -5
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -48,14 +48,25 @@ replaces `client.dispose()` for a client the hook connected, for example to keep
|
|
|
48
48
|
a client alive in a cache:
|
|
49
49
|
|
|
50
50
|
- A generated page reference, or `{ connect: connect<Name> }` for a root
|
|
51
|
-
ViewModel, is connected while the component is mounted
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
ViewModel, is connected while the component is mounted. A reference is
|
|
52
|
+
identified by its `connect` function, so an inline
|
|
53
|
+
`{ connect: connectWorkspace }` does not reconnect.
|
|
54
|
+
- When the component unmounts or the reference changes, the client stays
|
|
55
|
+
connected for `options.keepAlive` milliseconds (2000 by default), and the
|
|
56
|
+
next `useView` of the same reference takes it over with its state. StrictMode's
|
|
57
|
+
second mount, Fast Refresh, `<Activity>` and A→B→A navigation therefore
|
|
58
|
+
neither flash "Connecting…" nor remount a `ViewOutlet` subtree nor open the
|
|
59
|
+
route again; a component that mounts while its reference's client is kept
|
|
60
|
+
renders the state in its first render. `keepAlive: 0` disposes at once.
|
|
61
|
+
Kept clients are handed over, not shared: two mounted components of the same
|
|
62
|
+
reference have a client each.
|
|
54
63
|
- An already connected client is observed and left to its owner.
|
|
55
64
|
- `state` renders through `useSyncExternalStore`, so concurrent rendering sees
|
|
56
|
-
one consistent snapshot.
|
|
65
|
+
one consistent snapshot.
|
|
57
66
|
- `pending` is true while a reference connects. `error` holds a failed
|
|
58
|
-
connection; `retry()` connects again.
|
|
67
|
+
connection; `retry()` connects again. While the same reference connects again
|
|
68
|
+
(after `retry()`, or after a hidden `<Activity>` outlived the grace period),
|
|
69
|
+
`state` stays the last state.
|
|
59
70
|
|
|
60
71
|
A `connect` function created during render, such as
|
|
61
72
|
`useView({ connect: () => connectWorkspace() })`, is a new reference on every
|
|
@@ -63,6 +74,53 @@ render, so each render reconnects. In development `useView` logs a warning when
|
|
|
63
74
|
this repeats. Pass the generated function itself, a generated page reference,
|
|
64
75
|
or memoize the source with `useMemo`.
|
|
65
76
|
|
|
77
|
+
### Selecting state: `useViewState(view, selector, isEqual?)`
|
|
78
|
+
|
|
79
|
+
`useView` renders its component on every change of the View. A component that
|
|
80
|
+
shows one member can select it and re-render only when it changes, like
|
|
81
|
+
`useSyncExternalStoreWithSelector`. Pass the connected client, which keeps its
|
|
82
|
+
identity, to a memoized child:
|
|
83
|
+
|
|
84
|
+
```tsx
|
|
85
|
+
const Title = memo(function Title({ editor }: { editor: EditorClient | undefined }) {
|
|
86
|
+
const title = useViewState(editor, state => state.title);
|
|
87
|
+
return <h1>{title ?? "…"}</h1>;
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
function EditorPage({ page }: { page: EditorPageReference }) {
|
|
91
|
+
const editor = useView(page);
|
|
92
|
+
return <><Title editor={editor.client} /><Body editor={editor.client} /></>;
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`view` is a client or a `useView` handle (`undefined` while nothing is
|
|
97
|
+
connected returns `undefined`). The selector may be an inline function.
|
|
98
|
+
Members the View did not change keep their identity, so selecting a member,
|
|
99
|
+
also an object or a list, needs no `isEqual`; pass one for a derived value, such
|
|
100
|
+
as `state => state.items.filter(item => item.done)` with a shallow comparison.
|
|
101
|
+
|
|
102
|
+
### Large lists and concurrent rendering
|
|
103
|
+
|
|
104
|
+
The client applies each frame when it arrives and notifies once per animation
|
|
105
|
+
frame (0.14), so a burst of .NET changes renders once per frame, not once per
|
|
106
|
+
frame received. `useSyncExternalStore` renders those updates synchronously,
|
|
107
|
+
though, so a component that renders thousands of rows blocks typing for the
|
|
108
|
+
length of that render. Let React render the list in a background pass with
|
|
109
|
+
`useDeferredValue`, and keep the input outside the deferred part:
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
const { state } = useView(page);
|
|
113
|
+
const rows = useDeferredValue(state?.rows);
|
|
114
|
+
const stale = rows !== state?.rows;
|
|
115
|
+
<input {...filter.inputProps} />
|
|
116
|
+
<List rows={rows ?? []} style={{ opacity: stale ? 0.6 : 1 }} /> {/* List is memo() */}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`useTransition` is not needed for commands: their calls are asynchronous and
|
|
120
|
+
the state they produce arrives as a View change. For a scrolling window over a
|
|
121
|
+
large .NET collection, request only the visible rows with
|
|
122
|
+
[`useCollectionViewport`](#usecollectionviewportoptions).
|
|
123
|
+
|
|
66
124
|
### Read-only state and two-way binding
|
|
67
125
|
|
|
68
126
|
As in any MVVM View, the ViewModel's C# setters decide what the page may set.
|
|
@@ -88,10 +146,63 @@ export function CounterPage({ page }: { page: CounterPageReference }) {
|
|
|
88
146
|
The control shows the ViewModel's value, so it reverts when the setter throws
|
|
89
147
|
or keeps a different value.
|
|
90
148
|
|
|
149
|
+
### Fields: `useField(view, field, options?)`
|
|
150
|
+
|
|
151
|
+
Binds an `<input>`, `<textarea>` or `<select>` to a member while the component is mounted. Pass the generated
|
|
152
|
+
`{View}Fields` descriptor; it knows the member's kind, setter, checked write and validation:
|
|
153
|
+
|
|
154
|
+
```tsx
|
|
155
|
+
import { EditorFields, type EditorPageReference } from "./generated/editor.js";
|
|
156
|
+
|
|
157
|
+
export function EditorPage({ page }: { page: EditorPageReference }) {
|
|
158
|
+
const editor = useView(page);
|
|
159
|
+
const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
|
|
160
|
+
const step = useField(editor, EditorFields.step);
|
|
161
|
+
const done = useField(editor, EditorFields.done);
|
|
162
|
+
return <>
|
|
163
|
+
<input {...title.inputProps} />
|
|
164
|
+
{title.errors.map(message => <p key={message} role="alert">{message}</p>)}
|
|
165
|
+
{title.conflict && <p role="alert">
|
|
166
|
+
Changed elsewhere to “{title.conflict.value}”.
|
|
167
|
+
<button onClick={title.retry}>Keep mine</button> <button onClick={title.reset}>Take theirs</button>
|
|
168
|
+
</p>}
|
|
169
|
+
<input inputMode="decimal" {...step.inputProps} />
|
|
170
|
+
<input type="checkbox" {...done.inputProps} />
|
|
171
|
+
</>;
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
It returns the field's state (`value`, `text`, `editing`, `error`, `errors`, `conflict`), `input(value)`,
|
|
176
|
+
`commit()`, `retry()`, `reset()` and `inputProps`. For a boolean field `inputProps` is `checked`, `onChange`,
|
|
177
|
+
`onBlur` and `aria-invalid` for a checkbox; otherwise it is the field's `text` as `value`, `onChange`, the
|
|
178
|
+
composition handlers, `onBlur` and `aria-invalid`. Text inputs of numbers keep `-` and `1.` while the user types: a
|
|
179
|
+
text that does not parse stays the draft with an `invalid-text` error and nothing is written. The handlers are the
|
|
180
|
+
same on every render. `aria-invalid` is true while the field has `errors` or an `error`.
|
|
181
|
+
|
|
182
|
+
`options` are read once, when the field is created:
|
|
183
|
+
|
|
184
|
+
- `commit: "pause"` writes the draft after `delay` milliseconds without input (700 by default) and at once on
|
|
185
|
+
`commit()`, which blur calls; use it where each write is an undo step or starts work in .NET. The default,
|
|
186
|
+
`commit: "input"`, writes each input. `commit()` resolves with the field's state once its writes settled, so a
|
|
187
|
+
command that depends on the field can follow them and skip a failed write:
|
|
188
|
+
`if ((await title.commit()).error === undefined) await editor.save()`. Read the error from the resolved state: the
|
|
189
|
+
handle is the state of the render that created it.
|
|
190
|
+
- `checked: true` writes with the member's checked write, so a change by another writer while the user edits is a
|
|
191
|
+
conflict instead of being overwritten. A `rejected` receipt keeps the draft and sets `error` to a `FieldError` with
|
|
192
|
+
the setter's message; a `conflict` keeps the draft, sets `conflict` to the producer's `{ value, version }` and
|
|
193
|
+
writes nothing until `retry()` writes the draft over it or `reset()` takes it.
|
|
194
|
+
- `coalesce` and `keepDraftOnError` as for text inputs below.
|
|
195
|
+
|
|
196
|
+
`errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
|
|
197
|
+
or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
|
|
198
|
+
`invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
|
|
199
|
+
[field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#fields) for the receipts
|
|
200
|
+
and text forms.
|
|
201
|
+
|
|
91
202
|
### Text inputs: `useTextField(view, read, write, options?)`
|
|
92
203
|
|
|
93
204
|
Binds a controlled text input to a member through the framework-neutral
|
|
94
|
-
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
205
|
+
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#text-inputs)
|
|
95
206
|
while the component is mounted. `read` and `write` may close over render values:
|
|
96
207
|
|
|
97
208
|
```tsx
|
|
@@ -115,9 +226,11 @@ frame that answers an older keystroke never replaces newer text. At most one wri
|
|
|
115
226
|
in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
|
|
116
227
|
every change). Nothing is written during IME composition. Once the last write settled,
|
|
117
228
|
the field shows the View's value again, including any normalization the ViewModel
|
|
118
|
-
applied (trimmed, upper-cased). `write` may also be a command or a checked write
|
|
119
|
-
|
|
120
|
-
|
|
229
|
+
applied (trimmed, upper-cased). `write` may also be a command or a checked write,
|
|
230
|
+
whose receipt the field reads: `rejected` and `conflict` keep the draft and set `error`
|
|
231
|
+
to a `FieldError` of that kind, `committed-with-error` drops the draft and sets it too,
|
|
232
|
+
and `applied.validation` is `errors`. A failed write keeps the draft and sets `error`
|
|
233
|
+
(`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
|
|
121
234
|
exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
|
|
122
235
|
the user types: the field's own write causes it, and keys typed meanwhile would be
|
|
123
236
|
lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
|
|
@@ -144,8 +257,10 @@ function Counter({ page }: { page: CounterPageReference }) {
|
|
|
144
257
|
```
|
|
145
258
|
|
|
146
259
|
Components that pass a reference with the same `connect` function share one
|
|
147
|
-
client, which is disposed
|
|
148
|
-
|
|
260
|
+
client, which is disposed `options.keepAlive` milliseconds (2000 by default,
|
|
261
|
+
`0` at once) after the last of them unmounts, so a component that mounts again
|
|
262
|
+
meanwhile renders without suspending. The reference must be stable: a `connect`
|
|
263
|
+
function created during render never resolves.
|
|
149
264
|
|
|
150
265
|
The connections live in a module-wide cache until a component claims them,
|
|
151
266
|
because Suspense discards the state of a component that never mounted.
|
|
@@ -207,7 +322,7 @@ neither.
|
|
|
207
322
|
## `useOperation(start, options?)`
|
|
208
323
|
|
|
209
324
|
Observes a generated `start<Command>()` operation through the framework-neutral
|
|
210
|
-
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
325
|
+
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
211
326
|
`run(...args)` calls the latest `start`, so it may close over the current client:
|
|
212
327
|
|
|
213
328
|
```tsx
|
|
@@ -239,7 +354,7 @@ controller's options.
|
|
|
239
354
|
|
|
240
355
|
Admits only the newest of several reads, for example loading the item the user
|
|
241
356
|
selected last, through the framework-neutral
|
|
242
|
-
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
357
|
+
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
243
358
|
Each `run(intent)` replaces the queued intent and cancels the active read; the next
|
|
244
359
|
read starts only after the previous one reaches its terminal status and the intent's
|
|
245
360
|
optional `waitForCompletion` barrier:
|
|
@@ -269,7 +384,7 @@ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here sinc
|
|
|
269
384
|
`BridgeConnectionState` and `BridgeConnectionOptions` types) and returns
|
|
270
385
|
`{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
|
|
271
386
|
`connected`, `reconnecting` or `lost` (a closed set, see
|
|
272
|
-
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
387
|
+
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#connection-state)):
|
|
273
388
|
|
|
274
389
|
```tsx
|
|
275
390
|
import { useBridgeConnection } from "@runic-artifex/react";
|
|
@@ -290,7 +405,7 @@ subscribes again; an invalid one throws a `RangeError`. A server render reads
|
|
|
290
405
|
Follows the declared menu bar of a Runic Desktop window that leaves it to the
|
|
291
406
|
page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
|
|
292
407
|
wraps `createMenuBarController` from `@runic-artifex/views` (see
|
|
293
|
-
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
408
|
+
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
|
|
294
409
|
`MenuBarState`, and the bar is rendered by the menubar component of the
|
|
295
410
|
application's own UI library. Runic ships no menubar component.
|
|
296
411
|
|
|
@@ -320,7 +435,7 @@ The controller starts in an effect, so a server render reads `connecting`, and
|
|
|
320
435
|
|
|
321
436
|
Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
|
|
322
437
|
Menubar) with a controlled open menu; the
|
|
323
|
-
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
438
|
+
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
|
|
324
439
|
items and is tested with real keys:
|
|
325
440
|
|
|
326
441
|
```tsx
|
|
@@ -374,18 +489,21 @@ Check items are `Menubar.CheckboxItem checked`, radio groups
|
|
|
374
489
|
## Errors
|
|
375
490
|
|
|
376
491
|
The `error` of `useView` and of a command or operation handle is typed
|
|
377
|
-
`unknown`: it holds whatever the connection or the call rejected with.
|
|
378
|
-
|
|
379
|
-
`
|
|
492
|
+
`unknown`: it holds whatever the connection or the call rejected with. Show it
|
|
493
|
+
with `describeBridgeError(error)`, one English sentence, instead of
|
|
494
|
+
`String(error)`. A Bridge failure is a `BridgeError` from
|
|
495
|
+
`@runic-artifex/views`; narrow it with `isBridgeError` (or `instanceof`) before
|
|
496
|
+
reading `kind`, `route` or `detail`:
|
|
380
497
|
|
|
381
|
-
```
|
|
382
|
-
import {
|
|
498
|
+
```tsx
|
|
499
|
+
import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
|
|
383
500
|
|
|
384
|
-
const offline = error
|
|
501
|
+
const offline = isBridgeError(error, "disconnected");
|
|
502
|
+
{error !== undefined && <p role="alert">{describeBridgeError(error)}</p>}
|
|
385
503
|
```
|
|
386
504
|
|
|
387
505
|
`instanceof` holds for errors from every copy of the package on the page.
|
|
388
|
-
[Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
506
|
+
[Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#errors-and-diagnostics)
|
|
389
507
|
lists the kinds. Any other value, such as an exception that your own connect
|
|
390
508
|
function or command callback throws, arrives unchanged.
|
|
391
509
|
|
|
@@ -427,16 +545,16 @@ the application's own dialog.
|
|
|
427
545
|
such as a close during the page's first render, is answered by the
|
|
428
546
|
ViewModel's .NET fallback handler, or fails closed without one.
|
|
429
547
|
|
|
430
|
-
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.
|
|
548
|
+
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.14.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
|
|
431
549
|
has the .NET side and which View answers which departure. In a frontend test,
|
|
432
550
|
the generated mock's `interactions.<name>.request(input)` resolves with the
|
|
433
551
|
registered handler's answer; see the
|
|
434
|
-
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
552
|
+
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#testing).
|
|
435
553
|
|
|
436
554
|
## `useCollectionViewport(options)`
|
|
437
555
|
|
|
438
556
|
Follows a fixed-row-height scroll container and returns `{ viewport, ref }`.
|
|
439
|
-
`viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
557
|
+
`viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#collectionviewportoptions)
|
|
440
558
|
range for the container; it changes only when the range or sizes change. Send
|
|
441
559
|
the range to the ViewModel from an effect:
|
|
442
560
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ComponentType, type ReactNode } from "react";
|
|
2
|
-
import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeOperation, type BridgeOutcomeFailure, type LatestOperationController, type LatestOperationState, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewSource } from "@runic-artifex/views";
|
|
2
|
+
import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeField, type BridgeOperation, type BridgeOutcomeFailure, type FieldDefinition, type FieldOptions, type FieldState, type LatestOperationController, type LatestOperationState, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewSource } from "@runic-artifex/views";
|
|
3
3
|
export interface ViewHandle<TClient extends ViewClient> {
|
|
4
|
-
/** The latest state, or undefined until the client connects. */
|
|
4
|
+
/** The latest state, or undefined until the client connects. While the same reference connects again it stays the last state. */
|
|
5
5
|
readonly state: TClient["snapshot"] | undefined;
|
|
6
6
|
/** The connected client for commands, or undefined until it connects. */
|
|
7
7
|
readonly client: TClient | undefined;
|
|
@@ -15,18 +15,50 @@ export interface ViewHandle<TClient extends ViewClient> {
|
|
|
15
15
|
export interface UseViewOptions<TClient extends ViewClient> {
|
|
16
16
|
/** Releases a client this hook connected. Defaults to `client.dispose()`. */
|
|
17
17
|
readonly release?: (client: TClient) => void;
|
|
18
|
+
/**
|
|
19
|
+
* Milliseconds a client this hook connected stays connected after the component unmounts or the source changes,
|
|
20
|
+
* for the next hook that follows the same reference (StrictMode, HMR, `<Activity>`, A→B→A navigation). `0`
|
|
21
|
+
* disposes it at once. Defaults to 2000. Read once, when the hook is created.
|
|
22
|
+
*/
|
|
23
|
+
readonly keepAlive?: number;
|
|
18
24
|
}
|
|
19
25
|
/**
|
|
20
26
|
* Connects a generated View reference for the lifetime of the component and
|
|
21
|
-
* renders its state through `useSyncExternalStore`.
|
|
22
|
-
*
|
|
23
|
-
*
|
|
27
|
+
* renders its state through `useSyncExternalStore`.
|
|
28
|
+
*
|
|
29
|
+
* When the component unmounts or the reference changes, the client stays
|
|
30
|
+
* connected for `keepAlive` milliseconds (2000 by default), and the next
|
|
31
|
+
* `useView` of the same reference takes it over with its state: StrictMode's
|
|
32
|
+
* simulated unmount, Fast Refresh, `<Activity>` and A→B→A navigation neither
|
|
33
|
+
* show "Connecting…" nor open the route again. A component that mounts while a
|
|
34
|
+
* client of its reference is kept renders its state in the first render.
|
|
24
35
|
*
|
|
25
36
|
* A reference is identified by its `connect` function, so an inline
|
|
26
37
|
* `{ connect: connectWorkspace }` does not reconnect. In development a
|
|
27
38
|
* `connect` function recreated on every render logs a warning.
|
|
28
39
|
*/
|
|
29
40
|
export declare function useView<TClient extends ViewClient>(source: ViewSource<TClient>, options?: UseViewOptions<TClient>): ViewHandle<TClient>;
|
|
41
|
+
/**
|
|
42
|
+
* Renders one selected part of a View's state and re-renders only when that part changes, by `isEqual`
|
|
43
|
+
* (`Object.is` by default), like `useSyncExternalStoreWithSelector`. Pass the connected client, which keeps its
|
|
44
|
+
* identity, to a memoized child, so the child renders when its member changes and not on every change of the View:
|
|
45
|
+
*
|
|
46
|
+
* ```tsx
|
|
47
|
+
* const Title = memo(function Title({ editor }: { editor: EditorClient | undefined }) {
|
|
48
|
+
* const title = useViewState(editor, state => state.title);
|
|
49
|
+
* return <h1>{title ?? "…"}</h1>;
|
|
50
|
+
* });
|
|
51
|
+
* const view = useView(page);
|
|
52
|
+
* <Title editor={view.client} />
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* A `useView` handle works too, for example in the component that calls `useView`; that component still renders
|
|
56
|
+
* on every change of the handle. Returns `undefined` while there is no client and no state. The selector may be an
|
|
57
|
+
* inline function: a new function selects again, and an equal result keeps the previous value. Members the View did
|
|
58
|
+
* not change keep their identity, so selecting a member, or an object or array member, needs no `isEqual`; pass one
|
|
59
|
+
* for a derived value such as `state => state.items.filter(…)`.
|
|
60
|
+
*/
|
|
61
|
+
export declare function useViewState<TClient extends ViewClient, TSelected>(view: ViewHandle<TClient> | TClient | null | undefined, selector: (state: TClient["snapshot"]) => TSelected, isEqual?: (left: TSelected, right: TSelected) => boolean): TSelected | undefined;
|
|
30
62
|
/**
|
|
31
63
|
* A build-known map checks each generated reference kind against its component's `page` prop. A nullable
|
|
32
64
|
* reference, such as a region slot's `State["main"]`, checks its non-null kinds.
|
|
@@ -182,10 +214,91 @@ export interface TextFieldView<TClient extends ViewClient> {
|
|
|
182
214
|
* onCompositionStart={name.onCompositionStart} onCompositionEnd={name.onCompositionEnd} />
|
|
183
215
|
* ```
|
|
184
216
|
*
|
|
185
|
-
* `write` may be a generated setter, a command or a checked write. Its failure
|
|
217
|
+
* `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
|
|
218
|
+
* `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
|
|
219
|
+
* `useField` with its `{View}Fields` descriptor.
|
|
186
220
|
* Unmounting writes text that waits for a write in flight, and stops updating the handle.
|
|
187
221
|
*/
|
|
188
222
|
export declare function useTextField<TClient extends ViewClient>(view: TextFieldView<TClient>, read: (state: TClient["snapshot"]) => string, write: (client: TClient, value: string) => Promise<unknown>, options?: UseTextFieldOptions): TextFieldHandle;
|
|
223
|
+
/**
|
|
224
|
+
* What {@link useField} spreads on a checkbox (`<input type="checkbox">`): a boolean field. `onChange` reads `checked`.
|
|
225
|
+
*/
|
|
226
|
+
export interface FieldCheckboxProps {
|
|
227
|
+
readonly checked: boolean;
|
|
228
|
+
readonly onChange: (event: {
|
|
229
|
+
readonly currentTarget: {
|
|
230
|
+
readonly checked: boolean;
|
|
231
|
+
};
|
|
232
|
+
}) => void;
|
|
233
|
+
/** Commits the field (see `FieldHandle.commit`). */
|
|
234
|
+
readonly onBlur: () => void;
|
|
235
|
+
/** True while the field has validation messages (`errors`) or an `error`. */
|
|
236
|
+
readonly "aria-invalid": boolean;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* What {@link useField} spreads on an `<input>`, `<textarea>` or `<select>` of any field but a boolean one: the field's
|
|
240
|
+
* `text`, written through `inputText` (so `-` and `1.` survive typing into a number field), and IME composition.
|
|
241
|
+
*/
|
|
242
|
+
export interface FieldTextProps {
|
|
243
|
+
readonly value: string;
|
|
244
|
+
readonly onChange: (event: {
|
|
245
|
+
readonly currentTarget: {
|
|
246
|
+
readonly value: string;
|
|
247
|
+
};
|
|
248
|
+
}) => void;
|
|
249
|
+
/** The text is kept but not written until the IME composition ends. */
|
|
250
|
+
readonly onCompositionStart: () => void;
|
|
251
|
+
/** The composed text is written. */
|
|
252
|
+
readonly onCompositionEnd: (event: {
|
|
253
|
+
readonly currentTarget: {
|
|
254
|
+
readonly value: string;
|
|
255
|
+
};
|
|
256
|
+
}) => void;
|
|
257
|
+
/** Commits the field (see `FieldHandle.commit`). */
|
|
258
|
+
readonly onBlur: () => void;
|
|
259
|
+
/** True while the field has validation messages (`errors`) or an `error`. */
|
|
260
|
+
readonly "aria-invalid": boolean;
|
|
261
|
+
}
|
|
262
|
+
/** The props of a field's element: {@link FieldCheckboxProps} for a boolean field, otherwise {@link FieldTextProps}. */
|
|
263
|
+
export type FieldInputProps<TValue> = [TValue] extends [boolean | null] ? FieldCheckboxProps : FieldTextProps;
|
|
264
|
+
/** A field bound by {@link useField}: what it shows, the props of its element and its actions. */
|
|
265
|
+
export type FieldHandle<TValue> = FieldState<TValue> & {
|
|
266
|
+
/** Spread on the field's `<input>`, `<textarea>` or `<select>`. The handlers are the same on every render. */
|
|
267
|
+
readonly inputProps: FieldInputProps<TValue>;
|
|
268
|
+
/** The user changed the value, such as from a custom control. */
|
|
269
|
+
input(value: TValue): void;
|
|
270
|
+
/**
|
|
271
|
+
* The user is done with the field (`onBlur` calls it): with `commit: "pause"` the draft is written now. Resolves with
|
|
272
|
+
* the field's state once its writes settled, so a command that depends on the field can run after it and skip a
|
|
273
|
+
* failed write: `if ((await title.commit()).error === undefined) await editor.save()`. The handle is the state of
|
|
274
|
+
* the render that created it, so read the error from the resolved state. Never rejects.
|
|
275
|
+
*/
|
|
276
|
+
commit(): Promise<FieldState<TValue>>;
|
|
277
|
+
/** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
|
|
278
|
+
retry(): void;
|
|
279
|
+
/** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
|
|
280
|
+
reset(): void;
|
|
281
|
+
};
|
|
282
|
+
/**
|
|
283
|
+
* Binds an element to one View member while the component is mounted, through `createFieldController`: pass a
|
|
284
|
+
* generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Spread `inputProps` on
|
|
285
|
+
* an `<input>`, `<textarea>` or `<select>` (a checkbox for a boolean field). Typing never loses characters: the field
|
|
286
|
+
* shows a draft while its writes are in flight, writes nothing during IME composition, keeps text that does not
|
|
287
|
+
* parse (such as `1.` in a number field) as the draft, and once the last write settled shows the View's value.
|
|
288
|
+
* `options` are read when the component mounts; the descriptor's `read`, `write` and `errors` may close over render
|
|
289
|
+
* values, and the latest ones are used.
|
|
290
|
+
*
|
|
291
|
+
* ```tsx
|
|
292
|
+
* const editor = useView(page);
|
|
293
|
+
* const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
|
|
294
|
+
* <input {...title.inputProps} />
|
|
295
|
+
* {title.conflict && <button onClick={title.retry}>Keep mine</button>}
|
|
296
|
+
* ```
|
|
297
|
+
*
|
|
298
|
+
* With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
|
|
299
|
+
* conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
|
|
300
|
+
*/
|
|
301
|
+
export declare function useField<TClient extends ViewClient, TValue>(view: TextFieldView<TClient>, field: BridgeField<NoInfer<TClient>, NoInfer<TClient>["snapshot"], TValue> | FieldDefinition<NoInfer<TClient>, NoInfer<TClient>["snapshot"], TValue>, options?: FieldOptions): FieldHandle<TValue>;
|
|
189
302
|
export interface BridgeConnectionHandle {
|
|
190
303
|
/** The connection to the .NET host, as `onBridgeConnection` reports it. */
|
|
191
304
|
readonly state: BridgeConnectionState;
|
|
@@ -204,4 +317,5 @@ export declare function useBridgeConnection(options?: BridgeConnectionOptions):
|
|
|
204
317
|
export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
|
|
205
318
|
export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
|
|
206
319
|
export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
|
|
320
|
+
export { FieldError, type BridgeField, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
|
|
207
321
|
export { useMenuBar, type MenuBarEntry, type MenuBarHandle, type MenuBarInvokeResult, type MenuBarItem, type MenuBarMenu, type MenuBarRequest, type MenuBarSeparator, type MenuBarState, type UseMenuBarOptions, } from "./menu-bar.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createElement, useCallback, useEffect, useInsertionEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from "react";
|
|
2
|
-
import { createCommandController, createLatestOperationController, createOperationController, createTextFieldController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
|
|
3
|
-
import { isViewClient, viewSourceIdentity } from "@runic-artifex/views/bindings";
|
|
2
|
+
import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
|
|
3
|
+
import { isViewClient, viewSourceIdentity, viewSourcePreview } from "@runic-artifex/views/bindings";
|
|
4
4
|
// An inline `{ connect: () => connectX() }` creates a new function on every
|
|
5
5
|
// render, so every render reconnects and each connection renders again.
|
|
6
6
|
function warnInlineConnect(tracker, connect) {
|
|
@@ -55,9 +55,14 @@ function createViewStore(controller) {
|
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
57
|
* Connects a generated View reference for the lifetime of the component and
|
|
58
|
-
* renders its state through `useSyncExternalStore`.
|
|
59
|
-
*
|
|
60
|
-
*
|
|
58
|
+
* renders its state through `useSyncExternalStore`.
|
|
59
|
+
*
|
|
60
|
+
* When the component unmounts or the reference changes, the client stays
|
|
61
|
+
* connected for `keepAlive` milliseconds (2000 by default), and the next
|
|
62
|
+
* `useView` of the same reference takes it over with its state: StrictMode's
|
|
63
|
+
* simulated unmount, Fast Refresh, `<Activity>` and A→B→A navigation neither
|
|
64
|
+
* show "Connecting…" nor open the route again. A component that mounts while a
|
|
65
|
+
* client of its reference is kept renders its state in the first render.
|
|
61
66
|
*
|
|
62
67
|
* A reference is identified by its `connect` function, so an inline
|
|
63
68
|
* `{ connect: connectWorkspace }` does not reconnect. In development a
|
|
@@ -71,6 +76,7 @@ export function useView(source, options = {}) {
|
|
|
71
76
|
release.current(client);
|
|
72
77
|
else
|
|
73
78
|
client.dispose(); },
|
|
79
|
+
...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }),
|
|
74
80
|
}));
|
|
75
81
|
const [store] = useState(() => createViewStore(controller));
|
|
76
82
|
const tracker = useRef({ connect: undefined, text: "", times: [], warned: false });
|
|
@@ -80,8 +86,9 @@ export function useView(source, options = {}) {
|
|
|
80
86
|
warnInlineConnect(tracker.current, source.connect);
|
|
81
87
|
controller.setSource(source);
|
|
82
88
|
store.refresh();
|
|
83
|
-
//
|
|
84
|
-
|
|
89
|
+
// The client is kept for the next run (StrictMode, Fast Refresh, <Activity>) or the next component of the same
|
|
90
|
+
// reference; `current` stays, so a hidden <Activity> renders its last state.
|
|
91
|
+
return () => { controller.release(); };
|
|
85
92
|
// The source is identified by its client or connect function, not by its wrapper object.
|
|
86
93
|
}, [controller, store, identity]);
|
|
87
94
|
const current = useSyncExternalStore(store.subscribe, store.read, store.read);
|
|
@@ -90,11 +97,59 @@ export function useView(source, options = {}) {
|
|
|
90
97
|
// A connected client is readable before the effect observes it.
|
|
91
98
|
if (observed && current.client !== observed)
|
|
92
99
|
return { state: observed.snapshot, client: observed, error: undefined, pending: false, retry };
|
|
93
|
-
// Until the effect follows a changed reference, do not show the previous one.
|
|
94
|
-
if (viewSourceIdentity(current.source) !== identity)
|
|
100
|
+
// Until the effect follows a changed reference, do not show the previous one; show a client kept for it instead.
|
|
101
|
+
if (viewSourceIdentity(current.source) !== identity) {
|
|
102
|
+
const preview = viewSourcePreview(source);
|
|
103
|
+
if (preview)
|
|
104
|
+
return { state: preview.state, client: preview.client, error: undefined, pending: false, retry };
|
|
95
105
|
return { state: undefined, client: undefined, error: undefined, pending: source !== null && source !== undefined, retry };
|
|
106
|
+
}
|
|
96
107
|
return { state: current.state, client: current.client, error: current.error, pending: current.pending, retry };
|
|
97
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* Renders one selected part of a View's state and re-renders only when that part changes, by `isEqual`
|
|
111
|
+
* (`Object.is` by default), like `useSyncExternalStoreWithSelector`. Pass the connected client, which keeps its
|
|
112
|
+
* identity, to a memoized child, so the child renders when its member changes and not on every change of the View:
|
|
113
|
+
*
|
|
114
|
+
* ```tsx
|
|
115
|
+
* const Title = memo(function Title({ editor }: { editor: EditorClient | undefined }) {
|
|
116
|
+
* const title = useViewState(editor, state => state.title);
|
|
117
|
+
* return <h1>{title ?? "…"}</h1>;
|
|
118
|
+
* });
|
|
119
|
+
* const view = useView(page);
|
|
120
|
+
* <Title editor={view.client} />
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* A `useView` handle works too, for example in the component that calls `useView`; that component still renders
|
|
124
|
+
* on every change of the handle. Returns `undefined` while there is no client and no state. The selector may be an
|
|
125
|
+
* inline function: a new function selects again, and an equal result keeps the previous value. Members the View did
|
|
126
|
+
* not change keep their identity, so selecting a member, or an object or array member, needs no `isEqual`; pass one
|
|
127
|
+
* for a derived value such as `state => state.items.filter(…)`.
|
|
128
|
+
*/
|
|
129
|
+
export function useViewState(view, selector, isEqual = Object.is) {
|
|
130
|
+
const client = view && isViewClient(view) ? view : view?.client;
|
|
131
|
+
const fallback = client ? undefined : view?.state;
|
|
132
|
+
const subscribe = useCallback((onChange) => client ? client.subscribe(() => onChange()) : () => { }, [client]);
|
|
133
|
+
// The value last rendered, so a selector recreated on every render keeps an equal selection's identity.
|
|
134
|
+
const rendered = useRef(undefined);
|
|
135
|
+
const read = useMemo(() => {
|
|
136
|
+
let memo;
|
|
137
|
+
return () => {
|
|
138
|
+
const state = client ? client.snapshot : fallback;
|
|
139
|
+
if (memo && Object.is(memo.state, state))
|
|
140
|
+
return memo.value;
|
|
141
|
+
let value = state === undefined ? undefined : selector(state);
|
|
142
|
+
const previous = memo ?? rendered.current;
|
|
143
|
+
if (previous && previous.value !== undefined && value !== undefined && isEqual(previous.value, value))
|
|
144
|
+
value = previous.value;
|
|
145
|
+
memo = { state, value };
|
|
146
|
+
return value;
|
|
147
|
+
};
|
|
148
|
+
}, [client, fallback, selector, isEqual]);
|
|
149
|
+
const value = useSyncExternalStore(subscribe, read, read);
|
|
150
|
+
useEffect(() => { rendered.current = { value }; }, [value]);
|
|
151
|
+
return value;
|
|
152
|
+
}
|
|
98
153
|
const referenceKeys = new WeakMap();
|
|
99
154
|
let nextReferenceKey = 0;
|
|
100
155
|
function referenceKey(reference) {
|
|
@@ -223,7 +278,9 @@ export function useLatestOperation() {
|
|
|
223
278
|
* onCompositionStart={name.onCompositionStart} onCompositionEnd={name.onCompositionEnd} />
|
|
224
279
|
* ```
|
|
225
280
|
*
|
|
226
|
-
* `write` may be a generated setter, a command or a checked write. Its failure
|
|
281
|
+
* `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
|
|
282
|
+
* `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
|
|
283
|
+
* `useField` with its `{View}Fields` descriptor.
|
|
227
284
|
* Unmounting writes text that waits for a write in flight, and stops updating the handle.
|
|
228
285
|
*/
|
|
229
286
|
export function useTextField(view, read, write, options = {}) {
|
|
@@ -251,6 +308,89 @@ export function useTextField(view, read, write, options = {}) {
|
|
|
251
308
|
const value = current.editing ? current.value : state === undefined ? "" : read(state);
|
|
252
309
|
return { value, editing: current.editing, error: current.error, ...handlers };
|
|
253
310
|
}
|
|
311
|
+
const noFieldErrors = Object.freeze([]);
|
|
312
|
+
/** The text a field shows for a value, as the field controller formats it. */
|
|
313
|
+
function formatFieldValue(value) {
|
|
314
|
+
switch (typeof value) {
|
|
315
|
+
case "string": return value;
|
|
316
|
+
case "number":
|
|
317
|
+
case "bigint":
|
|
318
|
+
case "boolean": return String(value);
|
|
319
|
+
default: return "";
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Binds an element to one View member while the component is mounted, through `createFieldController`: pass a
|
|
324
|
+
* generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Spread `inputProps` on
|
|
325
|
+
* an `<input>`, `<textarea>` or `<select>` (a checkbox for a boolean field). Typing never loses characters: the field
|
|
326
|
+
* shows a draft while its writes are in flight, writes nothing during IME composition, keeps text that does not
|
|
327
|
+
* parse (such as `1.` in a number field) as the draft, and once the last write settled shows the View's value.
|
|
328
|
+
* `options` are read when the component mounts; the descriptor's `read`, `write` and `errors` may close over render
|
|
329
|
+
* values, and the latest ones are used.
|
|
330
|
+
*
|
|
331
|
+
* ```tsx
|
|
332
|
+
* const editor = useView(page);
|
|
333
|
+
* const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
|
|
334
|
+
* <input {...title.inputProps} />
|
|
335
|
+
* {title.conflict && <button onClick={title.retry}>Keep mine</button>}
|
|
336
|
+
* ```
|
|
337
|
+
*
|
|
338
|
+
* With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
|
|
339
|
+
* conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
|
|
340
|
+
*/
|
|
341
|
+
export function useField(view, field, options = {}) {
|
|
342
|
+
const latest = useRef(field);
|
|
343
|
+
useInsertionEffect(() => { latest.current = field; });
|
|
344
|
+
const controller = useMountedController(() => createFieldController({
|
|
345
|
+
...field.name === undefined ? {} : { name: field.name },
|
|
346
|
+
...field.kind === undefined ? {} : { kind: field.kind },
|
|
347
|
+
...field.nullable === undefined ? {} : { nullable: field.nullable },
|
|
348
|
+
...field.integer === undefined ? {} : { integer: field.integer },
|
|
349
|
+
...field.choices === undefined ? {} : { choices: field.choices },
|
|
350
|
+
read: state => latest.current.read(state),
|
|
351
|
+
write: (client, value) => latest.current.write(client, value),
|
|
352
|
+
...field.checked === undefined ? {} : { checked: (client, value, write) => latest.current.checked(client, value, write) },
|
|
353
|
+
...field.baseline === undefined ? {} : { baseline: client => latest.current.baseline(client) },
|
|
354
|
+
...field.errors === undefined ? {} : { errors: state => latest.current.errors(state) },
|
|
355
|
+
}, options));
|
|
356
|
+
const { state, client } = view;
|
|
357
|
+
useEffect(() => {
|
|
358
|
+
controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
|
|
359
|
+
}, [controller, state, client]);
|
|
360
|
+
const readCurrent = useCallback(() => controller.current, [controller]);
|
|
361
|
+
const current = useSyncExternalStore(controller.subscribe, readCurrent, readCurrent);
|
|
362
|
+
const actions = useMemo(() => ({
|
|
363
|
+
input: (value) => controller.input(value),
|
|
364
|
+
commit: () => controller.commit(),
|
|
365
|
+
retry: () => controller.retry(),
|
|
366
|
+
reset: () => controller.reset(),
|
|
367
|
+
onBlur: () => { void controller.commit(); },
|
|
368
|
+
onChange: (event) => controller.inputText(event.currentTarget.value),
|
|
369
|
+
onCheck: (event) => controller.input(event.currentTarget.checked),
|
|
370
|
+
onCompositionStart: () => controller.compositionStart(),
|
|
371
|
+
onCompositionEnd: (event) => controller.compositionEnd(event.currentTarget.value),
|
|
372
|
+
}), [controller]);
|
|
373
|
+
// Without a draft the field shows the state being rendered, which the effect passes to the controller after the
|
|
374
|
+
// render (setSource does not notify). Text that still means that value (such as `1.` for 1) stays.
|
|
375
|
+
const kind = controller.field.kind;
|
|
376
|
+
const value = current.editing ? current.value
|
|
377
|
+
: state === undefined ? (kind === "text" || kind === undefined ? "" : undefined)
|
|
378
|
+
: field.read(state);
|
|
379
|
+
const text = Object.is(value, current.value) ? current.text : formatFieldValue(value);
|
|
380
|
+
const errors = field.errors === undefined ? current.errors : state === undefined ? noFieldErrors : field.errors(state);
|
|
381
|
+
const invalid = errors.length > 0 || current.error !== undefined;
|
|
382
|
+
const inputProps = kind === "boolean"
|
|
383
|
+
? { checked: value === true, onChange: actions.onCheck, onBlur: actions.onBlur, "aria-invalid": invalid }
|
|
384
|
+
: {
|
|
385
|
+
value: text, onChange: actions.onChange, onCompositionStart: actions.onCompositionStart,
|
|
386
|
+
onCompositionEnd: actions.onCompositionEnd, onBlur: actions.onBlur, "aria-invalid": invalid,
|
|
387
|
+
};
|
|
388
|
+
return {
|
|
389
|
+
value, text, editing: current.editing, error: current.error, errors, conflict: current.conflict,
|
|
390
|
+
inputProps: inputProps,
|
|
391
|
+
input: actions.input, commit: actions.commit, retry: actions.retry, reset: actions.reset,
|
|
392
|
+
};
|
|
393
|
+
}
|
|
254
394
|
// The state before the component subscribes: a subscription reports it at once.
|
|
255
395
|
function currentBridgeConnection(options) {
|
|
256
396
|
let current = "connecting";
|
|
@@ -282,4 +422,5 @@ const serverConnectionState = () => "connecting";
|
|
|
282
422
|
export { retrySuspenseView, useSuspenseView } from "./suspense.js";
|
|
283
423
|
export { useCollectionViewport } from "./viewport.js";
|
|
284
424
|
export { onBridgeConnection } from "@runic-artifex/views";
|
|
425
|
+
export { FieldError, } from "@runic-artifex/views";
|
|
285
426
|
export { useMenuBar, } from "./menu-bar.js";
|
package/dist/suspense.d.ts
CHANGED
|
@@ -15,6 +15,12 @@ export interface SuspenseViewOptions {
|
|
|
15
15
|
* `RangeError`.
|
|
16
16
|
*/
|
|
17
17
|
readonly releaseTimeout?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Milliseconds the client stays connected after the last component that used it unmounted, so a component that
|
|
20
|
+
* mounts again (StrictMode, Fast Refresh, `<Activity>`, A→B→A navigation) renders at once instead of suspending. A
|
|
21
|
+
* whole number from 0 to 2147483647; `0` disposes at once. Defaults to 2000.
|
|
22
|
+
*/
|
|
23
|
+
readonly keepAlive?: number;
|
|
18
24
|
}
|
|
19
25
|
export interface SuspenseViewHandle<TClient extends ViewClient> {
|
|
20
26
|
/** The latest state. */
|
|
@@ -30,7 +36,8 @@ export interface SuspenseViewHandle<TClient extends ViewClient> {
|
|
|
30
36
|
* mounted, is released after `options.releaseTimeout` (ten seconds by default).
|
|
31
37
|
*
|
|
32
38
|
* Components that pass a reference with the same `connect` function share one
|
|
33
|
-
* client, which is disposed
|
|
39
|
+
* client, which is disposed `options.keepAlive` milliseconds (2000 by default)
|
|
40
|
+
* after the last of them unmounts. Pass a stable
|
|
34
41
|
* function such as a generated page reference or `{ connect: connectWorkspace }`:
|
|
35
42
|
* a function recreated on every render never resolves. An already connected
|
|
36
43
|
* client is observed and left to its owner.
|
package/dist/suspense.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useCallback, useEffect, useReducer, useSyncExternalStore } from "react";
|
|
2
|
-
import { isViewClient } from "@runic-artifex/views/bindings";
|
|
2
|
+
import { checkKeepAlive, isViewClient } from "@runic-artifex/views/bindings";
|
|
3
3
|
// Suspense discards the state of a component that never mounted, so pending
|
|
4
4
|
// connections live here, keyed by connect function, until a component claims them.
|
|
5
5
|
const suspended = new WeakMap();
|
|
@@ -37,7 +37,7 @@ function suspendedConnection(connector, releaseTimeout) {
|
|
|
37
37
|
}
|
|
38
38
|
return existing;
|
|
39
39
|
}
|
|
40
|
-
const entry = { status: "pending", promise: Promise.resolve(), users: 0, releaseTimeout };
|
|
40
|
+
const entry = { status: "pending", promise: Promise.resolve(), users: 0, releaseTimeout, keepAlive: 0 };
|
|
41
41
|
entry.promise = Promise.resolve().then(() => connector.connect()).then(client => {
|
|
42
42
|
entry.status = "ready";
|
|
43
43
|
entry.client = client;
|
|
@@ -72,13 +72,15 @@ export function retrySuspenseView(source) {
|
|
|
72
72
|
* mounted, is released after `options.releaseTimeout` (ten seconds by default).
|
|
73
73
|
*
|
|
74
74
|
* Components that pass a reference with the same `connect` function share one
|
|
75
|
-
* client, which is disposed
|
|
75
|
+
* client, which is disposed `options.keepAlive` milliseconds (2000 by default)
|
|
76
|
+
* after the last of them unmounts. Pass a stable
|
|
76
77
|
* function such as a generated page reference or `{ connect: connectWorkspace }`:
|
|
77
78
|
* a function recreated on every render never resolves. An already connected
|
|
78
79
|
* client is observed and left to its owner.
|
|
79
80
|
*/
|
|
80
81
|
export function useSuspenseView(source, options = {}) {
|
|
81
82
|
const releaseTimeout = checkReleaseTimeout(options.releaseTimeout);
|
|
83
|
+
const keepAlive = checkKeepAlive(options.keepAlive, "useSuspenseView's keepAlive");
|
|
82
84
|
const connector = isViewClient(source) ? undefined : source;
|
|
83
85
|
const entry = connector ? suspendedConnection(connector, releaseTimeout) : undefined;
|
|
84
86
|
const [, refresh] = useReducer((count) => count + 1, 0);
|
|
@@ -92,13 +94,14 @@ export function useSuspenseView(source, options = {}) {
|
|
|
92
94
|
return;
|
|
93
95
|
}
|
|
94
96
|
entry.users++;
|
|
97
|
+
entry.keepAlive = Math.max(entry.keepAlive, keepAlive);
|
|
95
98
|
clearTimeout(entry.timer);
|
|
96
99
|
return () => {
|
|
97
100
|
entry.users--;
|
|
98
101
|
if (entry.users === 0)
|
|
99
|
-
releaseLater(key, entry,
|
|
102
|
+
releaseLater(key, entry, entry.keepAlive);
|
|
100
103
|
};
|
|
101
|
-
}, [entry]);
|
|
104
|
+
}, [entry, keepAlive]);
|
|
102
105
|
if (entry?.status === "pending")
|
|
103
106
|
throw entry.promise;
|
|
104
107
|
if (entry?.status === "failed")
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runic-artifex/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "React hooks for generated Runic Views clients",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -30,10 +30,10 @@
|
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
32
|
"react": ">=18.3.0 <20",
|
|
33
|
-
"@runic-artifex/views": "0.
|
|
33
|
+
"@runic-artifex/views": "0.14.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@runic-artifex/views": "0.
|
|
36
|
+
"@runic-artifex/views": "0.14.0",
|
|
37
37
|
"@types/react": "19.3.0",
|
|
38
38
|
"@types/react-dom": "19.3.0",
|
|
39
39
|
"esbuild": "0.28.2",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
|
|
54
54
|
"directory": "packages/web/react"
|
|
55
55
|
},
|
|
56
|
-
"homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
56
|
+
"homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/react#readme",
|
|
57
57
|
"bugs": {
|
|
58
58
|
"url": "https://github.com/Runic-Artifex/runic-sdk/issues"
|
|
59
59
|
},
|
|
@@ -63,5 +63,5 @@
|
|
|
63
63
|
"views",
|
|
64
64
|
"react"
|
|
65
65
|
],
|
|
66
|
-
"gitHead": "
|
|
66
|
+
"gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
|
|
67
67
|
}
|