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

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.
Files changed (55) hide show
  1. package/ANGULAR_SIGNALS.md +4 -0
  2. package/CHANGELOG.md +396 -0
  3. package/CONTRIBUTING.md +74 -4
  4. package/ESLINT_PLUGIN.md +103 -8
  5. package/GOOD_PRACTICES.md +731 -380
  6. package/INTRODUCTION_ANGULAR_SIGNALS.md +199 -154
  7. package/UPGRADING_V18.md +5 -5
  8. package/UPGRADING_V19.md +439 -18
  9. package/eslint/configs/spec-ts-recommended.mjs +34 -0
  10. package/eslint/configs/template-recommended.mjs +2 -0
  11. package/eslint/configs/template-rules.mjs +11 -2
  12. package/eslint/configs/ts-recommended.mjs +6 -0
  13. package/eslint/configs/ts-rules.mjs +6 -2
  14. package/eslint/form-reads.mjs +63 -0
  15. package/eslint/index.mjs +17 -0
  16. package/eslint/rules/index.mjs +4 -0
  17. package/eslint/rules/no-direct-signal-mutation.mjs +58 -20
  18. package/eslint/rules/no-item-track-in-form-list.mjs +99 -0
  19. package/eslint/rules/no-uninvoked-signal-in-template.mjs +8 -3
  20. package/eslint/rules/require-model-change.mjs +89 -0
  21. package/eslint/template-ast.mjs +12 -2
  22. package/fesm2022/dsivd-prestations-ng.mjs +2766 -2073
  23. package/fesm2022/dsivd-prestations-ng.mjs.map +1 -1
  24. package/package.json +1 -2
  25. package/schematics/migration-collection.json +5 -0
  26. package/schematics/ng-add/index.js +2 -4
  27. package/schematics/ng-update/migrations/update-13_2_0/index.js +7 -2
  28. package/schematics/ng-update/migrations/update-19_2_0/index.js +39 -0
  29. package/schematics/utility/add-allowed-common-js-dependencies.js +39 -29
  30. package/schematics/utility/form-signal/class-migration.js +396 -0
  31. package/schematics/utility/form-signal/edits.js +34 -0
  32. package/schematics/utility/form-signal/form-signal-migration.js +184 -0
  33. package/schematics/utility/form-signal/page-classes.js +129 -0
  34. package/schematics/utility/form-signal/template-migration.js +666 -0
  35. package/schematics/utility/remove-emit-decorator-metadata.js +8 -9
  36. package/src/eslint/configs/__tests__/configs.test.mjs +46 -2
  37. package/src/eslint/configs/spec-ts-recommended.mjs +34 -0
  38. package/src/eslint/configs/template-recommended.mjs +2 -0
  39. package/src/eslint/configs/template-rules.mjs +11 -2
  40. package/src/eslint/configs/ts-recommended.mjs +6 -0
  41. package/src/eslint/configs/ts-rules.mjs +6 -2
  42. package/src/eslint/form-reads.mjs +63 -0
  43. package/src/eslint/index.mjs +17 -0
  44. package/src/eslint/rules/__tests__/no-direct-signal-mutation.test.mjs +58 -0
  45. package/src/eslint/rules/__tests__/no-item-track-in-form-list.test.mjs +127 -0
  46. package/src/eslint/rules/__tests__/no-uninvoked-signal-in-template.test.mjs +6 -0
  47. package/src/eslint/rules/__tests__/require-model-change.test.mjs +93 -0
  48. package/src/eslint/rules/index.mjs +4 -0
  49. package/src/eslint/rules/no-direct-signal-mutation.mjs +58 -20
  50. package/src/eslint/rules/no-item-track-in-form-list.mjs +99 -0
  51. package/src/eslint/rules/no-uninvoked-signal-in-template.mjs +8 -3
  52. package/src/eslint/rules/require-model-change.mjs +89 -0
  53. package/src/eslint/template-ast.mjs +12 -2
  54. package/types/dsivd-prestations-ng.d.ts +652 -240
  55. package/dsivd-prestations-ng-19.2.0-beta.2.tgz +0 -0
package/GOOD_PRACTICES.md CHANGED
@@ -1,97 +1,106 @@
1
- # Utilisation technique (DEV)
1
+ # Technical usage (DEV)
2
2
 
