@runic-artifex/svelte 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  # `@runic-artifex/svelte`
2
2
 
3
3
  Svelte 5 Application Views helpers. `@runic-artifex/svelte` exports `useView`,
4
- `ViewOutlet`, `ViewRegistry`, `useCommand`, `useOperation`, `useLatestOperation`
4
+ `ViewOutlet`, `RegionOutlets`, `ViewRegistry`, `useCommand`, `useOperation`, `useLatestOperation`
5
5
  and `useCollectionViewport` for generated Window/View clients. The
6
6
  `@runic-artifex/svelte/views` entry of earlier previews and the
7
7
  `@runic-artifex/svelte/experimental` entry of 0.9 are gone: import from
@@ -86,7 +86,7 @@ the failure. Await it with `{#await}`:
86
86
  The source is read once: wrap the component in `{#key page}` to follow another
87
87
  reference. Do not `{#await page.connect()}` directly: nothing would dispose
88
88
  that client. In SvelteKit, connect in a `load` function instead
89
- ([`@runic-artifex/sveltekit`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.1/packages/web/svelte/../sveltekit/README.md#connecting-in-load)).
89
+ ([`@runic-artifex/sveltekit`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/web/svelte/../sveltekit/README.md#connecting-in-load)).
90
90
 
91
91
  ### Selecting state: `$derived`
92
92
 
@@ -182,14 +182,33 @@ handle also has `value` and `text`, which `bind:value={title.value}` reads and s
182
182
  `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
183
183
  or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
184
184
  `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
185
- [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#fields) for the receipts
185
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#fields) for the receipts
186
186
  and text forms.
187
187
 
188
+ #### Row cells and nested members
189
+
190
+ Since 0.16, `InvoiceFields.address.street` and `InvoiceFields.lines.at(line.id).quantity` are fields too
191
+ (`field-paths/1`): a member of an object member, and a cell of a row that .NET edits with `[RunicRowEditor]`. Call
192
+ `useField(() => view, InvoiceFields.lines.at(line.id).quantity)` in the row's component and `{@attach quantity.attach}`
193
+ its input; `at(key)` returns the same descriptor for the same key. Such a field always writes checked, conflicts only
194
+ when another writer changed the same cell, and shows the messages .NET reports at the cell's validation path. See
195
+ [Fields below a member and row cells](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/web/svelte/../views/README.md#fields-below-a-member-and-row-cells).
196
+
197
+ ### Forms: `useForm(() => fields, options?)`
198
+
199
+ One state over field handles, and a `submit` that writes every field before its command (`createFormController` in
200
+ `@runic-artifex/views`). `dirty` counts drafts not written yet and the `dirty` option.
201
+
202
+ ```svelte
203
+ const form = useForm(() => ({ title, step }), { dirty: () => editor.state?.isDirty === true });
204
+ <button disabled={!form.valid || form.submitting} onclick={() => form.submit(() => editor.client!.save())}>Save</button>
205
+ ```
206
+
188
207
  ### Text inputs: `useTextField(view, read, write, options?)`
189
208
 
190
209
  Call during component initialization to bind a text input to a member through the
191
210
  framework-neutral
192
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#text-inputs):
211
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#text-inputs):
193
212
 
194
213
  ```svelte
195
214
  <script lang="ts">
@@ -261,6 +280,69 @@ text. It receives the reference whose kind has no component, and its markup
261
280
  </ViewOutlet>
262
281
  ```
263
282
 
283
+ ### Region collections
284
+
285
+ A .NET `[RunicRegionCollection]` member, such as `state.documents`, lists
286
+ regions that each keep their own back stack. `<RegionOutlets>` renders a
287
+ `ViewOutlet` for each region, keyed by the region's key, inside a
288
+ `<div data-region-key>`. The default `mode="keep-mounted"` keeps every region mounted
289
+ and sets `hidden` and an inline `display: none` on all but the selected one, so
290
+ a tab keeps its component, scroll position and unsent input. Author CSS cannot
291
+ show a hidden panel without `!important`. `mode="selected"` renders only the
292
+ selected region. The `fallback` snippet renders while there is no region, and
293
+ the `missing` snippet is passed to each outlet. A region with `content: null`
294
+ renders nothing.
295
+
296
+ The package has no tab bar. Build one with `regionEntries` and the generated
297
+ `selectDocuments(key)` and `closeDocuments(key)`. The `panelProps(entry)` prop returns attributes (`RegionPanelAttributes`) for
298
+ each region's wrapper, such as `id`, `role="tabpanel"` and `aria-labelledby`, so
299
+ each tab can name its panel in `aria-controls`. `hidden` and `data-region-key`
300
+ stay controlled by the outlet, and its `display: none` takes precedence over a
301
+ returned `style`.
302
+
303
+ ```svelte
304
+ <script lang="ts">
305
+ const tabId = (key: string) => `document-tab-${key}`;
306
+ const panelId = (key: string) => `document-panel-${key}`;
307
+ async function close(key: string) {
308
+ if ((await workspace.client?.closeDocuments(key))?.kind !== "Committed") return;
309
+ await tick();
310
+ const selected = selectedRegion(workspace.state?.documents);
311
+ if (selected) document.getElementById(tabId(selected.key))?.focus();
312
+ }
313
+ </script>
314
+
315
+ <div role="tablist">
316
+ {#each regionEntries(workspace.state?.documents) as tab (tab.key)}
317
+ <button id={tabId(tab.key)} role="tab" aria-selected={tab.selected} aria-controls={panelId(tab.key)}
318
+ onclick={() => workspace.client?.selectDocuments(tab.key)}>
319
+ {tab.content?.kind ?? "Empty"}
320
+ </button>
321
+ <button aria-label="Close" onclick={() => close(tab.key)}>×</button>
322
+ {/each}
323
+ </div>
324
+ <RegionOutlets collection={workspace.state?.documents} registry={documentPages}
325
+ panelProps={tab => ({ id: panelId(tab.key), role: "tabpanel", "aria-labelledby": tabId(tab.key) })}>
326
+ {#snippet fallback()}<p>No open documents</p>{/snippet}
327
+ </RegionOutlets>
328
+ ```
329
+
330
+ `selected` changes only when a switch or close commits. A departure guard can
331
+ keep the current tab, so highlight `selected` and do not move the highlight
332
+ before the request settles. `select…` and `close…` resolve to the .NET
333
+ `NavigationOutcome`, such as `{ kind: "Rejected", rejection: "Guard" }`.
334
+
335
+ Closing the selected tab removes its button, and the next tab becomes selected
336
+ when the close commits. After `closeDocuments` resolves with `kind: "Committed"`,
337
+ move focus to the button of the new selected tab, as `close` above does.
338
+
339
+ In both modes the region collection keeps presenting every region's content,
340
+ so the pages of hidden tabs stay live and still receive state. `"selected"`
341
+ mode only unmounts the components of the regions that are not selected.
342
+
343
+ `regionEntries`, `selectedRegion` and the region types are re-exported from
344
+ `@runic-artifex/views`.
345
+
264
346
  ## `useCommand(command)`
265
347
 
266
348
  Returns `{ run, pending, error, failure, reset }` with reactive `pending`, `error`
@@ -328,7 +410,7 @@ Cancel and other callbacks responsive during observation.
328
410
  ## `useLatestOperation()`
329
411
 
330
412
  For rapid read selection, `useLatestOperation()` wraps the framework-neutral
331
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#operation-feedback-and-latest-selection)
413
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#operation-feedback-and-latest-selection)
332
414
  for the component's lifetime. It coalesces the latest intent across delayed receipts
333
415
  and orders the next admission after terminal observation and any application drain
334
416
  barrier:
@@ -359,7 +441,7 @@ establish that replacement boundary and own the old work's drain. Lost terminal
359
441
  observation blocks further Starts instead of retrying blindly, with its reason in
360
442
  `error`; ordinary Cancel does not clear this block. Component destruction settles
361
443
  observation without cancelling accepted work. The
362
- [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/tests/fixtures/application/operations-consumer)
444
+ [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/tests/fixtures/application/operations-consumer)
363
445
  runs this hook against the packed packages and the desktop transport.
364
446
 
365
447
  ## `useBridgeConnection(options?)`
@@ -369,7 +451,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
369
451
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a reactive
370
452
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
371
453
  application closed the window, since 0.15; a closed set, see
372
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#connection-state)):
454
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#connection-state)):
373
455
 
374
456
  ```svelte
375
457
  <script lang="ts">
@@ -391,7 +473,7 @@ server render does not observe, and destroying the owner unsubscribes. An invali
391
473
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
392
474
  page (`DesktopMenuBarPresentation.Page`) while its owner lives. It wraps
393
475
  `createMenuBarController` from `@runic-artifex/views` (see
394
- [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`, where `state` is a
476
+ [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 }`, where `state` is a
395
477
  reactive `MenuBarState` property. The bar is rendered by the menubar component
396
478
  of the application's own UI library. Runic ships no menubar component.
397
479
 
@@ -420,7 +502,7 @@ the `shortcuts: "app"` lease.
420
502
  ### With Bits UI
421
503
 
422
504
  Bits UI's `Menubar.Root bind:value`; the
423
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
505
+ [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
424
506
  items and is tested with real keys:
425
507
 
426
508
  ```svelte
@@ -470,6 +552,23 @@ items and is tested with real keys:
470
552
  The host owns `checked`: bind it one way, as
471
553
  `bind:checked={() => item.checked ?? false, () => {}}`.
472
554
 
555
+ ## `useText(value, fallback?)`
556
+
557
+ Shows a text reference that a ViewModel produced, such as a status line or a
558
+ validation error's `text`, in the window's language, and renders again when the
559
+ language changes. A string shows as it is; `null` and `undefined` show
560
+ `fallback`. Connect the page's Translations runtime once with
561
+ `configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
562
+ `useWindowLocale()` reads the window's locale. With SvelteKit server
563
+ rendering, call `configureTranslatedText` in the browser only (for example in
564
+ `onMount`), or render on the server with `resolveTextReference` and the
565
+ request's locale.
566
+
567
+ ```svelte
568
+ const status = useText(() => view.state?.status);
569
+ <p>{status.current}</p>
570
+ ```
571
+
473
572
  ## Errors
474
573
 
475
574
  The `error` of `useView` and of a command or operation helper is typed
@@ -487,7 +586,7 @@ const message = $derived(describeBridgeError(view.error));
487
586
  ```
488
587
 
489
588
  `instanceof` holds for errors from every copy of the package on the page.
490
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#errors-and-diagnostics)
589
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#errors-and-diagnostics)
491
590
  lists the kinds. Any other value, such as an exception that your own connect
492
591
  function or command callback throws, arrives unchanged.
493
592
 
@@ -526,15 +625,49 @@ application's own dialog.
526
625
  departure before that is answered by the ViewModel's .NET fallback handler, or
527
626
  fails closed without one.
528
627
 
529
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.1/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
628
+ 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)
530
629
  has the .NET side and which View answers which departure. In a frontend test,
531
630
  the generated mock's `interactions.<name>.request(input)` resolves with the
532
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#testing).
631
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#testing).
632
+
633
+ ## View requests
634
+
635
+ A `ViewRequest<T>` property of the ViewModel asks the View for a one-way
636
+ presentation action, such as focusing a field or showing a toast, and is
637
+ `client.requests.<name>` on the generated client. Register the page's
638
+ handler in `$effect`: `handle((input, { signal }) => …)` returns the function
639
+ that removes it, so return that from the effect, and Svelte removes the handler
640
+ when the client changes or the component is destroyed:
641
+
642
+ ```svelte
643
+ <script lang="ts">
644
+ import { useView } from "@runic-artifex/svelte";
645
+ import type { EditPageReference } from "./generated/edit.js";
646
+
647
+ let { page }: { page: EditPageReference } = $props();
648
+ const view = useView(() => page);
649
+ let name: HTMLInputElement | undefined = $state();
650
+ $effect(() => view.client?.requests.focus.handle(({ member }) => {
651
+ if (member === "name") name?.focus();
652
+ }));
653
+ </script>
654
+
655
+ <input bind:this={name}>
656
+ ```
657
+
658
+ `input` is typed from the request's `ViewRequest<T>`. The handler runs once
659
+ the page painted the state the request was raised with, so the field of that
660
+ state is rendered; `signal` aborts when the handler is replaced or removed, the
661
+ client is disposed or the connection is lost. A request is never replayed: one
662
+ raised before the effect ran, or while the page is disconnected, is not
663
+ 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
664
+ test raise one with the generated mock's `requests.<name>.raise(input)` (the
665
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#testing)).
533
666
 
534
667
  ## `useCollectionViewport(options)`
535
668
 
536
669
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
537
- `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#collectionviewportoptions)
670
+ `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#collectionviewportoptions)
538
671
  range; `attach` is an attachment for the container. Call it during component
539
672
  initialization and send the range to the ViewModel from an effect:
540
673
 
@@ -556,3 +689,33 @@ initialization and send the range to the ViewModel from an effect:
556
689
  Translation helpers moved to
557
690
  [`@runic-artifex/translations-svelte`](https://www.npmjs.com/package/@runic-artifex/translations-svelte).
558
691
  Import them from there instead of `@runic-artifex/svelte`.
692
+
693
+ ## `useQueryCollection(collection, options)`
694
+
695
+ 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
696
+ loads the rows the container shows, with placeholders until they arrive, and lays them out with variable heights. Pass
697
+ getters of the collection and the options. `viewport` is the `QueryViewport` (`items` with `top` and `size`,
698
+ `totalSize`, `total`, `query`, `loading`, `error`); attach `attach` to the container and `measure(index)` to each row.
699
+ It is safe in SvelteKit: on the server, `viewport` stays empty.
700
+
701
+ ```svelte
702
+ <script lang="ts">
703
+ const list = useQueryCollection(() => view.client?.queries.rows, () => ({ estimateSize: 32 }));
704
+ </script>
705
+ <div {@attach list.attach} style="height: 480px; overflow: auto">
706
+ <div style="height: {list.viewport.totalSize}px; position: relative">
707
+ {#each list.viewport.items as item (item.key ?? `p${item.index}`)}
708
+ <div {@attach list.measure(item.index)} style="position: absolute; top: {item.top}px; width: 100%">{item.row?.label ?? "…"}</div>
709
+ {/each}
710
+ </div>
711
+ </div>
712
+ ```
713
+
714
+ ## Back and the URL
715
+
716
+ The package re-exports `installBackNavigation`, `installNavigationPath`,
717
+ `navigateBack`, `openNavigationPath` and `onNavigationPath` from
718
+ `@runic-artifex/views` (since 0.16). Call the installs once where the page
719
+ starts, before or after mounting: the mouse's Back button and Alt+Left then go
720
+ back in the .NET window, and `#/customers/42` follows its path region. See
721
+ [Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.16.0/packages/web/views/README.md#back-and-the-url).
@@ -0,0 +1,37 @@
1
+ <script lang="ts" generics="R extends PageReference">
2
+ import type { Snippet } from "svelte";
3
+ import { regionEntries, type PageReference, type RegionCollection, type RegionEntry } from "@runic-artifex/views";
4
+ import type { RegionPanelAttributes } from "./region-panel.js";
5
+ import ViewOutlet from "./ViewOutlet.svelte";
6
+ import type { ViewRegistry } from "./view-registry.js";
7
+
8
+ let { collection, registry, fallback, missing, mode = "keep-mounted", panelProps }: {
9
+ /** The presented region collection, such as `state.documents`. */
10
+ collection: RegionCollection<R> | null | undefined;
11
+ registry: ViewRegistry<R>;
12
+ /** Rendered while the collection has no region. */
13
+ fallback?: Snippet;
14
+ /** Renders a reference whose kind has no registered component, as in `ViewOutlet`. */
15
+ missing?: Snippet<[R]>;
16
+ /**
17
+ * `"keep-mounted"` (the default) renders every region and hides all but the selected one, so each region keeps
18
+ * its component and DOM. `"selected"` renders only the selected region.
19
+ */
20
+ mode?: "keep-mounted" | "selected";
21
+ /**
22
+ * Returns attributes for a region's wrapper, for example `{ id, role: "tabpanel", "aria-labelledby" }`, so a tab
23
+ * can point `aria-controls` at the panel.
24
+ */
25
+ panelProps?: (entry: RegionEntry<R>) => RegionPanelAttributes;
26
+ } = $props();
27
+ let shown = $derived(regionEntries(collection).filter(region => mode === "keep-mounted" || region.selected));
28
+ </script>
29
+
30
+ {#each shown as region (region.key)}
31
+ <!-- A hidden region also gets an inline display: none, which author CSS without !important cannot override. -->
32
+ <div {...panelProps?.(region)} data-region-key={region.key} hidden={!region.selected} style:display={region.selected ? undefined : "none"}>
33
+ <ViewOutlet content={region.content} {registry} {...missing ? { missing } : {}} />
34
+ </div>
35
+ {:else}
36
+ {@render fallback?.()}
37
+ {/each}
@@ -0,0 +1,46 @@
1
+ import type { Snippet } from "svelte";
2
+ import { type PageReference, type RegionCollection, type RegionEntry } from "@runic-artifex/views";
3
+ import type { RegionPanelAttributes } from "./region-panel.js";
4
+ import type { ViewRegistry } from "./view-registry.js";
5
+ declare function $$render<R extends PageReference>(): {
6
+ props: {
7
+ /** The presented region collection, such as `state.documents`. */
8
+ collection: RegionCollection<R> | null | undefined;
9
+ registry: ViewRegistry<R>;
10
+ /** Rendered while the collection has no region. */
11
+ fallback?: Snippet;
12
+ /** Renders a reference whose kind has no registered component, as in `ViewOutlet`. */
13
+ missing?: Snippet<[R]>;
14
+ /**
15
+ * `"keep-mounted"` (the default) renders every region and hides all but the selected one, so each region keeps
16
+ * its component and DOM. `"selected"` renders only the selected region.
17
+ */
18
+ mode?: "keep-mounted" | "selected";
19
+ /**
20
+ * Returns attributes for a region's wrapper, for example `{ id, role: "tabpanel", "aria-labelledby" }`, so a tab
21
+ * can point `aria-controls` at the panel.
22
+ */
23
+ panelProps?: (entry: RegionEntry<R>) => RegionPanelAttributes;
24
+ };
25
+ exports: {};
26
+ bindings: "";
27
+ slots: {};
28
+ events: {};
29
+ };
30
+ declare class __sveltets_Render<R extends PageReference> {
31
+ props(): ReturnType<typeof $$render<R>>['props'];
32
+ events(): ReturnType<typeof $$render<R>>['events'];
33
+ slots(): ReturnType<typeof $$render<R>>['slots'];
34
+ bindings(): "";
35
+ exports(): {};
36
+ }
37
+ interface $$IsomorphicComponent {
38
+ new <R extends PageReference>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<R>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<R>['props']>, ReturnType<__sveltets_Render<R>['events']>, ReturnType<__sveltets_Render<R>['slots']>> & {
39
+ $$bindings?: ReturnType<__sveltets_Render<R>['bindings']>;
40
+ } & ReturnType<__sveltets_Render<R>['exports']>;
41
+ <R extends PageReference>(internal: unknown, props: ReturnType<__sveltets_Render<R>['props']> & {}): ReturnType<__sveltets_Render<R>['exports']>;
42
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
43
+ }
44
+ declare const RegionOutlets: $$IsomorphicComponent;
45
+ type RegionOutlets<R extends PageReference> = InstanceType<typeof RegionOutlets<R>>;
46
+ export default RegionOutlets;
@@ -1,4 +1,6 @@
1
1
  export { default as ViewOutlet } from "./ViewOutlet.svelte";
2
+ export { default as RegionOutlets } from "./RegionOutlets.svelte";
3
+ export type { RegionPanelAttributes } from "./region-panel.js";
2
4
  export type { ViewRegistry } from "./view-registry.js";
3
5
  export { useSuspenseView, useView, type SuspenseViewHandle, type UseViewOptions, type ViewHandle } from "./use-view.svelte.js";
4
6
  export { preloadView, type PreloadViewOptions } from "@runic-artifex/views";
@@ -6,10 +8,18 @@ export { useCommand, type CommandHandle } from "./use-command.svelte.js";
6
8
  export { useOperation, type OperationHandle } from "./use-operation.svelte.js";
7
9
  export { useTextField, type TextFieldHandle, type TextFieldView, type UseTextFieldOptions } from "./use-text-field.svelte.js";
8
10
  export { useField, type FieldElement, type FieldHandle } from "./use-field.svelte.js";
11
+ export { useForm, type FormFieldHandle, type FormHandle, type UseFormOptions } from "./use-form.svelte.js";
12
+ export { commitAllFields, type FormState, type FormSubmitOptions, type FormSubmitResult } from "@runic-artifex/views";
9
13
  export { useLatestOperation, type LatestOperationHandle } from "./use-latest-operation.svelte.js";
10
14
  export { useCollectionViewport, type CollectionViewportHandle } from "./use-collection-viewport.svelte.js";
15
+ export { useQueryCollection, type QueryCollectionHandle } from "./use-query-collection.svelte.js";
11
16
  export { useBridgeConnection, type BridgeConnectionHandle } from "./use-bridge-connection.svelte.js";
12
17
  export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
13
- export { FieldError, type BridgeField, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
18
+ export { useText, useWindowLocale, type TextHandle, type WindowLocaleHandle } from "./use-text.svelte.js";
19
+ export { configureTranslatedText, resolveText, windowLocale, type TextReference, type TextTranslations, } from "@runic-artifex/views";
20
+ export { upload, type BlobRef, type RunicBlob, type UploadOptions, type UploadProgress } from "@runic-artifex/views";
21
+ export { regionEntries, selectedRegion, type RegionCollection, type RegionEntry, type RegionOutcome, type RegionSlot, } from "@runic-artifex/views";
22
+ export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, type NavigationPathChange, type NavigationPathOptions, type NavigationReply, } from "@runic-artifex/views";
23
+ export { FieldError, type BridgeField, type BridgeFieldConstraints, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
14
24
  export { useMenuBar, type MenuBarHandle, type UseMenuBarOptions } from "./use-menu-bar.svelte.js";
15
25
  export type { MenuBarEntry, MenuBarInvokeResult, MenuBarItem, MenuBarMenu, MenuBarRequest, MenuBarSeparator, MenuBarState, } from "@runic-artifex/views";
@@ -1,13 +1,23 @@
1
1
  export { default as ViewOutlet } from "./ViewOutlet.svelte";
2
+ export { default as RegionOutlets } from "./RegionOutlets.svelte";
2
3
  export { useSuspenseView, useView } from "./use-view.svelte.js";
3
4
  export { preloadView } from "@runic-artifex/views";
4
5
  export { useCommand } from "./use-command.svelte.js";
5
6
  export { useOperation } from "./use-operation.svelte.js";
6
7
  export { useTextField } from "./use-text-field.svelte.js";
7
8
  export { useField } from "./use-field.svelte.js";
9
+ export { useForm } from "./use-form.svelte.js";
10
+ export { commitAllFields } from "@runic-artifex/views";
8
11
  export { useLatestOperation } from "./use-latest-operation.svelte.js";
9
12
  export { useCollectionViewport } from "./use-collection-viewport.svelte.js";
13
+ export { useQueryCollection } from "./use-query-collection.svelte.js";
10
14
  export { useBridgeConnection } from "./use-bridge-connection.svelte.js";
11
15
  export { onBridgeConnection } from "@runic-artifex/views";
16
+ export { useText, useWindowLocale } from "./use-text.svelte.js";
17
+ export { configureTranslatedText, resolveText, windowLocale, } from "@runic-artifex/views";
18
+ // blobs/1: uploads from the page and the blob values of state.
19
+ export { upload } from "@runic-artifex/views";
20
+ export { regionEntries, selectedRegion, } from "@runic-artifex/views";
21
+ export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, } from "@runic-artifex/views";
12
22
  export { FieldError, } from "@runic-artifex/views";
13
23
  export { useMenuBar } from "./use-menu-bar.svelte.js";
@@ -0,0 +1,6 @@
1
+ import type { HTMLAttributes } from "svelte/elements";
2
+ /**
3
+ * Attributes that `RegionOutlets` merges onto a region's wrapper, such as `id`, `role` and `aria-labelledby`.
4
+ * `hidden` and `data-region-key` stay controlled by the outlet, and its `display: none` takes precedence over `style`.
5
+ */
6
+ export type RegionPanelAttributes = Omit<HTMLAttributes<HTMLDivElement>, "hidden" | "children">;
@@ -0,0 +1 @@
1
+ export {};
@@ -26,6 +26,8 @@ export interface FieldHandle<TValue> {
26
26
  readonly errors: readonly string[];
27
27
  /** The producer's field while a checked write's `conflict` keeps the draft; `undefined` otherwise. */
28
28
  readonly conflict: FieldBaseline<TValue> | undefined;
29
+ /** The member's validation is in progress, such as an asynchronous rule that is still checking: show "checking…". */
30
+ readonly validating: boolean;
29
31
  /** The user changed the value. */
30
32
  input(value: TValue): void;
31
33
  /**
@@ -63,4 +65,4 @@ export interface FieldHandle<TValue> {
63
65
  * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
64
66
  * conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
65
67
  */
66
- 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>;
68
+ 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>;
@@ -69,7 +69,7 @@ export function useField(view, field, options = {}) {
69
69
  };
70
70
  };
71
71
  // One derived per member, so a reader of one member runs again only when that member changes.
72
- const fields = derivedFields(() => current, ["value", "text", "editing", "error", "errors", "conflict"]);
72
+ const fields = derivedFields(() => current, ["value", "text", "editing", "error", "errors", "conflict", "validating"]);
73
73
  return {
74
74
  get value() { return fields.value(); },
75
75
  set value(value) { controller.input(value); },
@@ -79,6 +79,7 @@ export function useField(view, field, options = {}) {
79
79
  get error() { return fields.error(); },
80
80
  get errors() { return fields.errors(); },
81
81
  get conflict() { return fields.conflict(); },
82
+ get validating() { return fields.validating(); },
82
83
  input: (value) => controller.input(value),
83
84
  commit: () => controller.commit(),
84
85
  retry: () => controller.retry(),
@@ -0,0 +1,26 @@
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 === true`. */
6
+ readonly dirty?: () => boolean | undefined;
7
+ }
8
+ /** A form bound by {@link useForm}: its state, read reactively, and its actions. */
9
+ export interface FormHandle extends FormState {
10
+ /** Commits every field, waits for their writes and runs `command` unless a field's write or text failed. */
11
+ submit<T>(command: () => T | PromiseLike<T>, options?: FormSubmitOptions): Promise<FormSubmitResult<T>>;
12
+ /** Commits every field and resolves once their writes settled. */
13
+ commit(): Promise<FormState>;
14
+ /** Resets every field. */
15
+ reset(): void;
16
+ }
17
+ /**
18
+ * One dirty, pending and valid state over `useField` handles, and a `submit` that writes every field before its
19
+ * command (`createFormController` in `@runic-artifex/views`):
20
+ *
21
+ * ```svelte
22
+ * const form = useForm(() => ({ title, body }), { dirty: () => editor.state?.isDirty === true });
23
+ * <button disabled={!form.valid || form.submitting} onclick={() => form.submit(() => editor.client!.save())}>Save</button>
24
+ * ```
25
+ */
26
+ export declare function useForm(fields: () => FormFields<FormFieldHandle>, options?: UseFormOptions): FormHandle;
@@ -0,0 +1,40 @@
1
+ import { formFieldList, formStateOf, submitFields, } from "@runic-artifex/views";
2
+ /**
3
+ * One dirty, pending and valid state over `useField` handles, and a `submit` that writes every field before its
4
+ * command (`createFormController` in `@runic-artifex/views`):
5
+ *
6
+ * ```svelte
7
+ * const form = useForm(() => ({ title, body }), { dirty: () => editor.state?.isDirty === true });
8
+ * <button disabled={!form.valid || form.submitting} onclick={() => form.submit(() => editor.client!.save())}>Save</button>
9
+ * ```
10
+ */
11
+ export function useForm(fields, options = {}) {
12
+ let submitting = $state(false);
13
+ const state = $derived(formStateOf(formFieldList(fields()), options.dirty?.() === true, submitting));
14
+ return {
15
+ get dirty() { return state.dirty; },
16
+ get editing() { return state.editing; },
17
+ get validating() { return state.validating; },
18
+ get pending() { return state.pending; },
19
+ get valid() { return state.valid; },
20
+ get submitting() { return state.submitting; },
21
+ async submit(command, submitOptions = {}) {
22
+ if (submitting)
23
+ return { status: "busy" };
24
+ submitting = true;
25
+ const list = formFieldList(fields());
26
+ try {
27
+ return await submitFields(list, command, submitOptions, index => list[index]);
28
+ }
29
+ finally {
30
+ submitting = false;
31
+ }
32
+ },
33
+ async commit() {
34
+ await Promise.all(formFieldList(fields()).map(field => field.commit()));
35
+ return state;
36
+ },
37
+ reset() { for (const field of formFieldList(fields()))
38
+ field.reset(); },
39
+ };
40
+ }
@@ -0,0 +1,23 @@
1
+ import type { Attachment } from "svelte/attachments";
2
+ import { type QueryCollection, type QueryViewport, type QueryViewportOptions, type RunicQuery } from "@runic-artifex/views";
3
+ export interface QueryCollectionHandle<TRow> {
4
+ /** The rows to render with their offsets, the spacer's `totalSize`, the total, query, loading and error state. */
5
+ readonly viewport: QueryViewport<TRow>;
6
+ /** Attach to the scroll container: `<div {@attach list.attach}>`. */
7
+ readonly attach: Attachment<HTMLElement>;
8
+ /** Attach to each rendered row, so its height is measured: `<div {@attach list.measure(item.index)}>`. */
9
+ measure(index: number): Attachment<Element>;
10
+ /** Scrolls to the row with `key` in the current query; resolves `false` when no row has it. */
11
+ scrollToKey(key: string, align?: "start" | "center" | "end"): Promise<boolean>;
12
+ scrollToIndex(index: number, align?: "start" | "center" | "end"): void;
13
+ /** Changes the collection's sort and filter (ViewModel state every presentation shares). */
14
+ setQuery(query: RunicQuery): Promise<void>;
15
+ /** Loads the range again after a failure. */
16
+ retry(): void;
17
+ }
18
+ /**
19
+ * Follows a scroll container for a query collection (`client.queries.{name}`): it loads the rows the container shows
20
+ * from .NET, with placeholders until they arrive, and lays them out with variable heights. Call it during component
21
+ * initialization with getters, such as `useQueryCollection(() => view.client?.queries.rows, () => ({ estimateSize: 32 }))`.
22
+ */
23
+ export declare function useQueryCollection<TRow>(collection: () => QueryCollection<TRow> | undefined, options: () => QueryViewportOptions): QueryCollectionHandle<TRow>;
@@ -0,0 +1,54 @@
1
+ import { untrack } from "svelte";
2
+ import { createQueryViewportController, } from "@runic-artifex/views";
3
+ const empty = { items: [], totalSize: 0, total: null, query: { sort: [], filters: [] }, loading: false, error: undefined };
4
+ /**
5
+ * Follows a scroll container for a query collection (`client.queries.{name}`): it loads the rows the container shows
6
+ * from .NET, with placeholders until they arrive, and lays them out with variable heights. Call it during component
7
+ * initialization with getters, such as `useQueryCollection(() => view.client?.queries.rows, () => ({ estimateSize: 32 }))`.
8
+ */
9
+ export function useQueryCollection(collection, options) {
10
+ let viewport = $state.raw(empty);
11
+ let controller;
12
+ let container = null;
13
+ // Registered before the first flush, so a destroyed owner never leaks the controller (see useOperation).
14
+ $effect.pre(() => {
15
+ const current = collection();
16
+ if (!current) {
17
+ viewport = empty;
18
+ return;
19
+ }
20
+ const created = untrack(() => createQueryViewportController(current, options()));
21
+ controller = created;
22
+ const stop = created.subscribe(() => { viewport = created.current; });
23
+ created.attach(container);
24
+ viewport = created.current;
25
+ return () => {
26
+ stop();
27
+ created.dispose();
28
+ if (controller === created)
29
+ controller = undefined;
30
+ };
31
+ });
32
+ $effect.pre(() => {
33
+ const { estimateSize, overscan } = options();
34
+ untrack(() => controller?.update({ estimateSize, ...(overscan === undefined ? {} : { overscan }) }));
35
+ });
36
+ return {
37
+ get viewport() { return viewport; },
38
+ attach(element) {
39
+ container = element;
40
+ controller?.attach(element);
41
+ return () => { container = null; controller?.attach(null); };
42
+ },
43
+ measure: index => element => controller?.observe(element, index),
44
+ scrollToKey: async (key, align) => controller ? controller.scrollToKey(key, align) : false,
45
+ scrollToIndex: (index, align) => controller?.scrollToIndex(index, align),
46
+ setQuery: async (query) => {
47
+ const current = untrack(collection);
48
+ if (!current)
49
+ throw new TypeError("useQueryCollection has no collection yet.");
50
+ await current.setQuery(query);
51
+ },
52
+ retry: () => untrack(collection)?.retry(),
53
+ };
54
+ }
@@ -0,0 +1,24 @@
1
+ import { type TextReference } from "@runic-artifex/views";
2
+ export interface TextHandle {
3
+ /** The text in the window's language. A reactive property. */
4
+ readonly current: string;
5
+ }
6
+ export interface WindowLocaleHandle {
7
+ /** The window's locale that the application set, or `null` while it sets none. A reactive property. */
8
+ readonly current: string | null;
9
+ }
10
+ /**
11
+ * Follows a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
12
+ * window's language (`resolveText`), while its owner lives. `source` and `fallback` are read reactively, so pass
13
+ * functions: `useText(() => view.state?.status)`. A string shows as it is; `null` and `undefined` show `fallback`.
14
+ * Configure the page's Translations runtime once with `configureTranslatedText`; without one, a reference shows its
15
+ * fallback text. Call during component initialization (or in `$effect.root`).
16
+ *
17
+ * ```svelte
18
+ * const status = useText(() => view.state?.status);
19
+ * <p>{status.current}</p>
20
+ * ```
21
+ */
22
+ export declare function useText(source: () => TextReference | string | null | undefined, fallback?: () => string | undefined): TextHandle;
23
+ /** Follows the window's locale (`windowLocale`) while its owner lives, for example to set `lang`. */
24
+ export declare function useWindowLocale(): WindowLocaleHandle;
@@ -0,0 +1,28 @@
1
+ import { onWindowLocale, resolveText, subscribeText, windowLocale } from "@runic-artifex/views";
2
+ /**
3
+ * Follows a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
4
+ * window's language (`resolveText`), while its owner lives. `source` and `fallback` are read reactively, so pass
5
+ * functions: `useText(() => view.state?.status)`. A string shows as it is; `null` and `undefined` show `fallback`.
6
+ * Configure the page's Translations runtime once with `configureTranslatedText`; without one, a reference shows its
7
+ * fallback text. Call during component initialization (or in `$effect.root`).
8
+ *
9
+ * ```svelte
10
+ * const status = useText(() => view.state?.status);
11
+ * <p>{status.current}</p>
12
+ * ```
13
+ */
14
+ export function useText(source, fallback) {
15
+ let version = $state(0);
16
+ $effect.pre(() => subscribeText(() => { version++; }));
17
+ const current = $derived.by(() => {
18
+ void version;
19
+ return resolveText(source(), fallback?.());
20
+ });
21
+ return { get current() { return current; } };
22
+ }
23
+ /** Follows the window's locale (`windowLocale`) while its owner lives, for example to set `lang`. */
24
+ export function useWindowLocale() {
25
+ let current = $state(windowLocale());
26
+ $effect.pre(() => onWindowLocale(next => { current = next; }));
27
+ return { get current() { return current; } };
28
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@runic-artifex/svelte",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "description": "Svelte 5 Application Views helpers for Runic",
5
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/svelte#readme",
5
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/svelte#readme",
6
6
  "bugs": {
7
7
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
8
8
  },
@@ -35,12 +35,12 @@
35
35
  "clean": "bun -e \"import('node:fs').then(({rmSync}) => rmSync('dist', { recursive: true, force: true }))\"",
36
36
  "build": "bun run --bun clean && svelte-package -i src -o dist",
37
37
  "check": "svelte-check --tsconfig ./tsconfig.json",
38
- "test": "bun run --bun build && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && vitest run test/use-view.svelte.test.ts test/keep-alive.svelte.test.ts test/glue.svelte.test.ts test/use-operation.svelte.test.ts test/use-latest-operation.svelte.test.ts test/lifecycle.svelte.test.ts test/use-bridge-connection.svelte.test.ts test/use-menu-bar.svelte.test.ts test/use-text-field.svelte.test.ts test/use-field.svelte.test.ts test/text-field.browser.test.ts test/field.browser.test.ts",
38
+ "test": "bun run --bun build && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && vitest run test/use-view.svelte.test.ts test/keep-alive.svelte.test.ts test/glue.svelte.test.ts test/use-operation.svelte.test.ts test/use-latest-operation.svelte.test.ts test/lifecycle.svelte.test.ts test/use-bridge-connection.svelte.test.ts test/use-menu-bar.svelte.test.ts test/use-text-field.svelte.test.ts test/use-field.svelte.test.ts test/use-query-collection.svelte.test.ts test/text-field.browser.test.ts test/field.browser.test.ts",
39
39
  "pack:check": "bun pm pack --dry-run"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "svelte": ">=5.57.1 <6",
43
- "@runic-artifex/views": "0.15.1"
43
+ "@runic-artifex/views": "0.16.0"
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "packageManager": "bun@1.4.4",
55
55
  "devDependencies": {
56
- "@runic-artifex/views": "0.15.1",
56
+ "@runic-artifex/views": "0.16.0",
57
57
  "@sveltejs/adapter-static": "4.0.0",
58
58
  "@sveltejs/kit": "3.0.0",
59
59
  "@sveltejs/package": "3.0.0",
@@ -67,5 +67,5 @@
67
67
  "vitest": "5.0.3",
68
68
  "vite": "8.3.4"
69
69
  },
70
- "gitHead": "fce42f47296a4784532fbba0fec9602cd3778fbb"
70
+ "gitHead": "ff96e52727212344c407489283a9cafc614f0270"
71
71
  }