@runic-artifex/svelte 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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.17.0/packages/web/svelte/../sveltekit/README.md#connecting-in-load)).
90
90
 
91
91
  ### Selecting state: `$derived`
92
92
 
@@ -182,14 +182,35 @@ 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
186
- and text forms.
185
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#fields) for the receipts
186
+ and text forms. An `invalid-text` error has a `reason` and `arguments`: render `useText(() => name.error).current` after
187
+ `configureFieldErrorText` to show your own text for it in the window's language
188
+ ([Translating field errors](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#translating-field-errors)).
189
+
190
+ #### Row cells and nested members
191
+
192
+ Since 0.16, `InvoiceFields.address.street` and `InvoiceFields.lines.at(line.id).quantity` are fields too
193
+ (`field-paths/1`): a member of an object member, and a cell of a row that .NET edits with `[RunicRowEditor]`. Call
194
+ `useField(() => view, InvoiceFields.lines.at(line.id).quantity)` in the row's component and `{@attach quantity.attach}`
195
+ its input; `at(key)` returns the same descriptor for the same key. Such a field always writes checked, conflicts only
196
+ when another writer changed the same cell, and shows the messages .NET reports at the cell's validation path. See
197
+ [Fields below a member and row cells](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/svelte/../views/README.md#fields-below-a-member-and-row-cells).
198
+
199
+ ### Forms: `useForm(() => fields, options?)`
200
+
201
+ One state over field handles, and a `submit` that writes every field before its command (`createFormController` in
202
+ `@runic-artifex/views`). `dirty` counts drafts not written yet and the `dirty` option.
203
+
204
+ ```svelte
205
+ const form = useForm(() => ({ title, step }), { dirty: () => editor.state?.isDirty === true });
206
+ <button disabled={!form.valid || form.submitting} onclick={() => form.submit(() => editor.client!.save())}>Save</button>
207
+ ```
187
208
 
188
209
  ### Text inputs: `useTextField(view, read, write, options?)`
189
210
 
190
211
  Call during component initialization to bind a text input to a member through the
191
212
  framework-neutral
192
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.1/packages/web/views#text-inputs):
213
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#text-inputs):
193
214
 
194
215
  ```svelte
195
216
  <script lang="ts">
@@ -247,9 +268,17 @@ the reference as its `page` prop:
247
268
  ```
248
269
 
249
270
  The outlet is generic over the reference union, so the registry must have a
250
- component for every kind with a matching `page` prop. A different reference
251
- remounts the component, a kind without a component renders an English
252
- `<p role="alert">`, and the optional `fallback` snippet renders while `content` is empty.
271
+ component for every kind with a matching `page` prop. A component whose `page`
272
+ is a shared page reference, such as `ResultPagePageReference` of a .NET
273
+ [`[RunicSharedClient]`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/svelte/../../dotnet/Runic.Application.Views/README.md#shared-clients)
274
+ interface, registers for each of its kinds:
275
+ `{ ...registryEntries(resultPageKinds, ResultPage), settings: Settings }`. A different reference
276
+ remounts the component, and the optional `fallback` snippet renders while
277
+ `content` is empty. A kind without a component renders an English
278
+ `<p role="alert">` in a development build (`process.env.NODE_ENV`, which Vite
279
+ sets, is not `production`); a production build renders nothing and reports the
280
+ kind once through the page's error reporting (`installErrorReporting`,
281
+ `onBridgeDiagnostic`).
253
282
 
254
283
  The optional `missing` snippet replaces that alert, for example with localized
255
284
  text. It receives the reference whose kind has no component, and its markup
@@ -261,6 +290,69 @@ text. It receives the reference whose kind has no component, and its markup
261
290
  </ViewOutlet>
262
291
  ```
263
292
 
293
+ ### Region collections
294
+
295
+ A .NET `[RunicRegionCollection]` member, such as `state.documents`, lists
296
+ regions that each keep their own back stack. `<RegionOutlets>` renders a
297
+ `ViewOutlet` for each region, keyed by the region's key, inside a
298
+ `<div data-region-key>`. The default `mode="keep-mounted"` keeps every region mounted
299
+ and sets `hidden` and an inline `display: none` on all but the selected one, so
300
+ a tab keeps its component, scroll position and unsent input. Author CSS cannot
301
+ show a hidden panel without `!important`. `mode="selected"` renders only the
302
+ selected region. The `fallback` snippet renders while there is no region, and
303
+ the `missing` snippet is passed to each outlet. A region with `content: null`
304
+ renders nothing.
305
+
306
+ The package has no tab bar. Build one with `regionEntries` and the generated
307
+ `selectDocuments(key)` and `closeDocuments(key)`. The `panelProps(entry)` prop returns attributes (`RegionPanelAttributes`) for
308
+ each region's wrapper, such as `id`, `role="tabpanel"` and `aria-labelledby`, so
309
+ each tab can name its panel in `aria-controls`. `hidden` and `data-region-key`
310
+ stay controlled by the outlet, and its `display: none` takes precedence over a
311
+ returned `style`.
312
+
313
+ ```svelte
314
+ <script lang="ts">
315
+ const tabId = (key: string) => `document-tab-${key}`;
316
+ const panelId = (key: string) => `document-panel-${key}`;
317
+ async function close(key: string) {
318
+ if ((await workspace.client?.closeDocuments(key))?.kind !== "Committed") return;
319
+ await tick();
320
+ const selected = selectedRegion(workspace.state?.documents);
321
+ if (selected) document.getElementById(tabId(selected.key))?.focus();
322
+ }
323
+ </script>
324
+
325
+ <div role="tablist">
326
+ {#each regionEntries(workspace.state?.documents) as tab (tab.key)}
327
+ <button id={tabId(tab.key)} role="tab" aria-selected={tab.selected} aria-controls={panelId(tab.key)}
328
+ onclick={() => workspace.client?.selectDocuments(tab.key)}>
329
+ {tab.content?.kind ?? "Empty"}
330
+ </button>
331
+ <button aria-label="Close" onclick={() => close(tab.key)}>×</button>
332
+ {/each}
333
+ </div>
334
+ <RegionOutlets collection={workspace.state?.documents} registry={documentPages}
335
+ panelProps={tab => ({ id: panelId(tab.key), role: "tabpanel", "aria-labelledby": tabId(tab.key) })}>
336
+ {#snippet fallback()}<p>No open documents</p>{/snippet}
337
+ </RegionOutlets>
338
+ ```
339
+
340
+ `selected` changes only when a switch or close commits. A departure guard can
341
+ keep the current tab, so highlight `selected` and do not move the highlight
342
+ before the request settles. `select…` and `close…` resolve to the .NET
343
+ `NavigationOutcome`, such as `{ kind: "Rejected", rejection: "Guard" }`.
344
+
345
+ Closing the selected tab removes its button, and the next tab becomes selected
346
+ when the close commits. After `closeDocuments` resolves with `kind: "Committed"`,
347
+ move focus to the button of the new selected tab, as `close` above does.
348
+
349
+ In both modes the region collection keeps presenting every region's content,
350
+ so the pages of hidden tabs stay live and still receive state. `"selected"`
351
+ mode only unmounts the components of the regions that are not selected.
352
+
353
+ `regionEntries`, `selectedRegion` and the region types are re-exported from
354
+ `@runic-artifex/views`.
355
+
264
356
  ## `useCommand(command)`
265
357
 
266
358
  Returns `{ run, pending, error, failure, reset }` with reactive `pending`, `error`
@@ -328,7 +420,7 @@ Cancel and other callbacks responsive during observation.
328
420
  ## `useLatestOperation()`
329
421
 
330
422
  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)
423
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#operation-feedback-and-latest-selection)
332
424
  for the component's lifetime. It coalesces the latest intent across delayed receipts
333
425
  and orders the next admission after terminal observation and any application drain
334
426
  barrier:
@@ -359,7 +451,7 @@ establish that replacement boundary and own the old work's drain. Lost terminal
359
451
  observation blocks further Starts instead of retrying blindly, with its reason in
360
452
  `error`; ordinary Cancel does not clear this block. Component destruction settles
361
453
  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)
454
+ [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/tests/fixtures/application/operations-consumer)
363
455
  runs this hook against the packed packages and the desktop transport.
364
456
 
365
457
  ## `useBridgeConnection(options?)`
@@ -369,7 +461,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
369
461
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a reactive
370
462
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
371
463
  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)):
464
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#connection-state)):
373
465
 
374
466
  ```svelte
375
467
  <script lang="ts">
@@ -391,7 +483,7 @@ server render does not observe, and destroying the owner unsubscribes. An invali
391
483
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
392
484
  page (`DesktopMenuBarPresentation.Page`) while its owner lives. It wraps
393
485
  `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
486
+ [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`, where `state` is a
395
487
  reactive `MenuBarState` property. The bar is rendered by the menubar component
396
488
  of the application's own UI library. Runic ships no menubar component.
397
489
 
@@ -420,7 +512,7 @@ the `shortcuts: "app"` lease.
420
512
  ### With Bits UI
421
513
 
422
514
  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
515
+ [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
424
516
  items and is tested with real keys:
425
517
 
426
518
  ```svelte
@@ -470,6 +562,55 @@ items and is tested with real keys:
470
562
  The host owns `checked`: bind it one way, as
471
563
  `bind:checked={() => item.checked ?? false, () => {}}`.
472
564
 
565
+ ## `useText(value, fallback?)`
566
+
567
+ Shows a text reference that a ViewModel produced, such as a status line or a
568
+ validation error's `text`, in the window's language, and renders again when the
569
+ language changes. A string shows as it is; `null` and `undefined` show
570
+ `fallback`. Connect the page's Translations runtime once with
571
+ `configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
572
+ `useWindowLocale()` reads the window's locale.
573
+
574
+ `useTextLocale().current` is the locale that text is shown in, as a reactive
575
+ property. It is one handle for the page and needs no component, so the locale
576
+ resolver can read it; templates that call `m.*()` then render again on a
577
+ language switch. `syncDocumentLocale()` keeps `<html lang dir>` on that locale:
578
+
579
+ ```ts
580
+ // main.ts
581
+ const textLocale = useTextLocale();
582
+ configureLocaleResolver(() => textLocale.current ?? locale.getLocale());
583
+ configureTranslatedText({ ...locale, resolve, direction: localeDirection });
584
+ syncDocumentLocale();
585
+ ```
586
+
587
+ With SvelteKit server
588
+ rendering, call `configureTranslatedText` in the browser only (for example in
589
+ `onMount`), or render on the server with `resolveTextReference` and the
590
+ request's locale.
591
+
592
+ ```svelte
593
+ const status = useText(() => view.state?.status);
594
+ <p>{status.current}</p>
595
+ ```
596
+
597
+ ## `useAppearance()`
598
+
599
+ Follows the page's appearance while its owner lives, as the reactive property
600
+ `current`: the colour scheme, contrast and reduced motion of the page's engine,
601
+ combined with the desktop's text scale, accent colour, forced-colours palette,
602
+ contrast and motion that a Runic host pushes ([Appearance](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/views/README.md#appearance)).
603
+ Every member is `null` under server rendering, so a SvelteKit page renders the
604
+ same on the server and in the browser until the browser's first effect.
605
+
606
+ ```svelte
607
+ <script lang="ts">
608
+ import { useAppearance } from "@runic-artifex/svelte";
609
+ const look = useAppearance();
610
+ </script>
611
+ <main style:font-size="{look.current.textScale ?? 1}rem">…</main>
612
+ ```
613
+
473
614
  ## Errors
474
615
 
475
616
  The `error` of `useView` and of a command or operation helper is typed
@@ -487,7 +628,7 @@ const message = $derived(describeBridgeError(view.error));
487
628
  ```
488
629
 
489
630
  `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)
631
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#errors-and-diagnostics)
491
632
  lists the kinds. Any other value, such as an exception that your own connect
492
633
  function or command callback throws, arrives unchanged.
493
634
 
@@ -526,15 +667,49 @@ application's own dialog.
526
667
  departure before that is answered by the ViewModel's .NET fallback handler, or
527
668
  fails closed without one.
528
669
 
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)
670
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
530
671
  has the .NET side and which View answers which departure. In a frontend test,
531
672
  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).
673
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#testing).
674
+
675
+ ## View requests
676
+
677
+ A `ViewRequest<T>` property of the ViewModel asks the View for a one-way
678
+ presentation action, such as focusing a field or showing a toast, and is
679
+ `client.requests.<name>` on the generated client. Register the page's
680
+ handler in `$effect`: `handle((input, { signal }) => …)` returns the function
681
+ that removes it, so return that from the effect, and Svelte removes the handler
682
+ when the client changes or the component is destroyed:
683
+
684
+ ```svelte
685
+ <script lang="ts">
686
+ import { useView } from "@runic-artifex/svelte";
687
+ import type { EditPageReference } from "./generated/edit.js";
688
+
689
+ let { page }: { page: EditPageReference } = $props();
690
+ const view = useView(() => page);
691
+ let name: HTMLInputElement | undefined = $state();
692
+ $effect(() => view.client?.requests.focus.handle(({ member }) => {
693
+ if (member === "name") name?.focus();
694
+ }));
695
+ </script>
696
+
697
+ <input bind:this={name}>
698
+ ```
699
+
700
+ `input` is typed from the request's `ViewRequest<T>`. The handler runs once
701
+ the page painted the state the request was raised with, so the field of that
702
+ state is rendered; `signal` aborts when the handler is replaced or removed, the
703
+ client is disposed or the connection is lost. A request is never replayed: one
704
+ raised before the effect ran, or while the page is disconnected, is not
705
+ delivered later. See [View requests](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#view-requests) for the rules, and in a frontend
706
+ test raise one with the generated mock's `requests.<name>.raise(input)` (the
707
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#testing)).
533
708
 
534
709
  ## `useCollectionViewport(options)`
535
710
 
536
711
  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)
712
+ `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#collectionviewportoptions)
538
713
  range; `attach` is an attachment for the container. Call it during component
539
714
  initialization and send the range to the ViewModel from an effect:
540
715
 
@@ -556,3 +731,33 @@ initialization and send the range to the ViewModel from an effect:
556
731
  Translation helpers moved to
557
732
  [`@runic-artifex/translations-svelte`](https://www.npmjs.com/package/@runic-artifex/translations-svelte).
558
733
  Import them from there instead of `@runic-artifex/svelte`.
734
+
735
+ ## `useQueryCollection(collection, options)`
736
+
737
+ Follows a scroll container for a [query collection](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/views#query-collections) (`client.queries.{name}`), whose rows stay in .NET: it
738
+ loads the rows the container shows, with placeholders until they arrive, and lays them out with variable heights. Pass
739
+ getters of the collection and the options. `viewport` is the `QueryViewport` (`items` with `top` and `size`,
740
+ `totalSize`, `total`, `query`, `loading`, `error`); attach `attach` to the container and `measure(index)` to each row.
741
+ It is safe in SvelteKit: on the server, `viewport` stays empty.
742
+
743
+ ```svelte
744
+ <script lang="ts">
745
+ const list = useQueryCollection(() => view.client?.queries.rows, () => ({ estimateSize: 32 }));
746
+ </script>
747
+ <div {@attach list.attach} style="height: 480px; overflow: auto">
748
+ <div style="height: {list.viewport.totalSize}px; position: relative">
749
+ {#each list.viewport.items as item (item.key ?? `p${item.index}`)}
750
+ <div {@attach list.measure(item.index)} style="position: absolute; top: {item.top}px; width: 100%">{item.row?.label ?? "…"}</div>
751
+ {/each}
752
+ </div>
753
+ </div>
754
+ ```
755
+
756
+ ## Back and the URL
757
+
758
+ The package re-exports `installBackNavigation`, `installNavigationPath`,
759
+ `navigateBack`, `openNavigationPath` and `onNavigationPath` from
760
+ `@runic-artifex/views` (since 0.16). Call the installs once where the page
761
+ starts, before or after mounting: the mouse's Back button and Alt+Left then go
762
+ back in the .NET window, and `#/customers/42` follows its path region. See
763
+ [Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.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,6 +1,8 @@
1
1
  <script lang="ts" generics="R extends PageReference">
2
2
  import type { Component, Snippet } from "svelte";
3
3
  import type { PageReference } from "@runic-artifex/views";
4
+ import { missingViewMessage, reportMissingView } from "@runic-artifex/views/bindings";
5
+ import { isDevelopment } from "./development.js";
4
6
  import type { ViewRegistry } from "./view-registry.js";
5
7
 
6
8
  let { content, registry, fallback, missing }: {
@@ -9,20 +11,25 @@
9
11
  /** Rendered while there is no content. */
10
12
  fallback?: Snippet;
11
13
  /**
12
- * Renders a reference whose kind has no registered component, for example localized text.
13
- * Defaults to an English `<p role="alert">`.
14
+ * Renders a reference whose kind has no registered component, for example localized text. Without it, a
15
+ * development build renders an English `<p role="alert">`, and a production build renders nothing and reports
16
+ * the kind through the page's error reporting.
14
17
  */
15
18
  missing?: Snippet<[R]>;
16
19
  } = $props();
17
20
  let Resolved = $derived(content ? registry[content.kind as R["kind"]] as Component<{ page: R }> | undefined : undefined);
21
+ const development = isDevelopment();
22
+ $effect.pre(() => {
23
+ if (content && !Resolved && !missing && !development) reportMissingView(content.kind);
24
+ });
18
25
  </script>
19
26
 
20
27
  {#if content && Resolved}
21
28
  {#key content}<Resolved page={content} />{/key}
22
29
  {:else if content && missing}
23
30
  {@render missing(content)}
24
- {:else if content}
25
- <p role="alert">No web component is registered for {content.kind}.</p>
26
- {:else}
31
+ {:else if content && development}
32
+ <p role="alert">{missingViewMessage(content.kind)}</p>
33
+ {:else if !content}
27
34
  {@render fallback?.()}
28
35
  {/if}
@@ -8,8 +8,9 @@ declare function $$render<R extends PageReference>(): {
8
8
  /** Rendered while there is no content. */
9
9
  fallback?: Snippet;
10
10
  /**
11
- * Renders a reference whose kind has no registered component, for example localized text.
12
- * Defaults to an English `<p role="alert">`.
11
+ * Renders a reference whose kind has no registered component, for example localized text. Without it, a
12
+ * development build renders an English `<p role="alert">`, and a production build renders nothing and reports
13
+ * the kind through the page's error reporting.
13
14
  */
14
15
  missing?: Snippet<[R]>;
15
16
  };
@@ -0,0 +1,2 @@
1
+ /** Whether the page is a development build. A page whose bundler does not replace NODE_ENV counts as production. */
2
+ export declare function isDevelopment(): boolean;
@@ -0,0 +1,9 @@
1
+ /** Whether the page is a development build. A page whose bundler does not replace NODE_ENV counts as production. */
2
+ export function isDevelopment() {
3
+ try {
4
+ return process.env.NODE_ENV !== "production";
5
+ }
6
+ catch {
7
+ return false;
8
+ }
9
+ }
@@ -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,20 @@ 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, useTextLocale, useWindowLocale, type TextHandle, type TextLocaleHandle, type WindowLocaleHandle, } from "./use-text.svelte.js";
19
+ export { useAppearance, type AppearanceHandle } from "./use-appearance.svelte.js";
20
+ export { configureFieldErrorText, configureTranslatedText, fieldErrorText, resolveText, syncDocumentLocale, textDirection, windowLocale, type DocumentLocaleOptions, type FieldErrorArguments, type FieldErrorReason, type FieldErrorText, type TextReference, type TextTranslations, } from "@runic-artifex/views";
21
+ export { appearance, onAppearance, type Appearance, type AppearanceColorScheme, type AppearanceContrast, type AppearanceSystemColors, type HostAppearance, } from "@runic-artifex/views";
22
+ export { upload, type BlobRef, type RunicBlob, type UploadOptions, type UploadProgress } from "@runic-artifex/views";
23
+ export { regionEntries, selectedRegion, type RegionCollection, type RegionEntry, type RegionOutcome, type RegionSlot, } from "@runic-artifex/views";
24
+ export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, type NavigationPathChange, type NavigationPathOptions, type NavigationReply, } from "@runic-artifex/views";
25
+ export { FieldError, type BridgeField, type BridgeFieldConstraints, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
14
26
  export { useMenuBar, type MenuBarHandle, type UseMenuBarOptions } from "./use-menu-bar.svelte.js";
15
27
  export type { MenuBarEntry, MenuBarInvokeResult, MenuBarItem, MenuBarMenu, MenuBarRequest, MenuBarSeparator, MenuBarState, } from "@runic-artifex/views";
@@ -1,13 +1,25 @@
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, useTextLocale, useWindowLocale, } from "./use-text.svelte.js";
17
+ export { useAppearance } from "./use-appearance.svelte.js";
18
+ export { configureFieldErrorText, configureTranslatedText, fieldErrorText, resolveText, syncDocumentLocale, textDirection, windowLocale, } from "@runic-artifex/views";
19
+ export { appearance, onAppearance, } from "@runic-artifex/views";
20
+ // blobs/1: uploads from the page and the blob values of state.
21
+ export { upload } from "@runic-artifex/views";
22
+ export { regionEntries, selectedRegion, } from "@runic-artifex/views";
23
+ export { installBackNavigation, installNavigationPath, navigateBack, onNavigationPath, openNavigationPath, } from "@runic-artifex/views";
12
24
  export { FieldError, } from "@runic-artifex/views";
13
25
  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 {};
@@ -0,0 +1,18 @@
1
+ import { type Appearance } from "@runic-artifex/views";
2
+ export interface AppearanceHandle {
3
+ /** The page's appearance. A reactive property; every member is `null` under server rendering. */
4
+ readonly current: Appearance;
5
+ }
6
+ /**
7
+ * Follows the page's appearance (`appearance` from `@runic-artifex/views`) while its owner lives: the colour scheme,
8
+ * contrast and reduced motion of the page's engine combined with the desktop's values that a Runic host pushes
9
+ * (`appearance/1`), which also carry the text scale, the accent colour and the forced-colours palette.
10
+ *
11
+ * ```svelte
12
+ * <script lang="ts">
13
+ * const look = useAppearance();
14
+ * </script>
15
+ * <main style:font-size="{look.current.textScale ?? 1}rem">…</main>
16
+ * ```
17
+ */
18
+ export declare function useAppearance(): AppearanceHandle;
@@ -0,0 +1,22 @@
1
+ import { appearance, onAppearance, unknownAppearance } from "@runic-artifex/views";
2
+ /**
3
+ * Follows the page's appearance (`appearance` from `@runic-artifex/views`) while its owner lives: the colour scheme,
4
+ * contrast and reduced motion of the page's engine combined with the desktop's values that a Runic host pushes
5
+ * (`appearance/1`), which also carry the text scale, the accent colour and the forced-colours palette.
6
+ *
7
+ * ```svelte
8
+ * <script lang="ts">
9
+ * const look = useAppearance();
10
+ * </script>
11
+ * <main style:font-size="{look.current.textScale ?? 1}rem">…</main>
12
+ * ```
13
+ */
14
+ export function useAppearance() {
15
+ let current = $state.raw(typeof window === "undefined" ? unknownAppearance : appearance());
16
+ $effect.pre(() => {
17
+ const stop = onAppearance(next => { current = next; });
18
+ current = appearance();
19
+ return stop;
20
+ });
21
+ return { get current() { return current; } };
22
+ }
@@ -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,42 @@
1
+ import { type FieldError, 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 TextLocaleHandle {
7
+ /** The locale that text is shown in, or `undefined` before there is one. A reactive property. */
8
+ readonly current: string | undefined;
9
+ }
10
+ export interface WindowLocaleHandle {
11
+ /** The window's locale that the application set, or `null` while it sets none. A reactive property. */
12
+ readonly current: string | null;
13
+ }
14
+ /**
15
+ * Follows a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
16
+ * window's language (`resolveText`), while its owner lives. `source` and `fallback` are read reactively, so pass
17
+ * functions: `useText(() => view.state?.status)`. A string shows as it is; `null` and `undefined` show `fallback`.
18
+ * Configure the page's Translations runtime once with `configureTranslatedText`; without one, a reference shows its
19
+ * fallback text. A field's `FieldError` shows the application's text for it (`configureFieldErrorText`), or its English
20
+ * message: `useText(() => name.error)`. Call during component initialization (or in `$effect.root`).
21
+ *
22
+ * ```svelte
23
+ * const status = useText(() => view.state?.status);
24
+ * <p>{status.current}</p>
25
+ * ```
26
+ */
27
+ export declare function useText(source: () => TextReference | FieldError | string | null | undefined, fallback?: () => string | undefined): TextHandle;
28
+ /** Follows the window's locale (`windowLocale`) while its owner lives, for example to set `lang`. */
29
+ export declare function useWindowLocale(): WindowLocaleHandle;
30
+ /**
31
+ * Follows the locale that text is shown in (`textLocale`: the page's Translations locale, which follows the window's
32
+ * locale). Reading `current` in a template, `$derived` or `$effect` runs it again when the locale changes. It is one
33
+ * handle for the page and needs no component, so the page's locale resolver can read it: a template that calls
34
+ * `m.*()` then renders again on a language switch. `undefined` while the page has no Translations runtime and the
35
+ * application sets no window locale.
36
+ *
37
+ * ```ts
38
+ * const textLocale = useTextLocale();
39
+ * configureLocaleResolver(() => textLocale.current ?? locale.getLocale());
40
+ * ```
41
+ */
42
+ export declare function useTextLocale(): TextLocaleHandle;
@@ -0,0 +1,52 @@
1
+ import { createSubscriber } from "svelte/reactivity";
2
+ import { onWindowLocale, resolveText, subscribeText, textLocale, windowLocale } from "@runic-artifex/views";
3
+ /**
4
+ * Follows a text reference that a ViewModel produced, such as a status line or a validation message's `text`, in the
5
+ * window's language (`resolveText`), while its owner lives. `source` and `fallback` are read reactively, so pass
6
+ * functions: `useText(() => view.state?.status)`. A string shows as it is; `null` and `undefined` show `fallback`.
7
+ * Configure the page's Translations runtime once with `configureTranslatedText`; without one, a reference shows its
8
+ * fallback text. A field's `FieldError` shows the application's text for it (`configureFieldErrorText`), or its English
9
+ * message: `useText(() => name.error)`. Call during component initialization (or in `$effect.root`).
10
+ *
11
+ * ```svelte
12
+ * const status = useText(() => view.state?.status);
13
+ * <p>{status.current}</p>
14
+ * ```
15
+ */
16
+ export function useText(source, fallback) {
17
+ let version = $state(0);
18
+ $effect.pre(() => subscribeText(() => { version++; }));
19
+ const current = $derived.by(() => {
20
+ void version;
21
+ return resolveText(source(), fallback?.());
22
+ });
23
+ return { get current() { return current; } };
24
+ }
25
+ /** Follows the window's locale (`windowLocale`) while its owner lives, for example to set `lang`. */
26
+ export function useWindowLocale() {
27
+ let current = $state(windowLocale());
28
+ $effect.pre(() => onWindowLocale(next => { current = next; }));
29
+ return { get current() { return current; } };
30
+ }
31
+ const subscribeTextLocale = createSubscriber(update => subscribeText(update));
32
+ const textLocaleHandle = {
33
+ get current() {
34
+ subscribeTextLocale();
35
+ return textLocale();
36
+ },
37
+ };
38
+ /**
39
+ * Follows the locale that text is shown in (`textLocale`: the page's Translations locale, which follows the window's
40
+ * locale). Reading `current` in a template, `$derived` or `$effect` runs it again when the locale changes. It is one
41
+ * handle for the page and needs no component, so the page's locale resolver can read it: a template that calls
42
+ * `m.*()` then renders again on a language switch. `undefined` while the page has no Translations runtime and the
43
+ * application sets no window locale.
44
+ *
45
+ * ```ts
46
+ * const textLocale = useTextLocale();
47
+ * configureLocaleResolver(() => textLocale.current ?? locale.getLocale());
48
+ * ```
49
+ */
50
+ export function useTextLocale() {
51
+ return textLocaleHandle;
52
+ }
@@ -1,13 +1,14 @@
1
1
  import type { Component } from "svelte";
2
- import type { PageReference } from "@runic-artifex/views";
2
+ import type { PageReference, ViewRegistryPage } from "@runic-artifex/views";
3
3
  /**
4
4
  * Compile-time check that every View kind has a component with a matching page prop. A nullable
5
- * reference, such as a region slot's `State["main"]`, checks its non-null kinds.
5
+ * reference, such as a region slot's `State["main"]`, checks its non-null kinds. A component whose `page` is a shared
6
+ * page reference (`[RunicSharedClient]`), such as `ResultPagePageReference`, registers for each of its kinds.
6
7
  */
7
8
  export type ViewRegistry<R extends PageReference | null | undefined> = {
8
- readonly [K in NonNullable<R>["kind"]]: Component<{
9
- page: Extract<NonNullable<R>, {
10
- readonly kind: K;
11
- }>;
12
- }>;
9
+ readonly [K in NonNullable<R>["kind"]]: PageComponent<ViewRegistryPage<R, K>>;
13
10
  };
11
+ type PageComponent<P> = P extends unknown ? Component<{
12
+ page: P;
13
+ }> : never;
14
+ export {};
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@runic-artifex/svelte",
3
- "version": "0.15.1",
3
+ "version": "0.17.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.17.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/use-text.svelte.test.ts test/use-appearance.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.17.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.17.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": "daeb17e5c3fb0b625d5d988d359cd12ffa51f8c6"
71
71
  }