@runic-artifex/react 0.15.1 → 0.16.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 +176 -11
- package/dist/form.d.ts +32 -0
- package/dist/form.js +45 -0
- package/dist/index.d.ts +65 -4
- package/dist/index.js +60 -13
- package/dist/query.d.ts +20 -0
- package/dist/query.js +46 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -199,13 +199,41 @@ same on every render. `aria-invalid` is true while the field has `errors` or an
|
|
|
199
199
|
`errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
|
|
200
200
|
or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
|
|
201
201
|
`invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
|
|
202
|
-
[field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
202
|
+
[field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#fields) for the receipts
|
|
203
203
|
and text forms.
|
|
204
204
|
|
|
205
|
+
#### Row cells and nested members
|
|
206
|
+
|
|
207
|
+
Since 0.16, `InvoiceFields.address.street` and `InvoiceFields.lines.at(line.id).quantity` are fields too
|
|
208
|
+
(`field-paths/1`): a member of an object member, and a cell of a row that .NET edits with `[RunicRowEditor]`. Bind
|
|
209
|
+
each cell in the row's component; `at(key)` returns the same descriptor for the same key, so the field survives
|
|
210
|
+
re-renders and moves:
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
function LineRow({ invoice, line }: { invoice: InvoiceView; line: InvoiceLine }) {
|
|
214
|
+
const quantity = useField(invoice, InvoiceFields.lines.at(line.id).quantity, { commit: "pause" });
|
|
215
|
+
return <td><input {...quantity.inputProps} />{quantity.conflict && <button onClick={quantity.retry}>Keep mine</button>}</td>;
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Such a field always writes checked, conflicts only when another writer changed the same cell, and shows the messages
|
|
220
|
+
.NET reports at the cell's validation path. See [Fields below a member and row cells](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/web/react/../views/README.md#fields-below-a-member-and-row-cells).
|
|
221
|
+
|
|
222
|
+
### Forms: `useForm(fields, options?)`
|
|
223
|
+
|
|
224
|
+
One state over a component's field handles, and a `submit` that writes every field before its command
|
|
225
|
+
(`createFormController` in `@runic-artifex/views`). `dirty` counts drafts not written yet and the `dirty` option, such
|
|
226
|
+
as the View's `isDirty`; `pending` is true while a draft, a check (`validating`) or a submit runs.
|
|
227
|
+
|
|
228
|
+
```tsx
|
|
229
|
+
const form = useForm({ title, step }, { dirty: editor.state?.isDirty });
|
|
230
|
+
<button disabled={!form.valid || form.submitting} onClick={() => form.submit(() => editor.client!.save())}>Save</button>
|
|
231
|
+
```
|
|
232
|
+
|
|
205
233
|
### Text inputs: `useTextField(view, read, write, options?)`
|
|
206
234
|
|
|
207
235
|
Binds a controlled text input to a member through the framework-neutral
|
|
208
|
-
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
236
|
+
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#text-inputs)
|
|
209
237
|
while the component is mounted. `read` and `write` may close over render values:
|
|
210
238
|
|
|
211
239
|
```tsx
|
|
@@ -296,6 +324,69 @@ reference whose kind has no component, and its markup (including any `role`) is
|
|
|
296
324
|
missing={page => <p role="alert">{t("missingView", { kind: page.kind })}</p>} />
|
|
297
325
|
```
|
|
298
326
|
|
|
327
|
+
### Region collections
|
|
328
|
+
|
|
329
|
+
A .NET `[RunicRegionCollection]` member, such as `state.documents`, lists
|
|
330
|
+
regions that each keep their own back stack. `<RegionOutlets>` renders a
|
|
331
|
+
`ViewOutlet` for each region, keyed by the region's key, inside a
|
|
332
|
+
`<div data-region-key>`. The default `mode="keep-mounted"` keeps every region mounted
|
|
333
|
+
and sets `hidden` and an inline `display: none` on all but the selected one, so
|
|
334
|
+
a tab keeps its component, scroll position and unsent input. Author CSS cannot
|
|
335
|
+
show a hidden panel without `!important`. `mode="selected"` renders only the
|
|
336
|
+
selected region. `fallback` renders while there is no region, and `missing` is
|
|
337
|
+
passed to each outlet. A region with `content: null` renders nothing.
|
|
338
|
+
|
|
339
|
+
The package has no tab bar. Build one with `regionEntries` and the generated
|
|
340
|
+
`selectDocuments(key)` and `closeDocuments(key)`. `panelProps(entry)` returns attributes for each region's wrapper, such as `id`,
|
|
341
|
+
`role="tabpanel"` and `aria-labelledby`, so each tab can name its panel in
|
|
342
|
+
`aria-controls`. `hidden` and `data-region-key` stay controlled by the outlet,
|
|
343
|
+
and a returned `style` is merged with its `display: none`.
|
|
344
|
+
|
|
345
|
+
```tsx
|
|
346
|
+
const tabId = (key: string) => `document-tab-${key}`;
|
|
347
|
+
const panelId = (key: string) => `document-panel-${key}`;
|
|
348
|
+
const [refocus, setRefocus] = useState(false);
|
|
349
|
+
useEffect(() => {
|
|
350
|
+
if (!refocus) return;
|
|
351
|
+
const key = selectedRegion(state?.documents)?.key;
|
|
352
|
+
if (key) document.getElementById(tabId(key))?.focus();
|
|
353
|
+
setRefocus(false);
|
|
354
|
+
}, [refocus, state?.documents]);
|
|
355
|
+
async function close(key: string) {
|
|
356
|
+
if ((await client?.closeDocuments(key))?.kind === "Committed") setRefocus(true);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
<div role="tablist">
|
|
360
|
+
{regionEntries(state?.documents).map(tab => (
|
|
361
|
+
<span key={tab.key}>
|
|
362
|
+
<button id={tabId(tab.key)} role="tab" aria-selected={tab.selected} aria-controls={panelId(tab.key)}
|
|
363
|
+
onClick={() => void client?.selectDocuments(tab.key)}>
|
|
364
|
+
{tab.content?.kind ?? "Empty"}
|
|
365
|
+
</button>
|
|
366
|
+
<button aria-label="Close" onClick={() => void close(tab.key)}>×</button>
|
|
367
|
+
</span>
|
|
368
|
+
))}
|
|
369
|
+
</div>
|
|
370
|
+
<RegionOutlets collection={state?.documents} registry={documentPages} fallback={<p>No open documents</p>}
|
|
371
|
+
panelProps={tab => ({ id: panelId(tab.key), role: "tabpanel", "aria-labelledby": tabId(tab.key) })} />
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
`selected` changes only when a switch or close commits. A departure guard can
|
|
375
|
+
keep the current tab, so highlight `selected` and do not move the highlight
|
|
376
|
+
before the request settles. `select…` and `close…` resolve to the .NET
|
|
377
|
+
`NavigationOutcome`, such as `{ kind: "Rejected", rejection: "Guard" }`.
|
|
378
|
+
|
|
379
|
+
Closing the selected tab removes its button, and the next tab becomes selected
|
|
380
|
+
when the close commits. After `closeDocuments` resolves with `kind: "Committed"`,
|
|
381
|
+
move focus to the button of the new selected tab, as `close` above does.
|
|
382
|
+
|
|
383
|
+
In both modes the region collection keeps presenting every region's content,
|
|
384
|
+
so the pages of hidden tabs stay live and still receive state. `"selected"`
|
|
385
|
+
mode only unmounts the components of the regions that are not selected.
|
|
386
|
+
|
|
387
|
+
`regionEntries`, `selectedRegion` and the region types are re-exported from
|
|
388
|
+
`@runic-artifex/views`.
|
|
389
|
+
|
|
299
390
|
## `useCommand(command)`
|
|
300
391
|
|
|
301
392
|
Returns `{ run, pending, error, failure, reset }`. `run(...args)` calls the latest
|
|
@@ -325,7 +416,7 @@ neither.
|
|
|
325
416
|
## `useOperation(start, options?)`
|
|
326
417
|
|
|
327
418
|
Observes a generated `start<Command>()` operation through the framework-neutral
|
|
328
|
-
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
419
|
+
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
329
420
|
`run(...args)` calls the latest `start`, so it may close over the current client:
|
|
330
421
|
|
|
331
422
|
```tsx
|
|
@@ -357,7 +448,7 @@ controller's options.
|
|
|
357
448
|
|
|
358
449
|
Admits only the newest of several reads, for example loading the item the user
|
|
359
450
|
selected last, through the framework-neutral
|
|
360
|
-
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
451
|
+
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
361
452
|
Each `run(intent)` replaces the queued intent and cancels the active read; the next
|
|
362
453
|
read starts only after the previous one reaches its terminal status and the intent's
|
|
363
454
|
optional `waitForCompletion` barrier:
|
|
@@ -388,7 +479,7 @@ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here sinc
|
|
|
388
479
|
`{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
|
|
389
480
|
`connected`, `reconnecting`, `lost` or `closed` (the application closed the
|
|
390
481
|
window, since 0.15; a closed set, see
|
|
391
|
-
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
482
|
+
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#connection-state)):
|
|
392
483
|
|
|
393
484
|
```tsx
|
|
394
485
|
import { useBridgeConnection } from "@runic-artifex/react";
|
|
@@ -409,7 +500,7 @@ subscribes again; an invalid one throws a `RangeError`. A server render reads
|
|
|
409
500
|
Follows the declared menu bar of a Runic Desktop window that leaves it to the
|
|
410
501
|
page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
|
|
411
502
|
wraps `createMenuBarController` from `@runic-artifex/views` (see
|
|
412
|
-
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
503
|
+
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
|
|
413
504
|
`MenuBarState`, and the bar is rendered by the menubar component of the
|
|
414
505
|
application's own UI library. Runic ships no menubar component.
|
|
415
506
|
|
|
@@ -439,7 +530,7 @@ The controller starts in an effect, so a server render reads `connecting`, and
|
|
|
439
530
|
|
|
440
531
|
Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
|
|
441
532
|
Menubar) with a controlled open menu; the
|
|
442
|
-
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
533
|
+
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
|
|
443
534
|
items and is tested with real keys:
|
|
444
535
|
|
|
445
536
|
```tsx
|
|
@@ -490,6 +581,23 @@ With Radix (`@radix-ui/react-menubar`) the open menu is the root's controlled
|
|
|
490
581
|
Check items are `Menubar.CheckboxItem checked`, radio groups
|
|
491
582
|
`Menubar.RadioGroup value` with `Menubar.RadioItem`.
|
|
492
583
|
|
|
584
|
+
## `useText(value, fallback?)`
|
|
585
|
+
|
|
586
|
+
Shows a text reference that a ViewModel produced, such as a status line or a
|
|
587
|
+
validation error's `text`, in the window's language, and renders again when the
|
|
588
|
+
language changes. A string shows as it is; `null` and `undefined` show
|
|
589
|
+
`fallback`. Connect the page's Translations runtime once with
|
|
590
|
+
`configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
|
|
591
|
+
`useWindowLocale()` reads the window's locale.
|
|
592
|
+
|
|
593
|
+
```tsx
|
|
594
|
+
const status = useText(view.state?.status);
|
|
595
|
+
<p>{status}</p>
|
|
596
|
+
function ErrorLine({ error }: { error: BridgeValidationMessage }) {
|
|
597
|
+
return <li>{useText(error.text, error.message)}</li>;
|
|
598
|
+
}
|
|
599
|
+
```
|
|
600
|
+
|
|
493
601
|
## Errors
|
|
494
602
|
|
|
495
603
|
The `error` of `useView` and of a command or operation handle is typed
|
|
@@ -507,7 +615,7 @@ const offline = isBridgeError(error, "disconnected");
|
|
|
507
615
|
```
|
|
508
616
|
|
|
509
617
|
`instanceof` holds for errors from every copy of the package on the page.
|
|
510
|
-
[Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
618
|
+
[Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#errors-and-diagnostics)
|
|
511
619
|
lists the kinds. Any other value, such as an exception that your own connect
|
|
512
620
|
function or command callback throws, arrives unchanged.
|
|
513
621
|
|
|
@@ -549,16 +657,45 @@ the application's own dialog.
|
|
|
549
657
|
such as a close during the page's first render, is answered by the
|
|
550
658
|
ViewModel's .NET fallback handler, or fails closed without one.
|
|
551
659
|
|
|
552
|
-
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.
|
|
660
|
+
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
|
|
553
661
|
has the .NET side and which View answers which departure. In a frontend test,
|
|
554
662
|
the generated mock's `interactions.<name>.request(input)` resolves with the
|
|
555
663
|
registered handler's answer; see the
|
|
556
|
-
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
664
|
+
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#testing).
|
|
665
|
+
|
|
666
|
+
## View requests
|
|
667
|
+
|
|
668
|
+
A `ViewRequest<T>` property of the ViewModel asks the View for a one-way
|
|
669
|
+
presentation action, such as focusing a field or showing a toast, and is
|
|
670
|
+
`client.requests.<name>` on the generated client. Register the page's
|
|
671
|
+
handler in an effect: `handle((input, { signal }) => …)` returns the function
|
|
672
|
+
that removes it, so React removes the handler when the page unmounts or its
|
|
673
|
+
client changes:
|
|
674
|
+
|
|
675
|
+
```tsx
|
|
676
|
+
export function EditPage({ page }: { page: EditPageReference }) {
|
|
677
|
+
const { client } = useView(page);
|
|
678
|
+
const name = useRef<HTMLInputElement>(null);
|
|
679
|
+
useEffect(() => client?.requests.focus.handle(({ member }) => {
|
|
680
|
+
if (member === "name") name.current?.focus();
|
|
681
|
+
}), [client]);
|
|
682
|
+
return <input ref={name} />;
|
|
683
|
+
}
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
`input` is typed from the request's `ViewRequest<T>`. The handler runs once
|
|
687
|
+
the page painted the state the request was raised with, so the field of that
|
|
688
|
+
state is rendered; `signal` aborts when the handler is replaced or removed, the
|
|
689
|
+
client is disposed or the connection is lost. A request is never replayed: one
|
|
690
|
+
raised before the effect ran, or while the page is disconnected, is not
|
|
691
|
+
delivered later. See [View requests](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#view-requests) for the rules, and in a frontend
|
|
692
|
+
test raise one with the generated mock's `requests.<name>.raise(input)` (the
|
|
693
|
+
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#testing)).
|
|
557
694
|
|
|
558
695
|
## `useCollectionViewport(options)`
|
|
559
696
|
|
|
560
697
|
Follows a fixed-row-height scroll container and returns `{ viewport, ref }`.
|
|
561
|
-
`viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
698
|
+
`viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#collectionviewportoptions)
|
|
562
699
|
range for the container; it changes only when the range or sizes change. Send
|
|
563
700
|
the range to the ViewModel from an effect:
|
|
564
701
|
|
|
@@ -574,3 +711,31 @@ return <div ref={ref} style={{ height: 480, overflow: "auto" }}>
|
|
|
574
711
|
</div>
|
|
575
712
|
</div>;
|
|
576
713
|
```
|
|
714
|
+
|
|
715
|
+
## `useQueryCollection(collection, options)`
|
|
716
|
+
|
|
717
|
+
Follows a scroll container for a [query collection](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#query-collections) (`client.queries.{name}`), whose rows stay in .NET: it
|
|
718
|
+
loads the rows the container shows, with placeholders until they arrive, and lays them out with variable heights
|
|
719
|
+
(`estimateSize` for rows not measured yet). It returns the `QueryViewport` (`items` with `top` and `size`, `totalSize`,
|
|
720
|
+
`total`, `query`, `loading`, `error`), `ref` for the container, `measure(index)` for each row, and `scrollToKey`,
|
|
721
|
+
`scrollToIndex`, `setQuery` and `retry`:
|
|
722
|
+
|
|
723
|
+
```tsx
|
|
724
|
+
const list = useQueryCollection(client.queries.rows, { estimateSize: 32 });
|
|
725
|
+
return <div ref={list.ref} style={{ height: 480, overflow: "auto" }}>
|
|
726
|
+
<div style={{ height: list.totalSize, position: "relative" }}>
|
|
727
|
+
{list.items.map(item => <div key={item.key ?? `p${item.index}`} ref={list.measure(item.index)} style={{ position: "absolute", top: item.top, width: "100%" }}>
|
|
728
|
+
{item.row?.label ?? "…"}
|
|
729
|
+
</div>)}
|
|
730
|
+
</div>
|
|
731
|
+
</div>;
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
## Back and the URL
|
|
735
|
+
|
|
736
|
+
The package re-exports `installBackNavigation`, `installNavigationPath`,
|
|
737
|
+
`navigateBack`, `openNavigationPath` and `onNavigationPath` from
|
|
738
|
+
`@runic-artifex/views` (since 0.16). Call the installs once where the page
|
|
739
|
+
starts, before or after mounting: the mouse's Back button and Alt+Left then go
|
|
740
|
+
back in the .NET window, and `#/customers/42` follows its path region. See
|
|
741
|
+
[Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/web/views/README.md#back-and-the-url).
|
package/dist/form.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type FieldState, type FormField, type FormFields, type FormState, type FormSubmitOptions, type FormSubmitResult } from "@runic-artifex/views";
|
|
2
|
+
/** A field as {@link useForm} reads it: a `useField` handle. */
|
|
3
|
+
export type FormFieldHandle = FormField & Pick<FieldState<unknown>, "editing" | "validating" | "errors" | "error">;
|
|
4
|
+
export interface UseFormOptions {
|
|
5
|
+
/** Whether the View reports unsaved changes, such as `editor.state?.isDirty`. A field's draft makes the form dirty in any case. */
|
|
6
|
+
readonly dirty?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** A form bound by {@link useForm}: its state in this render and its actions, which are the same on every render. */
|
|
9
|
+
export type FormHandle = FormState & {
|
|
10
|
+
/**
|
|
11
|
+
* Commits every field, waits for their writes and runs `command` unless a field's write or text failed:
|
|
12
|
+
* `onClick={() => form.submit(() => editor.client!.save())}`. While it runs `submitting` is true and another `submit`
|
|
13
|
+
* resolves `busy`.
|
|
14
|
+
*/
|
|
15
|
+
submit<T>(command: () => T | PromiseLike<T>, options?: FormSubmitOptions): Promise<FormSubmitResult<T>>;
|
|
16
|
+
/** Commits every field and resolves once their writes settled, with the fields' state then. */
|
|
17
|
+
commit(): Promise<FormState>;
|
|
18
|
+
/** Resets every field. */
|
|
19
|
+
reset(): void;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* One dirty, pending and valid state over the `useField` handles of a component, and a `submit` that writes every
|
|
23
|
+
* field before its command (`createFormController` in `@runic-artifex/views`):
|
|
24
|
+
*
|
|
25
|
+
* ```tsx
|
|
26
|
+
* const title = useField(editor, EditorFields.title, { commit: "pause" });
|
|
27
|
+
* const body = useField(editor, EditorFields.body, { commit: "pause" });
|
|
28
|
+
* const form = useForm({ title, body }, { dirty: editor.state?.isDirty });
|
|
29
|
+
* <button disabled={!form.valid || form.submitting} onClick={() => form.submit(() => editor.client!.save())}>Save</button>
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function useForm(fields: FormFields<FormFieldHandle>, options?: UseFormOptions): FormHandle;
|
package/dist/form.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { useInsertionEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { formFieldList, formStateOf, submitFields, } from "@runic-artifex/views";
|
|
3
|
+
/**
|
|
4
|
+
* One dirty, pending and valid state over the `useField` handles of a component, and a `submit` that writes every
|
|
5
|
+
* field before its command (`createFormController` in `@runic-artifex/views`):
|
|
6
|
+
*
|
|
7
|
+
* ```tsx
|
|
8
|
+
* const title = useField(editor, EditorFields.title, { commit: "pause" });
|
|
9
|
+
* const body = useField(editor, EditorFields.body, { commit: "pause" });
|
|
10
|
+
* const form = useForm({ title, body }, { dirty: editor.state?.isDirty });
|
|
11
|
+
* <button disabled={!form.valid || form.submitting} onClick={() => form.submit(() => editor.client!.save())}>Save</button>
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export function useForm(fields, options = {}) {
|
|
15
|
+
const list = formFieldList(fields);
|
|
16
|
+
const latest = useRef(list);
|
|
17
|
+
useInsertionEffect(() => { latest.current = list; });
|
|
18
|
+
const [submitting, setSubmitting] = useState(false);
|
|
19
|
+
const busy = useRef(false);
|
|
20
|
+
const dirty = useRef(options.dirty === true);
|
|
21
|
+
dirty.current = options.dirty === true;
|
|
22
|
+
const actions = useMemo(() => ({
|
|
23
|
+
async submit(command, submitOptions = {}) {
|
|
24
|
+
if (busy.current)
|
|
25
|
+
return { status: "busy" };
|
|
26
|
+
busy.current = true;
|
|
27
|
+
setSubmitting(true);
|
|
28
|
+
// The handles of the latest render are the fields' state now.
|
|
29
|
+
try {
|
|
30
|
+
return await submitFields(latest.current, command, submitOptions, index => latest.current[index]);
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
busy.current = false;
|
|
34
|
+
setSubmitting(false);
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
async commit() {
|
|
38
|
+
const states = await Promise.all(latest.current.map(field => field.commit()));
|
|
39
|
+
return formStateOf(states, dirty.current, busy.current);
|
|
40
|
+
},
|
|
41
|
+
reset() { for (const field of latest.current)
|
|
42
|
+
field.reset(); },
|
|
43
|
+
}), []);
|
|
44
|
+
return { ...formStateOf(list, options.dirty === true, submitting), ...actions };
|
|
45
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type ComponentType, type ReactNode } from "react";
|
|
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";
|
|
1
|
+
import { type ComponentType, type HTMLAttributes, type ReactNode } from "react";
|
|
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 TextReference, type RegionCollection, type RegionEntry, type ViewClient, type ViewSource } from "@runic-artifex/views";
|
|
3
3
|
export interface ViewHandle<TClient extends ViewClient> {
|
|
4
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;
|
|
@@ -88,6 +88,41 @@ export interface ViewOutletProps<R extends PageReference> {
|
|
|
88
88
|
* component. A kind without a component renders `missing`, or an English alert without it.
|
|
89
89
|
*/
|
|
90
90
|
export declare function ViewOutlet<R extends PageReference>({ content, registry, fallback, missing }: ViewOutletProps<R>): ReactNode;
|
|
91
|
+
/** How {@link RegionOutlets} renders the regions of a collection. */
|
|
92
|
+
export type RegionOutletsMode = "keep-mounted" | "selected";
|
|
93
|
+
/**
|
|
94
|
+
* Attributes that {@link RegionOutlets} merges onto a region's wrapper, such as `id`, `role` and `aria-labelledby`.
|
|
95
|
+
* `hidden` and `data-region-key` stay controlled by the outlet, and a `style` is merged with its `display: none`.
|
|
96
|
+
*/
|
|
97
|
+
export type RegionPanelAttributes = Omit<HTMLAttributes<HTMLDivElement>, "hidden"> & {
|
|
98
|
+
readonly [attribute: `data-${string}`]: string | undefined;
|
|
99
|
+
};
|
|
100
|
+
export interface RegionOutletsProps<R extends PageReference> {
|
|
101
|
+
/** The presented region collection, such as `state.documents`. */
|
|
102
|
+
readonly collection: RegionCollection<R> | null | undefined;
|
|
103
|
+
readonly registry: ViewRegistry<R>;
|
|
104
|
+
/** Rendered while the collection has no region. Defaults to nothing. */
|
|
105
|
+
readonly fallback?: ReactNode;
|
|
106
|
+
/** Renders a reference whose kind has no registered component, as in {@link ViewOutlet}. */
|
|
107
|
+
readonly missing?: (content: R) => ReactNode;
|
|
108
|
+
/**
|
|
109
|
+
* `"keep-mounted"` (the default) renders every region and hides all but the selected one, so each region keeps
|
|
110
|
+
* its component and DOM. `"selected"` renders only the selected region.
|
|
111
|
+
*/
|
|
112
|
+
readonly mode?: RegionOutletsMode;
|
|
113
|
+
/**
|
|
114
|
+
* Returns attributes for a region's wrapper, for example `{ id, role: "tabpanel", "aria-labelledby" }`, so a tab
|
|
115
|
+
* can point `aria-controls` at the panel.
|
|
116
|
+
*/
|
|
117
|
+
readonly panelProps?: (entry: RegionEntry<R>) => RegionPanelAttributes;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Renders a {@link ViewOutlet} for the regions of a region collection, each in a `<div data-region-key>` keyed by
|
|
121
|
+
* the region's key. A region that is not selected is rendered with `hidden` and an inline `display: none`, which
|
|
122
|
+
* author CSS without `!important` cannot override. A new content reference in a region remounts only that region's
|
|
123
|
+
* component.
|
|
124
|
+
*/
|
|
125
|
+
export declare function RegionOutlets<R extends PageReference>({ collection, registry, fallback, missing, mode, panelProps }: RegionOutletsProps<R>): ReactNode;
|
|
91
126
|
export interface CommandHandle<TArgs extends readonly unknown[], TResult, TFailure = BridgeOutcomeFailure<TResult>> {
|
|
92
127
|
/**
|
|
93
128
|
* Runs the command. Resolves to its result, including a `BridgeOutcome` with a
|
|
@@ -298,7 +333,7 @@ export type FieldHandle<TValue> = FieldState<TValue> & {
|
|
|
298
333
|
* With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
|
|
299
334
|
* conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
|
|
300
335
|
*/
|
|
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>;
|
|
336
|
+
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<TValue>): FieldHandle<TValue>;
|
|
302
337
|
export interface BridgeConnectionHandle {
|
|
303
338
|
/** The connection to the .NET host, as `onBridgeConnection` reports it. */
|
|
304
339
|
readonly state: BridgeConnectionState;
|
|
@@ -314,8 +349,34 @@ export interface BridgeConnectionHandle {
|
|
|
314
349
|
* ```
|
|
315
350
|
*/
|
|
316
351
|
export declare function useBridgeConnection(options?: BridgeConnectionOptions): BridgeConnectionHandle;
|
|
352
|
+
/**
|
|
353
|
+
* Renders a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
|
|
354
|
+
* window's language (`resolveText`), and renders again when the language changes. A string renders as it is;
|
|
355
|
+
* `null` and `undefined` render `fallback`. Configure the page's Translations runtime once with
|
|
356
|
+
* `configureTranslatedText`; without one, a reference shows its fallback text.
|
|
357
|
+
*
|
|
358
|
+
* ```tsx
|
|
359
|
+
* const status = useText(view.state?.status);
|
|
360
|
+
* <p>{status}</p>
|
|
361
|
+
* {view.state?.validation.errors.map(error => <ErrorLine key={error.message} error={error} />)}
|
|
362
|
+
* function ErrorLine({ error }) { return <li>{useText(error.text, error.message)}</li>; }
|
|
363
|
+
* ```
|
|
364
|
+
*/
|
|
365
|
+
export declare function useText(value: TextReference | string | null | undefined, fallback?: string): string;
|
|
366
|
+
/**
|
|
367
|
+
* Renders the window's locale that the application set (`IRunicWindowLocale` in .NET), or `null` while it sets none,
|
|
368
|
+
* for example to set `lang` on an element. The server snapshot is `null`.
|
|
369
|
+
*/
|
|
370
|
+
export declare function useWindowLocale(): string | null;
|
|
317
371
|
export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
|
|
318
372
|
export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
|
|
373
|
+
export { useForm, type FormFieldHandle, type FormHandle, type UseFormOptions } from "./form.js";
|
|
374
|
+
export { commitAllFields, type FormState, type FormSubmitOptions, type FormSubmitResult } from "@runic-artifex/views";
|
|
375
|
+
export { useQueryCollection, type QueryCollectionHandle } from "./query.js";
|
|
319
376
|
export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
|
|
320
|
-
export {
|
|
377
|
+
export { upload, type BlobRef, type RunicBlob, type UploadOptions, type UploadProgress } from "@runic-artifex/views";
|
|
378
|
+
export { regionEntries, selectedRegion, type RegionCollection, type RegionEntry, type RegionOutcome, type RegionSlot, } from "@runic-artifex/views";
|
|
379
|
+
export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, type NavigationPathChange, type NavigationPathOptions, type NavigationReply, } from "@runic-artifex/views";
|
|
380
|
+
export { configureTranslatedText, resolveText, windowLocale, type TextReference, type TextTranslations, } from "@runic-artifex/views";
|
|
381
|
+
export { FieldError, type BridgeField, type BridgeFieldConstraints, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
|
|
321
382
|
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,5 +1,5 @@
|
|
|
1
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";
|
|
2
|
+
import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, onWindowLocale, resolveText, subscribeText, textVersion, windowLocale, regionEntries, } from "@runic-artifex/views";
|
|
3
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.
|
|
@@ -174,6 +174,22 @@ export function ViewOutlet({ content, registry, fallback = null, missing }) {
|
|
|
174
174
|
}
|
|
175
175
|
return createElement(component, { key: referenceKey(content), page: content });
|
|
176
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Renders a {@link ViewOutlet} for the regions of a region collection, each in a `<div data-region-key>` keyed by
|
|
179
|
+
* the region's key. A region that is not selected is rendered with `hidden` and an inline `display: none`, which
|
|
180
|
+
* author CSS without `!important` cannot override. A new content reference in a region remounts only that region's
|
|
181
|
+
* component.
|
|
182
|
+
*/
|
|
183
|
+
export function RegionOutlets({ collection, registry, fallback = null, missing, mode = "keep-mounted", panelProps }) {
|
|
184
|
+
const shown = regionEntries(collection).filter(region => mode === "keep-mounted" || region.selected);
|
|
185
|
+
if (shown.length === 0)
|
|
186
|
+
return fallback;
|
|
187
|
+
return shown.map(region => {
|
|
188
|
+
const panel = panelProps?.(region) ?? {};
|
|
189
|
+
const hidden = !region.selected;
|
|
190
|
+
return createElement("div", { ...panel, key: region.key, "data-region-key": region.key, hidden, style: hidden ? { ...panel.style, display: "none" } : panel.style }, createElement((ViewOutlet), { content: region.content, registry, ...(missing ? { missing } : {}) }));
|
|
191
|
+
});
|
|
192
|
+
}
|
|
177
193
|
// A command or operation controller lives while its component is mounted: unmounting disposes it,
|
|
178
194
|
// which stops its feedback and, for an operation, settles its pending run promises and stops
|
|
179
195
|
// observing accepted work (it never cancels the work). StrictMode's simulated unmount, and a component that React shows again (`<Activity>`),
|
|
@@ -309,16 +325,6 @@ export function useTextField(view, read, write, options = {}) {
|
|
|
309
325
|
return { value, editing: current.editing, error: current.error, ...handlers };
|
|
310
326
|
}
|
|
311
327
|
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
328
|
/**
|
|
323
329
|
* Binds an element to one View member while the component is mounted, through `createFieldController`: pass a
|
|
324
330
|
* generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Spread `inputProps` on
|
|
@@ -347,11 +353,16 @@ export function useField(view, field, options = {}) {
|
|
|
347
353
|
...field.nullable === undefined ? {} : { nullable: field.nullable },
|
|
348
354
|
...field.integer === undefined ? {} : { integer: field.integer },
|
|
349
355
|
...field.choices === undefined ? {} : { choices: field.choices },
|
|
356
|
+
...field.offset === undefined ? {} : { offset: field.offset },
|
|
357
|
+
...field.constraints === undefined ? {} : { constraints: field.constraints },
|
|
358
|
+
// field-paths/1: a field below a member (InvoiceFields.lines.at(key).quantity) always writes checked.
|
|
359
|
+
...field.checkedOnly === undefined ? {} : { checkedOnly: field.checkedOnly },
|
|
350
360
|
read: state => latest.current.read(state),
|
|
351
361
|
write: (client, value) => latest.current.write(client, value),
|
|
352
362
|
...field.checked === undefined ? {} : { checked: (client, value, write) => latest.current.checked(client, value, write) },
|
|
353
363
|
...field.baseline === undefined ? {} : { baseline: client => latest.current.baseline(client) },
|
|
354
364
|
...field.errors === undefined ? {} : { errors: state => latest.current.errors(state) },
|
|
365
|
+
...field.validating === undefined ? {} : { validating: state => latest.current.validating(state) },
|
|
355
366
|
}, options));
|
|
356
367
|
const { state, client } = view;
|
|
357
368
|
useEffect(() => {
|
|
@@ -376,9 +387,10 @@ export function useField(view, field, options = {}) {
|
|
|
376
387
|
const value = current.editing ? current.value
|
|
377
388
|
: state === undefined ? (kind === "text" || kind === undefined ? "" : undefined)
|
|
378
389
|
: field.read(state);
|
|
379
|
-
const text = Object.is(value, current.value) ? current.text :
|
|
390
|
+
const text = Object.is(value, current.value) ? current.text : controller.format(value);
|
|
380
391
|
const errors = field.errors === undefined ? current.errors : state === undefined ? noFieldErrors : field.errors(state);
|
|
381
392
|
const invalid = errors.length > 0 || current.error !== undefined;
|
|
393
|
+
const validating = field.validating === undefined ? current.validating : state !== undefined && field.validating(state);
|
|
382
394
|
const inputProps = kind === "boolean"
|
|
383
395
|
? { checked: value === true, onChange: actions.onCheck, onBlur: actions.onBlur, "aria-invalid": invalid }
|
|
384
396
|
: {
|
|
@@ -386,7 +398,7 @@ export function useField(view, field, options = {}) {
|
|
|
386
398
|
onCompositionEnd: actions.onCompositionEnd, onBlur: actions.onBlur, "aria-invalid": invalid,
|
|
387
399
|
};
|
|
388
400
|
return {
|
|
389
|
-
value, text, editing: current.editing, error: current.error, errors, conflict: current.conflict,
|
|
401
|
+
value, text, editing: current.editing, error: current.error, errors, conflict: current.conflict, validating,
|
|
390
402
|
inputProps: inputProps,
|
|
391
403
|
input: actions.input, commit: actions.commit, retry: actions.retry, reset: actions.reset,
|
|
392
404
|
};
|
|
@@ -419,8 +431,43 @@ export function useBridgeConnection(options = {}) {
|
|
|
419
431
|
return { state };
|
|
420
432
|
}
|
|
421
433
|
const serverConnectionState = () => "connecting";
|
|
434
|
+
/**
|
|
435
|
+
* Renders a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
|
|
436
|
+
* window's language (`resolveText`), and renders again when the language changes. A string renders as it is;
|
|
437
|
+
* `null` and `undefined` render `fallback`. Configure the page's Translations runtime once with
|
|
438
|
+
* `configureTranslatedText`; without one, a reference shows its fallback text.
|
|
439
|
+
*
|
|
440
|
+
* ```tsx
|
|
441
|
+
* const status = useText(view.state?.status);
|
|
442
|
+
* <p>{status}</p>
|
|
443
|
+
* {view.state?.validation.errors.map(error => <ErrorLine key={error.message} error={error} />)}
|
|
444
|
+
* function ErrorLine({ error }) { return <li>{useText(error.text, error.message)}</li>; }
|
|
445
|
+
* ```
|
|
446
|
+
*/
|
|
447
|
+
export function useText(value, fallback) {
|
|
448
|
+
const version = useSyncExternalStore(subscribeText, textVersion, textVersion);
|
|
449
|
+
// version is the language the text resolves in.
|
|
450
|
+
return useMemo(() => resolveText(value, fallback), [value, fallback, version]);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Renders the window's locale that the application set (`IRunicWindowLocale` in .NET), or `null` while it sets none,
|
|
454
|
+
* for example to set `lang` on an element. The server snapshot is `null`.
|
|
455
|
+
*/
|
|
456
|
+
export function useWindowLocale() {
|
|
457
|
+
return useSyncExternalStore(subscribeWindowLocale, windowLocale, serverWindowLocale);
|
|
458
|
+
}
|
|
459
|
+
const subscribeWindowLocale = (onChange) => onWindowLocale(() => onChange());
|
|
460
|
+
const serverWindowLocale = () => null;
|
|
422
461
|
export { retrySuspenseView, useSuspenseView } from "./suspense.js";
|
|
423
462
|
export { useCollectionViewport } from "./viewport.js";
|
|
463
|
+
export { useForm } from "./form.js";
|
|
464
|
+
export { commitAllFields } from "@runic-artifex/views";
|
|
465
|
+
export { useQueryCollection } from "./query.js";
|
|
424
466
|
export { onBridgeConnection } from "@runic-artifex/views";
|
|
467
|
+
// blobs/1: uploads from the page and the blob values of state.
|
|
468
|
+
export { upload } from "@runic-artifex/views";
|
|
469
|
+
export { regionEntries, selectedRegion, } from "@runic-artifex/views";
|
|
470
|
+
export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, } from "@runic-artifex/views";
|
|
471
|
+
export { configureTranslatedText, resolveText, windowLocale, } from "@runic-artifex/views";
|
|
425
472
|
export { FieldError, } from "@runic-artifex/views";
|
|
426
473
|
export { useMenuBar, } from "./menu-bar.js";
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type QueryCollection, type QueryViewport, type QueryViewportOptions, type RunicQuery } from "@runic-artifex/views";
|
|
2
|
+
export interface QueryCollectionHandle<TRow> extends QueryViewport<TRow> {
|
|
3
|
+
/** Attach to the scroll container: `<div ref={ref}>`. */
|
|
4
|
+
readonly ref: (element: HTMLElement | null) => void;
|
|
5
|
+
/** Attach to each rendered row, so its height is measured: `<div ref={measure(item.index)}>`. */
|
|
6
|
+
readonly measure: (index: number) => (element: Element | null) => void;
|
|
7
|
+
/** Scrolls to the row with `key` in the current query; resolves `false` when no row has it. */
|
|
8
|
+
scrollToKey(key: string, align?: "start" | "center" | "end"): Promise<boolean>;
|
|
9
|
+
scrollToIndex(index: number, align?: "start" | "center" | "end"): void;
|
|
10
|
+
/** Changes the collection's sort and filter (ViewModel state every presentation shares). */
|
|
11
|
+
setQuery(query: RunicQuery): Promise<void>;
|
|
12
|
+
/** Loads the range again after a failure. */
|
|
13
|
+
retry(): void;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Follows a scroll container for a query collection (`client.queries.{name}`): it loads the rows the container shows
|
|
17
|
+
* from .NET, with placeholders until they arrive, and lays them out with variable heights. Render `items` absolutely
|
|
18
|
+
* at `top` inside a spacer of `totalSize`, and attach `measure(item.index)` to each row.
|
|
19
|
+
*/
|
|
20
|
+
export declare function useQueryCollection<TRow>(collection: QueryCollection<TRow>, options: QueryViewportOptions): QueryCollectionHandle<TRow>;
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
import { createQueryViewportController, } from "@runic-artifex/views";
|
|
3
|
+
/**
|
|
4
|
+
* Follows a scroll container for a query collection (`client.queries.{name}`): it loads the rows the container shows
|
|
5
|
+
* from .NET, with placeholders until they arrive, and lays them out with variable heights. Render `items` absolutely
|
|
6
|
+
* at `top` inside a spacer of `totalSize`, and attach `measure(item.index)` to each row.
|
|
7
|
+
*/
|
|
8
|
+
export function useQueryCollection(collection, options) {
|
|
9
|
+
// The controller follows the collection while it has subscribers, so the hook does not dispose it.
|
|
10
|
+
const controller = useMemo(() => createQueryViewportController(collection, options), [collection]);
|
|
11
|
+
const { estimateSize, overscan } = options;
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
controller.update({ estimateSize, ...(overscan === undefined ? {} : { overscan }) });
|
|
14
|
+
}, [controller, estimateSize, overscan]);
|
|
15
|
+
const read = useCallback(() => controller.current, [controller]);
|
|
16
|
+
const viewport = useSyncExternalStore(controller.subscribe, read, read);
|
|
17
|
+
const ref = useCallback((element) => controller.attach(element), [controller]);
|
|
18
|
+
// One stable ref callback per index, so React does not detach and reattach every row on every render.
|
|
19
|
+
const observed = useRef(new Map());
|
|
20
|
+
const callbacks = useMemo(() => new Map(), [controller]);
|
|
21
|
+
const measure = useCallback((index) => {
|
|
22
|
+
let callback = callbacks.get(index);
|
|
23
|
+
if (!callback) {
|
|
24
|
+
// The callbacks of rows that scrolled away are dropped once there are many; attached rows keep theirs.
|
|
25
|
+
if (callbacks.size >= 1_000)
|
|
26
|
+
for (const cached of [...callbacks.keys()])
|
|
27
|
+
if (!observed.current.has(cached))
|
|
28
|
+
callbacks.delete(cached);
|
|
29
|
+
callback = (element) => {
|
|
30
|
+
observed.current.get(index)?.();
|
|
31
|
+
observed.current.delete(index);
|
|
32
|
+
if (element)
|
|
33
|
+
observed.current.set(index, controller.observe(element, index));
|
|
34
|
+
};
|
|
35
|
+
callbacks.set(index, callback);
|
|
36
|
+
}
|
|
37
|
+
return callback;
|
|
38
|
+
}, [controller, callbacks]);
|
|
39
|
+
return {
|
|
40
|
+
...viewport, ref, measure,
|
|
41
|
+
scrollToKey: (key, align) => controller.scrollToKey(key, align),
|
|
42
|
+
scrollToIndex: (index, align) => controller.scrollToIndex(index, align),
|
|
43
|
+
setQuery: query => collection.setQuery(query),
|
|
44
|
+
retry: () => collection.retry(),
|
|
45
|
+
};
|
|
46
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runic-artifex/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.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.16.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@runic-artifex/views": "0.
|
|
36
|
+
"@runic-artifex/views": "0.16.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.16.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": "ff96e52727212344c407489283a9cafc614f0270"
|
|
67
67
|
}
|