@runic-artifex/svelte 0.13.0 → 0.15.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
@@ -41,10 +41,64 @@ the same floor as SvelteKit 3 and `@runic-artifex/sveltekit`.
41
41
  Call `useView` during component initialization. `options.release(client)`
42
42
  replaces `client.dispose()` for a client the helper connected. It connects a generated page
43
43
  reference, or `{ connect: connect<Name> }` for a root ViewModel, while the
44
- component is mounted and disposes it on destroy or when the getter returns a
45
- reference with a different `connect` function. An already connected client is
46
- observed and left to its owner. The result exposes reactive `state`, `client`,
47
- `error` and `pending` properties and `retry()`.
44
+ component is mounted. An already connected client is observed and left to its
45
+ owner. The result exposes reactive `state`, `client`, `error` and `pending`
46
+ properties and `retry()`.
47
+
48
+ When the component is destroyed or the getter returns a reference with a
49
+ different `connect` function, the client stays connected for
50
+ `options.keepAlive` milliseconds (2000 by default), and the next `useView` of
51
+ the same reference takes it over with its state, before its first effect runs:
52
+ an `{#if}` that toggles, HMR and A→B→A navigation show the View at once instead
53
+ of "Connecting…" and do not open the route again. `keepAlive: 0` disposes at
54
+ once.
55
+
56
+ ### Awaiting the connection: `useSuspenseView(source, options?)` and `{#await}`
57
+
58
+ `useSuspenseView(page)` connects like `useView` during component
59
+ initialization and returns a promise that resolves once the View connected,
60
+ with reactive `state` and `client` that are never `undefined`, or rejects with
61
+ the failure. Await it with `{#await}`:
62
+
63
+ ```svelte
64
+ <script lang="ts">
65
+ import { describeBridgeError } from "@runic-artifex/views";
66
+ import { useSuspenseView } from "@runic-artifex/svelte";
67
+ import type { CounterPageReference } from "../generated/counter.js";
68
+
69
+ let { page }: { page: CounterPageReference } = $props();
70
+ const counter = useSuspenseView(page);
71
+ </script>
72
+
73
+ {#await counter}
74
+ <p>Connecting…</p>
75
+ {:then view}
76
+ <button onclick={() => view.client.increment()}>{view.state.count}</button>
77
+ {:catch error}
78
+ <p role="alert">{describeBridgeError(error)}</p>
79
+ {/await}
80
+ ```
81
+
82
+ The source is read once: wrap the component in `{#key page}` to follow another
83
+ reference. Do not `{#await page.connect()}` directly: nothing would dispose
84
+ 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)).
86
+
87
+ ### Selecting state: `$derived`
88
+
89
+ The handle's `state` changes with every change of the View. A `$derived` that
90
+ selects a member updates its dependents only when its value changed, so markup
91
+ or an `$effect` that reads `title` does not run again when another member
92
+ changes:
93
+
94
+ ```ts
95
+ const editor = useView(() => page);
96
+ const title = $derived(editor.state?.title);
97
+ ```
98
+
99
+ Members the View did not change keep their identity, so selecting a member,
100
+ also an object or a list, is enough. A derived value that builds a new object
101
+ each time, such as `items.filter(…)`, changes every time.
48
102
 
49
103
  ### Read-only state and `bind:value`
50
104
 
@@ -72,11 +126,66 @@ Read state one way from `state`. A property with a public C# setter also gets a
72
126
  </select>
