@runic-artifex/angular 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
@@ -23,6 +23,7 @@ signals and `retry()`:
23
23
  ```ts
24
24
  import { Component, input } from "@angular/core";
25
25
  import { injectCommand, injectView } from "@runic-artifex/angular";
26
+ import { describeBridgeError } from "@runic-artifex/views";
26
27
  import type { CounterPageReference } from "./generated/counter";
27
28
 
28
29
  @Component({
@@ -31,13 +32,14 @@ import type { CounterPageReference } from "./generated/counter";
31
32
  <button [disabled]="!counter.client() || increment.pending()" (click)="increment.run()">
32
33
  {{ counter.state()?.count ?? "…" }}
33
34
  </button>
34
- @if (increment.error() ?? counter.error(); as issue) { <p role="alert">{{ issue }}</p> }
35
+ @if (increment.error() ?? counter.error(); as issue) { <p role="alert">{{ describe(issue) }}</p> }
35
36
  `,
36
37
  })
37
38
  export class CounterPage {
38
39
  readonly page = input.required<CounterPageReference>();
39
40
  readonly counter = injectView(this.page);
40
41
  readonly increment = injectCommand(() => this.counter.client()?.increment());
42
+ readonly describe = describeBridgeError;
41
43
  }
42
44
  ```
43
45
 
@@ -47,6 +49,63 @@ already connected client is observed and left to its owner. Outside an
47
49
  injection context, pass `{ injector }`; pass `{ release }` to defer disposal,
48
50
  for example until queued commands finish.
49
51
 
52
+ A released client stays connected for `keepAlive` milliseconds (2000 by
53
+ default), and the next `injectView` of the same reference takes it over with
54
+ its state, before its effect runs: an `@if` that toggles, HMR and A→B→A
55
+ navigation show the View at once instead of "Connecting…" and do not open the
56
+ route again. `{ keepAlive: 0 }` disposes at once.
57
+
58
+ ### As a resource: `injectViewResource(source, options?)`
59
+
60
+ `injectViewResource` connects like `injectView` and returns an Angular
61
+ `Resource` (D053.11): `status()` is `loading` until the View connected, then
62
+ `resolved`, or `error` with the failure in `error()`; `value()` is the state,
63
+ never `undefined` once `hasValue()` is true; `client()` is the client and
64
+ `reload()` connects again. Templates branch on it as on any resource:
65
+
66
+ ```ts
67
+ @Component({
68
+ selector: "counter-page",
69
+ template: `
70
+ @if (counter.hasValue()) {
71
+ <button (click)="counter.client()?.increment()">{{ counter.value().count }}</button>
72
+ } @else if (counter.error(); as issue) {
73
+ <p role="alert">{{ describe(issue) }}</p>
74
+ <button (click)="counter.reload()">Retry</button>
75
+ } @else {
76
+ <p>Connecting…</p>
77
+ }
78
+ `,
79
+ })
80
+ export class CounterPage {
81
+ readonly page = input.required<CounterPageReference>();
82
+ readonly counter = injectViewResource(this.page);
83
+ readonly describe = describeBridgeError;
84
+ }
85
+ ```
86
+
87
+ A changed reference loads the new one, `null` makes it `idle`, and the
88
+ injector's destruction releases the client, with the same `keepAlive` as
89
+ `injectView`.
90
+
91
+ ### Selecting state: `computed`
92
+
93
+ `state()` changes with every change of the View. A `computed` that selects a
94
+ member notifies its consumers only when its value changed (`Object.is`, or its
95
+ `equal` option), so a template binding or an `effect` that reads `title()` does
96
+ not run again when another member changes:
97
+
98
+ ```ts
99
+ readonly editor = injectView(this.page);
100
+ readonly title = computed(() => this.editor.state()?.title);
101
+ readonly done = computed(() => this.editor.state()?.items.filter(item => item.done) ?? [],
102
+ { equal: (left, right) => left.length === right.length && left.every((item, index) => item === right[index]) });
103
+ ```
104
+
105
+ Members the View did not change keep their identity, so selecting a member,
106
+ also an object or a list, needs no `equal`; a derived value such as `filter`
107
+ does.
108
+
50
109
  ### Read-only state and two-way binding
51
110
 
52
111
  As in any MVVM View, the ViewModel's C# setters decide what the page may set.
@@ -75,6 +134,192 @@ export class CounterPage {
75
134
  }
76
135
  ```
77
136
 
