@runic-artifex/svelte 0.15.0 → 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
@@ -43,7 +43,11 @@ replaces `client.dispose()` for a client the helper connected. It connects a gen
43
43
  reference, or `{ connect: connect<Name> }` for a root ViewModel, while the
44
44
  component is mounted. An already connected client is observed and left to its
45
45
  owner. The result exposes reactive `state`, `client`, `error` and `pending`
46
- properties and `retry()`.
46
+ properties and `retry()`. Only `state` follows each published state: `client`
47
+ stays the same object for the connection, and `client`, `error` and `pending`
48
+ notify their readers only when their own value changes, so an `$effect` that
49
+ reads `client` to call a command does not run again when the command's answer
50
+ changes the state.
47
51
 
48
52
  When the component is destroyed or the getter returns a reference with a
49
53
  different `connect` function, the client stays connected for
@@ -82,7 +86,7 @@ the failure. Await it with `{#await}`:
82
86
  The source is read once: wrap the component in `{#key page}` to follow another
83
87
  reference. Do not `{#await page.connect()}` directly: nothing would dispose
84
88
  that client. In SvelteKit, connect in a `load` function instead
85
- ([`@runic-artifex/sveltekit`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/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)).
86
90
 
87
91
  ### Selecting state: `$derived`
88
92
 
@@ -178,14 +182,33 @@ handle also has `value` and `text`, which `bind:value={title.value}` reads and s
178
182
  `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
179
183
  or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
180
184
  `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
181
- [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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
182
186
  and text forms.
183
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
+
184
207
  ### Text inputs: `useTextField(view, read, write, options?)`
185
208
 
186
209
  Call during component initialization to bind a text input to a member through the
187
210
  framework-neutral
188
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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):
189
212
 
190
213
  ```svelte
191
214
  <script lang="ts">
@@ -257,6 +280,69 @@ text. It receives the reference whose kind has no component, and its markup
257
280
  </ViewOutlet>
258
281
  ```
259
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
+
260
346
  ## `useCommand(command)`
261
347
 
262
348
  Returns `{ run, pending, error, failure, reset }` with reactive `pending`, `error`
@@ -324,7 +410,7 @@ Cancel and other callbacks responsive during observation.
324
410
  ## `useLatestOperation()`
325
411
 
326
412
  For rapid read selection, `useLatestOperation()` wraps the framework-neutral
327
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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)
328
414
  for the component's lifetime. It coalesces the latest intent across delayed receipts
329
415
  and orders the next admission after terminal observation and any application drain
330
416
  barrier:
@@ -355,7 +441,7 @@ establish that replacement boundary and own the old work's drain. Lost terminal
355
441
  observation blocks further Starts instead of retrying blindly, with its reason in
356
442
  `error`; ordinary Cancel does not clear this block. Component destruction settles
357
443
  observation without cancelling accepted work. The
358
- [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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)
359
445
  runs this hook against the packed packages and the desktop transport.
360
446
 
361
447
  ## `useBridgeConnection(options?)`
@@ -365,7 +451,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
365
451
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a reactive
366
452
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
367
453
  application closed the window, since 0.15; a closed set, see
368
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#connection-state)):
454
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.16.0/packages/web/views#connection-state)):
369
455
 
370
456
  ```svelte
371
457
  <script lang="ts">
@@ -387,7 +473,7 @@ server render does not observe, and destroying the owner unsubscribes. An invali
387
473
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
388
474
  page (`DesktopMenuBarPresentation.Page`) while its owner lives. It wraps
389
475
  `createMenuBarController` from `@runic-artifex/views` (see
390
- [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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
391
477
  reactive `MenuBarState` property. The bar is rendered by the menubar component
392
478
  of the application's own UI library. Runic ships no menubar component.
393
479
 
@@ -416,7 +502,7 @@ the `shortcuts: "app"` lease.
416
502
  ### With Bits UI
417
503
 
418
504
  Bits UI's `Menubar.Root bind:value`; the
419
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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
420
506
  items and is tested with real keys:
421
507
 
422
508
  ```svelte
@@ -466,6 +552,23 @@ items and is tested with real keys:
466
552
  The host owns `checked`: bind it one way, as
467
553
  `bind:checked={() => item.checked ?? false, () => {}}`.
468
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
+
469
572
  ## Errors
470
573
 
471
574
  The `error` of `useView` and of a command or operation helper is typed