73
127
  ```
74
128
 
129
+ ### Fields: `useField(view, field, options?)`
130
+
131
+ Call during component initialization to bind an element to a member. Pass the generated `{View}Fields` descriptor; it
132
+ knows the member's kind, setter, checked write and validation. `{@attach field.attach}` wires the element:
133
+
134
+ ```svelte
135
+ <script lang="ts">
136
+ import { useField, useView } from "@runic-artifex/svelte";
137
+ import { EditorFields, type EditorPageReference } from "./generated/editor.js";
138
+
139
+ let { page }: { page: EditorPageReference } = $props();
140
+ const editor = useView(() => page);
141
+ const title = useField(() => editor, EditorFields.title, { commit: "pause", checked: true });
142
+ const step = useField(() => editor, EditorFields.step);
143
+ const done = useField(() => editor, EditorFields.done);
144
+ </script>
145
+
146
+ <input {@attach title.attach}>
147
+ {#each title.errors as message}<p role="alert">{message}</p>{/each}
148
+ {#if title.conflict}
149
+ <p role="alert">
150
+ Changed elsewhere to “{title.conflict.value}”.
151
+ <button onclick={title.retry}>Keep mine</button> <button onclick={title.reset}>Take theirs</button>
152
+ </p>
153
+ {/if}
154
+ <input type="number" {@attach step.attach}>
155
+ <input type="checkbox" {@attach done.attach}>
156
+ ```
157
+
158
+ The attachment writes what the user types (`input`; `change` of a `<select>` or checkbox), writes nothing during IME
159
+ composition, commits on blur, keeps the element's text (a checkbox's `checked`) equal to the field's without moving
160
+ the caret, and sets `aria-invalid` while the field has `errors` or an `error`. Number inputs keep `-` and `1.` while
161
+ the user types: a text that does not parse stays the draft with an `invalid-text` error and nothing is written. The
162
+ handle also has `value` and `text`, which `bind:value={title.value}` reads and sets, the reactive `editing`, `error`,
163
+ `errors` and `conflict`, and `input(value)`, `commit()`, `retry()` and `reset()`.
164
+
165
+ `options` are read once, when the field is created:
166
+
167
+ - `commit: "pause"` writes the draft after `delay` milliseconds without input (700 by default) and at once on
168
+ `commit()`, which blur calls; use it where each write is an undo step or starts work in .NET. The default,
169
+ `commit: "input"`, writes each input. `commit()` resolves with the field's state once its writes settled, so a
170
+ command that depends on the field can follow them and skip a failed write:
171
+ `if ((await title.commit()).error === undefined) await editor.save()`.
172
+ - `checked: true` writes with the member's checked write, so a change by another writer while the user edits is a
173
+ conflict instead of being overwritten. A `rejected` receipt keeps the draft and sets `error` to a `FieldError` with
174
+ the setter's message; a `conflict` keeps the draft, sets `conflict` to the producer's `{ value, version }` and
175
+ writes nothing until `retry()` writes the draft over it or `reset()` takes it.
176
+ - `coalesce` and `keepDraftOnError` as for text inputs below.
177
+
178
+ `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
179
+ or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
180
+ `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
182
+ and text forms.
183
+
75
184
  ### Text inputs: `useTextField(view, read, write, options?)`
76
185
 
77
186
  Call during component initialization to bind a text input to a member through the
78
187
  framework-neutral
79
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#text-inputs):
188
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#text-inputs):
80
189
 
81
190
  ```svelte
82
191
  <script lang="ts">
@@ -101,9 +210,11 @@ frame that answers an older keystroke never replaces newer text. At most one wri
101
210
  in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
102
211
  every change). Nothing is written during IME composition. Once the last write settled,
103
212
  the field shows the View's value again, including any normalization the ViewModel
104
- applied (trimmed, upper-cased). `write` may also be a command or a checked write. A
105
- failed write keeps the draft and sets `error` (`keepDraftOnError: false` shows the
106
- View's value instead); `reset()` drops the draft. `editing` is true while a draft
213
+ applied (trimmed, upper-cased). `write` may also be a command or a checked write,
214
+ whose receipt the field reads: `rejected` and `conflict` keep the draft and set `error`
215
+ to a `FieldError` of that kind, `committed-with-error` drops the draft and sets it too,
216
+ and `applied.validation` is `errors`. A failed write keeps the draft and sets `error`
217
+ (`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
107
218
  exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
108
219
  the user types: the field's own write causes it, and keys typed meanwhile would be
109
220
  lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
@@ -213,7 +324,7 @@ Cancel and other callbacks responsive during observation.
213
324
  ## `useLatestOperation()`
214
325
 
215
326
  For rapid read selection, `useLatestOperation()` wraps the framework-neutral
216
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#operation-feedback-and-latest-selection)
327
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#operation-feedback-and-latest-selection)
217
328
  for the component's lifetime. It coalesces the latest intent across delayed receipts
218
329
  and orders the next admission after terminal observation and any application drain
219
330
  barrier:
@@ -244,7 +355,7 @@ establish that replacement boundary and own the old work's drain. Lost terminal
244
355
  observation blocks further Starts instead of retrying blindly, with its reason in
245
356
  `error`; ordinary Cancel does not clear this block. Component destruction settles
246
357
  observation without cancelling accepted work. The
247
- [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/tests/fixtures/application/operations-consumer)
358
+ [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/tests/fixtures/application/operations-consumer)
248
359
  runs this hook against the packed packages and the desktop transport.
249
360
 
250
361
  ## `useBridgeConnection(options?)`
@@ -252,9 +363,9 @@ runs this hook against the packed packages and the desktop transport.
252
363
  Follows the page's connection to its .NET host. It wraps `onBridgeConnection`
253
364
  from `@runic-artifex/views` (re-exported here since 0.11, with the
254
365
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a reactive
255
- `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
256
- closed set, see
257
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#connection-state)):
366
+ `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
367
+ 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)):
258
369
 
259
370
  ```svelte
260
371
  <script lang="ts">
@@ -276,7 +387,7 @@ server render does not observe, and destroying the owner unsubscribes. An invali
276
387
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
277
388
  page (`DesktopMenuBarPresentation.Page`) while its owner lives. It wraps
278
389
  `createMenuBarController` from `@runic-artifex/views` (see
279
- [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`, where `state` is a
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
280
391
  reactive `MenuBarState` property. The bar is rendered by the menubar component
281
392
  of the application's own UI library. Runic ships no menubar component.
282
393
 
@@ -305,7 +416,7 @@ the `shortcuts: "app"` lease.
305
416
  ### With Bits UI
306
417
 
307
418
  Bits UI's `Menubar.Root bind:value`; the
308
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
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
309
420
  items and is tested with real keys:
310
421
 
311
422
  ```svelte
@@ -359,17 +470,20 @@ The host owns `checked`: bind it one way, as
359
470
 
360
471
  The `error` of `useView` and of a command or operation helper is typed
361
472
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
362
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
363
- `instanceof` before reading `kind`, `route` or `detail`:
473
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
474
+ `describeBridgeError(error)`, one English sentence, instead of `String(error)`,
475
+ and narrow it with `isBridgeError` (or `instanceof`) before reading `kind`,
476
+ `route` or `detail`:
364
477
 
365
478
  ```ts
366
- import { BridgeError } from "@runic-artifex/views";
479
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
367
480
 
368
- const offline = view.error instanceof BridgeError && view.error.kind === "disconnected";
481
+ const offline = $derived(isBridgeError(view.error, "disconnected"));
482
+ const message = $derived(describeBridgeError(view.error));
369
483
  ```
370
484
 
371
485
  `instanceof` holds for errors from every copy of the package on the page.
372
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#errors-and-diagnostics)
486
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#errors-and-diagnostics)
373
487
  lists the kinds. Any other value, such as an exception that your own connect
374
488
  function or command callback throws, arrives unchanged.
375
489
 
@@ -408,15 +522,15 @@ application's own dialog.
408
522
  departure before that is answered by the ViewModel's .NET fallback handler, or
409
523
  fails closed without one.
410
524
 
411
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.13.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
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)
412
526
  has the .NET side and which View answers which departure. In a frontend test,
413
527
  the generated mock's `interactions.<name>.request(input)` resolves with the
414
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#testing).
528
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#testing).
415
529
 
416
530
  ## `useCollectionViewport(options)`
417
531
 
418
532
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
419
- `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#collectionviewportoptions)
533
+ `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#collectionviewportoptions)
420
534
  range; `attach` is an attachment for the container. Call it during component
421
535
  initialization and send the range to the ViewModel from an effect:
422
536
 
@@ -1,12 +1,15 @@
1
1
  export { default as ViewOutlet } from "./ViewOutlet.svelte";
2
2
  export type { ViewRegistry } from "./view-registry.js";
3
- export { useView, type UseViewOptions, type ViewHandle } from "./use-view.svelte.js";
3
+ export { useSuspenseView, useView, type SuspenseViewHandle, type UseViewOptions, type ViewHandle } from "./use-view.svelte.js";
4
+ export { preloadView, type PreloadViewOptions } from "@runic-artifex/views";
4
5
  export { useCommand, type CommandHandle } from "./use-command.svelte.js";
5
6
  export { useOperation, type OperationHandle } from "./use-operation.svelte.js";
6
7
  export { useTextField, type TextFieldHandle, type TextFieldView, type UseTextFieldOptions } from "./use-text-field.svelte.js";
8
+ export { useField, type FieldElement, type FieldHandle } from "./use-field.svelte.js";
7
9
  export { useLatestOperation, type LatestOperationHandle } from "./use-latest-operation.svelte.js";
8
10
  export { useCollectionViewport, type CollectionViewportHandle } from "./use-collection-viewport.svelte.js";
9
11
  export { useBridgeConnection, type BridgeConnectionHandle } from "./use-bridge-connection.svelte.js";
10
12
  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";
11
14
  export { useMenuBar, type MenuBarHandle, type UseMenuBarOptions } from "./use-menu-bar.svelte.js";
12
15
  export type { MenuBarEntry, MenuBarInvokeResult, MenuBarItem, MenuBarMenu, MenuBarRequest, MenuBarSeparator, MenuBarState, } from "@runic-artifex/views";
@@ -1,10 +1,13 @@
1
1
  export { default as ViewOutlet } from "./ViewOutlet.svelte";
2
- export { useView } from "./use-view.svelte.js";
2
+ export { useSuspenseView, useView } from "./use-view.svelte.js";
3
+ export { preloadView } from "@runic-artifex/views";
3
4
  export { useCommand } from "./use-command.svelte.js";
4
5
  export { useOperation } from "./use-operation.svelte.js";
5
6
  export { useTextField } from "./use-text-field.svelte.js";
7
+ export { useField } from "./use-field.svelte.js";
6
8
  export { useLatestOperation } from "./use-latest-operation.svelte.js";
7
9
  export { useCollectionViewport } from "./use-collection-viewport.svelte.js";
8
10
  export { useBridgeConnection } from "./use-bridge-connection.svelte.js";
9
11
  export { onBridgeConnection } from "@runic-artifex/views";
12
+ export { FieldError, } from "@runic-artifex/views";
10
13
  export { useMenuBar } from "./use-menu-bar.svelte.js";
@@ -4,8 +4,8 @@ export interface BridgeConnectionHandle {
4
4
  readonly state: BridgeConnectionState;
5
5
  }
6
6
  /**
7
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting` or
8
- * `lost`) through `onBridgeConnection` while its owner lives. `state` holds the current state at
7
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
8
+ * `lost` or `closed`) through `onBridgeConnection` while its owner lives. `state` holds the current state at
9
9
  * once; the subscription starts with the owner's effects, so server rendering never observes.
10
10
  * Call during component initialization (or in `$effect.root`); owner destruction unsubscribes.
11
11
  *
@@ -1,7 +1,7 @@
1
1
  import { onBridgeConnection } from "@runic-artifex/views";
2
2
  /**
3
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting` or
4
- * `lost`) through `onBridgeConnection` while its owner lives. `state` holds the current state at
3
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
4
+ * `lost` or `closed`) through `onBridgeConnection` while its owner lives. `state` holds the current state at
5
5
  * once; the subscription starts with the owner's effects, so server rendering never observes.
6
6
  * Call during component initialization (or in `$effect.root`); owner destruction unsubscribes.
7
7
  *
@@ -0,0 +1,66 @@
1
+ import type { Attachment } from "svelte/attachments";
2
+ import { type BridgeField, type FieldBaseline, type FieldDefinition, type FieldOptions, type ViewClient, type FieldState } from "@runic-artifex/views";
3
+ import type { TextFieldView } from "./use-text-field.svelte.js";
4
+ /** The elements {@link FieldHandle.attach} wires. */
5
+ export type FieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
6
+ /** A field bound by {@link useField}. */
7
+ export interface FieldHandle<TValue> {
8
+ /**
9
+ * The draft while one exists, otherwise the member's value in the View's state. Setting it is an input by the user,
10
+ * as `bind:value` and `bind:checked` do.
11
+ */
12
+ value: TValue;
13
+ /**
14
+ * What a text input shows: the text typed while it does not parse or still means `value` (so `1.` stays while typing
15
+ * `1.5`), otherwise `value` formatted. Setting it is an input of text, parsed for the field's kind.
16
+ */
17
+ text: string;
18
+ /**
19
+ * True while a draft exists, from the first input until the last write settled and the state caught up, and after a
20
+ * failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state.
21
+ */
22
+ readonly editing: boolean;
23
+ /** Why the latest write or text failed (a `BridgeError` or a `FieldError`), until the next input, `retry()` or `reset()`. */
24
+ readonly error: unknown;
25
+ /** The member's validation messages in the View's state, or of the last checked write's receipt; `[]` when valid. */
26
+ readonly errors: readonly string[];
27
+ /** The producer's field while a checked write's `conflict` keeps the draft; `undefined` otherwise. */
28
+ readonly conflict: FieldBaseline<TValue> | undefined;
29
+ /** The user changed the value. */
30
+ input(value: TValue): void;
31
+ /**
32
+ * The user is done with the field (`attach` calls it on blur): with `commit: "pause"` the draft is written now.
33
+ * Resolves with the field's state once its writes settled, so a command that depends on the field can run after
34
+ * it and skip a failed write: `if ((await title.commit()).error === undefined) await editor.save()`. Never
35
+ * rejects; a failure is `error`.
36
+ */
37
+ commit(): Promise<FieldState<TValue>>;
38
+ /** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
39
+ retry(): void;
40
+ /** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
41
+ reset(): void;
42
+ /**
43
+ * Wires an `<input>`, `<textarea>` or `<select>` to the field: `<input {@attach title.attach}>`. It writes the text
44
+ * typed (`input` events; `change` of a `<select>` or checkbox, whose `checked` is the value), writes nothing during
45
+ * IME composition, commits on blur, keeps the element's text (a checkbox's `checked`) equal to the field's without
46
+ * moving the caret while it already shows it, and sets `aria-invalid` while the field has `errors` or an `error`.
47
+ */
48
+ readonly attach: Attachment<FieldElement>;
49
+ }
50
+ /**
51
+ * Binds an element to one View member while the calling component is mounted, through `createFieldController`: pass a
52
+ * generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Call it during
53
+ * component initialization; `options` are read then. Wire the element with `{@attach title.attach}`, or bind
54
+ * `bind:value={title.value}` and call `commit` on blur yourself.
55
+ *
56
+ * ```svelte
57
+ * const editor = useView(() => page);
58
+ * const title = useField(() => editor, EditorFields.title, { commit: "pause", checked: true });
59
+ * <input {@attach title.attach}>
60
+ * {#if title.conflict}<button onclick={title.retry}>Keep mine</button>{/if}
61
+ * ```
62
+ *
63
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
64
+ * conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
65
+ */
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>;
@@ -0,0 +1,85 @@
1
+ import { untrack } from "svelte";
2
+ import { createFieldController, } from "@runic-artifex/views";
3
+ /**
4
+ * Binds an element to one View member while the calling component is mounted, through `createFieldController`: pass a
5
+ * generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Call it during
6
+ * component initialization; `options` are read then. Wire the element with `{@attach title.attach}`, or bind
7
+ * `bind:value={title.value}` and call `commit` on blur yourself.
8
+ *
9
+ * ```svelte
10
+ * const editor = useView(() => page);
11
+ * const title = useField(() => editor, EditorFields.title, { commit: "pause", checked: true });
12
+ * <input {@attach title.attach}>
13
+ * {#if title.conflict}<button onclick={title.retry}>Keep mine</button>{/if}
14
+ * ```
15
+ *
16
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
17
+ * conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
18
+ */
19
+ export function useField(view, field, options = {}) {
20
+ const controller = createFieldController(field, options);
21
+ let current = $state.raw(controller.current);
22
+ const unsubscribe = controller.subscribe(() => { current = controller.current; });
23
+ // A pre effect runs when it is created, so the teardown exists even if the owner is destroyed before its first
24
+ // flush (see useOperation). It reads no state, so it never re-runs.
25
+ $effect.pre(() => () => { unsubscribe(); controller.dispose(); });
26
+ $effect.pre(() => {
27
+ const { state, client } = view();
28
+ untrack(() => {
29
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
30
+ current = controller.current;
31
+ });
32
+ });
33
+ const attach = element => {
34
+ const checkbox = element instanceof HTMLInputElement && element.type === "checkbox";
35
+ let composing = false;
36
+ const changed = () => {
37
+ if (checkbox)
38
+ controller.input(element.checked);
39
+ else
40
+ controller.inputText(element.value);
41
+ };
42
+ const compositionStart = () => { composing = true; controller.compositionStart(); };
43
+ const compositionEnd = () => { composing = false; controller.compositionEnd(element.value); };
44
+ const blur = () => { void controller.commit(); };
45
+ // A `<select>` and a checkbox report a choice with `change`; text inputs report each edit with `input`.
46
+ const event = checkbox || element instanceof HTMLSelectElement ? "change" : "input";
47
+ element.addEventListener(event, changed);
48
+ element.addEventListener("compositionstart", compositionStart);
49
+ element.addEventListener("compositionend", compositionEnd);
50
+ element.addEventListener("blur", blur);
51
+ // Only this effect reads the field, so a change of the field updates the element without wiring it again.
52
+ $effect(() => {
53
+ const { value, text, errors, error } = current;
54
+ element.setAttribute("aria-invalid", String(errors.length > 0 || error !== undefined));
55
+ if (checkbox) {
56
+ const checked = value === true;
57
+ if (element.checked !== checked)
58
+ element.checked = checked;
59
+ }
60
+ else if (!composing && element.value !== text)
61
+ element.value = text;
62
+ });
63
+ return () => {
64
+ element.removeEventListener(event, changed);
65
+ element.removeEventListener("compositionstart", compositionStart);
66
+ element.removeEventListener("compositionend", compositionEnd);
67
+ element.removeEventListener("blur", blur);
68
+ };
69
+ };
70
+ return {
71
+ get value() { return current.value; },
72
+ set value(value) { controller.input(value); },
73
+ get text() { return current.text; },
74
+ 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; },
79
+ input: (value) => controller.input(value),
80
+ commit: () => controller.commit(),
81
+ retry: () => controller.retry(),
82
+ reset: () => controller.reset(),
83
+ attach,
84
+ };
85
+ }
@@ -48,6 +48,8 @@ export interface TextFieldView<TClient extends ViewClient> {
48
48
  * <input bind:value={name.value} oncompositionstart={name.compositionStart} oncompositionend={name.compositionEnd}>
49
49
  * ```
50
50
  *
51
- * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
51
+ * `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
52
+ * `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
53
+ * `useField` with its `{View}Fields` descriptor.
52
54
  */
53
55
  export declare function useTextField<TClient extends ViewClient>(view: () => TextFieldView<TClient>, read: (state: TClient["snapshot"]) => string, write: (client: TClient, value: string) => Promise<unknown>, options?: UseTextFieldOptions): TextFieldHandle;
@@ -19,7 +19,9 @@ function textOf(event) {
19
19
  * <input bind:value={name.value} oncompositionstart={name.compositionStart} oncompositionend={name.compositionEnd}>
20
20
  * ```
21
21
  *
22
- * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
22
+ * `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
23
+ * `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
24
+ * `useField` with its `{View}Fields` descriptor.
23
25
  */
24
26
  export function useTextField(view, read, write, options = {}) {
25
27
  const controller = createTextFieldController({ read, write, ...options });
@@ -1,4 +1,4 @@
1
- import { type ViewClient, type ViewSource } from "@runic-artifex/views";
1
+ import { type ViewClient, type ViewConnector, type ViewSource } from "@runic-artifex/views";
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;
@@ -15,7 +15,11 @@ export interface ViewHandle<TClient extends ViewClient> {
15
15
  * Connects a generated View reference while the calling component is mounted
16
16
  * and exposes its state as reactive properties. Call it during component
17
17
  * initialization with a getter, such as `useView(() => page)`, so a changed
18
- * prop disposes the previous client and connects the new one.
18
+ * prop releases the previous client and connects the new one.
19
+ *
20
+ * A released client stays connected for `keepAlive` milliseconds (2000 by
21
+ * default), and the next `useView` of the same reference takes it over: an
22
+ * `{#if}` that toggles, HMR and A→B→A navigation show the View at once.
19
23
  *
20
24
  * A reference is identified by its `connect` function, so a getter returning a
21
25
  * new `{ connect: connectShell }` object does not reconnect.
@@ -23,5 +27,41 @@ export interface ViewHandle<TClient extends ViewClient> {
23
27
  export interface UseViewOptions<TClient extends ViewClient> {
24
28
  /** Releases a client this helper connected. Defaults to `client.dispose()`. */
25
29
  readonly release?: (client: TClient) => void;
30
+ /**
31
+ * Milliseconds a client this helper connected stays connected after the component unmounts or the source changes,
32
+ * for the next helper that follows the same reference (StrictMode, HMR, `<Activity>`, A→B→A navigation). `0`
33
+ * disposes it at once. Defaults to 2000. Read once, when the helper is created.
34
+ */
35
+ readonly keepAlive?: number;
26
36
  }
27
37
  export declare function useView<TClient extends ViewClient>(source: () => ViewSource<TClient>, options?: UseViewOptions<TClient>): ViewHandle<TClient>;
38
+ export interface SuspenseViewHandle<TClient extends ViewClient> {
39
+ /** The latest state. */
40
+ readonly state: TClient["snapshot"];
41
+ /** The connected client. */
42
+ readonly client: TClient;
43
+ }
44
+ /**
45
+ * Connects a generated View reference while the calling component is mounted, like {@link useView}, and returns a
46
+ * promise that resolves once it connected, with reactive `state` and `client` that are never `undefined`, or
47
+ * rejects with the connection failure. Call it during component initialization and await it in the markup:
48
+ *
49
+ * ```svelte
50
+ * <script lang="ts">
51
+ * let { page }: { page: CounterPageReference } = $props();
52
+ * const counter = useSuspenseView(page);
53
+ * </script>
54
+ *
55
+ * {#await counter}
56
+ * <p>Connecting…</p>
57
+ * {:then view}
58
+ * <button onclick={() => view.client.increment()}>{view.state.count}</button>
59
+ * {:catch error}
60
+ * <p role="alert">{describeBridgeError(error)}</p>
61
+ * {/await}
62
+ * ```
63
+ *
64
+ * The source is read once; key the component (`{#key page}`) to follow another reference. A reference whose client
65
+ * another component let go of within its `keepAlive` period resolves at once.
66
+ */
67
+ export declare function useSuspenseView<TClient extends ViewClient>(source: ViewConnector<TClient> | TClient, options?: UseViewOptions<TClient>): Promise<SuspenseViewHandle<TClient>>;
@@ -1,8 +1,11 @@
1
1
  import { untrack } from "svelte";
2
2
  import { createViewController } from "@runic-artifex/views";
3
- import { isViewClient, viewSourceIdentity } from "@runic-artifex/views/bindings";
3
+ import { isViewClient, viewSourceIdentity, viewSourcePreview } from "@runic-artifex/views/bindings";
4
4
  export function useView(source, options = {}) {
5
- const controller = createViewController(options.release ? { release: options.release } : {});
5
+ const controller = createViewController({
6
+ ...(options.release ? { release: options.release } : {}),
7
+ ...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }),
8
+ });
6
9
  let current = $state.raw(controller.current);
7
10
  const unsubscribe = controller.subscribe(() => { current = controller.current; });
8
11
  // A pre effect runs when it is created, so the teardown exists even if the
@@ -16,27 +19,61 @@ export function useView(source, options = {}) {
16
19
  current = controller.current;
17
20
  });
18
21
  });
19
- // A connected client is readable before the effect observes it, and a
20
- // changed reference does not show the previous one until the effect follows it.
21
- const observed = () => {
22
+ // A connected client is readable before the effect observes it, and a changed reference does not show the
23
+ // previous one until the effect follows it, but a client kept for it (keep-alive) instead.
24
+ const preview = () => {
22
25
  const value = source();
23
- return value && isViewClient(value) ? value : undefined;
26
+ if (value && isViewClient(value))
27
+ return value === current.client ? undefined : viewSourcePreview(value);
28
+ return fresh() ? undefined : viewSourcePreview(value);
24
29
  };
25
30
  const fresh = () => viewSourceIdentity(current.source) === identity;
26
31
  return {
27
- get state() {
28
- const value = observed();
29
- if (value && value !== current.client)
30
- return value.snapshot;
31
- return fresh() ? current.state : undefined;
32
- },
33
- get client() { return observed() ?? (fresh() ? current.client : undefined); },
32
+ get state() { return preview()?.state ?? (fresh() ? current.state : undefined); },
33
+ get client() { return preview()?.client ?? (fresh() ? current.client : undefined); },
34
34
  get error() { return fresh() ? current.error : undefined; },
35
35
  get pending() {
36
- if (observed())
36
+ if (preview())
37
37
  return false;
38
38
  return fresh() ? current.pending : identity !== undefined;
39
39
  },
40
40
  retry() { controller.retry(); },
41
41
  };
42
42
  }
43
+ /**
44
+ * Connects a generated View reference while the calling component is mounted, like {@link useView}, and returns a
45
+ * promise that resolves once it connected, with reactive `state` and `client` that are never `undefined`, or
46
+ * rejects with the connection failure. Call it during component initialization and await it in the markup:
47
+ *
48
+ * ```svelte
49
+ * <script lang="ts">
50
+ * let { page }: { page: CounterPageReference } = $props();
51
+ * const counter = useSuspenseView(page);
52
+ * </script>
53
+ *
54
+ * {#await counter}
55
+ * <p>Connecting…</p>
56
+ * {:then view}
57
+ * <button onclick={() => view.client.increment()}>{view.state.count}</button>
58
+ * {:catch error}
59
+ * <p role="alert">{describeBridgeError(error)}</p>
60
+ * {/await}
61
+ * ```
62
+ *
63
+ * The source is read once; key the component (`{#key page}`) to follow another reference. A reference whose client
64
+ * another component let go of within its `keepAlive` period resolves at once.
65
+ */
66
+ export function useSuspenseView(source, options = {}) {
67
+ const view = useView(() => source, options);
68
+ let settle;
69
+ const settled = new Promise(resolve => { settle = resolve; });
70
+ // Reads the handle in an effect, so the promise settles once the effect followed the source.
71
+ $effect.pre(() => { if (!view.pending)
72
+ settle(); });
73
+ return settled.then(() => {
74
+ if (view.error !== undefined || view.client === undefined)
75
+ throw view.error;
76
+ const client = view.client;
77
+ return { get state() { return view.state; }, client };
78
+ });
79
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@runic-artifex/svelte",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Svelte 5 Application Views helpers for Runic",
5
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/svelte#readme",
5
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.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/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/text-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/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.13.0"
43
+ "@runic-artifex/views": "0.15.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.13.0",
56
+ "@runic-artifex/views": "0.15.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": "3331f81c7a2de34e209b53eb07515323d6d15cf3"
70
+ "gitHead": "c94bda07cf363bad056eda86ae77c514b66e61dd"
71
71
  }