137
+ ### Text inputs
138
+
139
+ Bind a text input to a member with `injectTextField(view, read, write, options?)`,
140
+ which wraps the framework-neutral
141
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#text-inputs)
142
+ for the lifetime of the injection context:
143
+
144
+ ```ts
145
+ @Component({
146
+ selector: "person-page",
147
+ template: `
148
+ <input [value]="name.value()" (input)="name.input($event)"
149
+ (compositionstart)="name.compositionStart()" (compositionend)="name.compositionEnd($event)">
150
+ @if (name.error() !== undefined) { <p role="alert">{{ name.error() }}</p> }
151
+ `,
152
+ })
153
+ export class PersonPage {
154
+ readonly page = input.required<PersonPageReference>();
155
+ readonly person = injectView(this.page);
156
+ readonly name = injectTextField(this.person, state => state.name, (client, value) => client.setName(value));
157
+ }
158
+ ```
159
+
160
+ It returns the `value`, `editing` and `error` signals with `input(event | text)`,
161
+ `compositionStart()`, `compositionEnd(event | text)` and `reset()`. `view` is an
162
+ `injectView` handle or any pair of `state` and `client` signals. The options are
163
+ `coalesce`, `keepDraftOnError` and `injector` outside an injection context.
164
+ The field shows what the user typed while its writes are in flight, so a reply or
165
+ frame that answers an older keystroke never replaces newer text. At most one write is
166
+ in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
167
+ every change). Nothing is written during IME composition. Once the last write settled,
168
+ the field shows the View's value again, including any normalization the ViewModel
169
+ applied (trimmed, upper-cased). `write` may also be a command or a checked write,
170
+ whose receipt is read: a `rejected` or `conflict` receipt keeps the draft and sets
171
+ `error` to a `FieldError` of that kind, and `committed-with-error` drops the draft and
172
+ sets one too (see [Fields](#fields)). A failed write keeps the draft and sets `error`
173
+ (`keepDraftOnError: false` shows the View's value instead); `reset()` drops the draft. `editing` is true while a draft
174
+ exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
175
+ the user types: the field's own write causes it, and keys typed meanwhile would be
176
+ lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
177
+ Library `user.type`) against the mock with `latency: "slow"`; `fill()` sets the whole
178
+ text at once and hides the race.
179
+
180
+ ## Fields
181
+
182
+ For generated Views prefer `injectField(view, field, options?)`: pass a descriptor of the
183
+ generated `{View}Fields`, such as `EditorFields.title`. It wraps the framework-neutral
184
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#fields)
185
+ for every kind (text, numbers, booleans, enums) and returns signals and actions:
186
+
187
+ - `value`, `text` (what a text input shows: `1.` stays while typing `1.5`), `editing`,
188
+ `error` (a `BridgeError` or a `FieldError`), `errors` (the member's validation
189
+ messages) and `conflict`;
190
+ - `input(value)`, `inputText(event | text)`, `compositionStart()`,
191
+ `compositionEnd(event | text)`, `commit()`, `retry()` and `reset()`;
192
+ - `field`: the descriptor's `kind`, `nullable`, `integer` and `choices`.
193
+
194
+ ```ts
195
+ import { Component, input } from "@angular/core";
196
+ import { injectField, injectView } from "@runic-artifex/angular";
197
+ import { EditorFields, type EditorPageReference } from "./generated/editor";
198
+
199
+ @Component({
200
+ selector: "editor-page",
201
+ template: `
202
+ <input [value]="title.text()" [attr.aria-invalid]="title.errors().length > 0 || null"
203
+ (input)="title.inputText($event)" (blur)="title.commit()"
204
+ (compositionstart)="title.compositionStart()" (compositionend)="title.compositionEnd($event)">
205
+ @for (message of title.errors(); track message) { <p role="alert">{{ message }}</p> }
206
+ `,
207
+ })
208
+ export class EditorPage {
209
+ readonly page = input.required<EditorPageReference>();
210
+ readonly editor = injectView(this.page);
211
+ readonly title = injectField(this.editor, EditorFields.title);
212
+ }
213
+ ```
214
+
215
+ The options are those of the controller and `injector`:
216
+
217
+ - `commit: "pause"` writes the draft after `delay` milliseconds without input (700
218
+ by default) and at once on `commit()`, which blur calls; use it where each write is
219
+ an undo step or starts work in .NET. `commit()` resolves once the field's writes
220
+ settled, so a command that depends on the field can follow it:
221
+ `await this.title.commit(); await this.editor.client()?.save();`.
222
+ - `checked: true` writes with the member's checked write: a change by another writer
223
+ since the draft started is a conflict instead of being overwritten.
224
+ - `coalesce` and `keepDraftOnError`, as for `injectTextField`.
225
+
226
+ A checked write's receipt is read: `rejected` keeps the draft with a `FieldError`
227
+ `rejected`; `conflict` keeps the draft, sets `conflict` to the producer's
228
+ `{ value, version }` and writes nothing until `retry()` (write the draft over it) or
229
+ `reset()` (take the producer's value); `committed-with-error` keeps the committed value
230
+ with a `FieldError`. `errors` follows the member's validation in the View's state:
231
+
232
+ ```html
233
+ @if (title.conflict(); as theirs) {
234
+ <p role="alert">Changed elsewhere to “{{ theirs.value }}”.
235
+ <button (click)="title.retry()">Keep mine</button> <button (click)="title.reset()">Take theirs</button></p>
236
+ }
237
+ ```
238
+
239
+ ### `[runicField]` and Reactive Forms
240
+
241
+ `@runic-artifex/angular/forms` needs `@angular/forms` (an optional peer; the main
242
+ entry does not). `RunicFieldDirective` wires an `<input>`, `<textarea>` or
243
+ `<select>` in one attribute: input (`change` for checkboxes, radios and selects),
244
+ composition, `commit()` on blur, the element's `value` or `checked`, and
245
+ `aria-invalid`:
246
+
247
+ ```ts
248
+ import { RunicFieldDirective } from "@runic-artifex/angular/forms";
249
+
250
+ @Component({
251
+ selector: "editor-page",
252
+ imports: [RunicFieldDirective],
253
+ template: `<input [runicField]="title"> <input type="checkbox" [runicField]="pinned">`,
254
+ })
255
+ export class EditorPage {
256
+ readonly page = input.required<EditorPageReference>();
257
+ readonly editor = injectView(this.page);
258
+ readonly title = injectField(this.editor, EditorFields.title, { commit: "pause" });
259
+ readonly pinned = injectField(this.editor, EditorFields.pinned);
260
+ }
261
+ ```
262
+
263
+ It is also the `ControlValueAccessor` and validator of a `formControl` or
264
+ `formControlName` on the same element. The View's value flows into the control
265
+ without marking it dirty or emitting `valueChanges`, and a control's initial value
266
+ is not written; what the user types reaches the control as usual; `setValue`,
267
+ `patchValue` and `reset` write through to the View when they change the value (a
268
+ `null` from `reset()` of a nullable control is ignored for a non-nullable field);
269
+ `disable()` disables the element; and the control has the error
270
+ `{ runic: errors }` while the View reports validation messages for the member:
271
+
272
+ ```ts
273
+ import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms";
274
+
275
+ @Component({
276
+ selector: "editor-page",
277
+ imports: [RunicFieldDirective, ReactiveFormsModule],
278
+ template: `
279
+ <form [formGroup]="form">
280
+ <input formControlName="title" [runicField]="title">
281
+ @if (form.controls.title.errors?.["runic"]; as messages) { <p role="alert">{{ messages[0] }}</p> }
282
+ </form>
283
+ `,
284
+ })
285
+ export class EditorPage {
286
+ readonly page = input.required<EditorPageReference>();
287
+ readonly editor = injectView(this.page);
288
+ readonly title = injectField(this.editor, EditorFields.title);
289
+ readonly form = new FormGroup({ title: new FormControl("", { nonNullable: true }) });
290
+ }
291
+ ```
292
+
293
+ ### Signal Forms
294
+
295
+ `runicFieldModel(handle)` is a `WritableSignal` over a field for `form()` from
296
+ `@angular/forms/signals`: it reads `value`, and `set`/`update` call `input`.
297
+ `validateRunicField(path, handle)` adds the field's `errors` to the schema as
298
+ errors of kind `runic` with the message:
299
+
300
+ ```ts
301
+ import { form, FormField } from "@angular/forms/signals";
302
+ import { runicFieldModel, validateRunicField } from "@runic-artifex/angular/forms";
303
+
304
+ @Component({
305
+ selector: "editor-page",
306
+ imports: [FormField],
307
+ template: `<input [formField]="titleForm" (blur)="title.commit()">`,
308
+ })
309
+ export class EditorPage {
310
+ readonly page = input.required<EditorPageReference>();
311
+ readonly editor = injectView(this.page);
312
+ readonly title = injectField(this.editor, EditorFields.title);
313
+ readonly titleForm = form(runicFieldModel(this.title), path => validateRunicField(path, this.title));
314
+ }
315
+ ```
316
+
317
+ Signal Forms does not tell the field when the element loses focus: always bind
318
+ `(blur)="title.commit()"` next to `[formField]`, as above. Without it a
319
+ `commit: "pause"` field writes only after the pause, and a value typed just before
320
+ Save may still wait. `[formField]` also writes during IME composition; prefer
321
+ `[runicField]` where composition matters.
322
+
78
323
  ## Outlet
79
324
 
80
325
  Register a component for each generated View kind and pass the current
@@ -147,14 +392,14 @@ For example, a navigation command whose departure guard awaits a dialog's
147
392
  answer never completes while the answer waits behind it. Order such commands
148
393
  by dispatch instead: start the next one once the previous one has been sent,
149
394
  as the Notes example's
150
- [`WindowOperations.runDispatched`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/examples/notes-view-first/Angular/src/app/window-operations.ts)
395
+ [`WindowOperations.runDispatched`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/examples/notes-view-first/Angular/src/app/window-operations.ts)
151
396
  does for its navigation commands.
152
397
 
153
398
  ## Operations
154
399
 
155
400
  `injectOperation(start, options?)` observes a generated `start<Command>()` operation
156
401
  through the framework-neutral
157
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#operation-feedback-and-latest-selection)
402
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection)
158
403
  for the lifetime of the injection context:
159
404
 
160
405
  ```ts
@@ -166,9 +411,11 @@ readonly push = injectOperation((remote: string) => this.workspace.client()?.sta
166
411
  ```
167
412
 
168
413
  It returns `run(...args)`, `cancel()` and `reset()`, which never reject, and the
169
- `pending`, `admitting`, `operation`, `status`, `outcome`, `failure`, `error`,
414
+ `pending`, `admitting`, `operation`, `status`, `progress`, `outcome`, `failure`, `error`,
170
415
  `cancelled`, `cancellationRequested`, `cancelling`, `cancellation` and `cancelError`
171
- signals. A run that ends with a `cancelled` status sets `cancelled` and resolves to
416
+ signals. `progress` is how far the running operation got, from 0 to 1, when its
417
+ command reports progress (`RunicOperationProgress.Report` in .NET), for example
418
+ `<progress [value]="push.progress()">`; it is `undefined` while unknown and after the run. A run that ends with a `cancelled` status sets `cancelled` and resolves to
172
419
  `undefined` without an `error`; `failed` and `timed-out` statuses are still `error`.
173
420
  `pending` stays true after a Cancel response until the operation reaches its terminal
174
421
  status. Destroying the injection context settles run promises without cancelling
@@ -178,7 +425,7 @@ context.
178
425
 
179
426
  `injectLatestOperation(options?)` admits only the newest of several reads, for example
180
427
  loading the item the user selected last, through the framework-neutral
181
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#operation-feedback-and-latest-selection).
428
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#operation-feedback-and-latest-selection).
182
429
  Each `run(intent)` replaces the queued intent and cancels the active read; the next
183
430
  read starts only after the previous one reaches its terminal status and the intent's
184
431
  optional `waitForCompletion` barrier:
@@ -210,7 +457,7 @@ from `@runic-artifex/views` (re-exported here since 0.11, with the
210
457
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a signal of a
211
458
  `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
212
459
  closed set, see
213
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#connection-state)):
460
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#connection-state)):
214
461
 
215
462
  ```ts
216
463
  import { injectBridgeConnection } from "@runic-artifex/angular";
@@ -228,7 +475,7 @@ not observe and stays `connecting`. An invalid `lostAfter` throws a `RangeError`
228
475
  `injectMenuBar(options?)` follows the declared menu bar of a Runic Desktop
229
476
  window that leaves it to the page (`DesktopMenuBarPresentation.Page`) for the
230
477
  lifetime of the injection context. It wraps `createMenuBarController` from
231
- `@runic-artifex/views` (see [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#in-page-menu-bar))
478
+ `@runic-artifex/views` (see [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#in-page-menu-bar))
232
479
  and returns `{ state, invoke, handleKeyDown }`, where `state` is a signal of a
233
480
  `MenuBarState`. The bar is rendered by the application's own menubar, for
234
481
  example the CDK Menu's `cdkMenuBar`. Runic ships no menubar component.
@@ -253,7 +500,7 @@ it creates none and stays `connecting`.
253
500
  ### With the CDK Menu
254
501
 
255
502
  The CDK's `cdkMenuBar` with `CdkMenuTrigger.open()` for `open` requests; the
256
- [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
503
+ [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
257
504
  items (`cdkMenuItemCheckbox`, `cdkMenuItemRadio` in a `cdkMenuGroup`) and is
258
505
  tested with real keys:
259
506
 
@@ -306,18 +553,20 @@ export class AppMenuBar {
306
553
 
307
554
  The `error()` signal of `injectView` and of a command or operation is typed
308
555
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
309
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
310
- `instanceof` before reading `kind`, `route` or `detail`:
556
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
557
+ `describeBridgeError(error)`, one English sentence, instead of interpolating
558
+ the error, and narrow it with `isBridgeError` (or `instanceof`) before reading
559
+ `kind`, `route` or `detail`:
311
560
 
312
561
  ```ts
313
- import { BridgeError } from "@runic-artifex/views";
562
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
314
563
 
315
- const error = this.view.error();
316
- const offline = error instanceof BridgeError && error.kind === "disconnected";
564
+ readonly offline = computed(() => isBridgeError(this.view.error(), "disconnected"));
565
+ readonly message = computed(() => describeBridgeError(this.view.error()));
317
566
  ```
318
567
 
319
568
  `instanceof` holds for errors from every copy of the package on the page.
320
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#errors-and-diagnostics)
569
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#errors-and-diagnostics)
321
570
  lists the kinds. Any other value, such as an exception that your own connect
322
571
  function or command callback throws, arrives unchanged.
323
572
 
@@ -368,16 +617,16 @@ application's own dialog.
368
617
  departure before that is answered by the ViewModel's .NET fallback handler, or
369
618
  fails closed without one.
370
619
 
371
- 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)
620
+ 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)
372
621
  has the .NET side and which View answers which departure. In a frontend test,
373
622
  the generated mock's `interactions.<name>.request(input)` resolves with the
374
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#testing).
623
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#testing).
375
624
 
376
625
  ## Collection viewports
377
626
 
378
627
  `injectCollectionViewport(element, options)` follows a fixed-row-height scroll
379
628
  container and returns a signal with its
380
- [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/views#collectionviewportoptions)
629
+ [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/views#collectionviewportoptions)
381
630
  range. Pass the container as a signal, such as a `viewChild`, and the options as
382
631
  a function or signal, then send the range to the ViewModel from an effect:
383
632
 
@@ -0,0 +1,2 @@
1
+ export { RunicFieldDirective } from "./runic-field.directive.js";
2
+ export { runicFieldModel, validateRunicField } from "./signal-forms.js";
@@ -0,0 +1,2 @@
1
+ export { RunicFieldDirective } from "./runic-field.directive.js";
2
+ export { runicFieldModel, validateRunicField } from "./signal-forms.js";
@@ -0,0 +1,48 @@
1
+ import { type AbstractControl, type ControlValueAccessor, type ValidationErrors, type Validator } from "@angular/forms";
2
+ import type { FieldHandle } from "../inject-field.js";
3
+ import * as i0 from "@angular/core";
4
+ /**
5
+ * Wires an `<input>`, `<textarea>` or `<select>` to an {@link injectField} handle: `<input [runicField]="title">`.
6
+ *
7
+ * Alone, it writes what the user types (`input`; `change` for checkboxes, radios and selects), holds writes during IME
8
+ * composition, commits on blur, keeps the element's `value` (or `checked`) equal to the field without moving the
9
+ * caret, and sets `aria-invalid` while the field has an `error` or `errors`.
10
+ *
11
+ * It is also the `ControlValueAccessor` and `Validator` of a `formControl` or `formControlName` on the same element:
12
+ * the View's value flows into the control without marking it dirty or emitting `valueChanges`, the user's input
13
+ * reaches it as usual, `patchValue` and `reset` write through to the View when they change the value, `disable()`
14
+ * disables the element, and the control is invalid with `{ runic: errors }` while the View reports `errors`.
15
+ */
16
+ export declare class RunicFieldDirective implements ControlValueAccessor, Validator {
17
+ /** The field to wire, from {@link injectField}. */
18
+ readonly runicField: import("@angular/core").InputSignal<FieldHandle<unknown>>;
19
+ protected readonly invalid: import("@angular/core").Signal<boolean>;
20
+ private readonly element;
21
+ private readonly injector;
22
+ private composing;
23
+ private changed;
24
+ private touched;
25
+ private validatorChanged;
26
+ private validated;
27
+ private synced;
28
+ constructor();
29
+ private wiring;
30
+ private control;
31
+ private syncControl;
32
+ private changedByUser;
33
+ protected onInput(): void;
34
+ protected onChange(): void;
35
+ protected onCompositionStart(): void;
36
+ protected onCompositionEnd(): void;
37
+ protected onBlur(): void;
38
+ /** A value set by the form (`setValue`, `patchValue`, `reset`): written to the View when it differs from the field's. */
39
+ writeValue(value: unknown): void;
40
+ registerOnChange(fn: (value: unknown) => void): void;
41
+ registerOnTouched(fn: () => void): void;
42
+ setDisabledState(disabled: boolean): void;
43
+ /** `{ runic: errors }` while the View reports validation messages for the field. */
44
+ validate(_control?: AbstractControl): ValidationErrors | null;
45
+ registerOnValidatorChange(fn: () => void): void;
46
+ static ɵfac: i0.ɵɵFactoryDeclaration<RunicFieldDirective, never>;
47
+ static ɵdir: i0.ɵɵDirectiveDeclaration<RunicFieldDirective, "[runicField]", never, { "runicField": { "alias": "runicField"; "required": true; "isSignal": true; }; }, {}, never, never, true, never>;
48
+ }
@@ -0,0 +1,195 @@
1
+ import { afterRenderEffect, computed, Directive, effect, ElementRef, forwardRef, inject, Injector, input, untracked } from "@angular/core";
2
+ import { NG_VALIDATORS, NG_VALUE_ACCESSOR, NgControl, } from "@angular/forms";
3
+ import * as i0 from "@angular/core";
4
+ // No control synced yet: the first `writeValue` of a control is its setup, not a change by the form.
5
+ const unsynced = Symbol("unsynced");
6
+ /**
7
+ * Wires an `<input>`, `<textarea>` or `<select>` to an {@link injectField} handle: `<input [runicField]="title">`.
8
+ *
9
+ * Alone, it writes what the user types (`input`; `change` for checkboxes, radios and selects), holds writes during IME
10
+ * composition, commits on blur, keeps the element's `value` (or `checked`) equal to the field without moving the
11
+ * caret, and sets `aria-invalid` while the field has an `error` or `errors`.
12
+ *
13
+ * It is also the `ControlValueAccessor` and `Validator` of a `formControl` or `formControlName` on the same element:
14
+ * the View's value flows into the control without marking it dirty or emitting `valueChanges`, the user's input
15
+ * reaches it as usual, `patchValue` and `reset` write through to the View when they change the value, `disable()`
16
+ * disables the element, and the control is invalid with `{ runic: errors }` while the View reports `errors`.
17
+ */
18
+ export class RunicFieldDirective {
19
+ /** The field to wire, from {@link injectField}. */
20
+ runicField = input.required(/* @ts-ignore */
21
+ ...(ngDevMode ? [{ debugName: "runicField" }] : /* istanbul ignore next */ []));
22
+ invalid = computed(() => {
23
+ const field = this.runicField();
24
+ return field.error() !== undefined || field.errors().length !== 0;
25
+ }, /* @ts-ignore */
26
+ ...(ngDevMode ? [{ debugName: "invalid" }] : /* istanbul ignore next */ []));
27
+ element = inject(ElementRef).nativeElement;
28
+ // NgControl injects this directive as its accessor, so it is looked up when needed rather than injected.
29
+ injector = inject(Injector);
30
+ composing = false;
31
+ changed;
32
+ touched;
33
+ validatorChanged;
34
+ validated;
35
+ synced = unsynced;
36
+ constructor() {
37
+ afterRenderEffect({
38
+ write: () => {
39
+ const field = this.runicField();
40
+ const value = field.value();
41
+ const text = field.text();
42
+ if (this.composing)
43
+ return;
44
+ const element = this.element;
45
+ switch (this.wiring()) {
46
+ case "checkbox": {
47
+ const checkbox = element;
48
+ if (checkbox.checked !== (value === true))
49
+ checkbox.checked = value === true;
50
+ checkbox.indeterminate = value === null || value === undefined;
51
+ break;
52
+ }
53
+ case "radio": {
54
+ const radio = element;
55
+ if (radio.checked !== (radio.value === text))
56
+ radio.checked = radio.value === text;
57
+ break;
58
+ }
59
+ default:
60
+ // Only a changed value is assigned, which keeps the caret where it is.
61
+ if (element.value !== text)
62
+ element.value = text;
63
+ }
64
+ },
65
+ });
66
+ // The View's value, and the user's while a draft exists, flows into the control without dirtying it.
67
+ effect(() => {
68
+ this.runicField().value();
69
+ untracked(() => this.syncControl());
70
+ });
71
+ effect(() => {
72
+ const errors = this.runicField().errors();
73
+ untracked(() => {
74
+ if (this.validated !== undefined && errors !== this.validated)
75
+ this.validatorChanged?.();
76
+ });
77
+ });
78
+ }
79
+ wiring() {
80
+ const element = this.element;
81
+ if (element.tagName === "SELECT")
82
+ return "select";
83
+ if (element.tagName === "INPUT") {
84
+ const type = element.type;
85
+ if (type === "checkbox" || type === "radio")
86
+ return type;
87
+ }
88
+ return "text";
89
+ }
90
+ control() {
91
+ return this.injector.get(NgControl, null, { self: true, optional: true })?.control ?? undefined;
92
+ }
93
+ syncControl() {
94
+ const control = this.control();
95
+ if (control === undefined)
96
+ return;
97
+ this.synced = control;
98
+ const value = this.runicField().value();
99
+ if (!Object.is(control.value, value))
100
+ control.setValue(value, { emitEvent: false, emitModelToViewChange: false });
101
+ }
102
+ changedByUser() {
103
+ this.changed?.(this.runicField().value());
104
+ }
105
+ onInput() {
106
+ if (this.wiring() !== "text")
107
+ return;
108
+ this.runicField().inputText(this.element.value);
109
+ if (!this.composing)
110
+ this.changedByUser();
111
+ }
112
+ onChange() {
113
+ const field = this.runicField();
114
+ switch (this.wiring()) {
115
+ case "checkbox":
116
+ field.input(this.element.checked);
117
+ break;
118
+ case "radio":
119
+ if (!this.element.checked)
120
+ return;
121
+ field.inputText(this.element.value);
122
+ break;
123
+ case "select":
124
+ field.inputText(this.element.value);
125
+ break;
126
+ default: return;
127
+ }
128
+ this.changedByUser();
129
+ }
130
+ onCompositionStart() {
131
+ this.composing = true;
132
+ this.runicField().compositionStart();
133
+ }
134
+ onCompositionEnd() {
135
+ this.composing = false;
136
+ this.runicField().compositionEnd(this.element.value);
137
+ this.changedByUser();
138
+ }
139
+ onBlur() {
140
+ void this.runicField().commit();
141
+ this.touched?.();
142
+ }
143
+ /** A value set by the form (`setValue`, `patchValue`, `reset`): written to the View when it differs from the field's. */
144
+ writeValue(value) {
145
+ const control = this.control();
146
+ // Setting up a control writes its value first: the View's value is the one to keep.
147
+ if (this.changed === undefined || control !== this.synced) {
148
+ queueMicrotask(() => this.syncControl());
149
+ return;
150
+ }
151
+ const field = this.runicField();
152
+ if (Object.is(value, untracked(field.value)))
153
+ return;
154
+ if ((value === null || value === undefined) && !field.field.nullable) {
155
+ // `reset()` of a nullable control: a non-nullable field keeps its value, and the control shows it again.
156
+ queueMicrotask(() => this.syncControl());
157
+ return;
158
+ }
159
+ field.input(value);
160
+ }
161
+ registerOnChange(fn) { this.changed = fn; }
162
+ registerOnTouched(fn) { this.touched = fn; }
163
+ setDisabledState(disabled) { this.element.disabled = disabled; }
164
+ /** `{ runic: errors }` while the View reports validation messages for the field. */
165
+ validate(_control) {
166
+ const errors = untracked(this.runicField().errors);
167
+ this.validated = errors;
168
+ return errors.length === 0 ? null : { runic: errors };
169
+ }
170
+ registerOnValidatorChange(fn) { this.validatorChanged = fn; }
171
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.3", ngImport: i0, type: RunicFieldDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
172
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.2.3", type: RunicFieldDirective, isStandalone: true, selector: "[runicField]", inputs: { runicField: { classPropertyName: "runicField", publicName: "runicField", isSignal: true, isRequired: true, transformFunction: null } }, host: { listeners: { "input": "onInput()", "change": "onChange()", "compositionstart": "onCompositionStart()", "compositionend": "onCompositionEnd()", "blur": "onBlur()" }, properties: { "attr.aria-invalid": "invalid() ? 'true' : null" } }, providers: [
173
+ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RunicFieldDirective), multi: true },
174
+ { provide: NG_VALIDATORS, useExisting: forwardRef(() => RunicFieldDirective), multi: true },
175
+ ], ngImport: i0 });
176
+ }
177
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.3", ngImport: i0, type: RunicFieldDirective, decorators: [{
178
+ type: Directive,
179
+ args: [{
180
+ selector: "[runicField]",
181
+ standalone: true,
182
+ providers: [
183
+ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RunicFieldDirective), multi: true },
184
+ { provide: NG_VALIDATORS, useExisting: forwardRef(() => RunicFieldDirective), multi: true },
185
+ ],
186
+ host: {
187
+ "(input)": "onInput()",
188
+ "(change)": "onChange()",
189
+ "(compositionstart)": "onCompositionStart()",
190
+ "(compositionend)": "onCompositionEnd()",
191
+ "(blur)": "onBlur()",
192
+ "[attr.aria-invalid]": "invalid() ? 'true' : null",
193
+ },
194
+ }]
195
+ }], ctorParameters: () => [], propDecorators: { runicField: [{ type: i0.Input, args: [{ isSignal: true, alias: "runicField", required: true }] }] } });
@@ -0,0 +1,19 @@
1
+ import { type WritableSignal } from "@angular/core";
2
+ import { type PathKind, type SchemaPath, type SchemaPathRules } from "@angular/forms/signals";
3
+ import type { FieldHandle } from "../inject-field.js";
4
+ /**
5
+ * A `WritableSignal` over an {@link injectField} handle, for a Signal Forms `form()`: it reads the field's `value`,
6
+ * and `set` and `update` write through the field (`input`), so the form's `[formField]` edits the View.
7
+ *
8
+ * ```ts
9
+ * readonly title = injectField(this.editor, EditorFields.title);
10
+ * readonly titleForm = form(runicFieldModel(this.title), path => validateRunicField(path, this.title));
11
+ * // <input [formField]="titleForm" (blur)="title.commit()">
12
+ * ```
13
+ */
14
+ export declare function runicFieldModel<TValue>(handle: FieldHandle<TValue>): WritableSignal<TValue>;
15
+ /**
16
+ * Adds the field's validation messages (`errors()`) to a Signal Forms schema path as errors of kind `runic`, each
17
+ * with its message.
18
+ */
19
+ export declare function validateRunicField<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, handle: Pick<FieldHandle<unknown>, "errors">): void;
@@ -0,0 +1,29 @@
1
+ import { linkedSignal, untracked } from "@angular/core";
2
+ import { validate } from "@angular/forms/signals";
3
+ /**
4
+ * A `WritableSignal` over an {@link injectField} handle, for a Signal Forms `form()`: it reads the field's `value`,
5
+ * and `set` and `update` write through the field (`input`), so the form's `[formField]` edits the View.
6
+ *
7
+ * ```ts
8
+ * readonly title = injectField(this.editor, EditorFields.title);
9
+ * readonly titleForm = form(runicFieldModel(this.title), path => validateRunicField(path, this.title));
10
+ * // <input [formField]="titleForm" (blur)="title.commit()">
11
+ * ```
12
+ */
13
+ export function runicFieldModel(handle) {
14
+ const model = linkedSignal(() => handle.value(), /* @ts-ignore */
15
+ ...(ngDevMode ? [{ debugName: "model" }] : /* istanbul ignore next */ []));
16
+ model.set = value => handle.input(value);
17
+ model.update = update => handle.input(update(untracked(handle.value)));
18
+ return model;
19
+ }
20
+ /**
21
+ * Adds the field's validation messages (`errors()`) to a Signal Forms schema path as errors of kind `runic`, each
22
+ * with its message.
23
+ */
24
+ export function validateRunicField(path, handle) {
25
+ validate(path, () => {
26
+ const errors = handle.errors();
27
+ return errors.length === 0 ? undefined : errors.map((message) => ({ kind: "runic", message }));
28
+ });
29
+ }
@@ -1,7 +1,10 @@
1
1
  export { ViewOutlet, RunicViewOutlet, type ViewOutletMissingContext, type ViewRegistry } from "./view-outlet.js";
