@dsivd/prestations-ng 19.2.0-beta.21 → 19.2.0-beta.23

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.
@@ -1,20 +1,29 @@
1
1
  import { isComponentReceiver } from "../template-ast.mjs";
2
- import { astOf, readsForm, resolveRoot } from "../form-reads.mjs";
2
+ import { astOf, resolveRoot } from "../form-reads.mjs";
3
3
 
4
4
  /**
5
- * ESLint rule: a `@for` over a list of the form of the page whose rows edit their
6
- * item must not track the rows by the item itself (`track child`).
5
+ * ESLint rule: a `@for` over a list of the form of the page, or over the list held by the
6
+ * `model` of the component, whose rows edit their item must not track the rows by the item
7
+ * itself (`track child`).
7
8
  *
8
- * The form is never modified in place: writing a field of an item (`patchForm()`,
9
- * `patchItem()`) replaces the item with a copy. A row tracked by its item is then destroyed and
10
- * created again at every input, and the field being edited loses the focus. Track the rows by
11
- * `$index`, or by an identifier of the item (`track child.id`), which the copy keeps.
9
+ * These lists are never modified in place: writing a field of an item of the form
10
+ * (`patchForm()`, `patchItem()`) replaces the item with a copy, and a component extending
11
+ * `FoehnInputComponent` writes a new list in its model, its items replaced (`updateNgModel()`).
12
+ * A row tracked by its item is then destroyed and created again at every input, and the field
13
+ * being edited loses the focus; two items equal by value (e.g. two empty strings) even collide.
14
+ * Track the rows by `$index`, or by an identifier of the item (`track child.id`), which the copy
15
+ * keeps.
12
16
  *
13
17
  * A row edits its item when one of its elements has a `model` read from it
14
- * (`[model]="child.firstName"`, `[(model)]="child"`). A list only displayed is left alone.
18
+ * (`[model]="child.firstName"`, `[(model)]="child"`), or read from the list at the index of
19
+ * the row (`[model]="model()[i]"`, `let i = $index`). A list only displayed is left alone.
15
20
  * `$any(child)` counts as `child`.
16
21
  */
17
22
 
23
+ // The members holding a list whose items are replaced by a write: the form of the page, and
24
+ // the model of the component
25
+ const REPLACED_LISTS = new Set(["form", "model"]);
26
+
18
27
  /**
19
28
  * Whether the track expression of a `@for` is its item itself.
20
29
  */
@@ -34,12 +43,64 @@ function tracksItemItself(forBlock) {
34
43
  );
35
44
  }
36
45
 
