@runic-artifex/angular 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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.
@@ -79,7 +138,7 @@ export class CounterPage {
79
138
 
80
139
  Bind a text input to a member with `injectTextField(view, read, write, options?)`,
81
140
  which wraps the framework-neutral
82
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#text-inputs)
141
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#text-inputs)
83
142
  for the lifetime of the injection context:
84
143
 
85
144
  ```ts
@@ -107,15 +166,161 @@ frame that answers an older keystroke never replaces newer text. At most one wri
107
166
  in flight; text typed meanwhile is written next as one value (`coalesce: false` writes
108
167
  every change). Nothing is written during IME composition. Once the last write settled,
109
168
  the field shows the View's value again, including any normalization the ViewModel
110
- applied (trimmed, upper-cased). `write` may also be a command or a checked write. A
111
- failed write keeps the draft and sets `error` (`keepDraftOnError: false` shows the
112
- View's value instead); `reset()` drops the draft. `editing` is true while a draft
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
113
174
  exists. Don't disable the input on the View's busy state (`isSaving`, `can…`) while
114
175
  the user types: the field's own write causes it, and keys typed meanwhile would be
115
176
  lost. Test such fields by typing key by key (Playwright `pressSequentially`, Testing
116
177
  Library `user.type`) against the mock with `latency: "slow"`; `fill()` sets the whole
117
178
  text at once and hides the race.
118
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.15.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 with the field's state
220
+ once its writes settled, so a command that depends on the field can follow it
221
+ and skip a failed write:
222
+ `if ((await this.title.commit()).error === undefined) await this.editor.client()?.save();`.
223
+ - `checked: true` writes with the member's checked write: a change by another writer
224
+ since the draft started is a conflict instead of being overwritten.
225
+ - `coalesce` and `keepDraftOnError`, as for `injectTextField`.
226
+
227
+ A checked write's receipt is read: `rejected` keeps the draft with a `FieldError`
228
+ `rejected`; `conflict` keeps the draft, sets `conflict` to the producer's
229
+ `{ value, version }` and writes nothing until `retry()` (write the draft over it) or
230
+ `reset()` (take the producer's value); `committed-with-error` keeps the committed value
231
+ with a `FieldError`. `errors` follows the member's validation in the View's state:
232
+
233
+ ```html
234
+ @if (title.conflict(); as theirs) {
235
+ <p role="alert">Changed elsewhere to “{{ theirs.value }}”.
236
+ <button (click)="title.retry()">Keep mine</button> <button (click)="title.reset()">Take theirs</button></p>
237
+ }
238
+ ```
239
+
240
+ ### `[runicField]` and Reactive Forms
241
+
242
+ `@runic-artifex/angular/forms` needs `@angular/forms` (an optional peer; the main
243
+ entry does not). `RunicFieldDirective` wires an `<input>`, `<textarea>` or
244
+ `<select>` in one attribute: input (`change` for checkboxes, radios and selects),
245
+ composition, `commit()` on blur, the element's `value` or `checked`, and
246
+ `aria-invalid`:
247
+
248
+ ```ts
249
+ import { RunicFieldDirective } from "@runic-artifex/angular/forms";
250
+
251
+ @Component({
252
+ selector: "editor-page",
253
+ imports: [RunicFieldDirective],
254
+ template: `<input [runicField]="title"> <input type="checkbox" [runicField]="pinned">`,
255
+ })
256
+ export class EditorPage {
257
+ readonly page = input.required<EditorPageReference>();
258
+ readonly editor = injectView(this.page);
259
+ readonly title = injectField(this.editor, EditorFields.title, { commit: "pause" });
260
+ readonly pinned = injectField(this.editor, EditorFields.pinned);
261
+ }
262
+ ```
263
+
264
+ It is also the `ControlValueAccessor` and validator of a `formControl` or
265
+ `formControlName` on the same element. The View's value flows into the control
266
+ without marking it dirty or emitting `valueChanges`, and a control's initial value
267
+ is not written; what the user types reaches the control as usual; `setValue`,
268
+ `patchValue` and `reset` write through to the View when they change the value (a
269
+ `null` from `reset()` of a nullable control is ignored for a non-nullable field);
270
+ `disable()` disables the element; and the control has the error
271
+ `{ runic: errors }` while the View reports validation messages for the member:
272
+
273
+ ```ts
274
+ import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms";
275
+
276
+ @Component({
277
+ selector: "editor-page",
278
+ imports: [RunicFieldDirective, ReactiveFormsModule],
279
+ template: `
280
+ <form [formGroup]="form">
281
+ <input formControlName="title" [runicField]="title">
282
+ @if (form.controls.title.errors?.["runic"]; as messages) { <p role="alert">{{ messages[0] }}</p> }
283
+ </form>
284
+ `,
285
+ })
286
+ export class EditorPage {
287
+ readonly page = input.required<EditorPageReference>();
288
+ readonly editor = injectView(this.page);
289
+ readonly title = injectField(this.editor, EditorFields.title);
290
+ readonly form = new FormGroup({ title: new FormControl("", { nonNullable: true }) });
291
+ }
292
+ ```
293
+
294
+ ### Signal Forms
295
+
296
+ `runicFieldModel(handle)` is a `WritableSignal` over a field for `form()` from
297
+ `@angular/forms/signals`: it reads `value`, and `set`/`update` call `input`.
298
+ `validateRunicField(path, handle)` adds the field's `errors` to the schema as
299
+ errors of kind `runic` with the message:
300
+
301
+ ```ts
302
+ import { form, FormField } from "@angular/forms/signals";
303
+ import { runicFieldModel, validateRunicField } from "@runic-artifex/angular/forms";
304
+
305
+ @Component({
306
+ selector: "editor-page",
307
+ imports: [FormField],
308
+ template: `<input [formField]="titleForm" (blur)="title.commit()">`,
309
+ })
310
+ export class EditorPage {
311
+ readonly page = input.required<EditorPageReference>();
312
+ readonly editor = injectView(this.page);
313
+ readonly title = injectField(this.editor, EditorFields.title);
314
+ readonly titleForm = form(runicFieldModel(this.title), path => validateRunicField(path, this.title));
315
+ }
316
+ ```
317
+
318
+ Signal Forms does not tell the field when the element loses focus: always bind
319
+ `(blur)="title.commit()"` next to `[formField]`, as above. Without it a
320
+ `commit: "pause"` field writes only after the pause, and a value typed just before
321
+ Save may still wait. `[formField]` also writes during IME composition; prefer
322
+ `[runicField]` where composition matters.
323
+
119
324
  ## Outlet
120
325
 
121
326
  Register a component for each generated View kind and pass the current
@@ -188,14 +393,14 @@ For example, a navigation command whose departure guard awaits a dialog's
188
393
  answer never completes while the answer waits behind it. Order such commands
189
394
  by dispatch instead: start the next one once the previous one has been sent,
190
395
  as the Notes example's
191
- [`WindowOperations.runDispatched`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/examples/notes-view-first/Angular/src/app/window-operations.ts)
396
+ [`WindowOperations.runDispatched`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/examples/notes-view-first/Angular/src/app/window-operations.ts)
192
397
  does for its navigation commands.
193
398
 
194
399
  ## Operations
195
400
 
196
401
  `injectOperation(start, options?)` observes a generated `start<Command>()` operation
197
402
  through the framework-neutral
198
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#operation-feedback-and-latest-selection)
403
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#operation-feedback-and-latest-selection)
199
404
  for the lifetime of the injection context:
200
405
 
201
406
  ```ts
@@ -221,7 +426,7 @@ context.
221
426
 
222
427
  `injectLatestOperation(options?)` admits only the newest of several reads, for example
223
428
  loading the item the user selected last, through the framework-neutral
224
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#operation-feedback-and-latest-selection).
429
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#operation-feedback-and-latest-selection).
225
430
  Each `run(intent)` replaces the queued intent and cancels the active read; the next
226
431
  read starts only after the previous one reaches its terminal status and the intent's
227
432
  optional `waitForCompletion` barrier:
@@ -251,9 +456,9 @@ cancelling accepted work. Pass `injector` outside an injection context.
251
456
  host for the lifetime of the injection context. It wraps `onBridgeConnection`
252
457
  from `@runic-artifex/views` (re-exported here since 0.11, with the
253
458
  `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns `{ state }`, a signal of a
254
- `BridgeConnectionState`: `connecting`, `connected`, `reconnecting` or `lost` (a
255
- closed set, see
256
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#connection-state)):
459
+ `BridgeConnectionState`: `connecting`, `connected`, `reconnecting`, `lost` or `closed` (the
460
+ application closed the window, since 0.15; a closed set, see
461
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#connection-state)):
257
462
 
258
463
  ```ts
259
464
  import { injectBridgeConnection } from "@runic-artifex/angular";
@@ -271,7 +476,7 @@ not observe and stays `connecting`. An invalid `lostAfter` throws a `RangeError`
271
476
  `injectMenuBar(options?)` follows the declared menu bar of a Runic Desktop
272
477
  window that leaves it to the page (`DesktopMenuBarPresentation.Page`) for the
273
478
  lifetime of the injection context. It wraps `createMenuBarController` from
274
- `@runic-artifex/views` (see [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#in-page-menu-bar))
479
+ `@runic-artifex/views` (see [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#in-page-menu-bar))
275
480
  and returns `{ state, invoke, handleKeyDown }`, where `state` is a signal of a
276
481
  `MenuBarState`. The bar is rendered by the application's own menubar, for
277
482
  example the CDK Menu's `cdkMenuBar`. Runic ships no menubar component.
@@ -296,7 +501,7 @@ it creates none and stays `connecting`.
296
501
  ### With the CDK Menu
297
502
 
298
503
  The CDK's `cdkMenuBar` with `CdkMenuTrigger.open()` for `open` requests; the
299
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
504
+ [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
300
505
  items (`cdkMenuItemCheckbox`, `cdkMenuItemRadio` in a `cdkMenuGroup`) and is
301
506
  tested with real keys:
302
507
 
@@ -349,18 +554,20 @@ export class AppMenuBar {
349
554
 
350
555
  The `error()` signal of `injectView` and of a command or operation is typed
351
556
  `unknown`: it holds whatever the connection or the call rejected with. A Bridge
352
- failure is a `BridgeError` from `@runic-artifex/views`; narrow it with
353
- `instanceof` before reading `kind`, `route` or `detail`:
557
+ failure is a `BridgeError` from `@runic-artifex/views`. Show it with
558
+ `describeBridgeError(error)`, one English sentence, instead of interpolating
559
+ the error, and narrow it with `isBridgeError` (or `instanceof`) before reading
560
+ `kind`, `route` or `detail`:
354
561
 
355
562
  ```ts
356
- import { BridgeError } from "@runic-artifex/views";
563
+ import { describeBridgeError, isBridgeError } from "@runic-artifex/views";
357
564
 
358
- const error = this.view.error();
359
- const offline = error instanceof BridgeError && error.kind === "disconnected";
565
+ readonly offline = computed(() => isBridgeError(this.view.error(), "disconnected"));
566
+ readonly message = computed(() => describeBridgeError(this.view.error()));
360
567
  ```
361
568
 
362
569
  `instanceof` holds for errors from every copy of the package on the page.
363
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#errors-and-diagnostics)
570
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#errors-and-diagnostics)
364
571
  lists the kinds. Any other value, such as an exception that your own connect
365
572
  function or command callback throws, arrives unchanged.
366
573
 
@@ -411,16 +618,16 @@ application's own dialog.
411
618
  departure before that is answered by the ViewModel's .NET fallback handler, or
412
619
  fails closed without one.
413
620
 
414
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.13.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
621
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
415
622
  has the .NET side and which View answers which departure. In a frontend test,
416
623
  the generated mock's `interactions.<name>.request(input)` resolves with the
417
- registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#testing).
624
+ registered handler's answer; see the [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#testing).
418
625
 
419
626
  ## Collection viewports
420
627
 
421
628
  `injectCollectionViewport(element, options)` follows a fixed-row-height scroll
422
629
  container and returns a signal with its
423
- [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/views#collectionviewportoptions)
630
+ [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/views#collectionviewportoptions)
424
631
  range. Pass the container as a signal, such as a `viewChild`, and the options as
425
632
  a function or signal, then send the range to the ViewModel from an effect:
426
633
 
@@ -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,9 @@
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";
5
7
  export { injectTextField, type InjectTextFieldOptions, type TextFieldHandle, type TextFieldView } from "./inject-text-field.js";
6
8
  export { injectLatestOperation, type InjectLatestOperationOptions, type LatestOperationHandle, } from "./inject-latest-operation.js";
7
9
  export { injectCollectionViewport, type InjectCollectionViewportOptions } from "./inject-collection-viewport.js";
package/dist/esm/index.js CHANGED
@@ -1,7 +1,9 @@
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";
5
7
  export { injectTextField } from "./inject-text-field.js";
6
8
  export { injectLatestOperation, } from "./inject-latest-operation.js";
7
9
  export { injectCollectionViewport } from "./inject-collection-viewport.js";
@@ -9,8 +9,8 @@ export interface InjectBridgeConnectionOptions extends BridgeConnectionOptions {
9
9
  readonly injector?: Injector;
10
10
  }
11
11
  /**
12
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting` or
13
- * `lost`) as a signal through `onBridgeConnection`, for the lifetime of the injection context.
12
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
13
+ * `lost` or `closed`) as a signal through `onBridgeConnection`, for the lifetime of the injection context.
14
14
  * Destruction unsubscribes. Under server rendering (`PLATFORM_ID` `"server"`) it does not
15
15
  * observe and stays `connecting`.
16
16
  *
@@ -1,8 +1,8 @@
1
1
  import { assertInInjectionContext, DestroyRef, inject, Injector, PLATFORM_ID, signal } from "@angular/core";
2
2
  import { onBridgeConnection } from "@runic-artifex/views";
3
3
  /**
4
- * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting` or
5
- * `lost`) as a signal through `onBridgeConnection`, for the lifetime of the injection context.
4
+ * Follows the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`,
5
+ * `lost` or `closed`) as a signal through `onBridgeConnection`, for the lifetime of the injection context.
6
6
  * Destruction unsubscribes. Under server rendering (`PLATFORM_ID` `"server"`) it does not
7
7
  * observe and stays `connecting`.
8
8
  *
@@ -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
+ }
@@ -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.13.0",
3
+ "version": "0.15.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.13.0"
20
+ "@angular/forms": ">=22.0.0 <23",
21
+ "@runic-artifex/views": "0.15.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.13.0/packages/web/angular#readme",
35
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/angular#readme",
25
36
  "bugs": {
26
37
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
27
38
  },
@@ -45,11 +56,12 @@
45
56
  "pack:check": "bun pm pack --dry-run"
46
57
  },
47
58
  "devDependencies": {
48
- "@runic-artifex/views": "0.13.0",
59
+ "@runic-artifex/views": "0.15.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",
54
66
  "esbuild": "0.28.2",
55
67
  "happy-dom": "21.0.4",
@@ -57,5 +69,5 @@
57
69
  "typescript": "6.0.3",
58
70
  "vitest": "5.0.3"
59
71
  },
60
- "gitHead": "3331f81c7a2de34e209b53eb07515323d6d15cf3"
72
+ "gitHead": "c94bda07cf363bad056eda86ae77c514b66e61dd"
61
73
  }