2
2
  export { injectView, type InjectViewOptions, type ViewHandle } from "./inject-view.js";
3
+ export { injectViewResource, type InjectViewResourceOptions, type ViewResource } from "./inject-view-resource.js";
3
4
  export { injectCommand, type CommandHandle, type InjectCommandOptions } from "./inject-command.js";
4
5
  export { injectOperation, type InjectOperationOptions, type OperationHandle } from "./inject-operation.js";
6
+ export { injectField, type FieldHandle, type FieldView, type InjectFieldOptions } from "./inject-field.js";
7
+ export { injectTextField, type InjectTextFieldOptions, type TextFieldHandle, type TextFieldView } from "./inject-text-field.js";
5
8
  export { injectLatestOperation, type InjectLatestOperationOptions, type LatestOperationHandle, } from "./inject-latest-operation.js";
6
9
  export { injectCollectionViewport, type InjectCollectionViewportOptions } from "./inject-collection-viewport.js";
7
10
  export { injectBridgeConnection, type BridgeConnectionHandle, type InjectBridgeConnectionOptions } from "./inject-bridge-connection.js";
package/dist/esm/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  export { ViewOutlet, RunicViewOutlet } from "./view-outlet.js";
2
2
  export { injectView } from "./inject-view.js";
3
+ export { injectViewResource } from "./inject-view-resource.js";
3
4
  export { injectCommand } from "./inject-command.js";