46
+ /**
47
+ * Whether an expression reads a list whose items are replaced by a write: the form, or the
48
+ * model, directly or through a template name.
49
+ */
50
+ function readsReplacedList(expression, node) {
51
+ const root = resolveRoot(expression, node);
52
+ if (root?.forBlock) {
53
+ return readsReplacedList(
54
+ astOf(root.forBlock.expression),
55
+ root.forBlock.parent,
56
+ );
57
+ }
58
+ return REPLACED_LISTS.has(root?.member);
59
+ }
60
+
61
+ /**
62
+ * The `@for` whose list an expression reads at the index of the row (`model()[i]`,
63
+ * `form.children[$index].firstName`): an enclosing `@for` declaring the key as its `$index`
64
+ * (or an alias of it), over the same list, compared by its source.
65
+ */
66
+ function forBlockReadAtIndex(expression, node, textOf) {
67
+ for (let read = expression; read; read = read.receiver) {
68
+ if (read.type !== "KeyedRead" && read.type !== "SafeKeyedRead") {
69
+ continue;
70
+ }
71
+ const key = read.key;
72
+ if (key?.type !== "PropertyRead" || !isComponentReceiver(key.receiver)) {
73
+ continue;
74
+ }
75
+ for (let current = node; current; current = current.parent) {
76
+ if (current.type !== "ForLoopBlock") {
77
+ continue;
78
+ }
79
+ const variable = current.contextVariables?.find(
80
+ (contextVariable) => contextVariable.name === key.name,
81
+ );
82
+ if (!variable) {
83
+ continue;
84
+ }
85
+ // The innermost @for declaring the name binds it
86
+ if (
87
+ variable.value === "$index" &&
88
+ textOf(read.receiver) === textOf(astOf(current.expression))
89
+ ) {
90
+ return current;
91
+ }
92
+ break;
93
+ }
94
+ }
95
+ return undefined;
96
+ }
97
+
37
98
  export default {
38
99
  meta: {
39
100
  type: "problem",
40
101
  docs: {
41
102
  description:
42
- "Disallow tracking by the item itself the rows of a @for editing a list of the form",
103
+ "Disallow tracking by the item itself the rows of a @for editing a list of the form, or of the model of the component",
43
104
  category: "Possible Errors",
44
105
  recommended: true,
45
106
  },
@@ -47,7 +108,7 @@ export default {
47
108
  schema: [],
48
109
  messages: {
49
110
  itemTrack:
50
- "The rows of this list of the form are tracked by their item ('track {{item}}'): writing a field replaces the item, so its row is created again and the field being edited loses the focus. Track the rows by $index or by an identifier of the item.",
111
+ "The rows of this list are tracked by their item ('track {{item}}'): writing an item replaces it, so its row is created again and the field being edited loses the focus. Track the rows by $index or by an identifier of the item.",
51
112
  trackByIndex: "Track the rows by $index",
52
113
  },
53
114
  },
@@ -55,22 +116,34 @@ export default {
55
116
  create(context) {
56
117
  const candidates = [];
57
118
  const editingBlocks = new Set();
119
+ const textOf = (expression) =>
120
+ context.sourceCode.text
121
+ .slice(expression.sourceSpan.start, expression.sourceSpan.end)
122
+ .replace(/\s+/g, "");
58
123
 
59
124
  return {
60
125
  ForLoopBlock(node) {
61
126
  if (
62
127
  tracksItemItself(node) &&
63
- readsForm(astOf(node.expression), node.parent)
128
+ readsReplacedList(astOf(node.expression), node.parent)
64
129
  ) {
65
130
  candidates.push(node);
66
131
  }
67
132
  },
68
133
  Element(node) {
69
134
  const model = node.inputs?.find((input) => input.name === "model");
70
- const root = model && resolveRoot(astOf(model.value), node);
135
+ if (!model) {
136
+ return;
137
+ }
138
+ const expression = astOf(model.value);
139
+ const root = resolveRoot(expression, node);
71
140
  if (root?.forBlock) {
72
141
  editingBlocks.add(root.forBlock);
73
142
  }
143
+ const readAtIndex = forBlockReadAtIndex(expression, node, textOf);
144
+ if (readAtIndex) {
145
+ editingBlocks.add(readAtIndex);
146
+ }
74
147
  },
75
148
  "Program:exit"() {
76
149
  for (const forBlock of candidates) {
@@ -1,5 +1,5 @@
1
1
  import * as _angular_core from '@angular/core';
2
- import { ElementRef, OnInit, AfterViewInit, Signal, DestroyRef, WritableSignal, OnDestroy, InjectionToken, OnChanges, SimpleChanges, EnvironmentProviders, Injector, SimpleChange, AfterViewChecked, PipeTransform, TemplateRef, TrackByFunction, ErrorHandler, NgZone } from '@angular/core';
2
+ import { ElementRef, WritableSignal, OnInit, AfterViewInit, Signal, DestroyRef, OnDestroy, InjectionToken, OnChanges, SimpleChanges, EnvironmentProviders, Injector, SimpleChange, AfterViewChecked, PipeTransform, TemplateRef, TrackByFunction, ErrorHandler, NgZone } from '@angular/core';
3
3
  import { Params, Route, ActivatedRoute, ActivatedRouteSnapshot, CanActivateFn, Router, QueryParamsHandling } from '@angular/router';
4
4
  import { Observable, Subject, BehaviorSubject } from 'rxjs';
5
5
  import { NgModel, NgForm } from '@angular/forms';
@@ -121,6 +121,87 @@ interface FormError {
121
121
  message: string;
122
122
  }
123
123
 
124
+ type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7];
125
+ /**
126
+ * A path in an object: one of its keys, then the keys or the indexes of the objects and arrays it holds, e.g.
127
+ * `['firstName']`, `['address', 'locality']` or `['children', 0, 'firstName']`. For a union (`ApForm | AfForm`), the
128
+ * paths of each of its members.
129
+ */
130
+ type ObjectPath<T, D extends number = 7> = [D] extends [never] ? never : PathsOf<NonNullable<T>, D>;
131
+ type PathsOf<T, D extends number> = T extends readonly (infer E)[] ? [number] | [number, ...ObjectPath<E, Depth[D]>] : T extends object ? {
132
+ [K in keyof T & string]-?: [K] | [K, ...ObjectPath<T[K], Depth[D]>];
133
+ }[keyof T & string] : never;
134
+ /**
135
+ * The type of the value at a path of an object. For a union, the value in the members having the path.
136
+ */
137
+ type ObjectPathValue<T, P extends readonly unknown[]> = P extends readonly [infer K, ...infer R] ? ValueAtKey<NonNullable<T>, K, R> : T;
138
+ type ValueAtKey<T, K, R extends readonly unknown[]> = T extends readonly (infer E)[] ? ObjectPathValue<E, R> : K extends keyof T ? ObjectPathValue<T[K], R> : never;
139
+ /**
140
+ * Keys known at runtime only: a key with dots (`'address.street'`, `'children.0.firstName'`), or the list of the keys.
141
+ */
142
+ type ObjectKeys = string | readonly (string | number)[];
143
+ /**
144
+ * Reads and writes a value at a path of an object, without modifying the object: a write copies the objects and arrays
145
+ * along the path (with their prototype), and keeps the others as they are.
146
+ *
147
+ * A copy takes the own enumerable properties only: the objects along the path must be plain objects (e.g. the JSON of
148
+ * the backend), arrays or instances of classes with public fields. The copy of a `Date`, a `Map`, a `Set` or an
149
+ * instance with private fields (`#field`) loses their content, and their methods throw. The value written, and the
150
+ * objects beside the path, are not copied: they can be of any type.
151
+ *
152
+ * `get()`, `patch()` and `patchSignal()` take a path checked by TypeScript (a typo gives an error listing the valid
153
+ * keys). `getByKeys()` and `patchByKeys()` take keys known at runtime only (e.g. a key given as an input), not
154
+ * checked.
155
+ */
156
+ declare class ObjectPathHelper {
157
+ /**
158
+ * @param object an object
159
+ * @param path the keys and indexes leading to the value
160
+ * @returns the value at the path, `undefined` when an object of the path is `null` or `undefined`
161
+ */
162
+ static get<T, P extends ObjectPath<T>>(object: T, path: P): ObjectPathValue<T, P> | undefined;
163
+ /**
164
+ * Writes a value at a path of an object without modifying it.
165
+ *
166
+ * @param object an object
167
+ * @param path the keys and indexes leading to the value
168
+ * @param value the value to write
169
+ * @returns a new object, or the object itself when the value is already there
170
+ * @throws Error when an object of the path is `null` or `undefined`, as a write through it would
171
+ */
172
+ static patch<T, P extends ObjectPath<T>>(object: T, path: P, value: ObjectPathValue<T, P>): T;
173
+ /**
174
+ * Writes a value at a path of the object held by a signal, without modifying it in place: the signal gets a new
175
+ * object, and notifies its readers only when the value changes.
176
+ *
177
+ * @param signal a signal holding an object
178
+ * @param path the keys and indexes leading to the value
179
+ * @param value the value to write
180
+ * @throws Error when an object of the path, the value of the signal included, is `null` or `undefined`
181
+ */
182
+ static patchSignal<T, P extends ObjectPath<T>>(signal: WritableSignal<T>, path: P, value: ObjectPathValue<T, P>): void;
183
+ /**
184
+ * `get()` with keys known at runtime only, not checked by TypeScript.
185
+ *
186
+ * @param object an object
187
+ * @param keys `'address.street'`, or `['address', 'street']`
188
+ * @returns the value at the keys, `undefined` when an object of the path is `null` or `undefined`
189
+ */
190
+ static getByKeys(object: unknown, keys: ObjectKeys): unknown;
191
+ /**
192
+ * `patch()` with keys known at runtime only, not checked by TypeScript.
193
+ *
194
+ * @param object an object
195
+ * @param keys `'address.street'`, or `['address', 'street']`
196
+ * @param value the value to write
197
+ * @returns a new object, or the object itself when the value is already there
198
+ * @throws Error when an object of the path is `null` or `undefined`, as a write through it would
199
+ */
200
+ static patchByKeys<T>(object: T, keys: ObjectKeys, value: unknown): T;
201
+ private static keysOf;
202
+ private static patchFrom;
203
+ }
204
+
124
205
  /**
125
206
  * Interface representing a component that has custom error messages.
126
207
  * Used to break the dependency cycle between ValidationHandlerService and FoehnInputComponent.
@@ -236,7 +317,27 @@ declare abstract class FoehnInputComponent<T> implements OnInit, AfterViewInit {
236
317
  */
237
318
  onModelChange(_value: T | null | undefined): void;
238
319
  handleChange(value: T | null): void;
320
+ /**
321
+ * Writes the model, which the page gets through `modelChange`: always a new object or array, never the model
322
+ * modified in place. The model is a signal, which ignores the value it already holds: no `modelChange` would be
323
+ * emitted, and the page would never get the change. Also makes the model known (`model_`), and leaves the model
324
+ * of a disabled component alone, unless `updateModelWhenDisabled`.
325
+ *
326
+ * @param value the new model
327
+ */
239
328
  updateNgModel(value: T | null): void;
329
+ /**
330
+ * Writes a value at a path of the model, in a new model: the objects and arrays along the path are copied, the
331
+ * others are kept as they are (`ObjectPathHelper`), and the result goes through `updateNgModel()`. Bind a field of
332
+ * an object edited as is with `[model]="model()?.firstName" (modelChange)="patchNgModel(['firstName'], $event)"`,
333
+ * or replace an item of a list with `patchNgModel([index], item)`. The same value changes nothing.
334
+ *
335
+ * @param path the keys and indexes leading to the value, e.g. `['address', 'street']` or `[index]`
336
+ * @param value the new value (`null` and `undefined` included: the model of the `foehn-*` components can be)
337
+ * @throws Error when the page gives no model and `emptyModel()` neither, or when an object of the path is `null`
338
+ * or `undefined`
339
+ */
340
+ patchNgModel<P extends ObjectPath<T>>(path: P, value: ObjectPathValue<T, P> | null | undefined): void;
240
341
  hasErrorsToDisplay(): boolean;
241
342
  hasErrors(): boolean;
242
343
  hasInheritErrorFromParent(): boolean;
@@ -269,6 +370,14 @@ declare abstract class FoehnInputComponent<T> implements OnInit, AfterViewInit {
269
370
  * @returns whether the model has a value to display
270
371
  */
271
372
  protected hasValueToDisplay(value: T | null | undefined): boolean;
373
+ /**
374
+ * The model `patchNgModel()` starts from when the page gives none (`null` or `undefined`): none by default. To
375
+ * override in a component whose model can be missing, e.g. `return new Owner();`, the objects of its paths
376
+ * included.
377
+ *
378
+ * @returns a new empty model, or `null`
379
+ */
380
+ protected emptyModel(): T | null;
272
381
  protected isEmpty(data: unknown): boolean;
273
382
  protected isEmptyWhenTrimmedIfString(data: unknown): boolean;
274
383
  protected triggerUserInput(value: T | null | undefined): void;
@@ -509,87 +618,6 @@ declare class GesdemHandlerService {
509
618
  static ɵprov: _angular_core.ɵɵInjectableDeclaration<GesdemHandlerService>;
510
619
  }
511
620
 
512
- type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7];
513
- /**
514
- * A path in an object: one of its keys, then the keys or the indexes of the objects and arrays it holds, e.g.
515
- * `['firstName']`, `['address', 'locality']` or `['children', 0, 'firstName']`. For a union (`ApForm | AfForm`), the
516
- * paths of each of its members.
517
- */
518
- type ObjectPath<T, D extends number = 7> = [D] extends [never] ? never : PathsOf<NonNullable<T>, D>;
519
- type PathsOf<T, D extends number> = T extends readonly (infer E)[] ? [number] | [number, ...ObjectPath<E, Depth[D]>] : T extends object ? {
520
- [K in keyof T & string]-?: [K] | [K, ...ObjectPath<T[K], Depth[D]>];
521
- }[keyof T & string] : never;
522
- /**
523
- * The type of the value at a path of an object. For a union, the value in the members having the path.
524
- */
525
- type ObjectPathValue<T, P extends readonly unknown[]> = P extends readonly [infer K, ...infer R] ? ValueAtKey<NonNullable<T>, K, R> : T;
526
- type ValueAtKey<T, K, R extends readonly unknown[]> = T extends readonly (infer E)[] ? ObjectPathValue<E, R> : K extends keyof T ? ObjectPathValue<T[K], R> : never;
527
- /**
528
- * Keys known at runtime only: a key with dots (`'address.street'`, `'children.0.firstName'`), or the list of the keys.
529
- */
530
- type ObjectKeys = string | readonly (string | number)[];
531
- /**
532
- * Reads and writes a value at a path of an object, without modifying the object: a write copies the objects and arrays
533
- * along the path (with their prototype), and keeps the others as they are.
534
- *
535
- * A copy takes the own enumerable properties only: the objects along the path must be plain objects (e.g. the JSON of
536
- * the backend), arrays or instances of classes with public fields. The copy of a `Date`, a `Map`, a `Set` or an
537
- * instance with private fields (`#field`) loses their content, and their methods throw. The value written, and the
538
- * objects beside the path, are not copied: they can be of any type.
539
- *
540
- * `get()`, `patch()` and `patchSignal()` take a path checked by TypeScript (a typo gives an error listing the valid
541
- * keys). `getByKeys()` and `patchByKeys()` take keys known at runtime only (e.g. a key given as an input), not
542
- * checked.
543
- */
544
- declare class ObjectPathHelper {
545
- /**
546
- * @param object an object
547
- * @param path the keys and indexes leading to the value
548
- * @returns the value at the path, `undefined` when an object of the path is `null` or `undefined`
549
- */
550
- static get<T, P extends ObjectPath<T>>(object: T, path: P): ObjectPathValue<T, P> | undefined;
551
- /**
552
- * Writes a value at a path of an object without modifying it.
553
- *
554
- * @param object an object
555
- * @param path the keys and indexes leading to the value
556
- * @param value the value to write
557
- * @returns a new object, or the object itself when the value is already there
558
- * @throws Error when an object of the path is `null` or `undefined`, as a write through it would
559
- */
560
- static patch<T, P extends ObjectPath<T>>(object: T, path: P, value: ObjectPathValue<T, P>): T;
561
- /**
562
- * Writes a value at a path of the object held by a signal, without modifying it in place: the signal gets a new
563
- * object, and notifies its readers only when the value changes.
564
- *
565
- * @param signal a signal holding an object
566
- * @param path the keys and indexes leading to the value
567
- * @param value the value to write
568
- * @throws Error when an object of the path, the value of the signal included, is `null` or `undefined`
569
- */
570
- static patchSignal<T, P extends ObjectPath<T>>(signal: WritableSignal<T>, path: P, value: ObjectPathValue<T, P>): void;
571
- /**
572
- * `get()` with keys known at runtime only, not checked by TypeScript.
573
- *
574
- * @param object an object
575
- * @param keys `'address.street'`, or `['address', 'street']`
576
- * @returns the value at the keys, `undefined` when an object of the path is `null` or `undefined`
577
- */
578
- static getByKeys(object: unknown, keys: ObjectKeys): unknown;
579
- /**
580
- * `patch()` with keys known at runtime only, not checked by TypeScript.
581
- *
582
- * @param object an object
583
- * @param keys `'address.street'`, or `['address', 'street']`
584
- * @param value the value to write
585
- * @returns a new object, or the object itself when the value is already there
586
- * @throws Error when an object of the path is `null` or `undefined`, as a write through it would
587
- */
588
- static patchByKeys<T>(object: T, keys: ObjectKeys, value: unknown): T;
589
- private static keysOf;
590
- private static patchFrom;
591
- }
592
-
593
621
  type PlaceholderType = Record<string, string | null | undefined>;
594
622
  type DictionaryType = Record<string, string>;
595
623
  interface Language {
@@ -668,8 +696,12 @@ declare abstract class AbstractPageComponent<T extends I18nForm> implements OnIn
668
696
  */
669
697
  readonly form: _angular_core.WritableSignal<T | null | undefined>;
670
698
  /**
671
- * The reference of the demand, set when the form is loaded. A template, a `computed()` or an `effect()` reading it
672
- * follows it, also when the page sets it: read it with `untracked()` in an `effect()` which must not follow it.
699
+ * The reference of the demand, set when the form is loaded: `undefined` as long as no form was loaded from the
700
+ * backend, then its reference, or `null` when it has none (a demand not created yet). A page which doesn't set it
701
+ * itself can so derive "the form is loaded" from it: `computed(() => this.reference() !== undefined)`.
702
+ *
703
+ * A template, a `computed()` or an `effect()` reading it follows it, also when the page sets it: read it with
704
+ * `untracked()` in an `effect()` which must not follow it.
673
705
  */
674
706
  readonly reference: _angular_core.WritableSignal<string | null | undefined>;
675
707
  protected _destroyRef: DestroyRef;