@runic-artifex/react 0.12.1 → 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 +180 -23
- package/dist/index.d.ts +182 -5
- package/dist/index.js +193 -10
- package/dist/menu-bar.js +1 -1
- package/dist/suspense.d.ts +8 -1
- package/dist/suspense.js +8 -5
- package/package.json +7 -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,6 +146,97 @@ 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
|
+
|
|
202
|
+
### Text inputs: `useTextField(view, read, write, options?)`
|
|
203
|
+
|
|
204
|
+
Binds a controlled text input to a member through the framework-neutral
|
|
205
|
+
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#text-inputs)
|
|
206
|
+
while the component is mounted. `read` and `write` may close over render values:
|
|
207
|
+
|
|
208
|
+
```tsx
|
|
209
|
+
export function PersonPage({ page }: { page: PersonPageReference }) {
|
|
210
|
+
const person = useView(page);
|
|
211
|
+
const name = useTextField(person, state => state.name, (client, value) => client.setName(value));
|
|
212
|
+
return <>
|
|
213
|
+
<input value={name.value} onChange={name.onChange}
|
|
214
|
+
onCompositionStart={name.onCompositionStart} onCompositionEnd={name.onCompositionEnd} />
|
|
215
|
+
{name.error !== undefined && <p role="alert">{String(name.error)}</p>}
|
|
216
|
+
</>;
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
It returns `value`, `editing` and `error` with the `onChange`, `onCompositionStart`
|
|
221
|
+
and `onCompositionEnd` handlers and `reset()`. `view` is a `useView` handle or any
|
|
222
|
+
`{ state, client }`. The options `coalesce` and `keepDraftOnError` are read when the
|
|
223
|
+
component mounts.
|
|
224
|
+
The field shows what the user typed while its writes are in flight, so a reply or
|
|
225
|
+
frame that answers an older keystroke never replaces newer text. At most one write is
|
|
226
|
+
in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
|
|
227
|
+
every change). Nothing is written during IME composition. Once the last write settled,
|
|
228
|
+
the field shows the View's value again, including any normalization the ViewModel
|
|
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
|
|
234
|
+
exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
|
|
235
|
+
the user types: the field's own write causes it, and keys typed meanwhile would be
|
|
236
|
+
lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
|
|
237
|
+
Library `user.type`) against the mock with `latency: "slow"`; `fill()` sets the whole
|
|
238
|
+
text at once and hides the race.
|
|
239
|
+
|
|
91
240
|
## `useSuspenseView(source, options?)`
|
|
92
241
|
|
|
93
242
|
Suspends the component until a reference connects, then returns
|
|
@@ -108,8 +257,10 @@ function Counter({ page }: { page: CounterPageReference }) {
|
|
|
108
257
|
```
|
|
109
258
|
|
|
110
259
|
Components that pass a reference with the same `connect` function share one
|
|
111
|
-
client, which is disposed
|
|
112
|
-
|
|
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.
|
|
113
264
|
|
|
114
265
|
The connections live in a module-wide cache until a component claims them,
|
|
115
266
|
because Suspense discards the state of a component that never mounted.
|
|
@@ -171,7 +322,7 @@ neither.
|
|
|
171
322
|
## `useOperation(start, options?)`
|
|
172
323
|
|
|
173
324
|
Observes a generated `start<Command>()` operation through the framework-neutral
|
|
174
|
-
[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).
|
|
175
326
|
`run(...args)` calls the latest `start`, so it may close over the current client:
|
|
176
327
|
|
|
177
328
|
```tsx
|
|
@@ -182,12 +333,15 @@ const push = useOperation((remote: string) => client?.startPush(remote));
|
|
|
182
333
|
{push.error !== undefined && <p role="alert">{String(push.error)}</p>}
|
|
183
334
|
```
|
|
184
335
|
|
|
185
|
-
The result has `pending`, `admitting`, `operation`, `status`, `outcome`, `failure`,
|
|
336
|
+
The result has `pending`, `admitting`, `operation`, `status`, `progress`, `outcome`, `failure`,
|
|
186
337
|
`error`, `cancelled`, `cancellationRequested`, `cancelling`, `cancellation` and
|
|
187
338
|
`cancelError`, with `run(...args)`, `cancel()` and `reset()`, which never reject. A
|
|
188
339
|
run that ends with a `cancelled` status sets `cancelled` and resolves to `undefined`
|
|
189
340
|
without an `error`; `failed` and `timed-out` statuses are still `error`. `pending`
|
|
190
341
|
stays true after a Cancel response until the operation reaches its terminal status.
|
|
342
|
+
`progress` is how far the running operation got, from 0 to 1, when its command
|
|
343
|
+
reports progress (`RunicOperationProgress.Report` in .NET), for example
|
|
344
|
+
`<progress value={push.progress} />`; it is `undefined` while unknown and after the run.
|
|
191
345
|
Unmounting disposes the controller, as `useCommand` does: a run still in flight
|
|
192
346
|
resolves to `undefined`, `waitForCompletion` is not called after it, and accepted
|
|
193
347
|
work is never cancelled. StrictMode's simulated unmount, and a component that
|
|
@@ -200,7 +354,7 @@ controller's options.
|
|
|
200
354
|
|
|
201
355
|
Admits only the newest of several reads, for example loading the item the user
|
|
202
356
|
selected last, through the framework-neutral
|
|
203
|
-
[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).
|
|
204
358
|
Each `run(intent)` replaces the queued intent and cancels the active read; the next
|
|
205
359
|
read starts only after the previous one reaches its terminal status and the intent's
|
|
206
360
|
optional `waitForCompletion` barrier:
|
|
@@ -230,7 +384,7 @@ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here sinc
|
|
|
230
384
|
`BridgeConnectionState` and `BridgeConnectionOptions` types) and returns
|
|
231
385
|
`{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
|
|
232
386
|
`connected`, `reconnecting` or `lost` (a closed set, see
|
|
233
|
-
[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)):
|
|
234
388
|
|
|
235
389
|
```tsx
|
|
236
390
|
import { useBridgeConnection } from "@runic-artifex/react";
|
|
@@ -251,7 +405,7 @@ subscribes again; an invalid one throws a `RangeError`. A server render reads
|
|
|
251
405
|
Follows the declared menu bar of a Runic Desktop window that leaves it to the
|
|
252
406
|
page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
|
|
253
407
|
wraps `createMenuBarController` from `@runic-artifex/views` (see
|
|
254
|
-
[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
|
|
255
409
|
`MenuBarState`, and the bar is rendered by the menubar component of the
|
|
256
410
|
application's own UI library. Runic ships no menubar component.
|
|
257
411
|
|
|
@@ -281,7 +435,7 @@ The controller starts in an effect, so a server render reads `connecting`, and
|
|
|
281
435
|
|
|
282
436
|
Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
|
|
283
437
|
Menubar) with a controlled open menu; the
|
|
284
|
-
[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
|
|
285
439
|
items and is tested with real keys:
|
|
286
440
|
|
|
287
441
|
```tsx
|
|
@@ -335,18 +489,21 @@ Check items are `Menubar.CheckboxItem checked`, radio groups
|
|
|
335
489
|
## Errors
|
|
336
490
|
|
|
337
491
|
The `error` of `useView` and of a command or operation handle is typed
|
|
338
|
-
`unknown`: it holds whatever the connection or the call rejected with.
|
|
339
|
-
|
|
340
|
-
`
|
|
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`:
|
|
341
497
|
|
|
342
|
-
```
|
|
343
|
-
import {
|
|
498
|
+
```tsx
|
|
499
|
+
import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
|
|
344
500
|
|
|
345
|
-
const offline = error
|
|
501
|
+
const offline = isBridgeError(error, "disconnected");
|
|
502
|
+
{error !== undefined && <p role="alert">{describeBridgeError(error)}</p>}
|
|
346
503
|
```
|
|
347
504
|
|
|
348
505
|
`instanceof` holds for errors from every copy of the package on the page.
|
|
349
|
-
[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)
|
|
350
507
|
lists the kinds. Any other value, such as an exception that your own connect
|
|
351
508
|
function or command callback throws, arrives unchanged.
|
|
352
509
|
|
|
@@ -388,16 +545,16 @@ the application's own dialog.
|
|
|
388
545
|
such as a close during the page's first render, is answered by the
|
|
389
546
|
ViewModel's .NET fallback handler, or fails closed without one.
|
|
390
547
|
|
|
391
|
-
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)
|
|
392
549
|
has the .NET side and which View answers which departure. In a frontend test,
|
|
393
550
|
the generated mock's `interactions.<name>.request(input)` resolves with the
|
|
394
551
|
registered handler's answer; see the
|
|
395
|
-
[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).
|
|
396
553
|
|
|
397
554
|
## `useCollectionViewport(options)`
|
|
398
555
|
|
|
399
556
|
Follows a fixed-row-height scroll container and returns `{ viewport, ref }`.
|
|
400
|
-
`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)
|
|
401
558
|
range for the container; it changes only when the range or sizes change. Send
|
|
402
559
|
the range to the ViewModel from an effect:
|
|
403
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.
|
|
@@ -123,6 +155,150 @@ export interface LatestOperationHandle<TResult, TFailure = never> extends Latest
|
|
|
123
155
|
* ```
|
|
124
156
|
*/
|
|
125
157
|
export declare function useLatestOperation<TResult = void, TFailure = never>(): LatestOperationHandle<TResult, TFailure>;
|
|
158
|
+
export interface TextFieldHandle {
|
|
159
|
+
/** What the input shows: the draft while one exists, otherwise the member's value in the View's state. */
|
|
160
|
+
readonly value: string;
|
|
161
|
+
/**
|
|
162
|
+
* True while a draft exists, from the first input until the last write settled and the state caught up, and after a
|
|
163
|
+
* failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state, which
|
|
164
|
+
* the field's own write causes.
|
|
165
|
+
*/
|
|
166
|
+
readonly editing: boolean;
|
|
167
|
+
/** Why the latest write failed, until the next input or `reset()`. */
|
|
168
|
+
readonly error: unknown;
|
|
169
|
+
/** The input's `onChange`: the user changed the text. */
|
|
170
|
+
onChange(event: {
|
|
171
|
+
readonly currentTarget: {
|
|
172
|
+
readonly value: string;
|
|
173
|
+
};
|
|
174
|
+
}): void;
|
|
175
|
+
/** The input's `onCompositionStart`: the text is kept but not written until the IME composition ends. */
|
|
176
|
+
onCompositionStart(): void;
|
|
177
|
+
/** The input's `onCompositionEnd`: the composed text is written. */
|
|
178
|
+
onCompositionEnd(event: {
|
|
179
|
+
readonly currentTarget: {
|
|
180
|
+
readonly value: string;
|
|
181
|
+
};
|
|
182
|
+
}): void;
|
|
183
|
+
/** Drops the draft and the error and shows the View's value. Writes in flight still complete. */
|
|
184
|
+
reset(): void;
|
|
185
|
+
}
|
|
186
|
+
export interface UseTextFieldOptions {
|
|
187
|
+
/**
|
|
188
|
+
* With `true` (the default) at most one write is in flight, and text typed meanwhile is written next, as one
|
|
189
|
+
* value. With `false` every change is written. Read when the component mounts.
|
|
190
|
+
*/
|
|
191
|
+
readonly coalesce?: boolean;
|
|
192
|
+
/**
|
|
193
|
+
* With `true` (the default) a failed write keeps the draft and sets `error`; with `false` the field shows the
|
|
194
|
+
* View's value again. Read when the component mounts.
|
|
195
|
+
*/
|
|
196
|
+
readonly keepDraftOnError?: boolean;
|
|
197
|
+
}
|
|
198
|
+
/** The View a text field binds to: a {@link useView} handle, or any state and client. */
|
|
199
|
+
export interface TextFieldView<TClient extends ViewClient> {
|
|
200
|
+
readonly state: TClient["snapshot"] | undefined;
|
|
201
|
+
readonly client: TClient | undefined;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Binds a controlled text input to one member of a View while the component is mounted, through
|
|
205
|
+
* `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
|
|
206
|
+
* shows what the user typed, at most one write is in flight (newer text is written next), nothing is written during
|
|
207
|
+
* IME composition, and once the last write settled it shows the View's value, including any normalization. `read`
|
|
208
|
+
* and `write` may close over render values; the latest ones are used.
|
|
209
|
+
*
|
|
210
|
+
* ```tsx
|
|
211
|
+
* const person = useView(page);
|
|
212
|
+
* const name = useTextField(person, state => state.name, (client, value) => client.setName(value));
|
|
213
|
+
* <input value={name.value} onChange={name.onChange}
|
|
214
|
+
* onCompositionStart={name.onCompositionStart} onCompositionEnd={name.onCompositionEnd} />
|
|
215
|
+
* ```
|
|
216
|
+
*
|
|
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.
|
|
220
|
+
* Unmounting writes text that waits for a write in flight, and stops updating the handle.
|
|
221
|
+
*/
|
|
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>;
|
|
126
302
|
export interface BridgeConnectionHandle {
|
|
127
303
|
/** The connection to the .NET host, as `onBridgeConnection` reports it. */
|
|
128
304
|
readonly state: BridgeConnectionState;
|
|
@@ -141,4 +317,5 @@ export declare function useBridgeConnection(options?: BridgeConnectionOptions):
|
|
|
141
317
|
export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
|
|
142
318
|
export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
|
|
143
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";
|
|
144
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
|
-
import { createElement, useCallback, useEffect, useInsertionEffect, useReducer, useRef, useState, useSyncExternalStore, } from "react";
|
|
2
|
-
import { createCommandController, createLatestOperationController, createOperationController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
|
|
3
|
-
import { isViewClient, viewSourceIdentity } from "@runic-artifex/views/bindings";
|
|
1
|
+
import { createElement, useCallback, useEffect, useInsertionEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from "react";
|
|
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) {
|
|
@@ -209,6 +264,133 @@ export function useLatestOperation() {
|
|
|
209
264
|
const current = useSyncExternalStore(controller.subscribe, read, read);
|
|
210
265
|
return { ...current, run: controller.run, clear: controller.clear };
|
|
211
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Binds a controlled text input to one member of a View while the component is mounted, through
|
|
269
|
+
* `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
|
|
270
|
+
* shows what the user typed, at most one write is in flight (newer text is written next), nothing is written during
|
|
271
|
+
* IME composition, and once the last write settled it shows the View's value, including any normalization. `read`
|
|
272
|
+
* and `write` may close over render values; the latest ones are used.
|
|
273
|
+
*
|
|
274
|
+
* ```tsx
|
|
275
|
+
* const person = useView(page);
|
|
276
|
+
* const name = useTextField(person, state => state.name, (client, value) => client.setName(value));
|
|
277
|
+
* <input value={name.value} onChange={name.onChange}
|
|
278
|
+
* onCompositionStart={name.onCompositionStart} onCompositionEnd={name.onCompositionEnd} />
|
|
279
|
+
* ```
|
|
280
|
+
*
|
|
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.
|
|
284
|
+
* Unmounting writes text that waits for a write in flight, and stops updating the handle.
|
|
285
|
+
*/
|
|
286
|
+
export function useTextField(view, read, write, options = {}) {
|
|
287
|
+
const latest = useRef({ read, write });
|
|
288
|
+
useInsertionEffect(() => { latest.current = { read, write }; });
|
|
289
|
+
const controller = useMountedController(() => createTextFieldController({
|
|
290
|
+
read: state => latest.current.read(state),
|
|
291
|
+
write: (client, value) => latest.current.write(client, value),
|
|
292
|
+
...options.coalesce === undefined ? {} : { coalesce: options.coalesce },
|
|
293
|
+
...options.keepDraftOnError === undefined ? {} : { keepDraftOnError: options.keepDraftOnError },
|
|
294
|
+
}));
|
|
295
|
+
const { state, client } = view;
|
|
296
|
+
useEffect(() => {
|
|
297
|
+
controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
|
|
298
|
+
}, [controller, state, client]);
|
|
299
|
+
const readCurrent = useCallback(() => controller.current, [controller]);
|
|
300
|
+
const current = useSyncExternalStore(controller.subscribe, readCurrent, readCurrent);
|
|
301
|
+
const handlers = useMemo(() => ({
|
|
302
|
+
onChange: (event) => controller.input(event.currentTarget.value),
|
|
303
|
+
onCompositionStart: () => controller.compositionStart(),
|
|
304
|
+
onCompositionEnd: (event) => controller.compositionEnd(event.currentTarget.value),
|
|
305
|
+
reset: () => controller.reset(),
|
|
306
|
+
}), [controller]);
|
|
307
|
+
// Without a draft the field shows the state being rendered, which the effect passes to the controller after the render.
|
|
308
|
+
const value = current.editing ? current.value : state === undefined ? "" : read(state);
|
|
309
|
+
return { value, editing: current.editing, error: current.error, ...handlers };
|
|
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
|
+
}
|
|
212
394
|
// The state before the component subscribes: a subscription reports it at once.
|
|
213
395
|
function currentBridgeConnection(options) {
|
|
214
396
|
let current = "connecting";
|
|
@@ -240,4 +422,5 @@ const serverConnectionState = () => "connecting";
|
|
|
240
422
|
export { retrySuspenseView, useSuspenseView } from "./suspense.js";
|
|
241
423
|
export { useCollectionViewport } from "./viewport.js";
|
|
242
424
|
export { onBridgeConnection } from "@runic-artifex/views";
|
|
425
|
+
export { FieldError, } from "@runic-artifex/views";
|
|
243
426
|
export { useMenuBar, } from "./menu-bar.js";
|
package/dist/menu-bar.js
CHANGED
|
@@ -38,7 +38,7 @@ function createMenuBarStore(shortcuts) {
|
|
|
38
38
|
},
|
|
39
39
|
invoke: item => controller
|
|
40
40
|
? controller.invoke(item)
|
|
41
|
-
: Promise.reject(new BridgeError("disconnected", "The menu bar is not connected yet.", { route: "
|
|
41
|
+
: Promise.reject(new BridgeError("disconnected", "The menu bar is not connected yet.", { route: "runic.menu-bar" })),
|
|
42
42
|
handleKeyDown: event => controller?.handleKeyDown(event) ?? false,
|
|
43
43
|
};
|
|
44
44
|
}
|
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,13 +30,15 @@
|
|
|
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
|
+
"esbuild": "0.28.2",
|
|
39
40
|
"happy-dom": "21.0.4",
|
|
41
|
+
"playwright-core": "1.63.0",
|
|
40
42
|
"react": "19.3.0",
|
|
41
43
|
"react-dom": "19.3.0",
|
|
42
44
|
"typescript": "6.0.3",
|
|
@@ -51,7 +53,7 @@
|
|
|
51
53
|
"url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
|
|
52
54
|
"directory": "packages/web/react"
|
|
53
55
|
},
|
|
54
|
-
"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",
|
|
55
57
|
"bugs": {
|
|
56
58
|
"url": "https://github.com/Runic-Artifex/runic-sdk/issues"
|
|
57
59
|
},
|
|
@@ -61,5 +63,5 @@
|
|
|
61
63
|
"views",
|
|
62
64
|
"react"
|
|
63
65
|
],
|
|
64
|
-
"gitHead": "
|
|
66
|
+
"gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
|
|
65
67
|
}
|