4
5
  export { injectOperation } from "./inject-operation.js";
6
+ export { injectField } from "./inject-field.js";
7
+ export { injectTextField } from "./inject-text-field.js";
5
8
  export { injectLatestOperation, } from "./inject-latest-operation.js";
6
9
  export { injectCollectionViewport } from "./inject-collection-viewport.js";
7
10
  export { injectBridgeConnection } from "./inject-bridge-connection.js";
@@ -0,0 +1,64 @@
1
+ import { Injector, type Signal } from "@angular/core";
2
+ import { type BridgeField, type FieldBaseline, type FieldController, type FieldDefinition, type FieldOptions, type FieldState, type ViewClient } from "@runic-artifex/views";
3
+ /** The View a field binds to: an {@link injectView} handle, or any pair of state and client signals. */
4
+ export interface FieldView<TClient extends ViewClient> {
5
+ readonly state: Signal<TClient["snapshot"] | undefined>;
6
+ readonly client: Signal<TClient | undefined>;
7
+ }
8
+ export interface InjectFieldOptions extends FieldOptions {
9
+ /** Required outside an injection context. */
10
+ readonly injector?: Injector;
11
+ }
12
+ /** One View member bound to an input, as signals. See `FieldState` and `FieldController` in `@runic-artifex/views`. */
13
+ export interface FieldHandle<TValue> {
14
+ /** The draft while one exists, otherwise the member's value in the View's state. */
15
+ readonly value: Signal<TValue>;
16
+ /** What a text input shows: the text typed while it does not parse or still means `value`, otherwise `value` formatted. */
17
+ readonly text: Signal<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, which
21
+ * the field's own write causes.
22
+ */
23
+ readonly editing: Signal<boolean>;
24
+ /** Why the latest write or text failed: a `BridgeError` of the write, or a `FieldError`. `undefined` otherwise. */
25
+ readonly error: Signal<unknown>;
26
+ /** The member's validation messages; `[]` when valid. */
27
+ readonly errors: Signal<readonly string[]>;
28
+ /** The producer's value and version while a checked write's `conflict` keeps the draft. */
29
+ readonly conflict: Signal<FieldBaseline<TValue> | undefined>;
30
+ /** The definition's `kind`, `nullable`, `integer` and `choices`. */
31
+ readonly field: FieldController<unknown, unknown, TValue>["field"];
32
+ /** The user changed the value, such as a checkbox's `checked`. */
33
+ input(value: TValue): void;
34
+ /** The user changed the text: pass the `input` event, or the text. It is parsed for the field's kind. */
35
+ inputText(event: Event | string): void;
36
+ /** An IME composition started: the text is kept but not written until it ends. Bind it to `compositionstart`. */
37
+ compositionStart(): void;
38
+ /** The IME composition ended: pass the `compositionend` event, or the text, which is then written. */
39
+ compositionEnd(event: Event | string): void;
40
+ /**
41
+ * The user is done with the field (bind it to `blur`): with `commit: "pause"` the draft is written now. Resolves
42
+ * with the field's state once its writes settled, so a command that depends on the field can follow it.
43
+ */
44
+ commit(): Promise<FieldState<TValue>>;
45
+ /** Writes the draft again after a failed write; after a `conflict`, over the producer's value. */
46
+ retry(): void;
47
+ /** Drops the draft, the error and a conflict and shows the View's value. Writes in flight still complete. */
48
+ reset(): void;
49
+ }
50
+ /**
51
+ * Binds one member of a View to an input for the lifetime of the injection context, through
52
+ * `createFieldController`: pass a generated descriptor such as `EditorFields.title`. Typing never loses characters,
53
+ * nothing is written during IME composition, checked-write receipts and the member's validation show as `error`,
54
+ * `errors` and `conflict`, and once the last write settled the field shows the View's value.
55
+ *
56
+ * ```ts
57
+ * readonly editor = injectView(this.page);
58
+ * readonly title = injectField(this.editor, EditorFields.title);
59
+ * // <input [runicField]="title"> with RunicFieldDirective from @runic-artifex/angular/forms, or by hand:
60
+ * // <input [value]="title.text()" (input)="title.inputText($event)" (blur)="title.commit()"
61
+ * // (compositionstart)="title.compositionStart()" (compositionend)="title.compositionEnd($event)">
62
+ * ```
63
+ */
64
+ export declare function injectField<TClient extends ViewClient, TValue>(view: FieldView<TClient>, field: BridgeField<TClient, TClient["snapshot"], TValue> | FieldDefinition<TClient, TClient["snapshot"], TValue>, { injector: provided, ...options }?: InjectFieldOptions): FieldHandle<TValue>;
@@ -0,0 +1,56 @@
1
+ import { assertInInjectionContext, computed, DestroyRef, effect, inject, Injector, signal, untracked } from "@angular/core";
2
+ import { createFieldController, } 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 one member of a View to an input for the lifetime of the injection context, through
11
+ * `createFieldController`: pass a generated descriptor such as `EditorFields.title`. Typing never loses characters,
12
+ * nothing is written during IME composition, checked-write receipts and the member's validation show as `error`,
13
+ * `errors` and `conflict`, and once the last write settled the field shows the View's value.
14
+ *
15
+ * ```ts
16
+ * readonly editor = injectView(this.page);
17
+ * readonly title = injectField(this.editor, EditorFields.title);
18
+ * // <input [runicField]="title"> with RunicFieldDirective from @runic-artifex/angular/forms, or by hand:
19
+ * // <input [value]="title.text()" (input)="title.inputText($event)" (blur)="title.commit()"
20
+ * // (compositionstart)="title.compositionStart()" (compositionend)="title.compositionEnd($event)">
21
+ * ```
22
+ */
23
+ export function injectField(view, field, { injector: provided, ...options } = {}) {
24
+ if (!provided)
25
+ assertInInjectionContext(injectField);
26
+ const injector = provided ?? inject(Injector);
27
+ const controller = createFieldController(field, options);
28
+ const current = signal(controller.current, /* @ts-ignore */
29
+ ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
30
+ controller.subscribe(() => current.set(controller.current));
31
+ effect(() => {
32
+ const state = view.state();
33
+ const client = view.client();
34
+ untracked(() => {
35
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
36
+ current.set(controller.current);
37
+ });
38
+ }, { injector });
39
+ injector.get(DestroyRef).onDestroy(() => controller.dispose());
40
+ return {
41
+ value: computed(() => current().value),
42
+ text: computed(() => current().text),
43
+ editing: computed(() => current().editing),
44
+ error: computed(() => current().error),
45
+ errors: computed(() => current().errors),
46
+ conflict: computed(() => current().conflict),
47
+ field: controller.field,
48
+ input(value) { controller.input(value); },
49
+ inputText(event) { controller.inputText(textOf(event)); },
50
+ compositionStart() { controller.compositionStart(); },
51
+ compositionEnd(event) { controller.compositionEnd(textOf(event)); },
52
+ commit() { return controller.commit(); },
53
+ retry() { controller.retry(); },
54
+ reset() { controller.reset(); },
55
+ };
56
+ }
@@ -29,6 +29,6 @@ export function injectLatestOperation({ injector: provided } = {}) {
29
29
  pending: field("pending"), admitting: field("admitting"), operation: field("operation"), status: field("status"),
30
30
  outcome: field("outcome"), failure: field("failure"), error: field("error"), cancelled: field("cancelled"),
31
31
  cancellationRequested: field("cancellationRequested"), cancelling: field("cancelling"),
32
- cancellation: field("cancellation"), cancelError: field("cancelError"), blocked: field("blocked"),
32
+ progress: field("progress"), cancellation: field("cancellation"), cancelError: field("cancelError"), blocked: field("blocked"),
33
33
  };
34
34
  }
