@runic-artifex/vue 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
@@ -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,6 +140,103 @@ 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 once the field's writes settled, so a command that
185
+ depends on the field can follow them: `await title.commit(); await editor.save()`.
186
+ - `checked: true` writes with the member's checked write, so a change by another writer while the user edits is a
187
+ conflict instead of being overwritten. A `rejected` receipt keeps the draft and sets `error` to a `FieldError` with
188
+ the setter's message; a `conflict` keeps the draft, sets `conflict` to the producer's `{ value, version }` and
189
+ writes nothing until `retry()` writes the draft over it or `reset()` takes it.
190
+ - `coalesce` and `keepDraftOnError` as for text inputs below.
191
+
192
+ `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
193
+ or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
194
+ `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
195
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#fields) for the receipts
196
+ and text forms.
197
+
198
+ ### Text inputs: `useTextField(view, read, write, options?)`
199
+
200
+ Binds a text input to a member through the framework-neutral
201
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#text-inputs)
202
+ while the effect scope is active. Each field is a ref, so the handle can be destructured:
203
+
204
+ ```vue
205
+ <script setup lang="ts">
206
+ import { useTextField, useView } from "@runic-artifex/vue";
207
+ import type { PersonPageReference } from "./generated/person.js";
208
+
209
+ const props = defineProps<{ page: PersonPageReference }>();
210
+ const person = useView(() => props.page);
211
+ const { value: name, error } = useTextField(person, state => state.name, (client, value) => client.setName(value));
212
+ </script>
213
+
214
+ <template>
215
+ <input v-model="name">
216
+ <p v-if="error !== undefined" role="alert">{{ String(error) }}</p>
217
+ </template>
218
+ ```
219
+
220
+ It returns `value`, a writable computed for `v-model`, the `editing` and `error`
221
+ refs and `reset()`. `v-model` already writes nothing during IME composition. `view`
222
+ is a `useView` handle or any `{ state, client }` refs. The options are `coalesce` and
223
+ `keepDraftOnError`.
224
+ The field shows what the user typed while its writes are in flight, so a reply or
225
+ frame that answers an older keystroke never replaces newer text. At most one write is
226
+ in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
227
+ every change). Nothing is written during IME composition. Once the last write settled,
228
+ the field shows the View's value again, including any normalization the ViewModel
229
+ applied (trimmed, upper-cased). `write` may also be a command or a checked write,
230
+ whose receipt the field reads: `rejected` and `conflict` keep the draft and set `error`
231
+ to a `FieldError` of that kind, `committed-with-error` drops the draft and sets it too,
232
+ and `applied.validation` is `errors`. A failed write keeps the draft and sets `error`
233
+ (`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
234
+ exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
235
+ the user types: the field's own write causes it, and keys typed meanwhile would be
236
+ lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
237
+ Library `user.type`) against the mock with `latency: "slow"`; `fill()` sets the whole
238
+ text at once and hides the race.
239
+
88
240
  ## `ViewOutlet`
89
241
 
90
242
  Renders the component registered for a generated reference's `kind` and
@@ -148,7 +300,7 @@ neither.
148
300
  ## `useOperation(start, options?)`
149
301
 
150
302
  Observes a generated `start<Command>()` operation through the framework-neutral
151
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#operation-feedback-and-latest-selection)
303
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection)
152
304
  and returns each state field as a shallow ref, with `run`, `cancel` and `reset`:
153
305
 
154
306
  ```vue
@@ -165,19 +317,22 @@ const { run: push, cancel, pending, cancellationRequested, cancelled, error } =
165
317
  </template>
166
318
  ```
167
319
 
168
- The result has `pending`, `admitting`, `operation`, `status`, `outcome`, `failure`,
320
+ The result has `pending`, `admitting`, `operation`, `status`, `progress`, `outcome`, `failure`,
169
321
  `error`, `cancelled`, `cancellationRequested`, `cancelling`, `cancellation` and
170
322
  `cancelError`, with `run(...args)`, `cancel()` and `reset()`, which never reject. A
171
323
  run that ends with a `cancelled` status sets `cancelled` and resolves to `undefined`
172
324
  without an `error`; `failed` and `timed-out` statuses are still `error`. `pending`
173
325
  stays true after a Cancel response until the operation reaches its terminal status.
326
+ `progress` is how far the running operation got, from 0 to 1, when its command
327
+ reports progress (`RunicOperationProgress.Report` in .NET), for example
328
+ `<progress :value="progress">`; it is `undefined` while unknown and after the run.
174
329
  Disposing the effect scope settles run promises without cancelling accepted work.
175
330
 
176
331
  ## `useLatestOperation()`
177
332
 
178
333
  Admits only the newest of several reads, for example loading the item the user
179
334
  selected last, through the framework-neutral
180
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#operation-feedback-and-latest-selection),
335
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection),
181
336
  and returns each state field as a shallow ref, with `run` and `clear`. Each
182
337
  `run(intent)` replaces the queued intent and cancels the active read; the next read
183
338
  starts only after the previous one reaches its terminal status and the intent's
@@ -214,7 +369,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
214
369
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a shallow ref holding a
215
370
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
216
371
  closed set, see
217
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#connection-state)):
372
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#connection-state)):
218
373
 
219
374
  ```vue
220
375
  <script setup lang="ts">
@@ -237,7 +392,7 @@ development builds warn. An invalid `lostAfter` throws a `RangeError`.
237
392
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
238
393
  page (`DesktopMenuBarPresentation.Page`) until the current effect scope is
239
394
  disposed. It wraps `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 }`: `state` is a shallow ref
395
+ [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 }`: `state` is a shallow ref
241
396
  of a `MenuBarState`, and the bar is rendered by the menubar component of the
242
397
  application's own UI library. Runic ships no menubar component.
243
398
 
@@ -268,7 +423,7 @@ rendering creates no controller: `state` stays `connecting`.
268
423
  ### With Reka UI
269
424
 
270
425
  Reka UI's `MenubarRoot` with `v-model` of the open menu; the
271
- [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
426
+ [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
272
427
  items and is tested with real keys:
273
428
 
274
429
  ```vue
@@ -317,17 +472,20 @@ const { state: menuBar, invoke } = useMenuBar({
317
472
 
318
473
  The `error` of `useView` and of a command or operation handle is typed
319
474
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
320
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
321
- `instanceof` before reading `kind`, `route` or `detail`:
475
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
476
+ `describeBridgeError(error)`, one English sentence, instead of `String(error)`,
477
+ and narrow it with `isBridgeError` (or `instanceof`) before reading `kind`,
478
+ `route` or `detail`:
322
479
 
323
480
  ```ts
324
- import { BridgeError } from "@runic-artifex/views";
481
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
325
482
 
326
- const offline = error.value instanceof BridgeError && error.value.kind === "disconnected";
483
+ const offline = computed(() => isBridgeError(error.value, "disconnected"));
484
+ const message = computed(() => describeBridgeError(error.value));
327
485
  ```
328
486
 
329
487
  `instanceof` holds for errors from every copy of the package on the page.
330
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#errors-and-diagnostics)
488
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#errors-and-diagnostics)
331
489
  lists the kinds. Any other value, such as an exception that your own connect
332
490
  function or command callback throws, arrives unchanged.
333
491
 
@@ -374,15 +532,15 @@ application's own dialog.
374
532
  departure before that is answered by the ViewModel's .NET fallback handler, or
375
533
  fails closed without one.
376
534
 
377
- 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)
535
+ 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)
378
536
  has the .NET side and which View answers which departure. In a frontend test,
379
537
  the generated mock's `interactions.<name>.request(input)` resolves with the
380
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#testing).
538
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#testing).
381
539
 
382
540
  ## `useCollectionViewport(options)`
383
541
 
384
542
  Follows a fixed-row-height scroll container and returns `{ viewport, attach }`.
385
- `viewport` is a shallow ref with the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#collectionviewportoptions)
543
+ `viewport` is a shallow ref with the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#collectionviewportoptions)
386
544
  range; `attach` is a function ref for the container. Bind it to a native element
387
545
  such as a `<div>`: a component instance (`:ref="attach"` on a component) or a
388
546
  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
- import { type Component, type MaybeRefOrGetter, type Ref } 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";
1
+ import { type Component, type MaybeRefOrGetter, type Ref, type WritableComputedRef } from "vue";
2
+ import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeField, type BridgeOperation, type BridgeOutcomeFailure, type FieldBaseline, type FieldDefinition, 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.
@@ -147,6 +177,118 @@ export type LatestOperationHandle<TResult, TFailure = never> = {
147
177
  * ```
148
178
  */
149
179
  export declare function useLatestOperation<TResult = void, TFailure = never>(): LatestOperationHandle<TResult, TFailure>;
180
+ export interface TextFieldHandle {
181
+ /**
182
+ * What the input shows: the draft while one exists, otherwise the member's value in the View's state. Setting it
183
+ * is an input by the user, as `v-model` does; `v-model` also writes nothing during IME composition.
184
+ */
185
+ readonly value: WritableComputedRef<string>;
186
+ /**
187
+ * True while a draft exists, from the first input until the last write settled and the state caught up, and after a
188
+ * failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state, which
189
+ * the field's own write causes.
190
+ */
191
+ readonly editing: Readonly<Ref<boolean>>;
192
+ /** Why the latest write failed, until the next input or `reset()`. */
193
+ readonly error: Readonly<Ref<unknown>>;
194
+ /** Drops the draft and the error and shows the View's value. Writes in flight still complete. */
195
+ reset(): void;
196
+ }
197
+ export interface UseTextFieldOptions {
198
+ /**
199
+ * With `true` (the default) at most one write is in flight, and text typed meanwhile is written next, as one
200
+ * value. With `false` every input is written.
201
+ */
202
+ readonly coalesce?: boolean;
203
+ /** With `true` (the default) a failed write keeps the draft and sets `error`; with `false` the field shows the View's value again. */
204
+ readonly keepDraftOnError?: boolean;
205
+ }
206
+ /** The View a text field binds to: a {@link useView} handle, or any state and client refs. */
207
+ export interface TextFieldView<TClient extends ViewClient> {
208
+ readonly state: Readonly<Ref<TClient["snapshot"] | undefined>>;
209
+ readonly client: Readonly<Ref<TClient | undefined>>;
210
+ }
211
+ /**
212
+ * Binds a text input to one member of a View while the current effect scope is active, through
213
+ * `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
214
+ * shows what the user typed, at most one write is in flight (newer text is written next), and once the last write
215
+ * settled it shows the View's value, including any normalization. Each field is a ref, so the handle can be
216
+ * destructured. Call it in `setup()` or `effectScope().run()`: outside an effect scope it is never released
217
+ * (development builds warn).
218
+ *
219
+ * ```vue
220
+ * const person = useView(() => props.page);
221
+ * const { value: name, editing } = useTextField(person, state => state.name, (client, value) => client.setName(value));
222
+ * <input v-model="name">
223
+ * ```
224
+ *
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.
228
+ */
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 once the field's writes settled, so a command that depends on the field can run after it:
264
+ * `await title.commit(); await editor.save()`. Never rejects; a failure is `error`.
265
+ */
266
+ commit(): Promise<void>;
267
+ /** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
268
+ retry(): void;
269
+ /** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
270
+ reset(): void;
271
+ }
272
+ /**
273
+ * Binds an element to one View member while the current effect scope is active, through `createFieldController`:
274
+ * pass a generated descriptor such as `EditorFields.title`, or any definition with `read` and `write`. The handle is
275
+ * `reactive`; bind `v-model` to its `value` (`text` for number inputs) and call `commit` on blur. `v-model` already
276
+ * writes nothing while an IME composition is in progress. `options` are read once, when the field is created. Call
277
+ * it in `setup()` or `effectScope().run()`: outside an effect scope it is never released (development builds warn).
278
+ *
279
+ * ```vue
280
+ * const editor = useView(() => props.page);
281
+ * const title = useField(editor, EditorFields.title, { commit: "pause", checked: true });
282
+ * <input v-model="title.value" @blur="title.commit" :aria-invalid="title.errors.length > 0 || title.error !== undefined">
283
+ * <input type="number" v-model="step.text" @blur="step.commit">
284
+ * <input type="checkbox" v-model="done.value">
285
+ * ```
286
+ *
287
+ * With `checked: true` a `rejected` or `conflict` receipt keeps the draft and sets `error` (a `FieldError`), and a
288
+ * conflict holds further writes until `retry()` or `reset()`. Leaving the scope writes a value that waits to be
289
+ * written.
290
+ */
291
+ 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>;
150
292
  export interface BridgeConnectionHandle {
151
293
  /** The connection to the .NET host, as `onBridgeConnection` reports it. */
152
294
  readonly state: Readonly<Ref<BridgeConnectionState>>;
@@ -165,4 +307,5 @@ export interface BridgeConnectionHandle {
165
307
  export declare function useBridgeConnection(options?: BridgeConnectionOptions): BridgeConnectionHandle;
166
308
  export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
167
309
  export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
310
+ export { FieldError, type BridgeField, type BridgeFieldKind, type FieldBaseline, type FieldDefinition, type FieldErrorKind, type FieldOptions, type FieldState, } from "@runic-artifex/views";
168
311
  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 { defineComponent, h, shallowRef, toValue, watch, } from "vue";
2
- import { createCommandController, createLatestOperationController, createOperationController, 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) {
@@ -138,6 +172,99 @@ export function useLatestOperation() {
138
172
  releaseWithScope("useLatestOperation", () => controller.dispose());
139
173
  return { ...refs, run: controller.run, clear: controller.clear };
140
174
  }
175
+ /**
176
+ * Binds a text input to one member of a View while the current effect scope is active, through
177
+ * `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
178
+ * shows what the user typed, at most one write is in flight (newer text is written next), and once the last write
179
+ * settled it shows the View's value, including any normalization. Each field is a ref, so the handle can be
180
+ * destructured. Call it in `setup()` or `effectScope().run()`: outside an effect scope it is never released
181
+ * (development builds warn).
182
+ *
183
+ * ```vue
184
+ * const person = useView(() => props.page);
185
+ * const { value: name, editing } = useTextField(person, state => state.name, (client, value) => client.setName(value));
186
+ * <input v-model="name">
187
+ * ```
188
+ *
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.
192
+ */
193
+ export function useTextField(view, read, write, options = {}) {
194
+ const controller = createTextFieldController({ read, write, ...options });
195
+ const current = shallowRef(controller.current);
196
+ controller.subscribe(() => { current.value = controller.current; });
197
+ watch([view.state, view.client], ([state, client]) => {
198
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
199
+ current.value = controller.current;
200
+ }, { immediate: true });
201
+ releaseWithScope("useTextField", () => controller.dispose());
202
+ return {
203
+ value: computed({ get: () => current.value.value, set: text => controller.input(text) }),
204
+ editing: computed(() => current.value.editing),
205
+ error: computed(() => current.value.error),
206
+ reset: () => controller.reset(),
207
+ };
208
+ }
209
+ /**
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: async () => { await controller.commit(); },
264
+ retry: () => controller.retry(),
265
+ reset: () => controller.reset(),
266
+ });
267
+ }
141
268
  /**
142
269
  * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`
143
270
  * or `lost`) as a shallow ref through `onBridgeConnection`, until the current effect scope is
@@ -157,4 +284,5 @@ export function useBridgeConnection(options = {}) {
157
284
  }
158
285
  export { useCollectionViewport } from "./viewport.js";
159
286
  export { onBridgeConnection } from "@runic-artifex/views";
287
+ export { FieldError, } from "@runic-artifex/views";
160
288
  export { useMenuBar, } from "./menu-bar.js";
package/dist/menu-bar.js CHANGED
@@ -23,7 +23,7 @@ export function useMenuBar(options = {}) {
23
23
  }));
24
24
  return {
25
25
  state,
26
- invoke: () => Promise.reject(new BridgeError("unavailable", "The menu bar is not followed during server rendering.", { route: "__runicMenuBarInvoke" })),
26
+ invoke: () => Promise.reject(new BridgeError("unavailable", "The menu bar is not followed during server rendering.", { route: "runic.menu-bar" })),
27
27
  handleKeyDown: () => false,
28
28
  };
29
29
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vue",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Vue composables for generated Runic Views clients",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,11 +30,13 @@
30
30
  },
31
31
  "peerDependencies": {
32
32
  "vue": ">=3.5.30 <4",
33
- "@runic-artifex/views": "0.12.1"
33
+ "@runic-artifex/views": "0.14.0"
34
34
  },
35
35
  "devDependencies": {
36
- "@runic-artifex/views": "0.12.1",
36
+ "@runic-artifex/views": "0.14.0",
37
+ "esbuild": "0.28.2",
37
38
  "happy-dom": "21.0.4",
39
+ "playwright-core": "1.63.0",
38
40
  "typescript": "6.0.3",
39
41
  "vitest": "5.0.3",
40
42
  "vue": "3.5.43"
@@ -48,7 +50,7 @@
48
50
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
49
51
  "directory": "packages/web/vue"
50
52
  },
51
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/vue#readme",
53
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/vue#readme",
52
54
  "bugs": {
53
55
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
54
56
  },
@@ -58,5 +60,5 @@
58
60
  "views",
59
61
  "vue"
60
62
  ],
61
- "gitHead": "124a532e5861cff03e77d2ef0c5d4f081ee99a47"
63
+ "gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
62
64
  }