3
- > Ce guide décrit les bonnes pratiques pour développer une prestation avec `prestations-ng`.
4
- > Il a été mis à jour pour la version **v19+** : composants **standalone**, **signals** et
5
- > fonction **`inject`** (plus de modules, plus d'injection par constructeur).
3
+ > This guide describes the good practices to develop a prestation with `prestations-ng`.
4
+ > It has been updated for version **v19+**: **standalone** components, **signals** and the
5
+ > **`inject`** function (no more modules, no more constructor injection). Since **v19.2**,
6
+ > prestations-ng is **zoneless**: the examples hold the state of your components in signals,
7
+ > which works with or without zone.js (see [Zoneless application](good-practices#zoneless_application)).
6
8
  >
7
- > 📚 Pour aller plus loin :
9
+ > 📚 To go further:
8
10
  > [ANGULAR_SIGNALS.md](ANGULAR_SIGNALS.md) · [COMPONENTS.md](COMPONENTS.md) · [UPGRADING_V19.md](UPGRADING_V19.md)
9
11
 
10
- ## Sommaire
12
+ ## Table of contents
11
13
 
12
14
  - [Documentation](good-practices#documentation)
13
- - [Mise à jour de la librairie](good-practices#mise___jour_de_la_librairie)
14
- - [Accessibilité](good-practices#accessibilit_)
15
- - [Structure HTML](good-practices#structure_html)
16
- - [Le focus](good-practices#le_focus)
17
- - [La balise `<label>`](good-practices#la_balise__code__lt_label_gt___code_)
18
- - [La balise `<ul>` ou `<ol>`](good-practices#la_balise__code__lt_ul_gt___code__ou__code__lt_ol_gt___code_)
19
- - [La balise `<fieldset>` et `<legend>`](good-practices#la_balise__code__lt_fieldset_gt___code__et__code__lt_legend_gt___code_)
20
- - [Liseuse d'écran (afficher / masquer)](good-practices#liseuse_d__cran__afficher___masquer_)
21
- - [Une page prestations-ng](good-practices#une_page_prestations-ng)
22
- - [Le routage de vos pages](good-practices#le_routage_de_vos_pages)
23
- - [Formulaire simple](good-practices#formulaire_simple)
24
- - [Formulaire complexe (sous-routes)](good-practices#formulaire_complexe__sous-routes_)
25
- - [Création d'un composant réutilisable](good-practices#cr_ation_d_un_composant_r_utilisable)
26
- - [Exemple avec foehn-input-date de prestations-ng](good-practices#exemple_avec_foehn-input-date_de_prestations-ng)
27
- - [Afficher la validation globale du composant](good-practices#afficher_la_validation_globale_du_composant)
28
- - [Éviter des problèmes d'affichage d'erreurs dans une boucle `@for`](good-practices#_viter_des_probl_mes_d_affichage_d_erreurs_dans_une_boucle__code__for__code_)
29
- - [Validation du formulaire](good-practices#validation_du_formulaire)
30
- - [Gestion standard](good-practices#gestion_standard)
31
- - [Gestion manuelle](good-practices#gestion_manuelle)
15
+ - [Updating the library](good-practices#updating_the_library)
16
+ - [Accessibility](good-practices#accessibility)
17
+ - [HTML structure](good-practices#html_structure)
18
+ - [Focus](good-practices#focus)
19
+ - [The `<label>` tag](good-practices#the__code__lt_label_gt___code__tag)
20
+ - [The `<ul>` or `<ol>` tag](good-practices#the__code__lt_ul_gt___code__or__code__lt_ol_gt___code__tag)
21
+ - [The `<fieldset>` and `<legend>` tags](good-practices#the__code__lt_fieldset_gt___code__and__code__lt_legend_gt___code__tags)
22
+ - [Screen reader (show / hide)](good-practices#screen_reader__show___hide_)
23
+ - [A prestations-ng page](good-practices#a_prestations-ng_page)
24
+ - [Binding the fields of the form](good-practices#binding_the_fields_of_the_form)
25
+ - [Zoneless application](good-practices#zoneless_application)
26
+ - [Displaying an asynchronous state](good-practices#displaying_an_asynchronous_state)
27
+ - [Deriving a state from view queries](good-practices#deriving_a_state_from_view_queries)
28
+ - [Acting on the DOM after rendering](good-practices#acting_on_the_dom_after_rendering)
29
+ - [Testing a zoneless component](good-practices#testing_a_zoneless_component)
30
+ - [Routing your pages](good-practices#routing_your_pages)
31
+ - [Simple form](good-practices#simple_form)
32
+ - [Complex form (sub-routes)](good-practices#complex_form__sub-routes_)
33
+ - [Creating a reusable component](good-practices#creating_a_reusable_component)
34
+ - [Example with foehn-input-date of prestations-ng](good-practices#example_with_foehn-input-date_of_prestations-ng)
35
+ - [Displaying the global validation of the component](good-practices#displaying_the_global_validation_of_the_component)
36
+ - [Avoiding error display problems in a `@for` loop](good-practices#avoiding_error_display_problems_in_a__code__for__code__loop)
37
+ - [Types of the form fields](good-practices#types_of_the_form_fields)
38
+ - [Form validation](good-practices#form_validation)
39
+ - [Standard handling](good-practices#standard_handling)
40
+ - [Manual handling](good-practices#manual_handling)
32
41
  - [Back-end](good-practices#back-end)
33
42
  - [Front-end](good-practices#front-end)
34
- - [Validation manuelle d'un composant](good-practices#validation_manuelle_d_un_composant)
35
- - [Cacher une erreur](good-practices#cacher_une_erreur)
36
- - [Afficher une erreur](good-practices#afficher_une_erreur)
43
+ - [Manual validation of a component](good-practices#manual_validation_of_a_component)
44
+ - [Hiding an error](good-practices#hiding_an_error)
45
+ - [Displaying an error](good-practices#displaying_an_error)
37
46
 
38
- > ⚠️ Dans toutes vos pages HTML vous devez avoir un `<foehn-form>` et celui-ci **ne peut pas être
39
- > conditionnel** (pas de `@if` autour de `<foehn-form>`).
47
+ > ⚠️ All your HTML pages must have a `<foehn-form>`, and it **can't be
48
+ > conditional** (no `@if` around `<foehn-form>`).
40
49
 
41
50
  ## Documentation
42
51
 
43
52
  - [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
44
53
  - [prestations-ng](https://dsi-vd.github.io/prestations-ng/)
45
- - [prestations-ng (doc autogénérée)](https://dsi-vd.github.io/prestations-ng/generateddoc/)
46
- - [foehn](https://dsi-vd.github.io/foehn-design-system/components/detail/formulaire-prestation--default.html) (Charte graphique)
54
+ - [prestations-ng (generated doc)](https://dsi-vd.github.io/prestations-ng/generateddoc/)
55
+ - [foehn](https://dsi-vd.github.io/foehn-design-system/components/detail/formulaire-prestation--default.html) (Graphic charter)
47
56
  - [CSS](https://www.w3schools.com/css/default.asp)
48
57
  - [Bootstrap](https://getbootstrap.com/docs/5.3/layout/grid/)
49
58
  - [Flex - Bootstrap](https://getbootstrap.com/docs/5.3/utilities/flex/)
50
59
  - [Flex](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
51
60
  - [HTML](https://www.w3schools.com/html/default.asp)
52
- - [Éléments de section](https://www.alsacreations.com/article/lire/1376-html5-section-article-nav-header-footer-aside.html)
61
+ - [Section elements](https://www.alsacreations.com/article/lire/1376-html5-section-article-nav-header-footer-aside.html) (in French)
53
62
  - [Description list](https://www.w3schools.com/tags/tag_dl.asp)
54
63
  - [RXJS](https://rxjs-dev.firebaseapp.com/)
55
64
 
56
- ## Mise à jour de la librairie
65
+ ## Updating the library
57
66
 
58
- > ℹ️ Maintenez à jour vos librairies en vous inscrivant sur la page [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
59
- > et vous serez ainsi notifié des nouvelles releases. Cela vous permettra de profiter des corrections
60
- > de bug, améliorations et nouvelles fonctionnalités.
67
+ > ℹ️ Keep your libraries up to date by subscribing on the [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
68
+ > page: you will be notified of the new releases. You will then benefit from the bug fixes,
69
+ > improvements and new features.
61
70
  >
62
- > Prenez le temps de lire le [changelog](CHANGELOG.md) de **prestations-ng** à chaque nouvelle release.
71
+ > Take the time to read the [changelog](CHANGELOG.md) of **prestations-ng** at each new release.
63
72
  >
64
- > N'hésitez pas à ouvrir des tickets JIRA (PRESTAKIT-xxx) dans [PrestaKit (anc SDK Cyber)](https://issuetracker.etat-de-vaud.ch/outils/issuetracker/browse/PRESTAKIT)
65
- > pour signaler des bugs ou même à faire des propositions d'améliorations afin de
66
- > [contribuer](CONTRIBUTING.md) au développement de prestations-ng.
73
+ > Don't hesitate to open JIRA tickets (PRESTAKIT-xxx) in [PrestaKit (formerly SDK Cyber)](https://issuetracker.etat-de-vaud.ch/outils/issuetracker/browse/PRESTAKIT)
74
+ > to report bugs, or even to suggest improvements in order to
75
+ > [contribute](CONTRIBUTING.md) to the development of prestations-ng.
67
76
 
68
- Mettre à jour la librairie prestations-ng (npm) :
77
+ Update the prestations-ng library (npm):
69
78
 
70
79
  ```bash
71
80
  ng update @dsivd/prestations-ng
72
81
  ```
73
82
 
74
- ## Accessibilité
83
+ ## Accessibility
75
84
 
76
- > ℹ️ En développant des prestations pour l'État, nous devons faire tout notre possible pour rendre nos
77
- > pages web les plus accessibles possibles au grand public.
85
+ > ℹ️ When developing prestations for the State, we must do everything we can to make our web pages
86
+ > as accessible as possible to the general public.
78
87
  >
79
- > Prestations-ng fait une bonne partie du boulot pour nous mais c'est au développeur de prendre le
80
- > soin de mettre les efforts qu'il faut pour que la prestation reste accessible.
88
+ > Prestations-ng does a good part of the job for us, but it's up to the developer to make the
89
+ > necessary efforts so that the prestation stays accessible.
81
90
 
82
- ### Structure HTML
91
+ ### HTML structure
83
92
 
84
- > ⚠️ Nous recommandons :
93
+ > ⚠️ We recommend to:
85
94
  >
86
- > - une seule balise h1 (`<h1>`)
87
- > - respecter la hiérarchie h1, h2, h3..
88
- > - regrouper vos informations dans des sections (`<section>`) si vous avez plusieurs h2 (`<h2>`)
89
- > - utiliser la classe CSS `col-md-8` de Bootstrap pour définir la largeur de votre formulaire
90
- > - organisez votre texte avec des paragraphes (`<p>`)
91
- > - utiliser les balises `<dl>`, `<dt>` et `<dd>` pour afficher des clés / valeurs (voir [foehn-recap-section](https://dsi-vd.github.io/prestations-ng/recap))
92
- > - utiliser [foehn-abbr](https://dsi-vd.github.io/prestations-ng/misc) pour les abréviations tant que possible et sinon la balise abbr (`<abbr>`)
95
+ > - have a single h1 tag (`<h1>`)
96
+ > - respect the hierarchy h1, h2, h3..
97
+ > - group your information in sections (`<section>`) if you have several h2 (`<h2>`)
98
+ > - use the Bootstrap CSS class `col-md-8` to define the width of your form
99
+ > - organize your text with paragraphs (`<p>`)
100
+ > - use the `<dl>`, `<dt>` and `<dd>` tags to display keys / values (see [foehn-recap-section](https://dsi-vd.github.io/prestations-ng/recap))
101
+ > - use [foehn-abbr](https://dsi-vd.github.io/prestations-ng/misc) for the abbreviations whenever possible, and the abbr tag (`<abbr>`) otherwise
93
102
 
94
- Ce qu'il ne faut **pas** faire :
103
+ What **not** to do:
95
104
 
96
105
  ```html
97
106
  <h1>...</h1>
@@ -101,7 +110,7 @@ Ce qu'il ne faut **pas** faire :
101
110
  ... ... ...
102
111
  ```
103
112
 
104
- Ce qu'il **faut** faire :
113
+ What **to** do:
105
114
 
106
115
  ```html
107
116
  <h1>...</h1>
@@ -116,27 +125,27 @@ Ce qu'il **faut** faire :
116
125
  <section>...</section>
117
126
  ```
118
127
 
119
- Quelques attributs HTML utiles :
128
+ Some useful HTML attributes:
120
129
 
121
- - Pour les images (`<img>`)
122
- - `title="[texte explicite ici]"`
123
- - `alt="[texte explicite ici]"`
124
- - Pour les liens (`<a>`)
125
- - `title="[texte explicite ici]"`
130
+ - For the images (`<img>`)
131
+ - `title="[explicit text here]"`
132
+ - `alt="[explicit text here]"`
133
+ - For the links (`<a>`)
134
+ - `title="[explicit text here]"`
126
135
  - `target="_blank"`
127
- - [Rendre les balises accessibles](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
136
+ - [Make the tags accessible](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
128
137
  - [`aria-*`](https://w3c.github.io/using-aria/#aria-states-and-properties-aria-attributes)
129
138
  - [`role`](https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute)
130
139
 
131
- ### Le focus
140
+ ### Focus
132
141
 
133
- > ⚠️ Il est important que le focus dans une page HTML soit maîtrisé. Si le focus est perdu, alors la
134
- > liseuse d'écran le sera aussi.
142
+ > ⚠️ It's important that the focus in an HTML page is under control. If the focus is lost, the
143
+ > screen reader is lost too.
135
144
  >
136
- > Si, par exemple, on ouvre une modale en cliquant sur un bouton, alors à la fermeture de la modale,
137
- > le focus doit être remis sur le bouton déclencheur.
145
+ > If, for example, a modal is opened by clicking on a button, then when the modal is closed, the
146
+ > focus must be put back on the triggering button.
138
147
 
139
- Exemple :
148
+ Example:
140
149
 
141
150
  ```html
142
151
  <button
@@ -145,120 +154,129 @@ Exemple :
145
154
  (click)="openModal()"
146
155
  #modalTrigger
147
156
  >
148
- <!-- on déclare le déclencheur de la modale -->
157
+ <!-- we declare the trigger of the modal -->
149
158
  Open Modal
150
159
  </button>
151
160
  <foehn-modal
152
161
  modalHeaderText="Modal dialog"
153
162
  modalSize="modal-lg"
154
- [isModalVisible]="isModalVisible"
155
- (isModalVisibleChange)="updateVisibilityStatus($event)"
163
+ [(isModalVisible)]="isModalVisible"
156
164
  [modalTriggerHtmlElement]="modalTrigger"
157
165
  >
158
- <!-- on utilise le déclencheur -->
166
+ <!-- we use the trigger -->
159
167
  <div>Here is the dialog</div>
160
168
  </foehn-modal>
161
169
  ```
162
170
 
163
- ### La balise `<label>`
171
+ ```ts
172
+ // A signal: the modal is also displayed and hidden without zone.js
173
+ readonly isModalVisible = signal(false);
174
+
175
+ openModal(): void {
176
+ this.isModalVisible.set(true);
177
+ }
178
+ ```
164
179
 
165
- > ⚠️ Tous nos composants `foehn-input-*` disposent d'une balise label ([`<label>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/label))
166
- > qui décrit le champ de saisie. Il est important que celle-ci soit remplie avec un contenu explicite.
180
+ ### The `<label>` tag
181
+
182
+ > ⚠️ All our `foehn-input-*` components have a label tag ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label))
183
+ > which describes the input field. It's important that it is filled with an explicit content.
167
184
  >
168
- > Si pour une raison quelconque, le métier ne souhaite pas l'afficher, vous devez tout de même la
169
- > renseigner et ajouter un attribut `[isLabelSrOnly]="true"`. Le label ne sera pas affiché mais
170
- > uniquement lu par la liseuse d'écran.
185
+ > If for any reason the business doesn't want to display it, you must still fill it and add an
186
+ > `[isLabelSrOnly]="true"` attribute. The label won't be displayed, only read by the screen
187
+ > reader.
171
188
 
172
- Exemple :
189
+ Example:
173
190
 
174
191
  ```html
175
192
  <foehn-input-number
176
193
  name="..."
177
194
  [(model)]="..."
178
- [label]="'Le texte que la liseuse va lire'"
195
+ [label]="'The text read by the screen reader'"
179
196
  [isLabelSrOnly]="true"
180
197
  [required]="..."
181
198
  [maxlength]="..."
182
199
  />
183
200
  ```
184
201
 
185
- > 💡 `label`, `isLabelSrOnly`, `required`, ... sont désormais des **input signals** côté composant.
186
- > Vous continuez à les alimenter depuis le template parent via un binding `[label]="..."`.
187
- > À l'intérieur du composant, vous les lisez en les invoquant : `label()`, `required()`, ...
202
+ > 💡 `label`, `isLabelSrOnly`, `required`, ... are now **input signals** in the component.
203
+ > You keep feeding them from the parent template with a `[label]="..."` binding.
204
+ > Inside the component, you read them by calling them: `label()`, `required()`, ...
188
205
 
189
- ### La balise `<ul>` ou `<ol>`
206
+ ### The `<ul>` or `<ol>` tag
190
207
 
191
208
  > ⚠️
192
209
  >
193
- > - L'élément [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) doit être utilisé
194
- > pour regrouper plusieurs éléments qui n'ont pas de relation d'ordre. Si on hésite entre
195
- > [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) et
196
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul), on se demandera si changer
197
- > l'ordre des éléments de la liste a un impact : si le déplacement d'un élément change la
198
- > signification, cela signifie que l'ordre est important et qu'il faudra utiliser
199
- > [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol), sinon l'ordre n'importe pas
200
- > et [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) peut être utilisé.
201
- > - Si [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) ou
202
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) ne contient qu'un seul élément
203
- > [`<li>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/li) (non dynamique), alors on se
204
- > demandera si l'utilisation d'une liste est nécessaire et si un paragraphe
205
- > ([`<p>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/p)) ne serait pas une meilleure
210
+ > - The [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) element must be used
211
+ > to group several items that have no order relationship. If you hesitate between
212
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) and
213
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul), ask yourself whether
214
+ > changing the order of the items of the list has an impact: if moving an item changes the
215
+ > meaning, the order is important and
216
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) must be used, otherwise
217
+ > the order doesn't matter and [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)
218
+ > can be used.
219
+ > - If [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
220
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) only contains a single
221
+ > [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element (not dynamic),
222
+ > ask yourself whether a list is necessary and whether a paragraph
223
+ > ([`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)) wouldn't be a better
206
224
  > option.
207
- > - Ne **JAMAIS** mettre une autre balise que [`<li>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/li)
208
- > entre deux balises [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) ou
209
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul).
225
+ > - **NEVER** put a tag other than [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)
226
+ > between two [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
227
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) tags.
210
228
 
211
- Exemple :
229
+ Example:
212
230
 
213
231
  ```html
214
232
  <ul>
215
- <li>un artichaut</li>
233
+ <li>an artichoke</li>
216
234
  <li>
217
- Les trucs pour le gâteau
218
- <!-- On voit que </li> n'est pas là -->
235
+ The things for the cake
236
+ <!-- Note that </li> isn't there -->
219
237
  <ul>
220
- <li>trois œufs</li>
238
+ <li>three eggs</li>
221
239
  <li>
222
- La génoise
223
- <!-- Là on ouvre une autre liste -->
240
+ The sponge cake
241
+ <!-- Here we open another list -->
224
242
  <ul>
225
- <li>100g de sucre</li>
226
- <li>un œuf</li>
227
- <li>150g de farine</li>
243
+ <li>100g of sugar</li>
244
+ <li>an egg</li>
245
+ <li>150g of flour</li>
228
246
  </ul>
229
247
  </li>
230
- <!-- On ferme la liste la plus imbriquée -->
231
- <li>200g de chocolat</li>
248
+ <!-- We close the most nested list -->
249
+ <li>200g of chocolate</li>
232
250
  </ul>
233
- <!-- On ferme la liste imbriquée avec </li> -->
251
+ <!-- We close the nested list with </li> -->
234
252
  </li>
235
- <li>De l'essuie-tout</li>
253
+ <li>Paper towels</li>
236
254
  <li>
237
- A faire dans l'ordre pour une belle vaisselle
255
+ To do in this order for a nice dishwashing
238
256
  <ol>
239
- <li>Remplir le lave vaisselle</li>
240
- <li>Mettre une pastille pour lave vaisselle</li>
241
- <li>Fermer la porte du lave vaisselle</li>
242
- <li>Lancer le lave vaisselle</li>
257
+ <li>Fill the dishwasher</li>
258
+ <li>Put a dishwasher tablet</li>
259
+ <li>Close the door of the dishwasher</li>
260
+ <li>Start the dishwasher</li>
243
261
  </ol>
244
262
  </li>
245
263
  </ul>
246
264
  ```
247
265
 
248
- ### La balise `<fieldset>` et `<legend>`
266
+ ### The `<fieldset>` and `<legend>` tags
249
267
 
250
- > ⚠️ L'élément HTML [`<fieldset>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/fieldset) est
251
- > utilisé afin de regrouper plusieurs contrôles interactifs ainsi que des étiquettes
252
- > ([`<label>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/label)) dans un formulaire HTML
253
- > et on doit lui associer une légende
254
- > ([`<legend>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/legend)) décrivant ce groupe.
268
+ > ⚠️ The HTML element [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) is
269
+ > used to group several interactive controls as well as labels
270
+ > ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)) in an HTML form,
271
+ > and it must have a caption
272
+ > ([`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend)) describing this group.
255
273
  >
256
- > L'élément HTML [`<legend>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/legend) représente
257
- > une légende pour le contenu de son élément parent
258
- > [`<fieldset>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/fieldset). Il ne peut pas être
259
- > utilisé tout seul.
274
+ > The HTML element [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend) represents
275
+ > a caption for the content of its parent element
276
+ > [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset). It can't be
277
+ > used on its own.
260
278
 
261
- Exemple :
279
+ Example:
262
280
 
263
281
  ```html
264
282
  <form>
@@ -277,45 +295,46 @@ Exemple :
277
295
  </form>
278
296
  ```
279
297
 
280
- ### Liseuse d'écran (afficher / masquer)
298
+ ### Screen reader (show / hide)
281
299
 
282
- > ⚠️ Il est important de garder en tête qu'une liseuse d'écran va parcourir notre code HTML. De ce
283
- > fait, nous pouvons à tout moment décider de lui afficher explicitement du contenu à lire ou de lui
284
- > masquer du contenu pour ne pas surcharger l'information.
300
+ > ⚠️ It's important to keep in mind that a screen reader goes through our HTML code. So we can
301
+ > decide at any time to explicitly show it content to read, or to hide content from it so as not to
302
+ > overload the information.
285
303
 
286
- - Afficher uniquement pour la liseuse : utiliser la classe CSS `sr-only`
287
- - Masquer du contenu à la liseuse : utiliser l'attribut `aria-hidden="true"`
304
+ - Show only to the screen reader: use the CSS class `sr-only`
305
+ - Hide content from the screen reader: use the attribute `aria-hidden="true"`
288
306
 
289
- Exemple :
307
+ Example:
290
308
 
291
309
  ```html
292
310
  <a href="https://www.vd.ch">
293
311
  <span class="sr-only">
294
- <!-- Afficher uniquement pour la liseuse d'écran -->
295
- Retour à la page d'accueil
312
+ <!-- Show only to the screen reader -->
313
+ Back to the home page
296
314
  </span>
297
315
  <img
298
316
  aria-hidden="true"
299
317
  class="img-fluid footer-logo"
300
- src="[url_vers_mon_image]"
318
+ src="[url_to_my_image]"
301
319
  alt="Canton de Vaud"
302
320
  />
303
- <!-- Masquer uniquement pour la liseuse d'écran -->
321
+ <!-- Hide only from the screen reader -->
304
322
  </a>
305
323
  ```
306
324
 
307
- Le résultat de l'exemple ci-dessus sera un lien représenté par une image pour les voyants et un lien
308
- avec du texte pour les non-voyants.
325
+ The result of the example above is a link represented by an image for sighted people, and a link
326
+ with text for visually impaired people.
309
327
 
310
- ### Une page prestations-ng
328
+ ### A prestations-ng page
311
329
 
312
- 1. Étendre la classe abstraite `AbstractPageComponent` en spécifiant un modèle
313
- 2. Ajouter un titre h1 en utilisant `setPageTitle`
314
- 3. Implémenter la fonction `newForm`
315
- 4. Ajouter le `<foehn-form>` dans la page (⚠️ **il ne doit pas être conditionnel**)
316
- 5. La première balise d'en-tête de votre page doit être un h2 (`<h2>`)
317
- 6. Ajouter `<foehn-navigation>`
318
- 7. Si vous disposez de plusieurs pages, utiliser le composant `<foehn-page-counter>`
330
+ 1. Extend the abstract class `AbstractPageComponent`, specifying a model
331
+ 2. Add an h1 title with `setPageTitle`
332
+ 3. Implement the `newForm` function
333
+ 4. Add the `<foehn-form>` in the page (⚠️ **it must not be conditional**)
334
+ 5. The first heading tag of your page must be an h2 (`<h2>`)
335
+ 6. Add `<foehn-navigation>`
336
+ 7. If you have several pages, use the `<foehn-page-counter>` component
337
+ 8. Bind the fields of the form with `[model]` and `(modelChange)="patchForm([...], $event)"` (see below)
319
338
 
320
339
  `page-one.component.ts`
321
340
 
@@ -323,12 +342,12 @@ avec du texte pour les non-voyants.
323
342
  @Component({
324
343
  templateUrl: './page-one.component.html',
325
344
  imports: [
326
- // chaque composant importe ce dont il a besoin dans son template
345
+ // each component imports what its template needs
327
346
  FoehnFormComponent,
328
347
  FoehnNavigationComponent,
329
348
  FoehnPageCounterComponent,
330
349
  SdkDictionaryPipe,
331
- // ... vos composants foehn-* utilisés dans le template
350
+ // ... your foehn-* components used in the template
332
351
  ],
333
352
  })
334
353
  export class PageOneComponent
@@ -337,7 +356,7 @@ export class PageOneComponent
337
356
  {
338
357
  ngOnInit(): void {
339
358
  super.ngOnInit();
340
- // point (2) : ajoutera le titre h1
359
+ // point (2): adds the h1 title
341
360
  this.setPageTitle(this._dictionaryService.getKeySync('page.one.title'));
342
361
  }
343
362
 
@@ -348,28 +367,36 @@ export class PageOneComponent
348
367
  }
349
368
  ```
350
369
 
351
- > 💡 Plus de `constructor` : les dépendances de `AbstractPageComponent` (dont `_dictionaryService`)
352
- > sont injectées via `inject()` dans la classe abstraite. `activatedRoute` n'est donc plus un
353
- > paramètre de constructeur à passer.
370
+ > 💡 No more `constructor`: the dependencies of `AbstractPageComponent` (including `_dictionaryService`)
371
+ > are injected with `inject()` in the abstract class. `activatedRoute` is therefore no longer a
372
+ > constructor parameter to pass.
354
373
 
355
374
  `page-one.component.html`
356
375
 
357
376
  ```html
358
377
  <div class="container mt-5">
359
378
  <foehn-page-counter />
360
- <!-- point (7) : si besoin -->
379
+ <!-- point (7): if needed -->
361
380
 
362
- <!-- point (4) : doit toujours être présent dans la page et pas conditionnel (pas de @if) -->
381
+ <!-- point (4): must always be present in the page and not conditional (no @if) -->
363
382
  <foehn-form>
364
383
  <div class="row">
365
384
  <div class="col-md-8">
366
- <!-- point (5) : toujours avoir un <h2> en premier dans votre page -->
385
+ <!-- point (5): always have an <h2> first in your page -->
367
386
  <h2>
368
- {{ 'La_clé_du_dictionnaire_de_votre_titre_H2_ici' |
387
+ {{ 'The_dictionary_key_of_your_H2_title_here' |
369
388
  fromDictionary }}
370
389
  </h2>
371
390
 
372
- <!-- [VOS COMPOSANTS FOEHN ICI] -->
391
+ <!-- point (8) -->
392
+ @if (form(); as form) {
393
+ <foehn-input-text
394
+ name="firstName"
395
+ [model]="form.firstName"
396
+ (modelChange)="patchForm(['firstName'], $event)"
397
+ />
398
+ <!-- [YOUR FOEHN COMPONENTS HERE] -->
399
+ }
373
400
 
374
401
  <foehn-navigation
375
402
  id="navigation"
@@ -383,9 +410,229 @@ export class PageOneComponent
383
410
  </div>
384
411
  ```
385
412
 
386
- ## Le routage de vos pages
413
+ ### Binding the fields of the form
414
+
415
+ The `form` of a page is a signal: read it with `form()`, and never modify its value in place. Write a field with
416
+ `patchForm(path, value)`, which copies the objects along the path: the templates, the `computed()` and the
417
+ `effect()` reading the form follow every input of the user.
418
+
419
+ ```html
420
+ @if (form(); as form) {
421
+ <foehn-input-text
422
+ name="address.street"
423
+ [model]="form.address.street"
424
+ (modelChange)="patchForm(['address', 'street'], $event)"
425
+ />
426
+ @for (child of form.children; track child.id) {
427
+ <foehn-input-text
428
+ [name]="'children[' + $index + '].firstName'"
429
+ [model]="child.firstName"
430
+ (modelChange)="patchForm(['children', $index, 'firstName'], $event)"
431
+ />
432
+ } }
433
+ ```
434
+
435
+ ```ts
436
+ readonly childrenCount = computed(() => this.form()?.children.length ?? 0);
437
+
438
+ addChild(): void {
439
+ this.patchForm(['children'], [...(this.form()?.children ?? []), new Child()]);
440
+ }
441
+ ```
442
+
443
+ - The path is checked by TypeScript (a typo gives an error listing the valid keys).
444
+ - Never a `[model]` alone on a field the user can change: what the user enters would never reach the form
445
+ (`require-model-change` reports it). A field always disabled (`[disabled]="true"`), only displayed, is bound with
446
+ `[model]` alone.
447
+ - Track the rows of a list edited by its rows by an identifier (`track child.id`) or by `$index`, never by the
448
+ item: `patchForm()` replaces it, the row would be created again and lose the focus (`no-item-track-in-form-list`
449
+ reports it).
450
+ - A detail page (`AbstractListDetailPageComponent`) gives the path of its list with `getListPath()`, and writes the
451
+ item edited with `patchItem()`, `updateItem()` or `setItem()`.
452
+
453
+ ## Zoneless application
454
+
455
+ > ℹ️ Since v19.2, prestations-ng no longer needs zone.js and we recommend that you make your
456
+ > application zoneless (`provideZonelessChangeDetection()`, see
457
+ > [UPGRADING_V19.md](UPGRADING_V19.md#zoneless-optional-but-recommended)).
458
+ >
459
+ > Without zone.js, Angular only refreshes a component when it is notified of a change:
460
+ >
461
+ > - a listener of its template has been called (`(click)`, `(modelChange)`, `(userInput)`, ...),
462
+ > including the `[(model)]` two-way bindings
463
+ > - a signal read by its template has changed (`signal()`, `computed()`, `input()`, `model()`,
464
+ > `toSignal()`, ...)
465
+ > - `ChangeDetectorRef.markForCheck()` has been called, which is what the `async` pipe does when an
466
+ > observable emits
467
+
468
+ ### Displaying an asynchronous state
469
+
470
+ > ⚠️ A field modified elsewhere (in a `subscribe()`, a `setTimeout()`, a `Promise`, a
471
+ > callback, an `effect()`, ...) is no longer displayed until something else refreshes the component.
472
+ > Hold it in a **signal**.
473
+
474
+ What **not** to do:
475
+
476
+ ```ts
477
+ isLoading = true;
478
+
479
+ ngOnInit(): void {
480
+ this.myService.load().subscribe(() => {
481
+ this.isLoading = false; // not displayed without zone.js
482
+ });
483
+ }
484
+ ```
485
+
486
+ What **to** do:
487
+
488
+ ```ts
489
+ readonly isLoading = signal(true);
490
+
491
+ ngOnInit(): void {
492
+ this.myService.load().subscribe(() => {
493
+ this.isLoading.set(false);
494
+ });
495
+ }
496
+ ```
497
+
498
+ ```html
499
+ @if (isLoading()) {
500
+ <p>{{ 'page.loading' | fromDictionary }}</p>
501
+ }
502
+ ```
503
+
504
+ > 💡 For an observable displayed as is, `toSignal(this.myService.load())` or the `async` pipe do
505
+ > the job for you.
506
+
507
+ Do the same for a field read by the template that only a method called by a listener of the template
508
+ modifies: the listener notifies Angular, but the same method can later be called from a `subscribe()`
509
+ or an `effect()`, and the field would no longer be displayed. A signal notifies Angular whoever
510
+ modifies it.
511
+
512
+ In your pages (`AbstractPageComponent`), `form` and `reference` are signals too: write the form with `patchForm()`,
513
+ never in place, whoever calls the method (a listener, a callback, an `effect()`, ...). No `markForCheck()` is needed:
514
+
515
+ ```ts
516
+ ngOnInit(): void {
517
+ super.ngOnInit();
518
+ this.sessionInfoWithApplicationService.prefillForm((info) => {
519
+ this.patchForm(['firstName'], info?.firstName ?? null);
520
+ this.patchForm(['lastName'], info?.lastName ?? null);
521
+ });
522
+ }
523
+ ```
524
+
525
+ See "Binding the fields of the form" above.
526
+
527
+ ### Deriving a state from view queries
528
+
529
+ > ⚠️ A field read by the template and modified in `ngAfterViewInit()`, `ngAfterContentInit()` or
530
+ > `ngAfterViewChecked()` is no longer displayed until something else refreshes the component (with
531
+ > zone.js, the next refresh displayed it, after an `NG0100` error in development).
532
+ > Compute it with `computed()` from `viewChild()` or `contentChild()`.
533
+
534
+ What **not** to do:
535
+
536
+ ```ts
537
+ @ViewChild('referenceLink') referenceLink?: TemplateRef<unknown>;
538
+ columns: FoehnTableColumnConfiguration<Order>[] = [];
539
+
540
+ ngAfterViewInit(): void {
541
+ // not displayed without zone.js
542
+ this.columns = [{ id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink }];
543
+ }
544
+ ```
545
+
546
+ What **to** do:
547
+
548
+ ```ts
549
+ readonly referenceLink = viewChild<TemplateRef<unknown>>('referenceLink');
550
+ readonly columns = computed<FoehnTableColumnConfiguration<Order>[]>(() => [
551
+ { id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink() },
552
+ ]);
553
+ ```
554
+
555
+ ```html
556
+ <foehn-table
557
+ [name]="'orders'"
558
+ [columnsConfiguration]="columns()"
559
+ [model]="orders()"
560
+ ></foehn-table>
561
+
562
+ <ng-template #referenceLink let-order="item">
563
+ <a [routerLink]="['/demande', order.id]">{{ order.reference }}</a>
564
+ </ng-template>
565
+ ```
566
+
567
+ > 💡 The `computed()` follows the result of the `viewChild()`, including when the element appears or
568
+ > disappears in an `@if`: no need to hide the content until it is resolved. If the element must
569
+ > always exist, `viewChild.required()` guarantees it (error `NG0951` otherwise).
570
+
571
+ ### Acting on the DOM after rendering
572
+
573
+ > ⚠️ `NgZone` (`onStable`, `onMicrotaskEmpty`, `run()`, ...) no longer works without zone.js, and a
574
+ > `setTimeout()` doesn't wait for the rendering. To act on the rendered DOM (focus, scroll, ...), use
575
+ > `afterNextRender()`.
576
+
577
+ ```ts
578
+ readonly detailsVisible = signal(false);
579
+ readonly detailsField = viewChild<ElementRef<HTMLElement>>('detailsField');
580
+
581
+ private readonly injector = inject(Injector);
582
+
583
+ showDetails(): void {
584
+ this.detailsVisible.set(true);
585
+ // The field only exists once the details are rendered
586
+ afterNextRender(() => this.detailsField()?.nativeElement.focus(), {
587
+ injector: this.injector,
588
+ });
589
+ }
590
+ ```
591
+
592
+ ### Testing a zoneless component
593
+
594
+ > ⚠️ `fixture.detectChanges()` **forces** the refresh: a component that forgets to notify
595
+ > Angular (a field instead of a signal, a missing `markForCheck()`, ...) passes the test, but isn't
596
+ > refreshed in the application. Let Angular refresh the component, as in production, with
597
+ > `await fixture.whenStable()`.
598
+
599
+ ```ts
600
+ it('should display the details', async () => {
601
+ fixture.componentRef.setInput('showDetails', true);
602
+ await fixture.whenStable();
603
+
604
+ expect(fixture.nativeElement.querySelector('.details')).not.toBeNull();
605
+ });
606
+ ```
607
+
608
+ `await fixture.whenStable()` also waits for the pending tasks of the application, such as the debounced
609
+ `userInput` of the prestations-ng inputs: the test doesn't end before them (otherwise
610
+ `NG0205: Injector has already been destroyed`). But it doesn't wait for the HTTP requests of a spec:
611
+ `provideHttpClientTesting()` keeps them pending until the test answers them. Answer them first with
612
+ `HttpTestingController`, then `await fixture.whenStable()`:
387
613
 
388
- ### Formulaire simple
614
+ ```ts
615
+ it('should display the reference of the demand', async () => {
616
+ httpMock.expectOne('api/demande/1').flush({ reference: 'DEM-1' });
617
+ await fixture.whenStable();
618
+
619
+ expect(fixture.nativeElement.textContent).toContain('DEM-1');
620
+ });
621
+ ```
622
+
623
+ Keep `fixture.detectChanges()` for:
624
+
625
+ - checking an intermediate state, before the end of an asynchronous processing
626
+ - the tests with `vi.useFakeTimers()`: the refresh of Angular goes through timers, which must be
627
+ advanced (`await vi.advanceTimersByTimeAsync(...)`), otherwise `whenStable()` never ends
628
+
629
+ > 💡 So that the test goes through the same path as the user, trigger the events in the
630
+ > DOM (`input.dispatchEvent(new Event('change'))`, `button.click()`, ...) rather than calling the
631
+ > methods of the component or of its services.
632
+
633
+ ## Routing your pages
634
+
635
+ ### Simple form
389
636
 
390
637
  `app.routes.ts`
391
638
 
@@ -425,14 +672,14 @@ export const routes: Routes = [
425
672
  ];
426
673
  ```
427
674
 
428
- ### Formulaire complexe (sous-routes)
675
+ ### Complex form (sub-routes)
429
676
 
430
- > ℹ️ Préférez l'utilisation de **sous-routes** (`*.routes.ts`) pour regrouper vos routes et ainsi
431
- > mieux structurer votre projet.
677
+ > ℹ️ Prefer **sub-routes** (`*.routes.ts`) to group your routes and thus better structure your
678
+ > project.
432
679
  >
433
- > Comme il n'y a plus de modules (composants **standalone**), on ne charge plus un `*.module.ts` mais
434
- > un fichier de routes qui exporte une constante `Routes`. Voir [UPGRADING_V19.md](UPGRADING_V19.md)
435
- > pour le détail de la migration.
680
+ > As there are no more modules (**standalone** components), you no longer load a `*.module.ts` but
681
+ > a routes file exporting a `Routes` constant. See [UPGRADING_V19.md](UPGRADING_V19.md)
682
+ > for the details of the migration.
436
683
 
437
684
  `app.routes.ts`
438
685
 
@@ -472,9 +719,9 @@ export const routes: Routes = [
472
719
  ];
473
720
  ```
474
721
 
475
- > 💡 On charge donc `welcome.routes.ts` (et non plus `welcome.module.ts`) :
722
+ > 💡 So we load `welcome.routes.ts` (and no longer `welcome.module.ts`):
476
723
  > `loadChildren: () => import('./modules/welcome/welcome.routes').then((m) => m.welcome_routes)`
477
- > au lieu de `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
724
+ > instead of `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
478
725
 
479
726
  `welcome.routes.ts`
480
727
 
@@ -522,47 +769,52 @@ export const inscription_routes: Routes = [
522
769
  ];
523
770
  ```
524
771
 
525
- > 💡 Vous pouvez aussi charger paresseusement (`lazy-load`) un composant :
772
+ > 💡 You can also lazy-load a component:
526
773
  >
527
774
  > ```ts
528
775
  > { path: 'list', loadComponent: () => import('./demande-list-page/demande-list-page.component').then((m) => m.DemandeListPageComponent) },
529
776
  > ```
530
777
 
531
- ## Création d'un composant réutilisable
532
-
533
- > ℹ️ Créer un composant réutilisable en Angular n'est pas difficile mais pour qu'il soit adapté à
534
- > prestations-ng, c'est une autre affaire. Il va falloir respecter certaines règles, sans quoi, ça ne
535
- > fonctionnera pas correctement.
536
-
537
- ### Exemple avec foehn-input-date de prestations-ng
538
-
539
- Votre composant doit :
540
-
541
- 1. `selector` devrait commencer par `"app-..."` pour éviter d'éventuels conflits de nommage
542
- 2. avoir un `providers`
543
- 3. étendre `FoehnInputComponent` et vous devez lui préciser votre modèle de données
544
- 4. répartir les attributs de votre modèle de données dans des variables publiques utilisées dans
545
- votre HTML
546
- 5. implémenter une fonction `update` (ici ce sera `updateDate`) qui fera appel à `updateNgModel` pour
547
- maintenir la synchronisation de votre modèle de données avec votre page
548
- 6. implémenter une fonction `handleUserInput` qui fera appel à `handleChange` pour continuer à
549
- notifier le parent des changements de comportement de votre composant
550
- 7. implémenter une fonction `onModelChange` qui vous permettra d'initialiser correctement les
551
- variables publiques correspondant à votre modèle
552
- 8. implémenter une fonction `getValidValue` afin de reconstruire votre modèle de données avant de le
553
- retransmettre à votre page et retourner `null` si tous les attributs de votre objet sont vides (ça
554
- c'est pour que Java soit content)
555
-
556
- > 🚨 Points **standalone / signals** à respecter :
778
+ ## Creating a reusable component
779
+
780
+ > ℹ️ Creating a reusable component in Angular isn't difficult, but making it fit prestations-ng is
781
+ > another matter. Some rules must be respected, otherwise it won't work properly.
782
+
783
+ ### Example with foehn-input-date of prestations-ng
784
+
785
+ Your component must:
786
+
787
+ 1. `selector` should start with `"app-..."` to avoid possible naming conflicts
788
+ 2. have a `providers`
789
+ 3. extend `FoehnInputComponent`, to which you must give your data model
790
+ 4. spread the attributes of your data model in public **linked signals** (`linkedSignal()`) used
791
+ in your HTML: they follow the model of your page, and your sub-components change them
792
+ 5. implement an `update` function (here it will be `updateDate`) calling `updateNgModel` to
793
+ keep your data model synchronized with your page
794
+ 6. implement a `handleUserInput` function calling `handleChange` to keep
795
+ notifying the parent of the behavior changes of your component
796
+ 7. not override the `onModelChange` function for your linked signals, which already follow the
797
+ model: override it only to act on a new model of your page (e.g. to normalize it)
798
+ 8. implement a `getValidValue` function to rebuild your data model before sending it
799
+ back to your page, and return `null` if all the attributes of your object are empty (this
800
+ is to keep Java happy), once your model is known (`model_ !== undefined`): it is once the model of
801
+ your page has had a value to display, so that a model without any value (e.g. `[]`) is never
802
+ replaced by `null` without an input of the user
803
+
804
+ > 🚨 **standalone / signals** points to respect:
557
805
  >
558
- > - **Pas de `multi: true`** dans le `providers` (retiré depuis la migration standalone).
559
- > - Les `imports` du composant se déclarent **directement** dans le décorateur `@Component`. Chaque
560
- > composant charge ce dont il a besoin (voir `foehn-input-date` dans ce projet).
806
+ > - **No `multi: true`** in the `providers` (removed since the standalone migration).
807
+ > - The `imports` of the component are declared **directly** in the `@Component` decorator. Each
808
+ > component loads what it needs (see `foehn-input-date` in this project).
809
+ > - The state displayed by the component is held in **linked signals** (point 4), derived from the
810
+ > model: a plain field would not be displayed without zone.js, and a `signal()` filled by
811
+ > `onModelChange` (called by an `effect()`) would follow the model only at the next change
812
+ > detection.
561
813
 
562
814
  `input-date.component.ts`
563
815
 
564
816
  ```ts
565
- import { Component, forwardRef } from '@angular/core';
817
+ import { Component, forwardRef, linkedSignal } from '@angular/core';
566
818
 
567
819
  import { FoehnInputComponent } from '../foehn-input/foehn-input.component';
568
820
  import { FoehnInputNumberComponent } from '../foehn-input/foehn-input-number.component';
@@ -570,7 +822,7 @@ import { FoehnValidationAlertsComponent } from '../foehn-validation-alerts/foehn
570
822
  import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
571
823
 
572
824
  @Component({
573
- // point (1) : dans votre prestation, le selector sera plutôt 'app-...'
825
+ // point (1): in your prestation, the selector will rather be 'app-...'
574
826
  selector: 'app-input-date',
575
827
  templateUrl: './input-date.component.html',
576
828
  // point (2)
@@ -578,10 +830,10 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
578
830
  {
579
831
  provide: FoehnInputComponent,
580
832
  useExisting: forwardRef(() => InputDateComponent),
581
- // ⚠️ plus de `multi: true` en standalone
833
+ // ⚠️ no more `multi: true` in standalone
582
834
  },
583
835
  ],
584
- // les imports se déclarent directement ici : chaque composant charge ce dont il a besoin
836
+ // the imports are declared directly here: each component loads what it needs
585
837
  imports: [
586
838
  FoehnValidationAlertsComponent,
587
839
  FoehnInputNumberComponent,
@@ -589,12 +841,25 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
589
841
  ],
590
842
  })
591
843
  export class InputDateComponent extends FoehnInputComponent<number[]> {
592
- // point (3) : extends FoehnInputComponent<number[]>
593
-
594
- // point (4) : les attributs de votre modèle répartis en variables publiques
595
- day: string;
596
- month: string;
597
- year: string;
844
+ // point (3): extends FoehnInputComponent<number[]>
845
+
846
+ // point (4): the attributes of your model spread in public linked signals. A new model of your
847
+ // page resets them, a model too short to hold a date keeps them (previous value).
848
+ readonly day = linkedSignal<number[] | null | undefined, string | null>({
849
+ source: this.model,
850
+ computation: (value, previous) =>
851
+ this.getDatePart(value, 2, previous?.value),
852
+ });
853
+ readonly month = linkedSignal<number[] | null | undefined, string | null>({
854
+ source: this.model,
855
+ computation: (value, previous) =>
856
+ this.getDatePart(value, 1, previous?.value),
857
+ });
858
+ readonly year = linkedSignal<number[] | null | undefined, string | null>({
859
+ source: this.model,
860
+ computation: (value, previous) =>
861
+ this.getDatePart(value, 0, previous?.value),
862
+ });
598
863
 
599
864
  // point (5)
600
865
  updateDate(): void {
@@ -612,25 +877,14 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
612
877
  }
613
878
  }
614
879
 
615
- // point (7)
616
- override onModelChange(value: number[]): void {
617
- if (value && value.length > 2) {
618
- this.year = this.toString(value[0]);
619
- this.month = this.toString(value[1]);
620
- this.day = this.toString(value[2]);
621
- } else if (!value) {
622
- this.year = null;
623
- this.month = null;
624
- this.day = null;
625
- }
626
- }
880
+ // point (7): no onModelChange(), the linked signals of point (4) already follow the model
627
881
 
628
882
  // point (8)
629
883
  getValidValue(): number[] | null | undefined {
630
884
  if (
631
- this.isEmpty(this.day) &&
632
- this.isEmpty(this.month) &&
633
- this.isEmpty(this.year)
885
+ this.isEmpty(this.day()) &&
886
+ this.isEmpty(this.month()) &&
887
+ this.isEmpty(this.year())
634
888
  ) {
635
889
  if (this.model_ !== undefined) {
636
890
  return null;
@@ -640,26 +894,43 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
640
894
  }
641
895
 
642
896
  return [
643
- this.toNumber(this.year),
644
- this.toNumber(this.month),
645
- this.toNumber(this.day),
897
+ this.toNumber(this.year()),
898
+ this.toNumber(this.month()),
899
+ this.toNumber(this.day()),
646
900
  ];
647
901
  }
648
902
 
649
903
  // ...code
904
+
905
+ private getDatePart(
906
+ value: number[] | null | undefined,
907
+ index: number,
908
+ previous: string | null | undefined,
909
+ ): string | null {
910
+ if (value && value.length > 2) {
911
+ return this.toString(value[index]);
912
+ }
913
+ return value ? (previous ?? null) : null;
914
+ }
650
915
  }
651
916
  ```
652
917
 
653
- Chaque `foehn-input-*` utilisé dans votre vue doit :
918
+ > 💡 A field that only reads a property of the model can use the short form, e.g.
919
+ > `readonly street = linkedSignal(() => this.model()?.street ?? null);` (see `foehn-input-address`).
920
+ > It resets the field at every new model: use the form `{ source, computation }`, as above, when a
921
+ > field must keep its value on a partial model.
922
+
923
+ Each `foehn-input-*` used in your view must:
654
924
 
655
- 1. avoir un `id` qui concatène l'appel à la fonction `buildId()` et le nom de l'attribut de votre objet
656
- 2. avoir un `name` qui concatène l'input **signal** `name()` et le nom de l'attribut de votre objet
657
- 3. avoir un `label`
658
- 4. utiliser votre variable publique comme model en double-binding (banana in the box)
659
- 5. faire appel à `updateDate()` lors du déclenchement de l'événement `(modelChange)`
660
- 6. faire appel à `handleUserInput()` lors du déclenchement de l'événement `(userInput)`
925
+ 1. have an `id` concatenating the call to the `buildId()` function and the name of the attribute of your object
926
+ 2. have a `name` concatenating the **signal** input `name()` and the name of the attribute of your object
927
+ 3. have a `label`
928
+ 4. use your public signal as model in two-way binding (banana in the box): `[(model)]="day"`
929
+ reads and writes the signal (without the parentheses)
930
+ 5. call `updateDate()` when the `(modelChange)` event is triggered
931
+ 6. call `handleUserInput()` when the `(userInput)` event is triggered
661
932
 
662
- > 💡 `name` est désormais un **input signal**. On l'invoque : `name() + '_day'` (et non plus
933
+ > 💡 `name` is now an **input signal**. You call it: `name() + '_day'` (and no longer
663
934
  > `name + '_day'`).
664
935
 
665
936
  `input-date.component.html`
@@ -702,20 +973,20 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
702
973
  />
703
974
  ```
704
975
 
705
- ### Afficher la validation globale du composant
976
+ ### Displaying the global validation of the component
706
977
 
707
- - Il faut ajouter dans la partie HTML de votre composant le code décrit ci-dessous
708
- - Remonter une erreur correspondant au `name` de votre composant lorsque celui-ci est utilisé dans
709
- votre page de formulaire.
978
+ - Add the code below in the HTML part of your component
979
+ - Return an error matching the `name` of your component when it is used in
980
+ your form page.
710
981
 
711
- > 💡 Points **signals** à noter dans ce template :
982
+ > 💡 **signals** points to note in this template:
712
983
  >
713
- > - `@if` remplace `*ngIf` et les attributs du composant sont des signaux : on les invoque
984
+ > - `@if` replaces `*ngIf`, and the attributes of the component are signals: you call them
714
985
  > (`label()`, `required()`, `isLabelSrOnly()`, `hideNotRequiredExtraLabel()`, `helpText()`).
715
- > - `[ngClass]` est remplacé par des bindings `[class.xxx]="..."`.
986
+ > - `[ngClass]` is replaced by `[class.xxx]="..."` bindings.
716
987
 
717
988
  ```html
718
- <!-- (obligatoire) Affichera une barre verticale rouge sur l'entier du composant -->
989
+ <!-- (mandatory) Displays a red vertical bar on the whole component -->
719
990
  <div
720
991
  class="form-group"
721
992
  [class.has-danger]="hasErrorsToDisplay()"
@@ -723,12 +994,12 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
723
994
  [attr.id]="buildId('Container')"
724
995
  tabindex="-1"
725
996
  >
726
- <!-- (obligatoire) Permet de regrouper vos champs pour une validation globale -->
997
+ <!-- (mandatory) Groups your fields for a global validation -->
727
998
  <fieldset
728
999
  [attr.aria-describedby]="getDescribedBy()"
729
1000
  [attr.aria-invalid]="hasErrorsToDisplay() || null"
730
1001
  >
731
- <!-- (facultatif) Seulement si vous souhaitez afficher un label/legend global à votre composant -->
1002
+ <!-- (optional) Only if you want to display a global label/legend for your component -->
732
1003
  @if (!!label()) {
733
1004
  <legend
734
1005
  [class.visually-hidden]="isLabelSrOnly()"
@@ -743,10 +1014,10 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
743
1014
  </legend>
744
1015
  }
745
1016
 
746
- <!-- (obligatoire) -->
1017
+ <!-- (mandatory) -->
747
1018
  <foehn-validation-alerts [component]="this" />
748
1019
 
749
- <!-- (facultatif) Seulement si vous souhaitez pouvoir afficher un helpText global au composant -->
1020
+ <!-- (optional) Only if you want to be able to display a global helpText for the component -->
750
1021
  @if (helpText()) {
751
1022
  <small
752
1023
  [attr.id]="buildId() + 'Help'"
@@ -755,69 +1026,69 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
755
1026
  ></small>
756
1027
  }
757
1028
 
758
- <!-- ...vos foehn-input-* ici -->
1029
+ <!-- ...your foehn-input-* here -->
759
1030
  </fieldset>
760
1031
  </div>
761
1032
  ```
762
1033
 
763
- ### Éviter des problèmes d'affichage d'erreurs dans une boucle `@for`
1034
+ ### Avoiding error display problems in a `@for` loop
764
1035
 
765
- > ⚠️ Ne pas oublier de mettre un `track` avec un identifiant unique dans la boucle `@for` sinon la
766
- > validation ne s'affichera pas. Quand un identifiant unique tel que `id` n'est pas possible, tracker
767
- > par objet ou, en dernier recours, `track $index`.
1036
+ > ⚠️ Don't forget to put a `track` with a unique identifier in the `@for` loop, otherwise the
1037
+ > validation won't be displayed. When a unique identifier such as `id` isn't possible, track
1038
+ > by `$index`: never by object a list of the form whose rows edit their item (see "Binding the fields of the form").
768
1039
 
769
- > ℹ️ Dans une boucle `@for` d'Angular avec un composant `FoehnInputComponent`, si vous validez votre
770
- > formulaire, les erreurs remontées sont synchronisées avec l'index de vos composants répétés dans la
771
- > boucle.
1040
+ > ℹ️ In an Angular `@for` loop with a `FoehnInputComponent` component, if you validate your
1041
+ > form, the errors returned are synchronized with the index of your components repeated in the
1042
+ > loop.
772
1043
  >
773
- > **Scénario :** Dans votre liste, lorsque vous supprimez un composant qui contient des erreurs à
774
- > l'index 0 (par ex.) et que le composant suivant (index 1) n'a pas d'erreur ou pas les mêmes
775
- > erreurs, alors ce dernier se retrouve avec les erreurs du composant fraîchement supprimé à
776
- > l'index 0.
1044
+ > **Scenario:** In your list, when you remove a component that has errors at
1045
+ > index 0 (for example) and the next component (index 1) has no errors or not the same
1046
+ > errors, then the latter ends up with the errors of the component just removed at
1047
+ > index 0.
777
1048
  >
778
- > **Explication :** Ce phénomène est dû au fait que les erreurs remontées par GESDEM ne se
779
- > rafraîchissent que lors de la demande de sauvegarde des données. Du coup, le composant supprimé à
780
- > l'index 0 est remplacé par celui à l'index 1 mais les erreurs à l'index 0, elles, existent toujours
781
- > et se reportent donc sur le composant venant de l'index 1.
1049
+ > **Explanation:** This happens because the errors returned by GESDEM are only
1050
+ > refreshed when the data is saved. So the component removed at
1051
+ > index 0 is replaced by the one at index 1, but the errors at index 0 still exist
1052
+ > and are therefore carried over to the component coming from index 1.
782
1053
 
783
- Voici la bonne pratique à mettre en place pour palier à ces problèmes d'affichage d'erreurs dans une
784
- boucle `@for`.
1054
+ Here is the good practice to put in place to work around these error display problems in a
1055
+ `@for` loop.
785
1056
 
786
- Lorsque vous supprimez un élément dans votre liste, vous devez appeler une méthode se trouvant dans
787
- votre `AbstractPageComponent`. Cette méthode contiendra le code suivant :
1057
+ When you remove an item from your list, you must call a method of
1058
+ your `AbstractPageComponent`. This method will contain the following code:
788
1059
 
789
1060
  ```ts
790
1061
  /*
791
1062
  * if an inventory item that was in error is removed, this prevents the error to be displayed
792
1063
  * to the next item that has taken it's index
793
1064
  */
794
- this._gesdemService.validate(this.form).pipe(first()).subscribe();
1065
+ this._gesdemService.validate(this.form()).pipe(first()).subscribe();
795
1066
  ```
796
1067
 
797
- Voici un exemple de page de formulaire contenant cette méthode (1) :
1068
+ Here is an example of a form page containing this method (1):
798
1069
 
799
- > 💡 Plus de `constructor` : on fait de l'**inject**. Les dépendances de `AbstractPageComponent`
800
- > (dont `_dictionaryService` et `_gesdemService`) sont déjà injectées dans la classe abstraite. Pour
801
- > vos propres dépendances, utilisez `inject()`.
1070
+ > 💡 No more `constructor`: we use **inject**. The dependencies of `AbstractPageComponent`
1071
+ > (including `_dictionaryService` and `_gesdemService`) are already injected in the abstract class. For
1072
+ > your own dependencies, use `inject()`.
802
1073
 
803
1074
  ```ts
804
1075
  @Component({
805
- templateUrl: './votre-page.component.html',
1076
+ templateUrl: './your-page.component.html',
806
1077
  imports: [
807
- // ... vos composants foehn-*
1078
+ // ... your foehn-* components
808
1079
  ],
809
1080
  })
810
- export class VotrePageComponent
1081
+ export class YourPageComponent
811
1082
  extends AbstractPageComponent<BusinessForm>
812
1083
  implements OnInit
813
1084
  {
814
- // vos propres dépendances : inject() au lieu du constructor
1085
+ // your own dependencies: inject() instead of the constructor
815
1086
  private readonly metaService = inject(MetaService);
816
1087
 
817
1088
  ngOnInit(): void {
818
1089
  super.ngOnInit();
819
1090
  this.setPageTitle(
820
- this._dictionaryService.getKeySync('votre-page.title'),
1091
+ this._dictionaryService.getKeySync('your-page.title'),
821
1092
  );
822
1093
  }
823
1094
 
@@ -831,17 +1102,17 @@ export class VotrePageComponent
831
1102
  * if an inventory item that was in error is removed, this prevents the error to be displayed
832
1103
  * to the next item that has taken it's index
833
1104
  */
834
- this._gesdemService.validate(this.form).pipe(first()).subscribe();
1105
+ this._gesdemService.validate(this.form()).pipe(first()).subscribe();
835
1106
  }
836
1107
  }
837
1108
  ```
838
1109
 
839
- Il ne tient qu'à vous de décider comment appeler cette méthode lors de la suppression de l'élément de
840
- votre liste.
1110
+ It's up to you to decide how to call this method when the item is removed from
1111
+ your list.
841
1112
 
842
- Voici une manière élégante de gérer vos listes d'éléments :
1113
+ Here is an elegant way to handle your lists of items:
843
1114
 
844
- - Structure des dossiers et fichiers
1115
+ - Structure of the folders and files
845
1116
 
846
1117
  ```text
847
1118
  demande-page/
@@ -858,7 +1129,7 @@ demande-page/
858
1129
 
859
1130
  **vehicule-item**
860
1131
 
861
- `vehicule-item.component.html` contient le bouton pour la suppression de l'élément dans la liste (1).
1132
+ `vehicule-item.component.html` contains the button removing the item from the list (1).
862
1133
 
863
1134
  ```html
864
1135
  <div
@@ -871,7 +1142,7 @@ demande-page/
871
1142
  <foehn-validation-alerts [component]="this" />
872
1143
 
873
1144
  <div class="row d-flex align-items-end vehicule-infos">
874
- <!-- ... vos composants foehn-input-* -->
1145
+ <!-- ... your foehn-input-* components -->
875
1146
 
876
1147
  <div class="col-md-2 mt-md-0 mt-xs-2">
877
1148
  <button class="btn btn-danger" (click)="removeVehicule()">
@@ -883,10 +1154,10 @@ demande-page/
883
1154
  </div>
884
1155
  ```
885
1156
 
886
- `vehicule-item.component.ts` contient la fonction de suppression qui va remonter l'événement à son
887
- parent (la liste des éléments).
1157
+ `vehicule-item.component.ts` contains the removal function, which sends the event up to its
1158
+ parent (the list of items).
888
1159
 
889
- > 💡 `@Output() + EventEmitter` sont remplacés par la fonction `output()`.
1160
+ > 💡 `@Output() + EventEmitter` are replaced by the `output()` function.
890
1161
 
891
1162
  ```ts
892
1163
  @Component({
@@ -900,7 +1171,7 @@ parent (la liste des éléments).
900
1171
  ],
901
1172
  imports: [
902
1173
  FoehnValidationAlertsComponent,
903
- // ... vos foehn-input-*
1174
+ // ... your foehn-input-*
904
1175
  SdkDictionaryPipe,
905
1176
  ],
906
1177
  })
@@ -917,11 +1188,11 @@ export class VehiculeItemComponent extends FoehnInputComponent<Vehicule> {
917
1188
 
918
1189
  **vehicules-list**
919
1190
 
920
- `vehicules-list.component.html` contient votre boucle `@for` (1) et votre composant répétable (2) qui
921
- devra lui aussi remonter l'événement.
1191
+ `vehicules-list.component.html` contains your `@for` loop (1) and your repeatable component (2), which
1192
+ must also send the event up.
922
1193
 
923
- > ⚠️ Dans la boucle `@for` ne pas oublier de mettre un `track` (identifiant unique) sinon la
924
- > validation ne s'affichera pas. Ici nous trackons par exemple avec `vehicule.id`.
1194
+ > ⚠️ In the `@for` loop, don't forget to put a `track` (unique identifier), otherwise the
1195
+ > validation won't be displayed. Here, for example, we track with `vehicule.id`.
925
1196
 
926
1197
  ```html
927
1198
  <div
@@ -954,12 +1225,12 @@ devra lui aussi remonter l'événement.
954
1225
  ></small>
955
1226
  }
956
1227
 
957
- <!-- (1) votre boucle @for + track (identifiant unique) -->
958
- @for (vehicule of vehicules; track vehicule.id; let i = $index) {
959
- <!-- (2) votre composant réutilisable -->
1228
+ <!-- (1) your @for loop + track (unique identifier) -->
1229
+ @for (vehicule of vehicules(); track vehicule.id; let i = $index) {
1230
+ <!-- (2) your reusable component -->
960
1231
  <app-vehicule-item
961
1232
  [name]="name() + '[' + i + ']'"
962
- [(model)]="vehicule"
1233
+ [model]="vehicule"
963
1234
  (modelChange)="updateVehiculesList($event, i)"
964
1235
  (userInput)="handleUserInput($event, i)"
965
1236
  (removedVehicule)="handleRemovedVehicule(i)"
@@ -972,12 +1243,15 @@ devra lui aussi remonter l'événement.
972
1243
  </div>
973
1244
  ```
974
1245
 
975
- > 💡 Le `name` est un input signal : `[name]="name() + '[' + i + ']'"` (et non plus
1246
+ > 💡 The `name` is an input signal: `[name]="name() + '[' + i + ']'"` (and no longer
976
1247
  > `[name]="name + '[' + i + ']'"`).
1248
+ >
1249
+ > 💡 The variable of a `@for` loop can't be modified: the item is passed with `[model]`, and
1250
+ > the item of the list is replaced in `updateVehiculesList()` (called by `(modelChange)`).
977
1251
 
978
- `vehicules-list.component.ts` remonte à son tour l'événement (1) au parent (`AbstractPageComponent`)
979
- ainsi que supprimer l'élément de la liste (2). C'est aussi ici que vous pouvez gérer l'ajout d'un
980
- élément (3).
1252
+ `vehicules-list.component.ts` in turn sends the event (1) up to the parent (`AbstractPageComponent`)
1253
+ and removes the item from the list (2). This is also where you can handle the addition of an
1254
+ item (3).
981
1255
 
982
1256
  ```ts
983
1257
  @Component({
@@ -996,45 +1270,58 @@ ainsi que supprimer l'élément de la liste (2). C'est aussi ici que vous pouvez
996
1270
  ],
997
1271
  })
998
1272
  export class VehiculesListComponent extends FoehnInputComponent<Vehicule[]> {
999
- readonly removedVehicule = output<void>(); // (1) événement à remonter au parent
1273
+ readonly removedVehicule = output<void>(); // (1) event to send up to the parent
1274
+
1275
+ // Signal holding your repeatable items, derived from the model: it is replaced, never modified in place
1276
+ readonly vehicules = linkedSignal(() => this.model() ?? []);
1000
1277
 
1001
- vehicules: Vehicule[] = []; // Tableau contenant vos éléments répétables
1278
+ updateVehiculesList(vehicule: Vehicule, index: number): void {
1279
+ this.vehicules.update((vehicules) =>
1280
+ vehicules.map((item, i) => (i === index ? vehicule : item)),
1281
+ );
1282
+ this.getValidValueAndUpdateNgModel(); // Update of your model
1283
+ }
1002
1284
 
1003
1285
  handleRemovedVehicule(index: number): void {
1004
- // (2) votre fonction de suppression de l'élément ainsi que la transmission de l'évènement
1005
- this.vehicules.splice(index, 1); // suppression de l'élément
1006
- this.getValidValueAndUpdateNgModel(); // Mise à jour de votre modèle
1007
- this.removedVehicule.emit(); // (1) on remonte l'évènement
1286
+ // (2) your function removing the item and sending the event
1287
+ this.vehicules.update((vehicules) =>
1288
+ vehicules.filter((_vehicule, i) => i !== index),
1289
+ ); // removal of the item
1290
+ this.getValidValueAndUpdateNgModel(); // Update of your model
1291
+ this.removedVehicule.emit(); // (1) the event is sent up
1008
1292
  }
1009
1293
 
1010
1294
  addVehicule(): void {
1011
- // (3) Gestion de l'ajout d'un élément
1295
+ // (3) Handling of the addition of an item
1012
1296
  // ...code
1013
1297
  }
1014
1298
  }
1015
1299
  ```
1016
1300
 
1017
- > 💡 Plus besoin de définir une `trackByFn` dédiée : la nouvelle syntaxe `@for` utilise directement
1018
- > l'expression `track` (ici `vehicule.id`).
1301
+ > 💡 No need to define a dedicated `trackByFn` anymore: the new `@for` syntax directly uses
1302
+ > the `track` expression (here `vehicule.id`).
1019
1303
 
1020
1304
  **demande-page**
1021
1305
 
1022
- `demande-page.component.html` utilisera votre composant de liste de véhicule (1) et écoutera pour
1023
- l'événement de suppression (2).
1306
+ `demande-page.component.html` uses your vehicle list component (1) and listens to
1307
+ the removal event (2).
1024
1308
 
1025
1309
  ```html
1026
1310
  <foehn-form>
1027
1311
  <!-- ... -->
1028
1312
  <h2>{{ 'demande-page.vehicules' | fromDictionary }}</h2>
1029
1313
 
1314
+ @if (form(); as form) {
1030
1315
  <app-vehicules-list
1031
- [(model)]="form.vehicules"
1316
+ [model]="form.vehicules"
1317
+ (modelChange)="patchForm(['vehicules'], $event)"
1032
1318
  name="vehicules"
1033
1319
  [label]="'demande-page.vehicules-list' | fromDictionary"
1034
1320
  [required]="true"
1035
1321
  (removedVehicule)="handleRemovedVehicule()"
1036
1322
  />
1037
- <!-- (1) Utilisation de votre liste - (2) Appel de la méthode qui sauvegardera les données dans GESDEM afin de rafraîchir les erreurs -->
1323
+ }
1324
+ <!-- (1) Use of your list - (2) Call of the method saving the data in GESDEM to refresh the errors -->
1038
1325
 
1039
1326
  <foehn-navigation
1040
1327
  id="navigation"
@@ -1044,8 +1331,8 @@ l'événement de suppression (2).
1044
1331
  </foehn-form>
1045
1332
  ```
1046
1333
 
1047
- `demande-page.component.ts` se chargera de l'appel à GESDEM afin de re-générer les erreurs du
1048
- formulaire et ainsi rafraîchir l'index.
1334
+ `demande-page.component.ts` calls GESDEM to generate the errors of the
1335
+ form again, and thus refresh the index.
1049
1336
 
1050
1337
  ```ts
1051
1338
  @Component({
@@ -1062,25 +1349,78 @@ export class DemandePageComponent
1062
1349
  * if an inventory item that was in error is removed, this prevents the error to be displayed
1063
1350
  * to the next item that has taken it's index
1064
1351
  */
1065
- this._gesdemService.save(this.form).pipe(first()).subscribe();
1352
+ this._gesdemService.save(this.form()).pipe(first()).subscribe();
1066
1353
  }
1067
1354
  }
1068
1355
  ```
1069
1356
 
1070
- ## Validation du formulaire
1357
+ ## Types of the form fields
1358
+
1359
+ > ℹ️ `AbstractPageComponent` replaces `form` with the JSON sent by the backend, as is: at runtime, a field has
1360
+ > the type of the JSON written from the Java model, whatever its TypeScript type says.
1361
+
1362
+ Give the Java field the type matching the model of the component:
1363
+
1364
+ | Component | TypeScript model | Java field |
1365
+ | ------------------------------------------------------------------ | -------------------- | -------------------------------------- |
1366
+ | `foehn-input-text`, `foehn-input-textarea`, `foehn-input-email`... | `string` | `String` |
1367
+ | `foehn-input-time` | `string` | `String` with `@ValidStringTime` |
1368
+ | `foehn-input-date` | `(number \| null)[]` | `LenientLocalDate` |
1369
+ | `foehn-input-date-time` | `(number \| null)[]` | `LenientLocalDateTime` |
1370
+ | `foehn-boolean-checkbox`, `foehn-boolean-radio` | `boolean` | `Boolean` |
1371
+ | `foehn-input-number` | `string` | `Integer`, `BigDecimal`... (see below) |
1372
+
1373
+ > ⚠️ The model of `foehn-input-number` is a `string`: the component keeps the input as typed (decimal comma,
1374
+ > leading zeros, number of decimals). But the Java field is a number (`Integer`, `BigDecimal`), which is
1375
+ > written as a number in the JSON. The field holds `'0'` after the input of the user, and `0` once the form
1376
+ > comes back from the backend. The same happens with any component whose model is a `string` bound to a Java
1377
+ > field which isn't a `String`.
1378
+
1379
+ Never test such a field by its truthiness (`!!value`, `if (value)`, `value || ...`): `'0'` is true, `0` is
1380
+ false.
1381
+
1382
+ What **not** to do:
1383
+
1384
+ ```ts
1385
+ isAmountFilled(): boolean {
1386
+ // true after the input of '0', false once the form is loaded (0)
1387
+ return !!this.form()?.amount;
1388
+ }
1389
+ ```
1390
+
1391
+ What **to** do:
1392
+
1393
+ ```ts
1394
+ isAmountFilled(): boolean {
1395
+ const amount = this.form()?.amount;
1396
+ return amount !== null && amount !== undefined && amount !== '';
1397
+ }
1398
+
1399
+ getTotal(): number {
1400
+ // Number() converts '12.50' as well as 12.5
1401
+ return Number(this.form()?.amount ?? 0) + Number(this.form()?.fees ?? 0);
1402
+ }
1403
+ ```
1404
+
1405
+ > ⚠️ The values of the elements of `foehn-select` and `foehn-checkbox` must have the type of the Java field:
1406
+ > they are compared to the model with `===`. With `'1'` as value of an element and `1` sent by the backend
1407
+ > (`Integer`), no element is selected anymore once the form is loaded, and the component warns that the saved
1408
+ > value no longer exists in the list.
1409
+
1410
+ ## Form validation
1071
1411
 
1072
- > ℹ️ Lors de la sauvegarde de votre formulaire dans GESDEM, l'`AbstractPageComponent` gère pour vous
1073
- > l'affichage éventuel des erreurs.
1412
+ > ℹ️ When your form is saved in GESDEM, the `AbstractPageComponent` handles the
1413
+ > display of the errors for you.
1074
1414
  >
1075
- > Si par contre vous souhaitez sauvegarder les données ailleurs que dans GESDEM, vous serez confronté
1076
- > à la gestion manuelle de l'affichage des erreurs.
1415
+ > If, however, you want to save the data somewhere else than in GESDEM, you will have to handle
1416
+ > the display of the errors manually.
1077
1417
 
1078
- ### Gestion standard
1418
+ ### Standard handling
1079
1419
 
1080
- > ℹ️ Lors de l'enregistrement de vos données dans GESDEM, l'affichage des erreurs est automatiquement
1081
- > géré pour vous. Cependant, vous devez impérativement respecter certaines règles.
1420
+ > ℹ️ When your data is saved in GESDEM, the display of the errors is handled automatically
1421
+ > for you. However, you must respect some rules.
1082
1422
 
1083
- Prenons un exemple de modèle simple côté front à deux niveaux de profondeur :
1423
+ Let's take an example of a simple front-end model with two levels of depth:
1084
1424
 
1085
1425
  `identification.ts`
1086
1426
 
@@ -1100,44 +1440,52 @@ export class BusinessForm {
1100
1440
  }
1101
1441
  ```
1102
1442
 
1103
- > ⚠️ Le modèle ci-dessus devra impérativement être reflété dans le `name` de vos composants
1104
- > `foehn-input-*` de votre page.
1443
+ > ⚠️ The model above must be reflected in the `name` of the `foehn-input-*`
1444
+ > components of your page.
1105
1445
 
1106
1446
  `page-1.html`
1107
1447
 
1108
1448
  ```html
1449
+ @if (form(); as form) {
1109
1450
  <foehn-input-text
1110
- [(model)]="form.identification.firstName"
1451
+ [model]="form.identification.firstName"
1452
+ (modelChange)="patchForm(['identification', 'firstName'], $event)"
1111
1453
  name="identification.firstName"
1112
1454
  />
1113
- <!-- 2 niveaux de profondeur -->
1455
+ <!-- 2 levels of depth -->
1114
1456
 
1115
1457
  <foehn-input-text
1116
- [(model)]="form.identification.lastName"
1458
+ [model]="form.identification.lastName"
1459
+ (modelChange)="patchForm(['identification', 'lastName'], $event)"
1117
1460
  name="identification.lastName"
1118
1461
  />
1119
1462
 
1120
- <foehn-boolean-checkbox [(model)]="form.acceptCookies" name="acceptCookies" />
1121
- <!-- 1 niveau de profondeur -->
1463
+ <foehn-boolean-checkbox
1464
+ [model]="form.acceptCookies"
1465
+ (modelChange)="patchForm(['acceptCookies'], $event)"
1466
+ name="acceptCookies"
1467
+ />
1468
+ <!-- 1 level of depth -->
1469
+ }
1122
1470
  ```
1123
1471
 
1124
- - Côté back-end, vous pouvez gérer vos erreurs grâce aux annotations (`@NotEmpty`, `@NotNull`, ...),
1125
- et **prestations-be** fera le reste pour vous.
1126
- - Si vous souhaitez remonter une erreur spécifique à un champ de votre formulaire, voici la syntaxe :
1472
+ - On the back-end side, you can handle your errors with the annotations (`@NotEmpty`, `@NotNull`, ...),
1473
+ and **prestations-be** does the rest for you.
1474
+ - If you want to return an error specific to a field of your form, here is the syntax:
1127
1475
 
1128
1476
  ```java
1129
- new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "Le nom est obligatoire si vous ne spécifiez pas de prénom")
1477
+ new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name")
1130
1478
  ```
1131
1479
 
1132
- > ⚠️ Le nom de l'erreur doit impérativement correspondre au nom de votre composant dans votre page
1133
- > HTML.
1480
+ > ⚠️ The name of the error must match the name of your component in your HTML
1481
+ > page.
1134
1482
 
1135
- ### Gestion manuelle
1483
+ ### Manual handling
1136
1484
 
1137
1485
  #### Back-end
1138
1486
 
1139
- Côté back-end JAVA, le serveur devra retourner un objet contenant les erreurs du formulaire afin
1140
- d'être compatible avec prestations-ng.
1487
+ On the JAVA back-end side, the server must return an object containing the errors of the form to
1488
+ be compatible with prestations-ng.
1141
1489
 
1142
1490
  ```java
1143
1491
  @Getter
@@ -1151,40 +1499,41 @@ public class PostResponse<T> {
1151
1499
 
1152
1500
  @Builder.Default
1153
1501
  private List<AbstractSdkController.FormError> errors = new ArrayList<>();
1154
- // AbstractSdkController.FormError vient de prestations-be qui est la partie backend de prestations-ng
1502
+ // AbstractSdkController.FormError comes from prestations-be, the backend part of prestations-ng
1155
1503
  }
1156
1504
  ```
1157
1505
 
1158
- Ensuite, ajoutez vos erreurs dans votre modèle avant de le retourner au front-end :
1506
+ Then, add your errors to your model before returning it to the front-end:
1159
1507
 
1160
1508
  ```java
1161
1509
  List<AbstractSdkController.FormError> errors = new ArrayList<>();
1162
- errors.add(new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "Le nom est obligatoire si vous ne spécifiez pas de prénom"));
1510
+ errors.add(new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name"));
1163
1511
 
1164
1512
  PostResponse.<MyObject>builder().dto(myObject).errors(errors).build();
1165
1513
  ```
1166
1514
 
1167
1515
  #### Front-end
1168
1516
 
1169
- Côté front-end, comme la validation standard, les noms de vos composants `foehn-input-*` de votre
1170
- page HTML et le nom de vos erreurs devront correspondre.
1517
+ On the front-end side, as for the standard validation, the names of the `foehn-input-*` components of your
1518
+ HTML page and the names of your errors must match.
1171
1519
 
1172
1520
  ```html
1173
1521
  <foehn-input-text
1174
- [(model)]="form.identification.lastName"
1522
+ [model]="form.identification.lastName"
1523
+ (modelChange)="patchForm(['identification', 'lastName'], $event)"
1175
1524
  name="identification.lastName"
1176
1525
  />
1177
1526
  ```
1178
1527
 
1179
- > ⚠️ Au retour de la sauvegarde de vos données, vous allez devoir déclencher manuellement la
1180
- > validation.
1528
+ > ⚠️ When your data has been saved, you will have to trigger the validation
1529
+ > manually.
1181
1530
 
1182
- 1. Dans votre `page.ts`, créez une fonction `handleValidationErrors` pour gérer l'affichage des
1183
- erreurs.
1184
- 2. Cette fonction sera appelée au retour du back-end.
1531
+ 1. In your `page.ts`, create a `handleValidationErrors` function to handle the display of the
1532
+ errors.
1533
+ 2. This function is called when the back-end answers.
1185
1534
 
1186
- > 💡 Point **signals** : plus de `@ViewChild('formWithModels')`. Pour utiliser un composant dans le
1187
- > TypeScript, on utilise un **signal** `viewChild(...)`. On accède ensuite à l'instance en l'invoquant :
1535
+ > 💡 **signals** point: no more `@ViewChild('formWithModels')`. To use a component in the
1536
+ > TypeScript, use a `viewChild(...)` **signal**. Then access the instance by calling it:
1188
1537
  > `this.formWithModels()`.
1189
1538
 
1190
1539
  `page.ts`
@@ -1201,39 +1550,41 @@ import {
1201
1550
  // ...
1202
1551
  })
1203
1552
  export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1204
- // point (7 des signaux) : un signal viewChild au lieu de @ViewChild
1553
+ // a viewChild signal instead of @ViewChild
1205
1554
  readonly formWithModels = viewChild(FoehnFormComponent);
1206
1555
 
1207
- // vos propres dépendances via inject()
1556
+ // your own dependencies with inject()
1208
1557
  private readonly httpClient = inject(HttpClient);
1209
1558
 
1210
1559
  ngOnInit(): void {
1211
1560
  super.ngOnInit();
1212
- // Activer l'affichage des erreurs
1561
+ // Enable the display of the errors
1213
1562
  this._validationHandlerService.shouldDisplayErrors(true);
1214
1563
  }
1215
1564
 
1216
- // Fonction de sauvegarde
1565
+ // Save function
1217
1566
  save(): void {
1218
- // Activer l'affichage des erreurs
1567
+ // Enable the display of the errors
1219
1568
  this._validationHandlerService.shouldDisplayErrors(true);
1220
- // Appel au back pour faire votre validation
1569
+ // Call to the back-end to do your validation. The callback modifies no field of the page:
1570
+ // the services of prestations-ng (growl, errors) refresh the display themselves, also
1571
+ // without zone.js. A state of the page modified here should be a signal.
1221
1572
  this.httpClient
1222
- .post<PostResponse>('api_url_ici', votre_objet)
1573
+ .post<PostResponse>('api_url_here', your_object)
1223
1574
  .subscribe((response: PostResponse) => {
1224
1575
  if (!response.errors.length) {
1225
- // On prévient l'utilisateur que tout s'est bien passé
1576
+ // Tell the user that everything went well
1226
1577
  this._growlService.addWithType(
1227
1578
  GrowlType.SUCCESS,
1228
- 'Enregistrement effectué avec succès',
1579
+ 'Saved successfully',
1229
1580
  );
1230
1581
  }
1231
- // Gestion des erreurs au retour du back-end
1582
+ // Handling of the errors returned by the back-end
1232
1583
  this.handleValidationErrors(response.errors); // point (2)
1233
1584
  });
1234
1585
  }
1235
1586
 
1236
- // Affichage des erreurs
1587
+ // Display of the errors
1237
1588
  private handleValidationErrors(errors: ErrorTemplate[]): void {
1238
1589
  // point (1)
1239
1590
  const form = this.formWithModels();
@@ -1251,21 +1602,21 @@ export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1251
1602
 
1252
1603
  ```html
1253
1604
  <foehn-form>
1254
- <!-- ... vos composants foehn-input-* -->
1605
+ <!-- ... your foehn-input-* components -->
1255
1606
  </foehn-form>
1256
1607
  ```
1257
1608
 
1258
- ## Validation manuelle d'un composant
1609
+ ## Manual validation of a component
1259
1610
 
1260
- ### Cacher une erreur
1611
+ ### Hiding an error
1261
1612
 
1262
- > ✅ Utiliser la fonction `markAsDirty()` permet de simuler une interaction avec le composant.
1613
+ > ✅ The `markAsDirty()` function simulates an interaction with the component.
1263
1614
  >
1264
- > ℹ️ Permet de cacher l'erreur d'un composant foehn-input en erreur.
1615
+ > ℹ️ Hides the error of a foehn-input component in error.
1265
1616
 
1266
- ### Afficher une erreur
1617
+ ### Displaying an error
1267
1618
 
1268
- > ✅ Utiliser la fonction `markAsPristine()` remet le composant dans son état d'origine comme si
1269
- > aucune interaction n'avait été effectuée.
1619
+ > ✅ The `markAsPristine()` function puts the component back in its original state, as if
1620
+ > no interaction had happened.
1270
1621
  >
1271
- > ℹ️ Permet d'afficher l'erreur d'un composant foehn-input en erreur.
1622
+ > ℹ️ Displays the error of a foehn-input component in error.