@@ -23,7 +23,7 @@ export function injectMenuBar({ injector: provided, onRequest, ...options } = {}
23
23
  ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
24
24
  return {
25
25
  state: state.asReadonly(),
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
  }
@@ -27,6 +27,6 @@ export function injectOperation(start, { injector: provided, ...options } = {})
27
27
  pending: field("pending"), admitting: field("admitting"), operation: field("operation"), status: field("status"),
28
28
  outcome: field("outcome"), failure: field("failure"), error: field("error"), cancelled: field("cancelled"),
29
29
  cancellationRequested: field("cancellationRequested"), cancelling: field("cancelling"),
30
- cancellation: field("cancellation"), cancelError: field("cancelError"),
30
+ progress: field("progress"), cancellation: field("cancellation"), cancelError: field("cancelError"),
31
31
  };
32
32
  }
@@ -0,0 +1,55 @@
1
+ import { Injector, type Signal } from "@angular/core";
2
+ import { type ViewClient } from "@runic-artifex/views";
3
+ /** A text input bound to one View member. */
4
+ export interface TextFieldHandle {
5
+ /** What the input shows: the draft while one exists, otherwise the member's value in the View's state. */
6
+ readonly value: Signal<string>;
7
+ /**
8
+ * True while a draft exists, from the first input until the last write settled and the state caught up, and after a
9
+ * failed write. Keep the input enabled while it is true, rather than disabling it on the View's busy state, which
10
+ * the field's own write causes.
11
+ */
12
+ readonly editing: Signal<boolean>;
13
+ /** Why the latest write failed, until the next input or `reset()`. */
14
+ readonly error: Signal<unknown>;
15
+ /** The user changed the text: pass the `input` event, or the new text. */
16
+ input(event: Event | string): void;
17
+ /** An IME composition started: the text is kept but not written until it ends. Bind it to `compositionstart`. */
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 InjectTextFieldOptions {
25
+ /** Required outside an injection context. */
26
+ readonly injector?: Injector;
27
+ /**
28
+ * With `true` (the default) at most one write is in flight, and text typed meanwhile is written next, as one
29
+ * value. With `false` every input is written.
30
+ */
31
+ readonly coalesce?: boolean;
32
+ /** With `true` (the default) a failed write keeps the draft and sets `error`; with `false` the field shows the View's value again. */
33
+ readonly keepDraftOnError?: boolean;
34
+ }
35
+ /** The View a text field binds to: an {@link injectView} handle, or any pair of state and client signals. */
36
+ export interface TextFieldView<TClient extends ViewClient> {
37
+ readonly state: Signal<TClient["snapshot"] | undefined>;
38
+ readonly client: Signal<TClient | undefined>;
39
+ }
40
+ /**
41
+ * Binds a text input to one member of a View for the lifetime of the injection context, through
42
+ * `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
43
+ * shows what the user typed, at most one write is in flight (newer text is written next), nothing is written during
44
+ * IME composition, and once the last write settled it shows the View's value, including any normalization.
45
+ *
46
+ * ```ts
47
+ * readonly person = injectView(this.page);
48
+ * readonly name = injectTextField(this.person, state => state.name, (client, value) => client.setName(value));
49
+ * // <input [value]="name.value()" (input)="name.input($event)"
50
+ * // (compositionstart)="name.compositionStart()" (compositionend)="name.compositionEnd($event)">
51
+ * ```
52
+ *
53
+ * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
54
+ */
55
+ export declare function injectTextField<TClient extends ViewClient>(view: TextFieldView<TClient>, read: (state: TClient["snapshot"]) => string, write: (client: TClient, value: string) => Promise<unknown>, { injector: provided, ...options }?: InjectTextFieldOptions): TextFieldHandle;
@@ -0,0 +1,50 @@
1
+ import { assertInInjectionContext, computed, DestroyRef, effect, inject, Injector, signal, untracked } from "@angular/core";
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 for the lifetime of the injection context, through
11
+ * `createTextFieldController`. Typing key by key never loses characters: while its writes are in flight the field
12
+ * shows what the user typed, at most one write is in flight (newer text is written next), nothing is written during
13
+ * IME composition, and once the last write settled it shows the View's value, including any normalization.
14
+ *
15
+ * ```ts
16
+ * readonly person = injectView(this.page);
17
+ * readonly name = injectTextField(this.person, state => state.name, (client, value) => client.setName(value));
18
+ * // <input [value]="name.value()" (input)="name.input($event)"
19
+ * // (compositionstart)="name.compositionStart()" (compositionend)="name.compositionEnd($event)">
20
+ * ```
21
+ *
22
+ * `write` may be a generated setter, a command or a checked write. Its failure sets `error` and keeps the draft.
23
+ */
24
+ export function injectTextField(view, read, write, { injector: provided, ...options } = {}) {
25
+ if (!provided)
26
+ assertInInjectionContext(injectTextField);
27
+ const injector = provided ?? inject(Injector);
28
+ const controller = createTextFieldController({ read, write, ...options });
29
+ const current = signal(controller.current, /* @ts-ignore */
30
+ ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
31
+ controller.subscribe(() => current.set(controller.current));
32
+ effect(() => {
33
+ const state = view.state();
34
+ const client = view.client();
35
+ untracked(() => {
36
+ controller.setSource(state === undefined || client === undefined ? undefined : { state, client });
37
+ current.set(controller.current);
38
+ });
39
+ }, { injector });
40
+ injector.get(DestroyRef).onDestroy(() => controller.dispose());
41
+ return {
42
+ value: computed(() => current().value),
43
+ editing: computed(() => current().editing),
44
+ error: computed(() => current().error),
45
+ input(event) { controller.input(textOf(event)); },
46
+ compositionStart() { controller.compositionStart(); },
47
+ compositionEnd(event) { controller.compositionEnd(textOf(event)); },
48
+ reset() { controller.reset(); },
49
+ };
50
+ }
@@ -0,0 +1,39 @@
1
+ import { type Resource, type Signal } from "@angular/core";
2
+ import { type ViewClient, type ViewSource } from "@runic-artifex/views";
3
+ import type { InjectViewOptions } from "./inject-view.js";
4
+ /**
5
+ * A View connection as an Angular `Resource`: `value()` is the View's state, `status()` is `loading` until the
6
+ * client connected (`reloading` after `reload()`), then `resolved`, or `error` with `error()` the connection
7
+ * failure; `idle` while the source is `null` or `undefined`.
8
+ */
9
+ export interface ViewResource<TClient extends ViewClient> extends Resource<TClient["snapshot"] | undefined> {
10
+ /** The connected client for commands, or undefined until it connects. */
11
+ readonly client: Signal<TClient | undefined>;
12
+ /** Connects again, for example after a failure. Returns false while the source is `null` or `undefined`. */
13
+ reload(): boolean;
14
+ /** Releases the client and returns the resource to `idle`; the injector's destruction does this too. */
15
+ destroy(): void;
16
+ }
17
+ export type InjectViewResourceOptions<TClient extends ViewClient> = InjectViewOptions<TClient>;
18
+ /**
19
+ * Connects a generated View reference as an Angular `resource()` for the lifetime of the injection context, the
20
+ * asynchronous counterpart of `injectView` (D053.11): a template branches on `hasValue()`, `isLoading()` and
21
+ * `error()` as for any resource, and `value()` is never `undefined` once `hasValue()` is true.
22
+ *
23
+ * ```ts
24
+ * readonly page = input.required<CounterPageReference>();
25
+ * readonly counter = injectViewResource(this.page);
26
+ * ```
27
+ * ```html
28
+ * @if (counter.hasValue()) {
29
+ * <button (click)="counter.client()?.increment()">{{ counter.value().count }}</button>
30
+ * } @else if (counter.error()) {
31
+ * <p role="alert">{{ describe(counter.error()) }}</p> <button (click)="counter.reload()">Retry</button>
32
+ * } @else { <p>Connecting…</p> }
33
+ * ```
34
+ *
35
+ * A changed reference (by its `connect` function) releases the previous client and loads the new one. Released
36
+ * clients are kept for `keepAlive` milliseconds, as with `injectView`, so a component that is created again
37
+ * resolves at once.
38
+ */
39
+ export declare function injectViewResource<TClient extends ViewClient>(source: Signal<ViewSource<TClient>> | ViewSource<TClient>, options?: InjectViewResourceOptions<TClient>): ViewResource<TClient>;
@@ -0,0 +1,95 @@
1
+ import { assertInInjectionContext, computed, effect, inject, Injector, isSignal, resource, signal, untracked, } from "@angular/core";
2
+ import { createViewController } from "@runic-artifex/views";
3
+ import { viewSourceIdentity } from "@runic-artifex/views/bindings";
4
+ function asError(cause) {
5
+ return cause instanceof Error ? cause : new Error(String(cause), { cause });
6
+ }
7
+ /**
8
+ * Connects a generated View reference as an Angular `resource()` for the lifetime of the injection context, the
9
+ * asynchronous counterpart of `injectView` (D053.11): a template branches on `hasValue()`, `isLoading()` and
10
+ * `error()` as for any resource, and `value()` is never `undefined` once `hasValue()` is true.
11
+ *
12
+ * ```ts
13
+ * readonly page = input.required<CounterPageReference>();
14
+ * readonly counter = injectViewResource(this.page);
15
+ * ```
16
+ * ```html
17
+ * @if (counter.hasValue()) {
18
+ * <button (click)="counter.client()?.increment()">{{ counter.value().count }}</button>
19
+ * } @else if (counter.error()) {
20
+ * <p role="alert">{{ describe(counter.error()) }}</p> <button (click)="counter.reload()">Retry</button>
21
+ * } @else { <p>Connecting…</p> }
22
+ * ```
23
+ *
24
+ * A changed reference (by its `connect` function) releases the previous client and loads the new one. Released
25
+ * clients are kept for `keepAlive` milliseconds, as with `injectView`, so a component that is created again
26
+ * resolves at once.
27
+ */
28
+ export function injectViewResource(source, options = {}) {
29
+ if (!options.injector)
30
+ assertInInjectionContext(injectViewResource);
31
+ const injector = options.injector ?? inject(Injector);
32
+ const read = () => isSignal(source) ? source() : source;
33
+ const client = signal(undefined, /* @ts-ignore */
34
+ ...(ngDevMode ? [{ debugName: "client" }] : /* istanbul ignore next */ []));
35
+ const controllerOptions = {
36
+ ...(options.release ? { release: options.release } : {}),
37
+ ...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }),
38
+ };
39
+ // The source is identified by its client or `connect` function, so a new wrapper object does not reload.
40
+ const identity = computed(() => viewSourceIdentity(read()), /* @ts-ignore */
41
+ ...(ngDevMode ? [{ debugName: "identity" }] : /* istanbul ignore next */ []));
42
+ // The controller of the latest load. A resource that becomes idle does not abort its last load, so it is released here.
43
+ let active;
44
+ effect(() => {
45
+ if (identity() !== undefined)
46
+ return;
47
+ active?.dispose();
48
+ active = undefined;
49
+ client.set(undefined);
50
+ }, { injector });
51
+ const ref = resource({ ...(ngDevMode ? { debugName: "ref" } : /* istanbul ignore next */ {}), injector,
52
+ params: () => identity(),
53
+ stream: async ({ abortSignal }) => {
54
+ const controller = createViewController(controllerOptions);
55
+ active = controller;
56
+ abortSignal.addEventListener("abort", () => {
57
+ if (active === controller)
58
+ active = undefined;
59
+ controller.dispose();
60
+ if (untracked(client) === controller.current.client)
61
+ client.set(undefined);
62
+ }, { once: true });
63
+ controller.setSource(untracked(read));
64
+ if (controller.current.pending) {
65
+ await new Promise(resolve => {
66
+ const stop = controller.subscribe(() => { if (!controller.current.pending) {
67
+ stop();
68
+ resolve();
69
+ } });
70
+ abortSignal.addEventListener("abort", () => { stop(); resolve(); }, { once: true });
71
+ });
72
+ }
73
+ const value = signal(controller.current.error !== undefined ? { error: asError(controller.current.error) } : { value: controller.current.state });
74
+ if (abortSignal.aborted)
75
+ return value;
76
+ client.set(controller.current.client);
77
+ controller.subscribe(() => {
78
+ const current = controller.current;
79
+ client.set(current.client);
80
+ value.set(current.error !== undefined ? { error: asError(current.error) } : { value: current.state });
81
+ });
82
+ return value;
83
+ } });
84
+ return {
85
+ value: ref.value.asReadonly(),
86
+ status: ref.status,
87
+ error: ref.error,
88
+ isLoading: ref.isLoading,
89
+ snapshot: ref.snapshot,
90
+ hasValue: () => ref.hasValue(),
91
+ client: client.asReadonly(),
92
+ reload: () => ref.reload(),
93
+ destroy: () => ref.destroy(),
94
+ };
95
+ }
@@ -17,6 +17,12 @@ export interface InjectViewOptions<TClient extends ViewClient> {
17
17
  readonly injector?: Injector;
18
18
  /** Releases a client this helper connected. Defaults to `client.dispose()`. */
19
19
  readonly release?: (client: TClient) => void;
20
+ /**
21
+ * Milliseconds a client this helper connected stays connected after the component unmounts or the source changes,
22
+ * for the next helper that follows the same reference (StrictMode, HMR, `<Activity>`, A→B→A navigation). `0`
23
+ * disposes it at once. Defaults to 2000. Read once, when the helper is created.
24
+ */
25
+ readonly keepAlive?: number;
20
26
  }