@@ -483,7 +586,7 @@ const message = $derived(describeBridgeError(view.error));
483
586
  ```
484
587
 
485
588
  `instanceof` holds for errors from every copy of the package on the page.
486
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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)
487
590
  lists the kinds. Any other value, such as an exception that your own connect
488
591
  function or command callback throws, arrives unchanged.
489
592
 
@@ -522,15 +625,49 @@ application's own dialog.
522
625
  departure before that is answered by the ViewModel's .NET fallback handler, or
523
626
  fails closed without one.
524
627
 
525
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/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)
526
629
  has the .NET side and which View answers which departure. In a frontend test,
527
630
  the generated mock's `interactions.<name>.request(input)` resolves with the
528
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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)).
529
666
 
530
667
  ## `useCollectionViewport(options)`
531
668
 
532
669
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
533
- `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/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)
534
671
  range; `attach` is an attachment for the container. Call it during component
535
672
  initialization and send the range to the ViewModel from an effect:
536
673
 
@@ -552,3 +689,33 @@ initialization and send the range to the ViewModel from an effect:
552
689
  Translation helpers moved to
553
690
  [`@runic-artifex/translations-svelte`](https://www.npmjs.com/package/@runic-artifex/translations-svelte).
554
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;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Derives each member of a record that a controller replaces as a whole, so a reader of one member, such as an
3
+ * `$effect` that reads only `pending`, runs again only when that member changes and not with every new record.
4
+ * Call it where `$derived` may be created: during component initialization or in an `$effect.root`.
5
+ */
6
+ export declare function derivedFields<T extends object, K extends keyof T>(record: () => T, keys: readonly K[]): {
7
+ readonly [P in K]: () => T[P];
8
+ };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Derives each member of a record that a controller replaces as a whole, so a reader of one member, such as an
3
+ * `$effect` that reads only `pending`, runs again only when that member changes and not with every new record.
4
+ * Call it where `$derived` may be created: during component initialization or in an `$effect.root`.
5
+ */
6
+ export function derivedFields(record, keys) {
7
+ const readers = {};
8
+ for (const key of keys) {
9
+ const value = $derived(record()[key]);
10
+ readers[key] = () => value;
11
+ }
12
+ return readers;
13
+ }
@@ -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 {};
@@ -1,4 +1,5 @@
1
1
  import { createCommandController } from "@runic-artifex/views";
2
+ import { derivedFields } from "./derived-fields.svelte.js";
2
3
  /**
3
4
  * Tracks a command's pending state and failure as reactive properties. Called
4
5
  * during component initialization (or in `$effect.root`), owner destruction
@@ -24,11 +25,13 @@ export function useCommand(command) {
24
25
  if (!String(error?.message).includes("effect_orphan"))
25
26
  throw error;
26
27
  }
28
+ // One derived per member, so a reader of one member runs again only when that member changes.
29
+ const fields = derivedFields(() => current, ["pending", "error", "failure"]);
27
30
  return {
28
31
  run: controller.run,
29
- get pending() { return current.pending; },
30
- get error() { return current.error; },
31
- get failure() { return current.failure; },
32
+ get pending() { return fields.pending(); },
33
+ get error() { return fields.error(); },
34
+ get failure() { return fields.failure(); },
32
35
  reset: controller.reset,
33
36
  };
34
37
  }
@@ -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>;
@@ -1,5 +1,6 @@
1
1
  import { untrack } from "svelte";
2
2
  import { createFieldController, } from "@runic-artifex/views";
3
+ import { derivedFields } from "./derived-fields.svelte.js";
3
4
  /**
4
5
  * Binds an element to one View member while the calling component is mounted, through `createFieldController`: pass a
5
6
  * generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Call it during
@@ -67,15 +68,18 @@ export function useField(view, field, options = {}) {
67
68
  element.removeEventListener("blur", blur);
68
69
  };
69
70
  };
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", "validating"]);
70
73
  return {
71
- get value() { return current.value; },
74
+ get value() { return fields.value(); },
72
75
  set value(value) { controller.input(value); },
73
- get text() { return current.text; },
76
+ get text() { return fields.text(); },
74
77
  set text(text) { controller.inputText(text); },
75
- get editing() { return current.editing; },
76
- get error() { return current.error; },
77
- get errors() { return current.errors; },
78
- get conflict() { return current.conflict; },
78
+ get editing() { return fields.editing(); },
79
+ get error() { return fields.error(); },
80
+ get errors() { return fields.errors(); },
81
+ get conflict() { return fields.conflict(); },
82
+ get validating() { return fields.validating(); },
79
83
  input: (value) => controller.input(value),
80
84
  commit: () => controller.commit(),
81
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
+ }
@@ -1,4 +1,5 @@
1
1
  import { createLatestOperationController, } from "@runic-artifex/views";
2
+ import { derivedFields } from "./derived-fields.svelte.js";
2
3
  /**
3
4
  * Admits only the newest selection, for reads such as "load the selected item": each
4
5
  * `run(intent)` replaces the queued intent and cancels the active read, and the next read
@@ -14,22 +15,24 @@ export function useLatestOperation() {
14
15
  const unsubscribe = controller.subscribe(() => { current = controller.current; });
15
16
  // Registered before the first flush, so a destroyed owner never leaks the controller (see useOperation).
16
17
  $effect.pre(() => () => { unsubscribe(); controller.dispose(); });
18
+ // One derived per member, so a reader of one member runs again only when that member changes.
19
+ const fields = derivedFields(() => current, ["pending", "admitting", "operation", "status", "progress", "outcome", "failure", "error", "cancelled", "cancellationRequested", "cancelling", "cancellation", "cancelError", "blocked"]);
17
20
  return {
18
21
  run: controller.run,
19
22
  clear: controller.clear,
20
- get pending() { return current.pending; },
21
- get admitting() { return current.admitting; },
22
- get operation() { return current.operation; },
23
- get status() { return current.status; },
24
- get progress() { return current.progress; },
25
- get outcome() { return current.outcome; },
26
- get failure() { return current.failure; },
27
- get error() { return current.error; },
28
- get cancelled() { return current.cancelled; },
29
- get cancellationRequested() { return current.cancellationRequested; },
30
- get cancelling() { return current.cancelling; },
31
- get cancellation() { return current.cancellation; },
32
- get cancelError() { return current.cancelError; },
33
- get blocked() { return current.blocked; },
23
+ get pending() { return fields.pending(); },
24
+ get admitting() { return fields.admitting(); },
25
+ get operation() { return fields.operation(); },
26
+ get status() { return fields.status(); },
27
+ get progress() { return fields.progress(); },
28
+ get outcome() { return fields.outcome(); },
29
+ get failure() { return fields.failure(); },
30
+ get error() { return fields.error(); },
31
+ get cancelled() { return fields.cancelled(); },
32
+ get cancellationRequested() { return fields.cancellationRequested(); },
33
+ get cancelling() { return fields.cancelling(); },
34
+ get cancellation() { return fields.cancellation(); },
35
+ get cancelError() { return fields.cancelError(); },
36
+ get blocked() { return fields.blocked(); },
34
37
  };
35
38
  }
@@ -1,4 +1,5 @@
1
1
  import { createOperationController, } from "@runic-artifex/views";
2
+ import { derivedFields } from "./derived-fields.svelte.js";
2
3
  /**
3
4
  * Tracks Start admission, pending work, cancellation and terminal feedback as
4
5
  * reactive properties. Call during component initialization. Owner destruction
@@ -14,22 +15,24 @@ export function useOperation(start, options = {}) {
14
15
  // flush. onMount/onDestroy and $effect are deferred to that flush and would
15
16
  // leak the controller then. The effect reads no state, so it never re-runs.
16
17
  $effect.pre(() => () => { unsubscribe(); controller.dispose(); });
18
+ // One derived per member, so a reader of one member runs again only when that member changes.
19
+ const fields = derivedFields(() => current, ["pending", "admitting", "operation", "status", "progress", "outcome", "failure", "error", "cancelled", "cancellationRequested", "cancelling", "cancellation", "cancelError"]);
17
20
  return {
18
21
  run: controller.run,
19
22
  cancel: controller.cancel,
20
23
  reset: controller.reset,
21
- get pending() { return current.pending; },
22
- get admitting() { return current.admitting; },
23
- get operation() { return current.operation; },
24
- get status() { return current.status; },
25
- get progress() { return current.progress; },
26
- get outcome() { return current.outcome; },
27
- get failure() { return current.failure; },
28
- get error() { return current.error; },
29
- get cancelled() { return current.cancelled; },
30
- get cancellationRequested() { return current.cancellationRequested; },
31
- get cancelling() { return current.cancelling; },
32
- get cancellation() { return current.cancellation; },
33
- get cancelError() { return current.cancelError; },
24
+ get pending() { return fields.pending(); },
25
+ get admitting() { return fields.admitting(); },
26
+ get operation() { return fields.operation(); },
27
+ get status() { return fields.status(); },
28
+ get progress() { return fields.progress(); },
29
+ get outcome() { return fields.outcome(); },
30
+ get failure() { return fields.failure(); },
31
+ get error() { return fields.error(); },
32
+ get cancelled() { return fields.cancelled(); },
33
+ get cancellationRequested() { return fields.cancellationRequested(); },
34
+ get cancelling() { return fields.cancelling(); },
35
+ get cancellation() { return fields.cancellation(); },
36
+ get cancelError() { return fields.cancelError(); },
34
37
  };
35
38
  }
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  import { untrack } from "svelte";
2
2
  import { createTextFieldController } from "@runic-artifex/views";
3
+ import { derivedFields } from "./derived-fields.svelte.js";
3
4
  function textOf(event) {
4
5
  if (typeof event === "string")
5
6
  return event;
@@ -37,11 +38,13 @@ export function useTextField(view, read, write, options = {}) {
37
38
  current = controller.current;
38
39
  });
39
40
  });
41
+ // One derived per member, so a reader of one member runs again only when that member changes.
42
+ const fields = derivedFields(() => current, ["value", "editing", "error"]);
40
43
  return {
41
- get value() { return current.value; },
44
+ get value() { return fields.value(); },
42
45
  set value(text) { controller.input(text); },
43
- get editing() { return current.editing; },
44
- get error() { return current.error; },
46
+ get editing() { return fields.editing(); },
47
+ get error() { return fields.error(); },
45
48
  compositionStart: () => controller.compositionStart(),
46
49
  compositionEnd: (event) => controller.compositionEnd(textOf(event)),
47
50
  reset: () => controller.reset(),
@@ -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
+ }
@@ -2,7 +2,11 @@ import { type ViewClient, type ViewConnector, type ViewSource } from "@runic-art
2
2
  export interface ViewHandle<TClient extends ViewClient> {
3
3
  /** The latest state, or undefined until the client connects. */
4
4
  readonly state: TClient["snapshot"] | undefined;
5
- /** The connected client for commands, or undefined until it connects. */
5
+ /**
6
+ * The connected client for commands, or undefined until it connects. It stays the same object for the connection,
7
+ * and only `state` follows each published state, so an `$effect` that reads `client`, `error` or `pending` does not
8
+ * run again when the View's state changes.
9
+ */
6
10
  readonly client: TClient | undefined;
7
11
  /** The connection failure, if any. */
8
12
  readonly error: unknown;
@@ -28,15 +28,16 @@ export function useView(source, options = {}) {
28
28
  return fresh() ? undefined : viewSourcePreview(value);
29
29
  };
30
30
  const fresh = () => viewSourceIdentity(current.source) === identity;
31
+ // `current` is replaced with every published state, which only `state` follows. The other members are derived, so
32
+ // an `$effect` that reads only `client` (to call a command) does not run again when the answer publishes a state.
33
+ const client = $derived(preview()?.client ?? (fresh() ? current.client : undefined));
34
+ const error = $derived(fresh() ? current.error : undefined);
35
+ const pending = $derived(preview() ? false : fresh() ? current.pending : identity !== undefined);
31
36
  return {
32
37
  get state() { return preview()?.state ?? (fresh() ? current.state : undefined); },
33
- get client() { return preview()?.client ?? (fresh() ? current.client : undefined); },
34
- get error() { return fresh() ? current.error : undefined; },
35
- get pending() {
36
- if (preview())
37
- return false;
38
- return fresh() ? current.pending : identity !== undefined;
39
- },
38
+ get client() { return client; },
39
+ get error() { return error; },
40
+ get pending() { return pending; },
40
41
  retry() { controller.retry(); },
41
42
  };
42
43
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@runic-artifex/svelte",
3
- "version": "0.15.0",
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.0/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.0"
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.0",
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": "c94bda07cf363bad056eda86ae77c514b66e61dd"
70
+ "gitHead": "ff96e52727212344c407489283a9cafc614f0270"
71
71
  }