@runic-artifex/svelte 0.12.1 → 0.14.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.14.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,6 +126,100 @@ 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 once the field's writes settled, so a command that
170
+ depends on the field can follow them: `await title.commit(); await editor.save()`.
171
+ - `checked: true` writes with the member's checked write, so a change by another writer while the user edits is a
172
+ conflict instead of being overwritten. A `rejected` receipt keeps the draft and sets `error` to a `FieldError` with
173
+ the setter's message; a `conflict` keeps the draft, sets `conflict` to the producer's `{ value, version }` and
174
+ writes nothing until `retry()` writes the draft over it or `reset()` takes it.
175
+ - `coalesce` and `keepDraftOnError` as for text inputs below.
176
+
177
+ `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
178
+ or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
179
+ `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
180
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#fields) for the receipts
181
+ and text forms.
182
+
183
+ ### Text inputs: `useTextField(view, read, write, options?)`
184
+
185
+ Call during component initialization to bind a text input to a member through the
186
+ framework-neutral
187
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#text-inputs):
188
+
189
+ ```svelte
190
+ <script lang="ts">
191
+ import { useTextField, useView } from "@runic-artifex/svelte";
192
+ import type { PersonPageReference } from "./generated/person.js";
193
+
194
+ let { page }: { page: PersonPageReference } = $props();
195
+ const person = useView(() => page);
196
+ const name = useTextField(() => person, state => state.name, (client, value) => client.setName(value));
197
+ </script>
198
+
199
+ <input bind:value={name.value} oncompositionstart={name.compositionStart} oncompositionend={name.compositionEnd}>
200
+ {#if name.error !== undefined}<p role="alert">{String(name.error)}</p>{/if}
201
+ ```
202
+
203
+ It returns `value`, which `bind:value` reads and sets, the reactive `editing` and
204
+ `error`, and `compositionStart()`, `compositionEnd(event | text)` and `reset()`.
205
+ `view` returns a `useView` handle or any `{ state, client }`. The options are
206
+ `coalesce` and `keepDraftOnError`.
207
+ The field shows what the user typed while its writes are in flight, so a reply or
208
+ frame that answers an older keystroke never replaces newer text. At most one write is
209
+ in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
210
+ every change). Nothing is written during IME composition. Once the last write settled,
211
+ the field shows the View's value again, including any normalization the ViewModel
212
+ applied (trimmed, upper-cased). `write` may also be a command or a checked write,
213
+ whose receipt the field reads: `rejected` and `conflict` keep the draft and set `error`
214
+ to a `FieldError` of that kind, `committed-with-error` drops the draft and sets it too,
215
+ and `applied.validation` is `errors`. A failed write keeps the draft and sets `error`
216
+ (`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
217
+ exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
218
+ the user types: the field's own write causes it, and keys typed meanwhile would be
219
+ lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
220
+ Library `user.type`) against the mock with `latency: "slow"`; `fill()` sets the whole
221
+ text at once and hides the race.
222
+
75
223
  ## `ViewOutlet`
76
224
 
77
225
  Renders the component registered for a generated reference's `kind` and passes
@@ -134,8 +282,7 @@ neither.
134
282
  ## `useOperation(start, options?)`
135
283
 
136
284
  Call during component initialization to observe a generated operation's admission,
137
- pending state, terminal outcome and cancellation. Progress and recovery stay in the
138
- generated View snapshot:
285
+ pending state, progress, terminal outcome and cancellation:
139
286
 
140
287
  ```svelte
141
288
  <script lang="ts">
@@ -148,16 +295,18 @@ generated View snapshot:
148
295
 
149
296
  <button disabled={!workspace.client || push.pending} onclick={() => push.run("origin")}>Push</button>
150
297
  {#if push.pending}
151
- <p role="status">{workspace.state?.operationMessage ?? "Starting…"}</p>
298
+ <progress value={push.progress}></progress>
152
299
  <button disabled={push.cancellationRequested} onclick={() => push.cancel()}>Cancel</button>
153
300
  {/if}
154
301
  {#if push.cancelled}<p role="status">Push cancelled.</p>{/if}
155
302
  {#if push.error ?? push.cancelError}<p role="alert">{String(push.error ?? push.cancelError)}</p>{/if}
156
303
  ```
157
304
 
158
- The result exposes reactive `pending`, `admitting`, `operation`, `status`, `outcome`,
305
+ The result exposes reactive `pending`, `admitting`, `operation`, `status`, `progress`, `outcome`,
159
306
  `failure`, `error`, `cancelled`, `cancellationRequested`, `cancelling`, `cancellation`
160
- and `cancelError`, with `run(...args)`, `cancel()` and `reset()`. Both async methods never
307
+ and `cancelError`, with `run(...args)`, `cancel()` and `reset()`. `progress` is how far
308
+ the running operation got, from 0 to 1, when its command reports progress
309
+ (`RunicOperationProgress.Report` in .NET); it is `undefined` while unknown and after the run. Both async methods never
161
310
  reject. A run that ends with a `cancelled` status sets `cancelled` and leaves `error`
162
311
  undefined; `failed` and `timed-out` statuses are still `error`. Cancel before a delayed Start receipt is retained for that captured run;
163
312
  its response does not release pending state. `reset()` clears feedback while
@@ -174,7 +323,7 @@ Cancel and other callbacks responsive during observation.
174
323
  ## `useLatestOperation()`
175
324
 
176
325
  For rapid read selection, `useLatestOperation()` wraps the framework-neutral
177
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#operation-feedback-and-latest-selection)
326
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection)
178
327
  for the component's lifetime. It coalesces the latest intent across delayed receipts
179
328
  and orders the next admission after terminal observation and any application drain
180
329
  barrier:
@@ -205,7 +354,7 @@ establish that replacement boundary and own the old work's drain. Lost terminal
205
354
  observation blocks further Starts instead of retrying blindly, with its reason in
206
355
  `error`; ordinary Cancel does not clear this block. Component destruction settles
207
356
  observation without cancelling accepted work. The
208
- [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/tests/fixtures/application/operations-consumer)
357
+ [operations package consumer](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/tests/fixtures/application/operations-consumer)
209
358
  runs this hook against the packed packages and the desktop transport.
210
359
 
211
360
  ## `useBridgeConnection(options?)`
@@ -215,7 +364,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
215
364
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a reactive
216
365
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
217
366
  closed set, see
218
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#connection-state)):
367
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#connection-state)):
219
368
 
220
369
  ```svelte
221
370
  <script lang="ts">
@@ -237,7 +386,7 @@ server render does not observe, and destroying the owner unsubscribes. An invali
237
386
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
238
387
  page (`DesktopMenuBarPresentation.Page`) while its owner lives. It wraps
239
388
  `createMenuBarController` from `@runic-artifex/views` (see
240
- [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`, where `state` is a
389
+ [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`, where `state` is a
241
390
  reactive `MenuBarState` property. The bar is rendered by the menubar component
242
391
  of the application's own UI library. Runic ships no menubar component.
243
392
 
@@ -266,7 +415,7 @@ the `shortcuts: "app"` lease.
266
415
  ### With Bits UI
267
416
 
268
417
  Bits UI's `Menubar.Root bind:value`; the
269
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
418
+ [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
270
419
  items and is tested with real keys:
271
420
 
272
421
  ```svelte
@@ -320,17 +469,20 @@ The host owns `checked`: bind it one way, as
320
469
 
321
470
  The `error` of `useView` and of a command or operation helper is typed
322
471
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
323
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
324
- `instanceof` before reading `kind`, `route` or `detail`:
472
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
473
+ `describeBridgeError(error)`, one English sentence, instead of `String(error)`,
474
+ and narrow it with `isBridgeError` (or `instanceof`) before reading `kind`,
475
+ `route` or `detail`:
325
476
 
326
477
  ```ts
327
- import { BridgeError } from "@runic-artifex/views";
478
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
328
479
 
329
- const offline = view.error instanceof BridgeError && view.error.kind === "disconnected";
480
+ const offline = $derived(isBridgeError(view.error, "disconnected"));
481
+ const message = $derived(describeBridgeError(view.error));
330
482
  ```
331
483
 
332
484
  `instanceof` holds for errors from every copy of the package on the page.
333
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#errors-and-diagnostics)
485
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#errors-and-diagnostics)
334
486
  lists the kinds. Any other value, such as an exception that your own connect
335
487
  function or command callback throws, arrives unchanged.
336
488
 
@@ -369,15 +521,15 @@ application's own dialog.
369
521
  departure before that is answered by the ViewModel's .NET fallback handler, or
370
522
  fails closed without one.
371
523
 
372
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.12.1/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
524
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.14.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
373
525
  has the .NET side and which View answers which departure. In a frontend test,
374
526
  the generated mock's `interactions.<name>.request(input)` resolves with the
375
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#testing).
527
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#testing).
376
528
 
377
529
  ## `useCollectionViewport(options)`
378
530
 
379
531
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
380
- `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#collectionviewportoptions)
532
+ `viewport` is the reactive [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#collectionviewportoptions)
381
533
  range; `attach` is an attachment for the container. Call it during component
382
534
  initialization and send the range to the ViewModel from an effect:
383
535
 
@@ -1,11 +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";
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";
6
9
  export { useLatestOperation, type LatestOperationHandle } from "./use-latest-operation.svelte.js";
7
10
  export { useCollectionViewport, type CollectionViewportHandle } from "./use-collection-viewport.svelte.js";
8
11
  export { useBridgeConnection, type BridgeConnectionHandle } from "./use-bridge-connection.svelte.js";
9
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";
10
14
  export { useMenuBar, type MenuBarHandle, type UseMenuBarOptions } from "./use-menu-bar.svelte.js";
11
15
  export type { MenuBarEntry, MenuBarInvokeResult, MenuBarItem, MenuBarMenu, MenuBarRequest, MenuBarSeparator, MenuBarState, } from "@runic-artifex/views";
@@ -1,9 +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";
6
+ export { useTextField } from "./use-text-field.svelte.js";
7
+ export { useField } from "./use-field.svelte.js";
5
8
  export { useLatestOperation } from "./use-latest-operation.svelte.js";
6
9
  export { useCollectionViewport } from "./use-collection-viewport.svelte.js";
7
10
  export { useBridgeConnection } from "./use-bridge-connection.svelte.js";
8
11
  export { onBridgeConnection } from "@runic-artifex/views";
12
+ export { FieldError, } from "@runic-artifex/views";
9
13
  export { useMenuBar } from "./use-menu-bar.svelte.js";
@@ -0,0 +1,65 @@
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: `await title.commit(); await editor.save()`. Never rejects; a failure is `error`.
35
+ */
36
+ commit(): Promise<FieldState<TValue>>;
37
+ /** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
38
+ retry(): void;
39
+ /** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
40
+ reset(): void;
41
+ /**
42
+ * Wires an `<input>`, `<textarea>` or `<select>` to the field: `<input {@attach title.attach}>`. It writes the text
43
+ * typed (`input` events; `change` of a `<select>` or checkbox, whose `checked` is the value), writes nothing during
44
+ * IME composition, commits on blur, keeps the element's text (a checkbox's `checked`) equal to the field's without
45
+ * moving the caret while it already shows it, and sets `aria-invalid` while the field has `errors` or an `error`.
46
+ */
47
+ readonly attach: Attachment<FieldElement>;
48
+ }
49
+ /**
50
+ * Binds an element to one View member while the calling component is mounted, through `createFieldController`: pass a
51
+ * generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. Call it during
52
+ * component initialization; `options` are read then. Wire the element with `{@attach title.attach}`, or bind
53
+ * `bind:value={title.value}` and call `commit` on blur yourself.
54
+ *
55
+ * ```svelte
56
+ * const editor = useView(() => page);
57
+ * const title = useField(() => editor, EditorFields.title, { commit: "pause", checked: true });
58
+ * <input {@attach title.attach}>
59
+ * {#if title.conflict}<button onclick={title.retry}>Keep mine</button>{/if}
60
+ * ```
61
+ *
62
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
63
+ * conflict holds further writes until `retry()` or `reset()`. Unmounting writes a value that waits to be written.
64
+ */
65
+ 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
+ }
@@ -21,6 +21,7 @@ export function useLatestOperation() {
21
21
  get admitting() { return current.admitting; },
22
22
  get operation() { return current.operation; },
23
23
  get status() { return current.status; },
24
+ get progress() { return current.progress; },
24
25
  get outcome() { return current.outcome; },
25
26
  get failure() { return current.failure; },
26
27
  get error() { return current.error; },
@@ -36,7 +36,7 @@ export function useMenuBar(options = {}) {
36
36
  get state() { return state; },
37
37
  invoke: item => controller
38
38
  ? controller.invoke(item)
39
- : Promise.reject(new BridgeError("disconnected", "The menu bar is not connected yet.", { route: "__runicMenuBarInvoke" })),
39
+ : Promise.reject(new BridgeError("disconnected", "The menu bar is not connected yet.", { route: "runic.menu-bar" })),
40
40
  handleKeyDown: event => controller?.handleKeyDown(event) ?? false,
41
41
  };
42
42
  }
@@ -5,6 +5,6 @@ export interface OperationHandle<TArgs extends readonly unknown[], TResult, TFai
5
5
  * Tracks Start admission, pending work, cancellation and terminal feedback as
6
6
  * reactive properties. Call during component initialization. Owner destruction
7
7
  * detaches observation and settles run promises without cancelling accepted work.
8
- * Progress remains in the generated View snapshot, where the application owns it.
8
+ * `progress` follows the running operation (`BridgeOperation.subscribe`).
9
9
  */
10
10
  export declare function useOperation<TArgs extends readonly unknown[], TResult, TFailure = never>(start: (...args: TArgs) => BridgeOperation<TResult, TFailure> | undefined | PromiseLike<BridgeOperation<TResult, TFailure> | undefined>, options?: OperationControllerOptions<TResult, TFailure>): OperationHandle<TArgs, TResult, TFailure>;
@@ -3,7 +3,7 @@ import { createOperationController, } from "@runic-artifex/views";
3
3
  * Tracks Start admission, pending work, cancellation and terminal feedback as
4
4
  * reactive properties. Call during component initialization. Owner destruction
5
5
  * detaches observation and settles run promises without cancelling accepted work.
6
- * Progress remains in the generated View snapshot, where the application owns it.
6
+ * `progress` follows the running operation (`BridgeOperation.subscribe`).
7
7
  */
8
8
  export function useOperation(start, options = {}) {
9
9
  const controller = createOperationController(start, options);
@@ -22,6 +22,7 @@ export function useOperation(start, options = {}) {
22
22
  get admitting() { return current.admitting; },
23
23
  get operation() { return current.operation; },
24
24
  get status() { return current.status; },
25
+ get progress() { return current.progress; },
25
26
  get outcome() { return current.outcome; },
26
27
  get failure() { return current.failure; },
27
28
  get error() { return current.error; },
@@ -0,0 +1,55 @@
1
+ import { type ViewClient } from "@runic-artifex/views";
2
+ /** A text input bound to one View member. */
3
+ export interface TextFieldHandle {
4
+ /**
5
+ * What the input shows: the draft while one exists, otherwise the member's value in the View's state. Setting it
6
+ * is an input by the user, as `bind:value` does.
7
+ */
8
+ value: string;
9
+ /**
10
+ * True while a draft exists, from the first input until the last write settled and the state caught up, and after a
11
+ * failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state, which
12
+ * the field's own write causes.
13
+ */
14
+ readonly editing: boolean;
15
+ /** Why the latest write failed, until the next input or `reset()`. */
16
+ readonly error: unknown;
17
+ /** An IME composition started: the text is kept but not written until it ends. Use it as `oncompositionstart`. */
18
+ compositionStart(): void;
19
+ /** The IME composition ended: pass the `compositionend` event, or the text, which is then written. */
20
+ compositionEnd(event: Event | string): void;
21
+ /** Drops the draft and the error and shows the View's value. Writes in flight still complete. */
22
+ reset(): void;
23
+ }
24
+ export interface UseTextFieldOptions {
25
+ /**
26
+ * With `true` (the default) at most one write is in flight, and text typed meanwhile is written next, as one
27
+ * value. With `false` every input is written.
28
+ */
29
+ readonly coalesce?: boolean;
30
+ /** With `true` (the default) a failed write keeps the draft and sets `error`; with `false` the field shows the View's value again. */
31
+ readonly keepDraftOnError?: boolean;
32
+ }
33
+ /** The View a text field binds to: a `useView` handle, or any state and client. */
34
+ export interface TextFieldView<TClient extends ViewClient> {
35
+ readonly state: TClient["snapshot"] | undefined;
36
+ readonly client: TClient | undefined;
37
+ }
38
+ /**
39
+ * Binds a text input to one member of a View while the calling component is mounted, through
40
+ * `createTextFieldController`. Call it during component initialization. Typing key by key never loses characters:
41
+ * while its writes are in flight the field shows what the user typed, at most one write is in flight (newer text is
42
+ * written next), nothing is written during IME composition, and once the last write settled it shows the View's
43
+ * value, including any normalization.
44
+ *
45
+ * ```svelte
46
+ * const person = useView(() => page);
47
+ * const name = useTextField(() => person, state => state.name, (client, value) => client.setName(value));
48
+ * <input bind:value={name.value} oncompositionstart={name.compositionStart} oncompositionend={name.compositionEnd}>
49
+ * ```
50
+ *
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.
54
+ */
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;
@@ -0,0 +1,49 @@
1
+ import { untrack } from "svelte";
2
+ import { createTextFieldController } from "@runic-artifex/views";
3
+ function textOf(event) {
4
+ if (typeof event === "string")
5
+ return event;
6
+ const target = event.target;
7
+ return typeof target?.value === "string" ? target.value : "";
8
+ }
9
+ /**
10
+ * Binds a text input to one member of a View while the calling component is mounted, through
11
+ * `createTextFieldController`. Call it during component initialization. Typing key by key never loses characters:
12
+ * while its writes are in flight the field shows what the user typed, at most one write is in flight (newer text is
13
+ * written next), nothing is written during IME composition, and once the last write settled it shows the View's
14
+ * value, including any normalization.
15
+ *
16
+ * ```svelte
17
+ * const person = useView(() => page);
18
+ * const name = useTextField(() => person, state => state.name, (client, value) => client.setName(value));
19
+ * <input bind:value={name.value} oncompositionstart={name.compositionStart} oncompositionend={name.compositionEnd}>
20
+ * ```
21
+ *
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.
25
+ */
26
+ export function useTextField(view, read, write, options = {}) {
27
+ const controller = createTextFieldController({ read, write, ...options });
28
+ let current = $state.raw(controller.current);
29
+ const unsubscribe = controller.subscribe(() => { current = controller.current; });
30
+ // A pre effect runs when it is created, so the teardown exists even if the owner is destroyed before its first
31
+ // flush (see useOperation). It reads no state, so it never re-runs.
32
+ $effect.pre(() => () => { unsubscribe(); controller.dispose(); });
33
+ $effect.pre(() => {
34
+ const { state, client } = view();
35
+ untrack(() => {
36
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
37
+ current = controller.current;
38
+ });
39
+ });
40
+ return {
41
+ get value() { return current.value; },
42
+ set value(text) { controller.input(text); },
43
+ get editing() { return current.editing; },
44
+ get error() { return current.error; },
45
+ compositionStart: () => controller.compositionStart(),
46
+ compositionEnd: (event) => controller.compositionEnd(textOf(event)),
47
+ reset: () => controller.reset(),
48
+ };
49
+ }
@@ -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.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Svelte 5 Application Views helpers for Runic",
5
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/svelte#readme",
5
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.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",
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.12.1"
43
+ "@runic-artifex/views": "0.14.0"
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public",
@@ -53,18 +53,19 @@
53
53
  },
54
54
  "packageManager": "bun@1.4.4",
55
55
  "devDependencies": {
56
- "@runic-artifex/views": "0.12.1",
56
+ "@runic-artifex/views": "0.14.0",
57
57
  "@sveltejs/adapter-static": "4.0.0",
58
58
  "@sveltejs/kit": "3.0.0",
59
59
  "@sveltejs/package": "3.0.0",
60
60
  "@sveltejs/vite-plugin-svelte": "7.3.1",
61
61
  "@types/node": "24.19.1",
62
62
  "happy-dom": "^21.0.4",
63
+ "playwright-core": "1.63.0",
63
64
  "svelte": "5.57.1",
64
65
  "svelte-check": "4.7.6",
65
66
  "typescript": "6.0.3",
66
67
  "vitest": "5.0.3",
67
68
  "vite": "8.3.4"
68
69
  },
69
- "gitHead": "124a532e5861cff03e77d2ef0c5d4f081ee99a47"
70
+ "gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
70
71
  }