21
27
  /**
22
28
  * Connects a generated View reference for the lifetime of the injection
@@ -24,6 +30,11 @@ export interface InjectViewOptions<TClient extends ViewClient> {
24
30
  * signal, such as a `page` input, to follow it: a changed reference releases
25
31
  * the previous client and connects the new one.
26
32
  *
33
+ * A released client stays connected for `keepAlive` milliseconds (2000 by
34
+ * default), and the next `injectView` of the same reference takes it over with
35
+ * its state: an `@if` that toggles, HMR and A→B→A navigation show the View at
36
+ * once instead of opening the route again.
37
+ *
27
38
  * A reference is identified by its `connect` function, so a signal producing a
28
39
  * new `{ connect: connectShell }` object does not reconnect.
29
40
  */
@@ -1,12 +1,17 @@
1
1
  import { assertInInjectionContext, computed, DestroyRef, effect, inject, Injector, isSignal, signal, untracked } from "@angular/core";
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
  /**
5
5
  * Connects a generated View reference for the lifetime of the injection
6
6
  * context (normally a component) and exposes its state as signals. Pass a
7
7
  * signal, such as a `page` input, to follow it: a changed reference releases
8
8
  * the previous client and connects the new one.
9
9
  *
10
+ * A released client stays connected for `keepAlive` milliseconds (2000 by
11
+ * default), and the next `injectView` of the same reference takes it over with
12
+ * its state: an `@if` that toggles, HMR and A→B→A navigation show the View at
13
+ * once instead of opening the route again.
14
+ *
10
15
  * A reference is identified by its `connect` function, so a signal producing a
11
16
  * new `{ connect: connectShell }` object does not reconnect.
12
17
  */
