@runic-artifex/react 0.15.1 → 0.17.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 +217 -15
- package/dist/form.d.ts +32 -0
- package/dist/form.js +45 -0
- package/dist/index.d.ts +103 -13
- package/dist/index.js +100 -16
- 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,43 @@ 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.
|
|
203
|
-
and text forms.
|
|
202
|
+
[field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#fields) for the receipts
|
|
203
|
+
and text forms. An `invalid-text` error has a `reason` and `arguments`: render `useText(name.error)` after
|
|
204
|
+
`configureFieldErrorText` to show your own text for it in the window's language
|
|
205
|
+
([Translating field errors](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#translating-field-errors)).
|
|
206
|
+
|
|
207
|
+
#### Row cells and nested members
|
|
208
|
+
|
|
209
|
+
Since 0.16, `InvoiceFields.address.street` and `InvoiceFields.lines.at(line.id).quantity` are fields too
|
|
210
|
+
(`field-paths/1`): a member of an object member, and a cell of a row that .NET edits with `[RunicRowEditor]`. Bind
|
|
211
|
+
each cell in the row's component; `at(key)` returns the same descriptor for the same key, so the field survives
|
|
212
|
+
re-renders and moves:
|
|
213
|
+
|
|
214
|
+
```tsx
|
|
215
|
+
function LineRow({ invoice, line }: { invoice: InvoiceView; line: InvoiceLine }) {
|
|
216
|
+
const quantity = useField(invoice, InvoiceFields.lines.at(line.id).quantity, { commit: "pause" });
|
|
217
|
+
return <td><input {...quantity.inputProps} />{quantity.conflict && <button onClick={quantity.retry}>Keep mine</button>}</td>;
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Such a field always writes checked, conflicts only when another writer changed the same cell, and shows the messages
|
|
222
|
+
.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.17.0/packages/web/react/../views/README.md#fields-below-a-member-and-row-cells).
|
|
223
|
+
|
|
224
|
+
### Forms: `useForm(fields, options?)`
|
|
225
|
+
|
|
226
|
+
One state over a component's field handles, and a `submit` that writes every field before its command
|
|
227
|
+
(`createFormController` in `@runic-artifex/views`). `dirty` counts drafts not written yet and the `dirty` option, such
|
|
228
|
+
as the View's `isDirty`; `pending` is true while a draft, a check (`validating`) or a submit runs.
|
|
229
|
+
|
|
230
|
+
```tsx
|
|
231
|
+
const form = useForm({ title, step }, { dirty: editor.state?.isDirty });
|
|
232
|
+
<button disabled={!form.valid || form.submitting} onClick={() => form.submit(() => editor.client!.save())}>Save</button>
|
|
233
|
+
```
|
|
204
234
|
|
|
205
235
|
### Text inputs: `useTextField(view, read, write, options?)`
|
|
206
236
|
|
|
207
237
|
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.
|
|
238
|
+
[text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#text-inputs)
|
|
209
239
|
while the component is mounted. `read` and `write` may close over render values:
|
|
210
240
|
|
|
211
241
|
```tsx
|
|
@@ -284,9 +314,16 @@ const { state } = useSuspenseView(page, { releaseTimeout: 30_000 });
|
|
|
284
314
|
`<ViewOutlet content={reference} registry={pages} fallback={…} />` renders the
|
|
285
315
|
component registered for `reference.kind` with the reference as its `page`
|
|
286
316
|
prop. Declare the registry with `satisfies ViewRegistry<State["main"]>` so each
|
|
287
|
-
kind has a component whose `page` prop matches. A
|
|
288
|
-
|
|
289
|
-
|
|
317
|
+
kind has a component whose `page` prop matches. A component whose `page` is a
|
|
318
|
+
shared page reference, such as `ResultPagePageReference` of a .NET
|
|
319
|
+
[`[RunicSharedClient]`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/react/../../dotnet/Runic.Application.Views/README.md#shared-clients)
|
|
320
|
+
interface, registers for each of its kinds:
|
|
321
|
+
`{ ...registryEntries(resultPageKinds, ResultPage), settings: Settings }`. A different reference
|
|
322
|
+
remounts the component, and `fallback` renders while `content` is empty. A kind
|
|
323
|
+
without a component renders an English `<p role="alert">` in a development build
|
|
324
|
+
(`process.env.NODE_ENV` is not `production`); a production build renders nothing
|
|
325
|
+
and reports the kind once through the page's error reporting
|
|
326
|
+
(`installErrorReporting`, `onBridgeDiagnostic`).
|
|
290
327
|
|
|
291
328
|
`missing` replaces that alert, for example with localized text. It receives the
|
|
292
329
|
reference whose kind has no component, and its markup (including any `role`) is yours:
|
|
@@ -296,6 +333,69 @@ reference whose kind has no component, and its markup (including any `role`) is
|
|
|
296
333
|
missing={page => <p role="alert">{t("missingView", { kind: page.kind })}</p>} />
|
|
297
334
|
```
|
|
298
335
|
|
|
336
|
+
### Region collections
|
|
337
|
+
|
|
338
|
+
A .NET `[RunicRegionCollection]` member, such as `state.documents`, lists
|
|
339
|
+
regions that each keep their own back stack. `<RegionOutlets>` renders a
|
|
340
|
+
`ViewOutlet` for each region, keyed by the region's key, inside a
|
|
341
|
+
`<div data-region-key>`. The default `mode="keep-mounted"` keeps every region mounted
|
|
342
|
+
and sets `hidden` and an inline `display: none` on all but the selected one, so
|
|
343
|
+
a tab keeps its component, scroll position and unsent input. Author CSS cannot
|
|
344
|
+
show a hidden panel without `!important`. `mode="selected"` renders only the
|
|
345
|
+
selected region. `fallback` renders while there is no region, and `missing` is
|
|
346
|
+
passed to each outlet. A region with `content: null` renders nothing.
|
|
347
|
+
|
|
348
|
+
The package has no tab bar. Build one with `regionEntries` and the generated
|
|
349
|
+
`selectDocuments(key)` and `closeDocuments(key)`. `panelProps(entry)` returns attributes for each region's wrapper, such as `id`,
|
|
350
|
+
`role="tabpanel"` and `aria-labelledby`, so each tab can name its panel in
|
|
351
|
+
`aria-controls`. `hidden` and `data-region-key` stay controlled by the outlet,
|
|
352
|
+
and a returned `style` is merged with its `display: none`.
|
|
353
|
+
|
|
354
|
+
```tsx
|
|
355
|
+
const tabId = (key: string) => `document-tab-${key}`;
|
|
356
|
+
const panelId = (key: string) => `document-panel-${key}`;
|
|
357
|
+
const [refocus, setRefocus] = useState(false);
|
|
358
|
+
useEffect(() => {
|
|
359
|
+
if (!refocus) return;
|
|
360
|
+
const key = selectedRegion(state?.documents)?.key;
|
|
361
|
+
if (key) document.getElementById(tabId(key))?.focus();
|
|
362
|
+
setRefocus(false);
|
|
363
|
+
}, [refocus, state?.documents]);
|
|
364
|
+
async function close(key: string) {
|
|
365
|
+
if ((await client?.closeDocuments(key))?.kind === "Committed") setRefocus(true);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
<div role="tablist">
|
|
369
|
+
{regionEntries(state?.documents).map(tab => (
|
|
370
|
+
<span key={tab.key}>
|
|
371
|
+
<button id={tabId(tab.key)} role="tab" aria-selected={tab.selected} aria-controls={panelId(tab.key)}
|
|
372
|
+
onClick={() => void client?.selectDocuments(tab.key)}>
|
|
373
|
+
{tab.content?.kind ?? "Empty"}
|
|
374
|
+
</button>
|
|
375
|
+
<button aria-label="Close" onClick={() => void close(tab.key)}>×</button>
|
|
376
|
+
</span>
|
|
377
|
+
))}
|
|
378
|
+
</div>
|
|
379
|
+
<RegionOutlets collection={state?.documents} registry={documentPages} fallback={<p>No open documents</p>}
|
|
380
|
+
panelProps={tab => ({ id: panelId(tab.key), role: "tabpanel", "aria-labelledby": tabId(tab.key) })} />
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
`selected` changes only when a switch or close commits. A departure guard can
|
|
384
|
+
keep the current tab, so highlight `selected` and do not move the highlight
|
|
385
|
+
before the request settles. `select…` and `close…` resolve to the .NET
|
|
386
|
+
`NavigationOutcome`, such as `{ kind: "Rejected", rejection: "Guard" }`.
|
|
387
|
+
|
|
388
|
+
Closing the selected tab removes its button, and the next tab becomes selected
|
|
389
|
+
when the close commits. After `closeDocuments` resolves with `kind: "Committed"`,
|
|
390
|
+
move focus to the button of the new selected tab, as `close` above does.
|
|
391
|
+
|
|
392
|
+
In both modes the region collection keeps presenting every region's content,
|
|
393
|
+
so the pages of hidden tabs stay live and still receive state. `"selected"`
|
|
394
|
+
mode only unmounts the components of the regions that are not selected.
|
|
395
|
+
|
|
396
|
+
`regionEntries`, `selectedRegion` and the region types are re-exported from
|
|
397
|
+
`@runic-artifex/views`.
|
|
398
|
+
|
|
299
399
|
## `useCommand(command)`
|
|
300
400
|
|
|
301
401
|
Returns `{ run, pending, error, failure, reset }`. `run(...args)` calls the latest
|
|
@@ -325,7 +425,7 @@ neither.
|
|
|
325
425
|
## `useOperation(start, options?)`
|
|
326
426
|
|
|
327
427
|
Observes a generated `start<Command>()` operation through the framework-neutral
|
|
328
|
-
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
428
|
+
[operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
329
429
|
`run(...args)` calls the latest `start`, so it may close over the current client:
|
|
330
430
|
|
|
331
431
|
```tsx
|
|
@@ -357,7 +457,7 @@ controller's options.
|
|
|
357
457
|
|
|
358
458
|
Admits only the newest of several reads, for example loading the item the user
|
|
359
459
|
selected last, through the framework-neutral
|
|
360
|
-
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
460
|
+
[latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#operation-feedback-and-latest-selection).
|
|
361
461
|
Each `run(intent)` replaces the queued intent and cancels the active read; the next
|
|
362
462
|
read starts only after the previous one reaches its terminal status and the intent's
|
|
363
463
|
optional `waitForCompletion` barrier:
|
|
@@ -388,7 +488,7 @@ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here sinc
|
|
|
388
488
|
`{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
|
|
389
489
|
`connected`, `reconnecting`, `lost` or `closed` (the application closed the
|
|
390
490
|
window, since 0.15; a closed set, see
|
|
391
|
-
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
491
|
+
[Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#connection-state)):
|
|
392
492
|
|
|
393
493
|
```tsx
|
|
394
494
|
import { useBridgeConnection } from "@runic-artifex/react";
|
|
@@ -409,7 +509,7 @@ subscribes again; an invalid one throws a `RangeError`. A server render reads
|
|
|
409
509
|
Follows the declared menu bar of a Runic Desktop window that leaves it to the
|
|
410
510
|
page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
|
|
411
511
|
wraps `createMenuBarController` from `@runic-artifex/views` (see
|
|
412
|
-
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
512
|
+
[In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
|
|
413
513
|
`MenuBarState`, and the bar is rendered by the menubar component of the
|
|
414
514
|
application's own UI library. Runic ships no menubar component.
|
|
415
515
|
|
|
@@ -439,7 +539,7 @@ The controller starts in an effect, so a server render reads `connecting`, and
|
|
|
439
539
|
|
|
440
540
|
Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
|
|
441
541
|
Menubar) with a controlled open menu; the
|
|
442
|
-
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
542
|
+
[Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
|
|
443
543
|
items and is tested with real keys:
|
|
444
544
|
|
|
445
545
|
```tsx
|
|
@@ -490,6 +590,51 @@ With Radix (`@radix-ui/react-menubar`) the open menu is the root's controlled
|
|
|
490
590
|
Check items are `Menubar.CheckboxItem checked`, radio groups
|
|
491
591
|
`Menubar.RadioGroup value` with `Menubar.RadioItem`.
|
|
492
592
|
|
|
593
|
+
## `useText(value, fallback?)`
|
|
594
|
+
|
|
595
|
+
Shows a text reference that a ViewModel produced, such as a status line or a
|
|
596
|
+
validation error's `text`, in the window's language, and renders again when the
|
|
597
|
+
language changes. A string shows as it is; `null` and `undefined` show
|
|
598
|
+
`fallback`. Connect the page's Translations runtime once with
|
|
599
|
+
`configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
|
|
600
|
+
`useWindowLocale()` reads the window's locale.
|
|
601
|
+
|
|
602
|
+
`useTextLocale()` renders the locale that text is shown in, and renders again
|
|
603
|
+
when it changes. Call it in a component that renders the page's own messages,
|
|
604
|
+
so `m.*()` runs again after a language switch; the component's children render
|
|
605
|
+
with it, except memoized ones. `syncDocumentLocale()`, once in `main.tsx`, keeps
|
|
606
|
+
`<html lang dir>` on that locale.
|
|
607
|
+
|
|
608
|
+
```tsx
|
|
609
|
+
function Toolbar() {
|
|
610
|
+
useTextLocale();
|
|
611
|
+
return <button>{m.save()}</button>;
|
|
612
|
+
}
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
```tsx
|
|
616
|
+
const status = useText(view.state?.status);
|
|
617
|
+
<p>{status}</p>
|
|
618
|
+
function ErrorLine({ error }: { error: BridgeValidationMessage }) {
|
|
619
|
+
return <li>{useText(error.text, error.message)}</li>;
|
|
620
|
+
}
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
## `useAppearance()`
|
|
624
|
+
|
|
625
|
+
Renders the page's appearance and renders again when it changes: the colour
|
|
626
|
+
scheme, contrast and reduced motion of the page's engine, combined with the
|
|
627
|
+
desktop's text scale, accent colour, forced-colours palette, contrast and motion
|
|
628
|
+
that a Runic host pushes ([Appearance](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/views/README.md#appearance)). The server snapshot
|
|
629
|
+
has every member `null`.
|
|
630
|
+
|
|
631
|
+
```tsx
|
|
632
|
+
function Shell({ children }: { readonly children: ReactNode }) {
|
|
633
|
+
const { textScale, reducedMotion } = useAppearance();
|
|
634
|
+
return <main style={{ fontSize: `${textScale ?? 1}rem` }} data-motion={reducedMotion ? "reduce" : "full"}>{children}</main>;
|
|
635
|
+
}
|
|
636
|
+
```
|
|
637
|
+
|
|
493
638
|
## Errors
|
|
494
639
|
|
|
495
640
|
The `error` of `useView` and of a command or operation handle is typed
|
|
@@ -507,7 +652,7 @@ const offline = isBridgeError(error, "disconnected");
|
|
|
507
652
|
```
|
|
508
653
|
|
|
509
654
|
`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.
|
|
655
|
+
[Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#errors-and-diagnostics)
|
|
511
656
|
lists the kinds. Any other value, such as an exception that your own connect
|
|
512
657
|
function or command callback throws, arrives unchanged.
|
|
513
658
|
|
|
@@ -549,16 +694,45 @@ the application's own dialog.
|
|
|
549
694
|
such as a close during the page's first render, is answered by the
|
|
550
695
|
ViewModel's .NET fallback handler, or fails closed without one.
|
|
551
696
|
|
|
552
|
-
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.
|
|
697
|
+
The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
|
|
553
698
|
has the .NET side and which View answers which departure. In a frontend test,
|
|
554
699
|
the generated mock's `interactions.<name>.request(input)` resolves with the
|
|
555
700
|
registered handler's answer; see the
|
|
556
|
-
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.
|
|
701
|
+
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#testing).
|
|
702
|
+
|
|
703
|
+
## View requests
|
|
704
|
+
|
|
705
|
+
A `ViewRequest<T>` property of the ViewModel asks the View for a one-way
|
|
706
|
+
presentation action, such as focusing a field or showing a toast, and is
|
|
707
|
+
`client.requests.<name>` on the generated client. Register the page's
|
|
708
|
+
handler in an effect: `handle((input, { signal }) => …)` returns the function
|
|
709
|
+
that removes it, so React removes the handler when the page unmounts or its
|
|
710
|
+
client changes:
|
|
711
|
+
|
|
712
|
+
```tsx
|
|
713
|
+
export function EditPage({ page }: { page: EditPageReference }) {
|
|
714
|
+
const { client } = useView(page);
|
|
715
|
+
const name = useRef<HTMLInputElement>(null);
|
|
716
|
+
useEffect(() => client?.requests.focus.handle(({ member }) => {
|
|
717
|
+
if (member === "name") name.current?.focus();
|
|
718
|
+
}), [client]);
|
|
719
|
+
return <input ref={name} />;
|
|
720
|
+
}
|
|
721
|
+
```
|
|
722
|
+
|
|
723
|
+
`input` is typed from the request's `ViewRequest<T>`. The handler runs once
|
|
724
|
+
the page painted the state the request was raised with, so the field of that
|
|
725
|
+
state is rendered; `signal` aborts when the handler is replaced or removed, the
|
|
726
|
+
client is disposed or the connection is lost. A request is never replayed: one
|
|
727
|
+
raised before the effect ran, or while the page is disconnected, is not
|
|
728
|
+
delivered later. See [View requests](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#view-requests) for the rules, and in a frontend
|
|
729
|
+
test raise one with the generated mock's `requests.<name>.raise(input)` (the
|
|
730
|
+
[Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#testing)).
|
|
557
731
|
|
|
558
732
|
## `useCollectionViewport(options)`
|
|
559
733
|
|
|
560
734
|
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.
|
|
735
|
+
`viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#collectionviewportoptions)
|
|
562
736
|
range for the container; it changes only when the range or sizes change. Send
|
|
563
737
|
the range to the ViewModel from an effect:
|
|
564
738
|
|
|
@@ -574,3 +748,31 @@ return <div ref={ref} style={{ height: 480, overflow: "auto" }}>
|
|
|
574
748
|
</div>
|
|
575
749
|
</div>;
|
|
576
750
|
```
|
|
751
|
+
|
|
752
|
+
## `useQueryCollection(collection, options)`
|
|
753
|
+
|
|
754
|
+
Follows a scroll container for a [query collection](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#query-collections) (`client.queries.{name}`), whose rows stay in .NET: it
|
|
755
|
+
loads the rows the container shows, with placeholders until they arrive, and lays them out with variable heights
|
|
756
|
+
(`estimateSize` for rows not measured yet). It returns the `QueryViewport` (`items` with `top` and `size`, `totalSize`,
|
|
757
|
+
`total`, `query`, `loading`, `error`), `ref` for the container, `measure(index)` for each row, and `scrollToKey`,
|
|
758
|
+
`scrollToIndex`, `setQuery` and `retry`:
|
|
759
|
+
|
|
760
|
+
```tsx
|
|
761
|
+
const list = useQueryCollection(client.queries.rows, { estimateSize: 32 });
|
|
762
|
+
return <div ref={list.ref} style={{ height: 480, overflow: "auto" }}>
|
|
763
|
+
<div style={{ height: list.totalSize, position: "relative" }}>
|
|
764
|
+
{list.items.map(item => <div key={item.key ?? `p${item.index}`} ref={list.measure(item.index)} style={{ position: "absolute", top: item.top, width: "100%" }}>
|
|
765
|
+
{item.row?.label ?? "…"}
|
|
766
|
+
</div>)}
|
|
767
|
+
</div>
|
|
768
|
+
</div>;
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
## Back and the URL
|
|
772
|
+
|
|
773
|
+
The package re-exports `installBackNavigation`, `installNavigationPath`,
|
|
774
|
+
`navigateBack`, `openNavigationPath` and `onNavigationPath` from
|
|
775
|
+
`@runic-artifex/views` (since 0.16). Call the installs once where the page
|
|
776
|
+
starts, before or after mounting: the mouse's Back button and Alt+Left then go
|
|
777
|
+
back in the .NET window, and `#/customers/42` follows its path region. See
|
|
778
|
+
[Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.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 Appearance, 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 ViewRegistryPage, type FieldError, 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;
|
|
@@ -61,15 +61,15 @@ export declare function useView<TClient extends ViewClient>(source: ViewSource<T
|
|
|
61
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;
|
|
62
62
|
/**
|
|
63
63
|
* A build-known map checks each generated reference kind against its component's `page` prop. A nullable
|
|
64
|
-
* reference, such as a region slot's `State["main"]`, checks its non-null kinds.
|
|
64
|
+
* reference, such as a region slot's `State["main"]`, checks its non-null kinds. A component whose `page` is a shared
|
|
65
|
+
* page reference (`[RunicSharedClient]`), such as `ResultPagePageReference`, registers for each of its kinds.
|
|
65
66
|
*/
|
|
66
67
|
export type ViewRegistry<R extends PageReference | null | undefined> = {
|
|
67
|
-
readonly [K in NonNullable<R>["kind"]]:
|
|
68
|
-
readonly page: Extract<NonNullable<R>, {
|
|
69
|
-
readonly kind: K;
|
|
70
|
-
}>;
|
|
71
|
-
}>;
|
|
68
|
+
readonly [K in NonNullable<R>["kind"]]: PageComponent<ViewRegistryPage<R, K>>;
|
|
72
69
|
};
|
|
70
|
+
type PageComponent<P> = P extends unknown ? ComponentType<{
|
|
71
|
+
readonly page: P;
|
|
72
|
+
}> : never;
|
|
73
73
|
export interface ViewOutletProps<R extends PageReference> {
|
|
74
74
|
/** The presented reference, such as `state.main`. */
|
|
75
75
|
readonly content: R | null | undefined;
|
|
@@ -77,17 +77,54 @@ export interface ViewOutletProps<R extends PageReference> {
|
|
|
77
77
|
/** Rendered while there is no content. Defaults to nothing. */
|
|
78
78
|
readonly fallback?: ReactNode;
|
|
79
79
|
/**
|
|
80
|
-
* Renders a reference whose kind has no registered component, for example localized text.
|
|
81
|
-
*
|
|
80
|
+
* Renders a reference whose kind has no registered component, for example localized text. Without it, a
|
|
81
|
+
* development build renders an English `<p role="alert">` and a production build renders nothing and reports the
|
|
82
|
+
* kind through the page's error reporting.
|
|
82
83
|
*/
|
|
83
84
|
readonly missing?: (content: R) => ReactNode;
|
|
84
85
|
}
|
|
85
86
|
/**
|
|
86
87
|
* Renders the registered component for a generated View reference and passes
|
|
87
88
|
* the reference as its `page` prop. A different reference remounts the
|
|
88
|
-
* component. A kind without a component renders `missing
|
|
89
|
+
* component. A kind without a component renders `missing`; without it, an English alert in development, and
|
|
90
|
+
* nothing in production, where the kind is reported (`installErrorReporting`, `onBridgeDiagnostic`).
|
|
89
91
|
*/
|
|
90
92
|
export declare function ViewOutlet<R extends PageReference>({ content, registry, fallback, missing }: ViewOutletProps<R>): ReactNode;
|
|
93
|
+
/** How {@link RegionOutlets} renders the regions of a collection. */
|
|
94
|
+
export type RegionOutletsMode = "keep-mounted" | "selected";
|
|
95
|
+
/**
|
|
96
|
+
* Attributes that {@link RegionOutlets} merges onto a region's wrapper, such as `id`, `role` and `aria-labelledby`.
|
|
97
|
+
* `hidden` and `data-region-key` stay controlled by the outlet, and a `style` is merged with its `display: none`.
|
|
98
|
+
*/
|
|
99
|
+
export type RegionPanelAttributes = Omit<HTMLAttributes<HTMLDivElement>, "hidden"> & {
|
|
100
|
+
readonly [attribute: `data-${string}`]: string | undefined;
|
|
101
|
+
};
|
|
102
|
+
export interface RegionOutletsProps<R extends PageReference> {
|
|
103
|
+
/** The presented region collection, such as `state.documents`. */
|
|
104
|
+
readonly collection: RegionCollection<R> | null | undefined;
|
|
105
|
+
readonly registry: ViewRegistry<R>;
|
|
106
|
+
/** Rendered while the collection has no region. Defaults to nothing. */
|
|
107
|
+
readonly fallback?: ReactNode;
|
|
108
|
+
/** Renders a reference whose kind has no registered component, as in {@link ViewOutlet}. */
|
|
109
|
+
readonly missing?: (content: R) => ReactNode;
|
|
110
|
+
/**
|
|
111
|
+
* `"keep-mounted"` (the default) renders every region and hides all but the selected one, so each region keeps
|
|
112
|
+
* its component and DOM. `"selected"` renders only the selected region.
|
|
113
|
+
*/
|
|
114
|
+
readonly mode?: RegionOutletsMode;
|
|
115
|
+
/**
|
|
116
|
+
* Returns attributes for a region's wrapper, for example `{ id, role: "tabpanel", "aria-labelledby" }`, so a tab
|
|
117
|
+
* can point `aria-controls` at the panel.
|
|
118
|
+
*/
|
|
119
|
+
readonly panelProps?: (entry: RegionEntry<R>) => RegionPanelAttributes;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Renders a {@link ViewOutlet} for the regions of a region collection, each in a `<div data-region-key>` keyed by
|
|
123
|
+
* the region's key. A region that is not selected is rendered with `hidden` and an inline `display: none`, which
|
|
124
|
+
* author CSS without `!important` cannot override. A new content reference in a region remounts only that region's
|
|
125
|
+
* component.
|
|
126
|
+
*/
|
|
127
|
+
export declare function RegionOutlets<R extends PageReference>({ collection, registry, fallback, missing, mode, panelProps }: RegionOutletsProps<R>): ReactNode;
|
|
91
128
|
export interface CommandHandle<TArgs extends readonly unknown[], TResult, TFailure = BridgeOutcomeFailure<TResult>> {
|
|
92
129
|
/**
|
|
93
130
|
* Runs the command. Resolves to its result, including a `BridgeOutcome` with a
|
|
@@ -298,7 +335,7 @@ export type FieldHandle<TValue> = FieldState<TValue> & {
|
|
|
298
335
|
* With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
|
|
299
336
|
* conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
|
|
300
337
|
*/
|
|
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>;
|
|
338
|
+
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
339
|
export interface BridgeConnectionHandle {
|
|
303
340
|
/** The connection to the .NET host, as `onBridgeConnection` reports it. */
|
|
304
341
|
readonly state: BridgeConnectionState;
|
|
@@ -314,8 +351,61 @@ export interface BridgeConnectionHandle {
|
|
|
314
351
|
* ```
|
|
315
352
|
*/
|
|
316
353
|
export declare function useBridgeConnection(options?: BridgeConnectionOptions): BridgeConnectionHandle;
|
|
354
|
+
/**
|
|
355
|
+
* Renders a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
|
|
356
|
+
* window's language (`resolveText`), and renders again when the language changes. A string renders as it is;
|
|
357
|
+
* `null` and `undefined` render `fallback`. Configure the page's Translations runtime once with
|
|
358
|
+
* `configureTranslatedText`; without one, a reference shows its fallback text. A field's `FieldError` renders the
|
|
359
|
+
* application's text for it (`configureFieldErrorText`), or its English message: `useText(name.error)`.
|
|
360
|
+
*
|
|
361
|
+
* ```tsx
|
|
362
|
+
* const status = useText(view.state?.status);
|
|
363
|
+
* <p>{status}</p>
|
|
364
|
+
* {view.state?.validation.errors.map(error => <ErrorLine key={error.message} error={error} />)}
|
|
365
|
+
* function ErrorLine({ error }) { return <li>{useText(error.text, error.message)}</li>; }
|
|
366
|
+
* ```
|
|
367
|
+
*/
|
|
368
|
+
export declare function useText(value: TextReference | FieldError | string | null | undefined, fallback?: string): string;
|
|
369
|
+
/**
|
|
370
|
+
* Renders the window's locale that the application set (`IRunicWindowLocale` in .NET), or `null` while it sets none,
|
|
371
|
+
* for example to set `lang` on an element. The server snapshot is `null`.
|
|
372
|
+
*/
|
|
373
|
+
export declare function useWindowLocale(): string | null;
|
|
374
|
+
/**
|
|
375
|
+
* Renders the page's appearance (`appearance` from `@runic-artifex/views`): the colour scheme, contrast and reduced
|
|
376
|
+
* motion of the page's engine combined with the desktop's values that a Runic host pushes (`appearance/1`), which also
|
|
377
|
+
* carry the text scale, the accent colour and the forced-colours palette. Renders again when any of them changes. The
|
|
378
|
+
* server snapshot has every member `null`.
|
|
379
|
+
*
|
|
380
|
+
* ```tsx
|
|
381
|
+
* const { textScale, reducedMotion } = useAppearance();
|
|
382
|
+
* ```
|
|
383
|
+
*/
|
|
384
|
+
export declare function useAppearance(): Appearance;
|
|
385
|
+
/**
|
|
386
|
+
* Renders the locale that text is shown in (`textLocale`: the page's Translations locale, which follows the window's
|
|
387
|
+
* locale), and renders again when it changes. Call it in a component that renders the page's own messages, so that
|
|
388
|
+
* `m.*()` runs again after a language switch; the component's children render with it, except memoized ones.
|
|
389
|
+
* `undefined` while the page has no Translations runtime and the application sets no window locale.
|
|
390
|
+
*
|
|
391
|
+
* ```tsx
|
|
392
|
+
* function Toolbar() {
|
|
393
|
+
* useTextLocale();
|
|
394
|
+
* return <button>{m.save()}</button>;
|
|
395
|
+
* }
|
|
396
|
+
* ```
|
|
397
|
+
*/
|
|
398
|
+
export declare function useTextLocale(): string | undefined;
|
|
317
399
|
export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
|
|
318
400
|
export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
|
|
401
|
+
export { useForm, type FormFieldHandle, type FormHandle, type UseFormOptions } from "./form.js";
|
|
402
|
+
export { commitAllFields, type FormState, type FormSubmitOptions, type FormSubmitResult } from "@runic-artifex/views";
|
|
403
|
+
export { useQueryCollection, type QueryCollectionHandle } from "./query.js";
|
|
319
404
|
export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
|
|
320
|
-
export {
|
|
405
|
+
export { upload, type BlobRef, type RunicBlob, type UploadOptions, type UploadProgress } from "@runic-artifex/views";
|
|
406
|
+
export { regionEntries, selectedRegion, type RegionCollection, type RegionEntry, type RegionOutcome, type RegionSlot, } from "@runic-artifex/views";
|
|
407
|
+
export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, type NavigationPathChange, type NavigationPathOptions, type NavigationReply, } from "@runic-artifex/views";
|
|
408
|
+
export { configureFieldErrorText, configureTranslatedText, fieldErrorText, resolveText, syncDocumentLocale, textDirection, windowLocale, type DocumentLocaleOptions, type FieldErrorArguments, type FieldErrorReason, type FieldErrorText, type TextReference, type TextTranslations, } from "@runic-artifex/views";
|
|
409
|
+
export { appearance, onAppearance, type Appearance, type AppearanceColorScheme, type AppearanceContrast, type AppearanceSystemColors, type HostAppearance, } from "@runic-artifex/views";
|
|
410
|
+
export { FieldError, type BridgeField, type BridgeFieldConstraints, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
|
|
321
411
|
export { useMenuBar, type MenuBarEntry, type MenuBarHandle, type MenuBarInvokeResult, type MenuBarItem, type MenuBarMenu, type MenuBarRequest, type MenuBarSeparator, type MenuBarState, type UseMenuBarOptions, } from "./menu-bar.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createElement, useCallback, useEffect, useInsertionEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from "react";
|
|
2
|
-
import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
|
|
3
|
-
import { isViewClient, viewSourceIdentity, viewSourcePreview } from "@runic-artifex/views/bindings";
|
|
2
|
+
import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, onWindowLocale, appearance, onAppearance, unknownAppearance, resolveText, subscribeText, textLocale, textVersion, windowLocale, regionEntries, } from "@runic-artifex/views";
|
|
3
|
+
import { isViewClient, missingViewMessage, reportMissingView, 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) {
|
|
@@ -161,7 +161,8 @@ function referenceKey(reference) {
|
|
|
161
161
|
/**
|
|
162
162
|
* Renders the registered component for a generated View reference and passes
|
|
163
163
|
* the reference as its `page` prop. A different reference remounts the
|
|
164
|
-
* component. A kind without a component renders `missing
|
|
164
|
+
* component. A kind without a component renders `missing`; without it, an English alert in development, and
|
|
165
|
+
* nothing in production, where the kind is reported (`installErrorReporting`, `onBridgeDiagnostic`).
|
|
165
166
|
*/
|
|
166
167
|
export function ViewOutlet({ content, registry, fallback = null, missing }) {
|
|
167
168
|
if (!content)
|
|
@@ -170,10 +171,29 @@ export function ViewOutlet({ content, registry, fallback = null, missing }) {
|
|
|
170
171
|
if (!component) {
|
|
171
172
|
if (missing)
|
|
172
173
|
return missing(content);
|
|
173
|
-
|
|
174
|
+
if (process.env.NODE_ENV !== "production")
|
|
175
|
+
return createElement("p", { role: "alert" }, missingViewMessage(content.kind));
|
|
176
|
+
reportMissingView(content.kind);
|
|
177
|
+
return null;
|
|
174
178
|
}
|
|
175
179
|
return createElement(component, { key: referenceKey(content), page: content });
|
|
176
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Renders a {@link ViewOutlet} for the regions of a region collection, each in a `<div data-region-key>` keyed by
|
|
183
|
+
* the region's key. A region that is not selected is rendered with `hidden` and an inline `display: none`, which
|
|
184
|
+
* author CSS without `!important` cannot override. A new content reference in a region remounts only that region's
|
|
185
|
+
* component.
|
|
186
|
+
*/
|
|
187
|
+
export function RegionOutlets({ collection, registry, fallback = null, missing, mode = "keep-mounted", panelProps }) {
|
|
188
|
+
const shown = regionEntries(collection).filter(region => mode === "keep-mounted" || region.selected);
|
|
189
|
+
if (shown.length === 0)
|
|
190
|
+
return fallback;
|
|
191
|
+
return shown.map(region => {
|
|
192
|
+
const panel = panelProps?.(region) ?? {};
|
|
193
|
+
const hidden = !region.selected;
|
|
194
|
+
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 } : {}) }));
|
|
195
|
+
});
|
|
196
|
+
}
|
|
177
197
|
// A command or operation controller lives while its component is mounted: unmounting disposes it,
|
|
178
198
|
// which stops its feedback and, for an operation, settles its pending run promises and stops
|
|
179
199
|
// observing accepted work (it never cancels the work). StrictMode's simulated unmount, and a component that React shows again (`<Activity>`),
|
|
@@ -309,16 +329,6 @@ export function useTextField(view, read, write, options = {}) {
|
|
|
309
329
|
return { value, editing: current.editing, error: current.error, ...handlers };
|
|
310
330
|
}
|
|
311
331
|
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
332
|
/**
|
|
323
333
|
* Binds an element to one View member while the component is mounted, through `createFieldController`: pass a
|
|
324
334
|
* generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Spread `inputProps` on
|
|
@@ -347,11 +357,16 @@ export function useField(view, field, options = {}) {
|
|
|
347
357
|
...field.nullable === undefined ? {} : { nullable: field.nullable },
|
|
348
358
|
...field.integer === undefined ? {} : { integer: field.integer },
|
|
349
359
|
...field.choices === undefined ? {} : { choices: field.choices },
|
|
360
|
+
...field.offset === undefined ? {} : { offset: field.offset },
|
|
361
|
+
...field.constraints === undefined ? {} : { constraints: field.constraints },
|
|
362
|
+
// field-paths/1: a field below a member (InvoiceFields.lines.at(key).quantity) always writes checked.
|
|
363
|
+
...field.checkedOnly === undefined ? {} : { checkedOnly: field.checkedOnly },
|
|
350
364
|
read: state => latest.current.read(state),
|
|
351
365
|
write: (client, value) => latest.current.write(client, value),
|
|
352
366
|
...field.checked === undefined ? {} : { checked: (client, value, write) => latest.current.checked(client, value, write) },
|
|
353
367
|
...field.baseline === undefined ? {} : { baseline: client => latest.current.baseline(client) },
|
|
354
368
|
...field.errors === undefined ? {} : { errors: state => latest.current.errors(state) },
|
|
369
|
+
...field.validating === undefined ? {} : { validating: state => latest.current.validating(state) },
|
|
355
370
|
}, options));
|
|
356
371
|
const { state, client } = view;
|
|
357
372
|
useEffect(() => {
|
|
@@ -376,9 +391,10 @@ export function useField(view, field, options = {}) {
|
|
|
376
391
|
const value = current.editing ? current.value
|
|
377
392
|
: state === undefined ? (kind === "text" || kind === undefined ? "" : undefined)
|
|
378
393
|
: field.read(state);
|
|
379
|
-
const text = Object.is(value, current.value) ? current.text :
|
|
394
|
+
const text = Object.is(value, current.value) ? current.text : controller.format(value);
|
|
380
395
|
const errors = field.errors === undefined ? current.errors : state === undefined ? noFieldErrors : field.errors(state);
|
|
381
396
|
const invalid = errors.length > 0 || current.error !== undefined;
|
|
397
|
+
const validating = field.validating === undefined ? current.validating : state !== undefined && field.validating(state);
|
|
382
398
|
const inputProps = kind === "boolean"
|
|
383
399
|
? { checked: value === true, onChange: actions.onCheck, onBlur: actions.onBlur, "aria-invalid": invalid }
|
|
384
400
|
: {
|
|
@@ -386,7 +402,7 @@ export function useField(view, field, options = {}) {
|
|
|
386
402
|
onCompositionEnd: actions.onCompositionEnd, onBlur: actions.onBlur, "aria-invalid": invalid,
|
|
387
403
|
};
|
|
388
404
|
return {
|
|
389
|
-
value, text, editing: current.editing, error: current.error, errors, conflict: current.conflict,
|
|
405
|
+
value, text, editing: current.editing, error: current.error, errors, conflict: current.conflict, validating,
|
|
390
406
|
inputProps: inputProps,
|
|
391
407
|
input: actions.input, commit: actions.commit, retry: actions.retry, reset: actions.reset,
|
|
392
408
|
};
|
|
@@ -419,8 +435,76 @@ export function useBridgeConnection(options = {}) {
|
|
|
419
435
|
return { state };
|
|
420
436
|
}
|
|
421
437
|
const serverConnectionState = () => "connecting";
|
|
438
|
+
/**
|
|
439
|
+
* Renders a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
|
|
440
|
+
* window's language (`resolveText`), and renders again when the language changes. A string renders as it is;
|
|
441
|
+
* `null` and `undefined` render `fallback`. Configure the page's Translations runtime once with
|
|
442
|
+
* `configureTranslatedText`; without one, a reference shows its fallback text. A field's `FieldError` renders the
|
|
443
|
+
* application's text for it (`configureFieldErrorText`), or its English message: `useText(name.error)`.
|
|
444
|
+
*
|
|
445
|
+
* ```tsx
|
|
446
|
+
* const status = useText(view.state?.status);
|
|
447
|
+
* <p>{status}</p>
|
|
448
|
+
* {view.state?.validation.errors.map(error => <ErrorLine key={error.message} error={error} />)}
|
|
449
|
+
* function ErrorLine({ error }) { return <li>{useText(error.text, error.message)}</li>; }
|
|
450
|
+
* ```
|
|
451
|
+
*/
|
|
452
|
+
export function useText(value, fallback) {
|
|
453
|
+
const version = useSyncExternalStore(subscribeText, textVersion, textVersion);
|
|
454
|
+
// version is the language the text resolves in.
|
|
455
|
+
return useMemo(() => resolveText(value, fallback), [value, fallback, version]);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Renders the window's locale that the application set (`IRunicWindowLocale` in .NET), or `null` while it sets none,
|
|
459
|
+
* for example to set `lang` on an element. The server snapshot is `null`.
|
|
460
|
+
*/
|
|
461
|
+
export function useWindowLocale() {
|
|
462
|
+
return useSyncExternalStore(subscribeWindowLocale, windowLocale, serverWindowLocale);
|
|
463
|
+
}
|
|
464
|
+
const subscribeWindowLocale = (onChange) => onWindowLocale(() => onChange());
|
|
465
|
+
const serverWindowLocale = () => null;
|
|
466
|
+
/**
|
|
467
|
+
* Renders the page's appearance (`appearance` from `@runic-artifex/views`): the colour scheme, contrast and reduced
|
|
468
|
+
* motion of the page's engine combined with the desktop's values that a Runic host pushes (`appearance/1`), which also
|
|
469
|
+
* carry the text scale, the accent colour and the forced-colours palette. Renders again when any of them changes. The
|
|
470
|
+
* server snapshot has every member `null`.
|
|
471
|
+
*
|
|
472
|
+
* ```tsx
|
|
473
|
+
* const { textScale, reducedMotion } = useAppearance();
|
|
474
|
+
* ```
|
|
475
|
+
*/
|
|
476
|
+
export function useAppearance() {
|
|
477
|
+
return useSyncExternalStore(subscribeAppearance, appearance, serverAppearance);
|
|
478
|
+
}
|
|
479
|
+
const subscribeAppearance = (onChange) => onAppearance(() => onChange());
|
|
480
|
+
const serverAppearance = () => unknownAppearance;
|
|
481
|
+
/**
|
|
482
|
+
* Renders the locale that text is shown in (`textLocale`: the page's Translations locale, which follows the window's
|
|
483
|
+
* locale), and renders again when it changes. Call it in a component that renders the page's own messages, so that
|
|
484
|
+
* `m.*()` runs again after a language switch; the component's children render with it, except memoized ones.
|
|
485
|
+
* `undefined` while the page has no Translations runtime and the application sets no window locale.
|
|
486
|
+
*
|
|
487
|
+
* ```tsx
|
|
488
|
+
* function Toolbar() {
|
|
489
|
+
* useTextLocale();
|
|
490
|
+
* return <button>{m.save()}</button>;
|
|
491
|
+
* }
|
|
492
|
+
* ```
|
|
493
|
+
*/
|
|
494
|
+
export function useTextLocale() {
|
|
495
|
+
return useSyncExternalStore(subscribeText, textLocale, textLocale);
|
|
496
|
+
}
|
|
422
497
|
export { retrySuspenseView, useSuspenseView } from "./suspense.js";
|
|
423
498
|
export { useCollectionViewport } from "./viewport.js";
|
|
499
|
+
export { useForm } from "./form.js";
|
|
500
|
+
export { commitAllFields } from "@runic-artifex/views";
|
|
501
|
+
export { useQueryCollection } from "./query.js";
|
|
424
502
|
export { onBridgeConnection } from "@runic-artifex/views";
|
|
503
|
+
// blobs/1: uploads from the page and the blob values of state.
|
|
504
|
+
export { upload } from "@runic-artifex/views";
|
|
505
|
+
export { regionEntries, selectedRegion, } from "@runic-artifex/views";
|
|
506
|
+
export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, } from "@runic-artifex/views";
|
|
507
|
+
export { configureFieldErrorText, configureTranslatedText, fieldErrorText, resolveText, syncDocumentLocale, textDirection, windowLocale, } from "@runic-artifex/views";
|
|
508
|
+
export { appearance, onAppearance, } from "@runic-artifex/views";
|
|
425
509
|
export { FieldError, } from "@runic-artifex/views";
|
|
426
510
|
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.17.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.17.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@runic-artifex/views": "0.
|
|
36
|
+
"@runic-artifex/views": "0.17.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.17.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": "daeb17e5c3fb0b625d5d988d359cd12ffa51f8c6"
|
|
67
67
|
}
|