@runic-artifex/vue 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
@@ -40,9 +40,15 @@ connected:
40
40
 
41
41
  - A generated page reference, or `{ connect: connect<Name> }` for a root
42
42
  ViewModel, is connected while the current effect scope (normally the
43
- component) is active. Disposing the scope or changing the reference disposes
44
- the client. A reference is identified by its `connect` function, so a getter
45
- that returns a new `{ connect: connectWorkspace }` object does not reconnect.
43
+ component) is active. A reference is identified by its `connect` function, so
44
+ a getter that returns a new `{ connect: connectWorkspace }` object does not
45
+ reconnect.
46
+ - Disposing the scope or changing the reference keeps the client connected for
47
+ `options.keepAlive` milliseconds (2000 by default), and the next `useView` of
48
+ the same reference takes it over with its state in `setup()`, so a `v-if`
49
+ that toggles, HMR and A→B→A navigation show the View at once instead of
50
+ "Connecting…" and do not open the route again. `keepAlive: 0` disposes at
51
+ once.
46
52
  - An already connected client is observed and left to its owner.
47
53
  - The source can be a value, a ref or a getter such as `() => props.page`.
48
54
  - `pending` is true while a reference connects. `error` holds a failed
@@ -55,6 +61,55 @@ effect scope, for example from a plain module or an event handler, nothing ever
55
61
  releases them: `useView` keeps its client connected. Development builds warn
56
62
  in the console when that happens.
57
63
 
64
+ ### Async setup: `useSuspenseView(source, options?)`
65
+
66
+ `await useSuspenseView(page)` in an async `setup()` (a top-level `await` in
67
+ `<script setup>`) connects like `useView` and resolves once the View
68
+ connected, with `state` (a ref that is never `undefined`) and `client`.
69
+ `<Suspense>` shows its `#fallback` meanwhile:
70
+
71
+ ```vue
72
+ <!-- CounterPage.vue -->
73
+ <script setup lang="ts">
74
+ import { useSuspenseView } from "@runic-artifex/vue";
75
+ import type { CounterPageReference } from "../generated/counter.js";
76
+
77
+ const props = defineProps<{ page: CounterPageReference }>();
78
+ const { state, client } = await useSuspenseView(props.page);
79
+ </script>
80
+
81
+ <template><button @click="client.increment()">{{ state.count }}</button></template>
82
+ ```
83
+
84
+ ```vue
85
+ <Suspense>
86
+ <CounterPage :page="page" :key="page.kind" />
87
+ <template #fallback><p>Connecting…</p></template>
88
+ </Suspense>
89
+ ```
90
+
91
+ A failed connection rejects, so the error reaches `onErrorCaptured` of a
92
+ parent; render the component again, for example with a new `key`, to connect
93
+ again. Call `useSuspenseView` before any other `await` in `setup()`. The
94
+ source is read once: key the component by its reference to follow another one.
95
+
96
+ ### Selecting state: `computed`
97
+
98
+ `useView` exposes the whole state as one shallow ref, which changes with every
99
+ change of the View. A `computed` that selects a member triggers its dependents
100
+ only when its value changed (Vue 3.4+), so a template part or a `watch` that
101
+ reads `title` does not run again when another member changes:
102
+
103
+ ```ts
104
+ const editor = useView(page);
105
+ const title = computed(() => editor.state.value?.title);
106
+ ```
107
+
108
+ Members the View did not change keep their identity, so selecting a member,
109
+ also an object or a list, is enough. A computed that builds a new value, such
110
+ as `items.filter(…)`, changes every time; compare it yourself
111
+ (`computed(previous => …)` returns `previous` when equal).
112
+
58
113
  ### Read-only state and `v-model`
59
114
 
60
115
  As in any MVVM View, the ViewModel's C# setters decide what the page may set.