@@ -14,7 +19,10 @@ export function injectView(source, options = {}) {
14
19
  if (!options.injector)
15
20
  assertInInjectionContext(injectView);
16
21
  const injector = options.injector ?? inject(Injector);
17
- const controller = createViewController(options.release ? { release: options.release } : {});
22
+ const controller = createViewController({
23
+ ...(options.release ? { release: options.release } : {}),
24
+ ...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }),
25
+ });
18
26
  const current = signal(controller.current, /* @ts-ignore */
19
27
  ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
20
28
  controller.subscribe(() => current.set(controller.current));
@@ -37,17 +45,20 @@ export function injectView(source, options = {}) {
37
45
  });
38
46
  }, { injector });
39
47
  injector.get(DestroyRef).onDestroy(() => controller.dispose());
48
+ // A connected client is readable before the effect observes it, and so is a client kept for the reference
49
+ // (keep-alive), so a component that is created again shows its View at once.
50
+ const preview = computed(() => {
51
+ const value = observed();
52
+ if (value)
53
+ return value === current().client ? undefined : viewSourcePreview(value);
54
+ return fresh() ? undefined : viewSourcePreview(read());
55
+ }, /* @ts-ignore */
56
+ ...(ngDevMode ? [{ debugName: "preview" }] : /* istanbul ignore next */ []));
40
57
  return {
41
- // A connected client is readable before the effect observes it.
42
- state: computed(() => {
43
- const value = observed();
44
- if (value && value !== current().client)
45
- return value.snapshot;
46
- return fresh() ? current().state : undefined;
47
- }),
48
- client: computed(() => observed() ?? (fresh() ? current().client : undefined)),
58
+ state: computed(() => preview()?.state ?? (fresh() ? current().state : undefined)),
59
+ client: computed(() => preview()?.client ?? (fresh() ? current().client : undefined)),
49
60
  error: computed(() => fresh() ? current().error : undefined),
50
- pending: computed(() => observed() ? false : fresh() ? current().pending : identity() !== undefined),
61
+ pending: computed(() => preview() ? false : fresh() ? current().pending : identity() !== undefined),
51
62
  retry: () => controller.retry(),
52
63
  };
53
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/angular",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -8,11 +8,22 @@
8
8
  "import": "./dist/esm/index.js",
9
9
  "default": "./dist/esm/index.js"
10
10
  },
11
+ "./forms": {
12
+ "types": "./dist/esm/forms/index.d.ts",
13
+ "import": "./dist/esm/forms/index.js",
14
+ "default": "./dist/esm/forms/index.js"
15
+ },
11
16
  "./package.json": "./package.json"
12
17
  },
13
18
  "peerDependencies": {
14
19
  "@angular/core": ">=22.0.0 <23",
15
- "@runic-artifex/views": "0.12.1"
20
+ "@angular/forms": ">=22.0.0 <23",
21
+ "@runic-artifex/views": "0.14.0"
22
+ },
23
+ "peerDependenciesMeta": {
24
+ "@angular/forms": {
25
+ "optional": true
26
+ }
16
27
  },
17
28
  "description": "Angular outlet and signals for Runic Views",
18
29
  "license": "MIT",
@@ -21,7 +32,7 @@
21
32
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
22
33
  "directory": "packages/web/angular"
23
34
  },
24
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.1/packages/web/angular#readme",
35
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/angular#readme",
25
36
  "bugs": {
26
37
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
27
38
  },
@@ -45,15 +56,18 @@
45
56
  "pack:check": "bun pm pack --dry-run"
46
57
  },
47
58
  "devDependencies": {
48
- "@runic-artifex/views": "0.12.1",
59
+ "@runic-artifex/views": "0.14.0",
49
60
  "@angular/common": "22.2.3",
50
61
  "@angular/compiler": "22.2.3",
51
62
  "@angular/compiler-cli": "22.2.3",
52
63
  "@angular/core": "22.2.3",
64
+ "@angular/forms": "22.2.3",
53
65
  "@angular/platform-browser": "22.2.3",
66
+ "esbuild": "0.28.2",
54
67
  "happy-dom": "21.0.4",
68
+ "playwright-core": "1.63.0",
55
69
  "typescript": "6.0.3",
56
70
  "vitest": "5.0.3"
57
71
  },
58
- "gitHead": "124a532e5861cff03e77d2ef0c5d4f081ee99a47"
72
+ "gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
59
73
  }