@@ -85,10 +140,66 @@ const step = computed({ get: () => state.value?.step ?? 1, set: value => void se
85
140
  </template>
86
141
  ```
87
142
 
143
+ ### Fields: `useField(view, field, options?)`
144
+
145
+ Binds an element to a member while the effect scope is active. Pass the generated `{View}Fields` descriptor; it knows
146
+ the member's kind, setter, checked write and validation. The handle is `reactive`, so bind its members directly:
147
+
148
+ ```vue
149
+ <script setup lang="ts">
150
+ import { useField, useView } from "@runic-artifex/vue";
151
+ import { EditorFields, type EditorPageReference } from "./generated/editor.js";
152
+
153
+ const props = defineProps<{ page: EditorPageReference }>();
154
+ const editor = useView(() => props.page);
155
+ const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
156
+ const step = useField(editor, EditorFields.step);
157
+ const done = useField(editor, EditorFields.done);
158
+ const mode = useField(editor, EditorFields.mode);
159
+ </script>
160
+
161
+ <template>
162
+ <input v-model="title.value" @blur="title.commit" :aria-invalid="title.errors.length > 0 || title.error !== undefined">
163
+ <p v-for="message in title.errors" :key="message" role="alert">{{ message }}</p>
164
+ <p v-if="title.conflict" role="alert">
165
+ Changed elsewhere to “{{ title.conflict.value }}”.
166
+ <button @click="title.retry">Keep mine</button> <button @click="title.reset">Take theirs</button>
167
+ </p>
168
+ <input type="number" v-model="step.text" @blur="step.commit">
169
+ <input type="checkbox" v-model="done.value">
170
+ <select v-model="mode.value"><option v-for="choice in EditorFields.mode.choices" :key="choice">{{ choice }}</option></select>
171
+ </template>
172
+ ```
173
+
174
+ It has `value` and `text`, which `v-model` reads and sets, the read-only `editing`, `error`, `errors` and
175
+ `conflict`, and `input(value)`, `commit()`, `retry()` and `reset()`. Bind number inputs to `text`: it keeps `-` and
176
+ `1.` while the user types, and a text that does not parse stays the draft with an `invalid-text` error while nothing
177
+ is written. A string set on `value` of a field that is not text is taken as its text, as `v-model` on
178
+ `<input type="number">` sets one. `v-model` already writes nothing during IME composition.
179
+
180
+ `options` are read once, when the field is created:
181
+
182
+ - `commit: "pause"` writes the draft after `delay` milliseconds without input (700 by default) and at once on
183
+ `commit()`, which blur calls; use it where each write is an undo step or starts work in .NET. The default,
184
+ `commit: "input"`, writes each input. `commit()` resolves with the field's state once its writes settled, so a
185
+ command that depends on the field can follow them and skip a failed write:
186
+ `if ((await title.commit()).error === undefined) await editor.save()`.
187
+ - `checked: true` writes with the member's checked write, so a change by another writer while the user edits is a
188
+ conflict instead of being overwritten. A `rejected` receipt keeps the draft and sets `error` to a `FieldError` with
189
+ the setter's message; a `conflict` keeps the draft, sets `conflict` to the producer's `{ value, version }` and
190
+ writes nothing until `retry()` writes the draft over it or `reset()` takes it.
191
+ - `coalesce` and `keepDraftOnError` as for text inputs below.
192
+
193
+ `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
194
+ or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
195
+ `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
196
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#fields) for the receipts
197
+ and text forms.
198
+
88
199
  ### Text inputs: `useTextField(view, read, write, options?)`
89
200
 
90
201
  Binds a text input to a member through the framework-neutral
91
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#text-inputs)
202
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#text-inputs)
92
203
  while the effect scope is active. Each field is a ref, so the handle can be destructured:
93
204
 
94
205
  ```vue
@@ -116,9 +227,11 @@ frame that answers an older keystroke never replaces newer text. At most one wri
116
227
  in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
117
228
  every change). Nothing is written during IME composition. Once the last write settled,
118
229
  the field shows the View's value again, including any normalization the ViewModel
119
- applied (trimmed, upper-cased). `write` may also be a command or a checked write. A
120
- failed write keeps the draft and sets `error` (`keepDraftOnError: false` shows the
121
- View's value instead); `reset()` drops the draft. `editing` is true while a draft
230
+ applied (trimmed, upper-cased). `write` may also be a command or a checked write,
231
+ whose receipt the field reads: `rejected` and `conflict` keep the draft and set `error`
232
+ to a `FieldError` of that kind, `committed-with-error` drops the draft and sets it too,
233
+ and `applied.validation` is `errors`. A failed write keeps the draft and sets `error`
234
+ (`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
122
235
  exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
123
236
  the user types: the field's own write causes it, and keys typed meanwhile would be
124
237
  lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
@@ -188,7 +301,7 @@ neither.
188
301
  ## `useOperation(start, options?)`
189
302
 
190
303
  Observes a generated `start<Command>()` operation through the framework-neutral
191
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#operation-feedback-and-latest-selection)
304
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#operation-feedback-and-latest-selection)
192
305
  and returns each state field as a shallow ref, with `run`, `cancel` and `reset`:
193
306
 
194
307
  ```vue
@@ -220,7 +333,7 @@ Disposing the effect scope settles run promises without cancelling accepted work
220
333
 
221
334
  Admits only the newest of several reads, for example loading the item the user
222
335
  selected last, through the framework-neutral
223
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#operation-feedback-and-latest-selection),
336
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#operation-feedback-and-latest-selection),
224
337
  and returns each state field as a shallow ref, with `run` and `clear`. Each
225
338
  `run(intent)` replaces the queued intent and cancels the active read; the next read
226
339
  starts only after the previous one reaches its terminal status and the intent's
@@ -255,9 +368,9 @@ accepted work.
255
368
  Follows the page's connection to its .NET host. It wraps `onBridgeConnection`
256
369
  from `@runic-artifex/views` (re-exported here since 0.11, with the
257
370
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a shallow ref holding a
258
- `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
259
- closed set, see
260
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#connection-state)):
371
+ `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
372
+ application closed the window, since 0.15; a closed set, see
373
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#connection-state)):
261
374
 
262
375
  ```vue
263
376
  <script setup lang="ts">
@@ -280,7 +393,7 @@ development builds warn. An invalid `lostAfter` throws a `RangeError`.
280
393
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
281
394
  page (`DesktopMenuBarPresentation.Page`) until the current effect scope is
282
395
  disposed. It wraps `createMenuBarController` from `@runic-artifex/views` (see
283
- [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 }`: `state` is a shallow ref
396
+ [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 }`: `state` is a shallow ref
284
397
  of a `MenuBarState`, and the bar is rendered by the menubar component of the
285
398
  application's own UI library. Runic ships no menubar component.
286
399
 
@@ -311,7 +424,7 @@ rendering creates no controller: `state` stays `connecting`.
311
424
  ### With Reka UI
312
425
 
313
426
  Reka UI's `MenubarRoot` with `v-model` of the open menu; the
314
- [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
427
+ [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
315
428
  items and is tested with real keys:
316
429
 
317
430
  ```vue
@@ -360,17 +473,20 @@ const { state: menuBar, invoke } = useMenuBar({
360
473
 
361
474
  The `error` of `useView` and of a command or operation handle is typed
362
475
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
363
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
364
- `instanceof` before reading `kind`, `route` or `detail`:
476
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
477
+ `describeBridgeError(error)`, one English sentence, instead of `String(error)`,
478
+ and narrow it with `isBridgeError` (or `instanceof`) before reading `kind`,
479
+ `route` or `detail`:
365
480
 
366
481
  ```ts
367
- import { BridgeError } from "@runic-artifex/views";
482
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
368
483
 
369
- const offline = error.value instanceof BridgeError && error.value.kind === "disconnected";
484
+ const offline = computed(() => isBridgeError(error.value, "disconnected"));
485
+ const message = computed(() => describeBridgeError(error.value));
370
486
  ```
371
487
 
372
488
  `instanceof` holds for errors from every copy of the package on the page.
373
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#errors-and-diagnostics)
489
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#errors-and-diagnostics)
374
490
  lists the kinds. Any other value, such as an exception that your own connect
375
491
  function or command callback throws, arrives unchanged.
376
492
 
@@ -417,15 +533,15 @@ application's own dialog.
417
533
  departure before that is answered by the ViewModel's .NET fallback handler, or
418
534
  fails closed without one.
419
535
 
420
- 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)
536
+ 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)
421
537
  has the .NET side and which View answers which departure. In a frontend test,
422
538
  the generated mock's `interactions.<name>.request(input)` resolves with the
423
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#testing).
539
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#testing).
424
540
 
425
541
  ## `useCollectionViewport(options)`
426
542
 
427
543
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
428
- `viewport` is a shallow ref with the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#collectionviewportoptions)
544
+ `viewport` is a shallow ref with the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#collectionviewportoptions)
429
545
  range; `attach` is a function ref for the container. Bind it to a native element
430
546
  such as a `<div>`: a component instance (`:ref="attach"` on a component) or a
431
547
  non-HTML element detaches the viewport, and development builds warn. Pass a getter for the
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Component, type MaybeRefOrGetter, type Ref, type WritableComputedRef } from "vue";
2
- import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeOperation, type BridgeOutcomeFailure, type LatestOperationController, type LatestOperationState, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewSource } from "@runic-artifex/views";
2
+ import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeField, type BridgeOperation, type BridgeOutcomeFailure, type FieldBaseline, type FieldDefinition, type FieldState, type FieldOptions, type LatestOperationController, type LatestOperationState, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewConnector, type ViewSource } from "@runic-artifex/views";
3
3
  export interface ViewHandle<TClient extends ViewClient> {
4
4
  /** The latest state, or undefined until the client connects. */
5
5
  readonly state: Readonly<Ref<TClient["snapshot"] | undefined>>;
@@ -26,8 +26,38 @@ export interface ViewHandle<TClient extends ViewClient> {
26
26
  export interface UseViewOptions<TClient extends ViewClient> {
27
27
  /** Releases a client this composable connected. Defaults to `client.dispose()`. */
28
28
  readonly release?: (client: TClient) => void;
29
+ /**
30
+ * Milliseconds a client this composable connected stays connected after the component unmounts or the source changes,
31
+ * for the next composable that follows the same reference (StrictMode, HMR, `<Activity>`, A→B→A navigation). `0`
32
+ * disposes it at once. Defaults to 2000. Read once, when the composable is created.
33
+ */
34
+ readonly keepAlive?: number;
29
35
  }
30
36
  export declare function useView<TClient extends ViewClient>(source: MaybeRefOrGetter<ViewSource<TClient>>, options?: UseViewOptions<TClient>): ViewHandle<TClient>;
37
+ export interface SuspenseViewHandle<TClient extends ViewClient> {
38
+ /** The latest state. */
39
+ readonly state: Readonly<Ref<TClient["snapshot"]>>;
40
+ /** The connected client. */
41
+ readonly client: TClient;
42
+ }
43
+ /**
44
+ * Connects a generated View reference for the current effect scope, like {@link useView}, and resolves once it
45
+ * connected, with refs that are never `undefined`. Await it in an async `setup()` (`<script setup>` with a top-level
46
+ * `await`) under `<Suspense>`, which shows its `#fallback` until the View connected:
47
+ *
48
+ * ```vue
49
+ * <script setup lang="ts">
50
+ * const { state, client } = await useSuspenseView(props.page);
51
+ * </script>
52
+ * <template><button @click="client.increment()">{{ state.count }}</button></template>
53
+ * ```
54
+ *
55
+ * A failed connection rejects, so the error reaches `onErrorCaptured` of a parent; render the component again (for
56
+ * example with a new `key`) to connect again. Call it before any other `await` in `setup()`, while the scope is
57
+ * active: it registers the scope's cleanup first, so the client is released however the component ends. A
58
+ * reference whose client another component let go of within its `keepAlive` period resolves at once.
59
+ */
60
+ export declare function useSuspenseView<TClient extends ViewClient>(source: ViewConnector<TClient> | TClient, options?: UseViewOptions<TClient>): Promise<SuspenseViewHandle<TClient>>;
31
61
  /**
32
62
  * A build-known map checks each generated reference kind against its component's `page` prop. A nullable
33
63
  * reference, such as a region slot's `State["main"]`, checks its non-null kinds.
@@ -192,16 +222,81 @@ export interface TextFieldView<TClient extends ViewClient> {
192
222
  * <input v-model="name">
193
223
  * ```
194
224
  *
195
- * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
225
+ * `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
226
+ * `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
227
+ * `useField` with its `{View}Fields` descriptor.
196
228
  */
197
229
  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;
230
+ /**
231
+ * A field bound by {@link useField}: a `reactive` object, so a template binds its members directly, such as
232
+ * `v-model="title.value"`.
233
+ */
234
+ export interface FieldHandle<TValue> {
235
+ /**
236
+ * The draft while one exists, otherwise the member's value in the View's state. Setting it is an input by the user,
237
+ * as `v-model` does: a string set on a field that is not text (such as from `<input type="number">` while its text
238
+ * does not parse) is the field's text, as `text` is.
239
+ */
240
+ value: TValue;
241
+ /**
242
+ * What a text input shows: the text typed while it does not parse or still means `value` (so `1.` stays while typing
243
+ * `1.5`), otherwise `value` formatted. Setting it is an input of text, parsed for the field's kind: bind number
244
+ * inputs with `v-model="step.text"`. The number `v-model` sets on `<input type="number">` once its text is one is
245
+ * an input of that value.
246
+ */
247
+ text: string;
248
+ /**
249
+ * True while a draft exists, from the first input until the last write settled and the state caught up, and after a
250
+ * failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state.
251
+ */
252
+ readonly editing: boolean;
253
+ /** Why the latest write or text failed (a `BridgeError` or a {@link FieldError}), until the next input, `retry()` or `reset()`. */
254
+ readonly error: unknown;
255
+ /** The member's validation messages in the View's state, or of the last checked write's receipt; `[]` when valid. */
256
+ readonly errors: readonly string[];
257
+ /** The producer's field while a checked write's `conflict` keeps the draft; `undefined` otherwise. */
258
+ readonly conflict: FieldBaseline<TValue> | undefined;
259
+ /** The user changed the value. */
260
+ input(value: TValue): void;
261
+ /**
262
+ * The user is done with the field (`@blur="title.commit"`): with `commit: "pause"` the draft is written now.
263
+ * Resolves with the field's state once its writes settled, so a command that depends on the field can run after it
264
+ * and skip a failed write: `if ((await title.commit()).error === undefined) await editor.save()`. Never rejects; a
265
+ * failure is `error`.
266
+ */
267
+ commit(): Promise<FieldState<TValue>>;
268
+ /** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
269
+ retry(): void;
270
+ /** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
271
+ reset(): void;
272
+ }
273
+ /**
274
+ * Binds an element to one View member while the current effect scope is active, through `createFieldController`:
275
+ * pass a generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. The handle is
276
+ * `reactive`; bind `v-model` to its `value` (`text` for number inputs) and call `commit` on blur. `v-model` already
277
+ * writes nothing while an IME composition is in progress. `options` are read once, when the field is created. Call
278
+ * it in `setup()` or `effectScope().run()`: outside an effect scope it is never released (development builds warn).
279
+ *
280
+ * ```vue
281
+ * const editor = useView(() => props.page);
282
+ * const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
283
+ * <input v-model="title.value" @blur="title.commit" :aria-invalid="title.errors.length > 0 || title.error !== undefined">
284
+ * <input type="number" v-model="step.text" @blur="step.commit">
285
+ * <input type="checkbox" v-model="done.value">
286
+ * ```
287
+ *
288
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
289
+ * conflict holds further writes until `retry()` or `reset()`. Leaving the scope writes a value that waits to be
290
+ * written.
291
+ */
292
+ 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>;
198
293
  export interface BridgeConnectionHandle {
199
294
  /** The connection to the .NET host, as `onBridgeConnection` reports it. */
200
295
  readonly state: Readonly<Ref<BridgeConnectionState>>;
201
296
  }
202
297
  /**
203
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`
204
- * or `lost`) as a shallow ref through `onBridgeConnection`, until the current effect scope is
298
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
299
+ * `lost` or `closed`) as a shallow ref through `onBridgeConnection`, until the current effect scope is
205
300
  * disposed. Call it in `setup()` or `effectScope().run()`: outside an effect scope it is never
206
301
  * released (development builds warn).
207
302
  *
@@ -213,4 +308,5 @@ export interface BridgeConnectionHandle {
213
308
  export declare function useBridgeConnection(options?: BridgeConnectionOptions): BridgeConnectionHandle;
214
309
  export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
215
310
  export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
311
+ export { FieldError, type BridgeField, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
216
312
  export { useMenuBar, type MenuBarEntry, type MenuBarHandle, type MenuBarInvokeResult, type MenuBarItem, type MenuBarMenu, type MenuBarRequest, type MenuBarSeparator, type MenuBarState, type UseMenuBarOptions, } from "./menu-bar.js";
package/dist/index.js CHANGED
@@ -1,9 +1,12 @@
1
- import { computed, defineComponent, h, shallowRef, toValue, watch, } from "vue";
2
- import { createCommandController, createLatestOperationController, createOperationController, createTextFieldController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
1
+ import { computed, defineComponent, h, reactive, shallowRef, toValue, watch, } from "vue";
2
+ import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
3
3
  import { viewSourceIdentity } from "@runic-artifex/views/bindings";
4
4
  import { releaseWithScope } from "./scope.js";
5
+ function controllerOptions(options) {
6
+ return { ...(options.release ? { release: options.release } : {}), ...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }) };
7
+ }
5
8
  export function useView(source, options = {}) {
6
- const controller = createViewController(options.release ? { release: options.release } : {});
9
+ const controller = createViewController(controllerOptions(options));
7
10
  const state = shallowRef();
8
11
  const client = shallowRef();
9
12
  const error = shallowRef();
@@ -23,6 +26,37 @@ export function useView(source, options = {}) {
23
26
  releaseWithScope("useView", () => controller.dispose());
24
27
  return { state, client, error, pending, retry: () => controller.retry() };
25
28
  }
29
+ /**
30
+ * Connects a generated View reference for the current effect scope, like {@link useView}, and resolves once it
31
+ * connected, with refs that are never `undefined`. Await it in an async `setup()` (`<script setup>` with a top-level
32
+ * `await`) under `<Suspense>`, which shows its `#fallback` until the View connected:
33
+ *
34
+ * ```vue
35
+ * <script setup lang="ts">
36
+ * const { state, client } = await useSuspenseView(props.page);
37
+ * </script>
38
+ * <template><button @click="client.increment()">{{ state.count }}</button></template>
39
+ * ```
40
+ *
41
+ * A failed connection rejects, so the error reaches `onErrorCaptured` of a parent; render the component again (for
42
+ * example with a new `key`) to connect again. Call it before any other `await` in `setup()`, while the scope is
43
+ * active: it registers the scope's cleanup first, so the client is released however the component ends. A
44
+ * reference whose client another component let go of within its `keepAlive` period resolves at once.
45
+ */
46
+ export async function useSuspenseView(source, options = {}) {
47
+ const view = useView(source, options);
48
+ if (view.pending.value) {
49
+ await new Promise(resolve => {
50
+ const stop = watch(view.pending, pending => { if (!pending) {
51
+ stop();
52
+ resolve();
53
+ } }, { flush: "sync" });
54
+ });
55
+ }
56
+ if (view.error.value !== undefined || view.client.value === undefined)
57
+ throw view.error.value;
58
+ return { state: view.state, client: view.client.value };
59
+ }
26
60
  const referenceKeys = new WeakMap();
27
61
  let nextReferenceKey = 0;
28
62
  function referenceKey(reference) {
@@ -152,7 +186,9 @@ export function useLatestOperation() {
152
186
  * <input v-model="name">
153
187
  * ```
154
188
  *
155
- * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
189
+ * `write` may be a generated setter, a command or a checked write. Its failure, and a checked write's `rejected` or
190
+ * `conflict` receipt, keep the draft and set `error` (a receipt's is a `FieldError`). For a generated member, prefer
191
+ * `useField` with its `{View}Fields` descriptor.
156
192
  */
157
193
  export function useTextField(view, read, write, options = {}) {
158
194
  const controller = createTextFieldController({ read, write, ...options });
@@ -171,8 +207,67 @@ export function useTextField(view, read, write, options = {}) {
171
207
  };
172
208
  }
173
209
  /**
174
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`
175
- * or `lost`) as a shallow ref through `onBridgeConnection`, until the current effect scope is
210
+ * Binds an element to one View member while the current effect scope is active, through `createFieldController`:
211
+ * pass a generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. The handle is
212
+ * `reactive`; bind `v-model` to its `value` (`text` for number inputs) and call `commit` on blur. `v-model` already
213
+ * writes nothing while an IME composition is in progress. `options` are read once, when the field is created. Call
214
+ * it in `setup()` or `effectScope().run()`: outside an effect scope it is never released (development builds warn).
215
+ *
216
+ * ```vue
217
+ * const editor = useView(() => props.page);
218
+ * const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
219
+ * <input v-model="title.value" @blur="title.commit" :aria-invalid="title.errors.length > 0 || title.error !== undefined">
220
+ * <input type="number" v-model="step.text" @blur="step.commit">
221
+ * <input type="checkbox" v-model="done.value">
222
+ * ```
223
+ *
224
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
225
+ * conflict holds further writes until `retry()` or `reset()`. Leaving the scope writes a value that waits to be
226
+ * written.
227
+ */
228
+ export function useField(view, field, options = {}) {
229
+ const controller = createFieldController(field, options);
230
+ const current = shallowRef(controller.current);
231
+ controller.subscribe(() => { current.value = controller.current; });
232
+ watch([view.state, view.client], ([state, client]) => {
233
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
234
+ current.value = controller.current;
235
+ }, { immediate: true });
236
+ releaseWithScope("useField", () => controller.dispose());
237
+ const kind = controller.field.kind;
238
+ // `v-model` on `<input type="number">` sets a string while its text is not a number.
239
+ const textual = kind === undefined || kind === "text";
240
+ return reactive({
241
+ value: computed({
242
+ get: () => current.value.value,
243
+ set: (value) => {
244
+ if (typeof value === "string" && !textual)
245
+ controller.inputText(value);
246
+ else
247
+ controller.input(value);
248
+ },
249
+ }),
250
+ // `v-model` on `<input type="number">` sets a number once its text is one.
251
+ text: computed({
252
+ get: () => current.value.text,
253
+ set: (text) => { if (typeof text === "string")
254
+ controller.inputText(text);
255
+ else
256
+ controller.input(text); },
257
+ }),
258
+ editing: computed(() => current.value.editing),
259
+ error: computed(() => current.value.error),
260
+ errors: computed(() => current.value.errors),
261
+ conflict: computed(() => current.value.conflict),
262
+ input: (value) => controller.input(value),
263
+ commit: () => controller.commit(),
264
+ retry: () => controller.retry(),
265
+ reset: () => controller.reset(),
266
+ });
267
+ }
268
+ /**
269
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
270
+ * `lost` or `closed`) as a shallow ref through `onBridgeConnection`, until the current effect scope is
176
271
  * disposed. Call it in `setup()` or `effectScope().run()`: outside an effect scope it is never
177
272
  * released (development builds warn).
178
273
  *
@@ -189,4 +284,5 @@ export function useBridgeConnection(options = {}) {
189
284
  }
190
285
  export { useCollectionViewport } from "./viewport.js";
191
286
  export { onBridgeConnection } from "@runic-artifex/views";
287
+ export { FieldError, } from "@runic-artifex/views";
192
288
  export { useMenuBar, } from "./menu-bar.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vue",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Vue composables for generated Runic Views clients",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,10 +30,10 @@
30
30
  },
31
31
  "peerDependencies": {
32
32
  "vue": ">=3.5.30 <4",
33
- "@runic-artifex/views": "0.13.0"
33
+ "@runic-artifex/views": "0.15.0"
34
34
  },
35
35
  "devDependencies": {
36
- "@runic-artifex/views": "0.13.0",
36
+ "@runic-artifex/views": "0.15.0",
37
37
  "esbuild": "0.28.2",
38
38
  "happy-dom": "21.0.4",
39
39
  "playwright-core": "1.63.0",
@@ -50,7 +50,7 @@
50
50
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
51
51
  "directory": "packages/web/vue"
52
52
  },
53
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/vue#readme",
53
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/vue#readme",
54
54
  "bugs": {
55
55
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
56
56
  },
@@ -60,5 +60,5 @@
60
60
  "views",
61
61
  "vue"
62
62
  ],
63
- "gitHead": "3331f81c7a2de34e209b53eb07515323d6d15cf3"
63
+ "gitHead": "c94bda07cf363bad056eda86ae77c514b66e61dd"
64
64
  }