ngx-recipe-forms 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -48
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
# ngx-recipe-forms
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Generic **recipe-based** form engine, built on Angular Signal Forms (`@angular/forms/signals`, Angular 22.2) and Tailwind 4.
|
|
4
|
+
A recipe is **an object typed by the model**, declared in code; the engine derives the Signal Forms schema, the rendering, the messages and the layout from it.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
To write a recipe, follow [`AGENTS.md`](https://github.com/SrenoG/ngx-recipe-forms/blob/main/AGENTS.md) (in French: method, catalog, pitfalls, checklist).
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## What the library does
|
|
9
9
|
|
|
10
|
-
- **
|
|
11
|
-
- **
|
|
12
|
-
- **Messages
|
|
13
|
-
- **
|
|
14
|
-
- **Sections
|
|
15
|
-
- **
|
|
16
|
-
- **
|
|
10
|
+
- **Recipe types**: `FormRecipe<TModel>`, nodes `section`, `row`, `sectionGroup`, `field`, `linked`, `array`; controls and rules constrained by the type of the value; typed builder `recipeBuilder<TModel>()`. The nodes of an `array` item are built with `recipeBuilder<ItemModel, RootModel>()`: their rules read the root through `ctx.root(key)`.
|
|
11
|
+
- **Schema**: `RecipeSchema.build(recipe)` turns each rule into a native function (`required`, `pattern`, `min`…, `validate`, `validateTree`, `validateAsync`, `metadata`), and applies `disabled`, `hidden`, `readonly` (per field, per section or for the whole recipe), the rules of `array` items (`applyEach`), the rules of the whole list (`minItems`, `maxItems`, `unique`, `validate`), non-blocking warnings (`warn`), linked controls and `extraRules`. When a server validator fails, the engine sets the "validation unavailable" warning without blocking: the server still decides on save.
|
|
12
|
+
- **Messages**: priority field → recipe → default → raw message; server errors are shown by their `message`, translated by the caller, otherwise by the key `errors.<code>`; a field error set by the host application as `{ kind: 'server', error: { code, constraint?, message } }` is read as is.
|
|
13
|
+
- **Server errors by path**: `RecipeServerPaths` records the position → key mapping of each `array` when the request is sent; `rooms[2].code` is set on the item that was at position 2, the error clears as soon as the value changes, and whatever cannot be placed comes out through `unplacedServerErrors`.
|
|
14
|
+
- **Sections**: `RecipeSections` (field index, error count, first field in error).
|
|
15
|
+
- **Tailwind layout**, **response time measurement** of server validators.
|
|
16
|
+
- **Rendering**: `<app-recipe-form>`, `<app-recipe-node>`, `<app-recipe-section-group>` (`plain`, `panel` and `tabs` formats, error counts per panel or per tab, opening the panel or activating the tab of the first field in error; no format destroys a section), `<app-recipe-field>`, `array` as a list or a table with a slot and an API (`addItem`, `removeItem`, `has`, `items`, declared sort). Default wrappers `app-input-text`, `app-input-number` (decimals bounded by `minFractionDigits` and `maxFractionDigits`), `app-select`, `app-date-picker`, `app-date-picker-multiple`, `app-checkbox`, `app-button`, `app-panel`, `app-tabs` (with `TabPanelDirective`), and `app-message` for field, group and list messages. Under a field: the hint (`hintKey`, conditional through `{ key, when?, showWhenReadonly? }`, hidden in read-only mode like the required asterisk), then the translated reason of an active `disabled` rule (`reasonKey`), in the same style, removed when the field is enabled again. The `labelKey` options of a `select` are translated by the engine before they reach the wrapper. A table `array` scrolls in its own container (`overflow-x-auto`); a cell message wraps instead of widening its column.
|
|
17
17
|
|
|
18
|
-
##
|
|
18
|
+
## Usage
|
|
19
19
|
|
|
20
20
|
```ts
|
|
21
|
-
// 1.
|
|
21
|
+
// 1. The form model, in plain values (the conversion to the DTO stays in the mapper).
|
|
22
22
|
interface CourseFormData { deliveryMode: string | null; sessions: readonly CourseSession[]; totalHours: number | null; }
|
|
23
23
|
interface CourseSession extends ArrayItem { date: Date | null; hours: number | null; }
|
|
24
24
|
|
|
25
|
-
// 2.
|
|
25
|
+
// 2. The recipe, built from its context (permission signals, options, validators).
|
|
26
26
|
const b = recipeBuilder<CourseFormData>();
|
|
27
27
|
const item = recipeBuilder<Omit<CourseSession, 'key'>, CourseFormData>();
|
|
28
28
|
export const courseRecipe = (ctx: Ctx) => b.recipe('course', {
|
|
@@ -48,7 +48,7 @@ export const courseRecipe = (ctx: Ctx) => b.recipe('course', {
|
|
|
48
48
|
],
|
|
49
49
|
});
|
|
50
50
|
|
|
51
|
-
// 3.
|
|
51
|
+
// 3. The caller creates the FieldTree and receives the submitted value.
|
|
52
52
|
readonly model = signal<CourseFormData>(initial);
|
|
53
53
|
readonly form = form(this.model, RecipeSchema.build(this.recipe, { timing: inject(FORM_VALIDATION_TIMING) }));
|
|
54
54
|
```
|
|
@@ -69,11 +69,11 @@ readonly form = form(this.model, RecipeSchema.build(this.recipe, { timing: injec
|
|
|
69
69
|
(dateRemoved)="api.removeItem(keyOf($event))"
|
|
70
70
|
/>
|
|
71
71
|
</ng-template>
|
|
72
|
-
<button appRecipeActions type="submit">
|
|
72
|
+
<button appRecipeActions type="submit">Save</button>
|
|
73
73
|
</app-recipe-form>
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
Providers: `provideRecipeForms({ production, translator, translationChanges, keyGenerator })`. `translator` and `translationChanges` are factories run in the injection context (`useFactory`). For example with Transloco:
|
|
77
77
|
|
|
78
78
|
```ts
|
|
79
79
|
provideRecipeForms({
|
|
@@ -82,50 +82,50 @@ provideRecipeForms({
|
|
|
82
82
|
const transloco = inject(TranslocoService);
|
|
83
83
|
return (key, params) => transloco.translate(key, params);
|
|
84
84
|
},
|
|
85
|
-
//
|
|
85
|
+
// A new object on each event: lazily loaded scope, language change.
|
|
86
86
|
translationChanges: () => toSignal(inject(TranslocoService).events$),
|
|
87
87
|
});
|
|
88
88
|
```
|
|
89
89
|
|
|
90
|
-
`translationChanges` (
|
|
90
|
+
`translationChanges` (token `RECIPE_FORM_TRANSLATION_CHANGES`, a constant signal by default) returns a signal whose value changes each time translations are loaded or changed. The engine reads it before calling the translator for tab titles, error count texts, the `labelKey` options of a `select` and the `recipeTranslate` pipe: a scope loaded after the first render replaces the raw keys on screen. A value equal to the previous one (`Object.is`) triggers nothing: with Transloco, `langChanges$` alone is not enough, since it does not change when a scope loads.
|
|
91
91
|
|
|
92
|
-
##
|
|
92
|
+
## Plugging in your design system
|
|
93
93
|
|
|
94
|
-
-
|
|
95
|
-
- **
|
|
96
|
-
- **Messages,
|
|
97
|
-
-
|
|
98
|
-
-
|
|
99
|
-
- `app-input-text
|
|
100
|
-
- `app-input-number
|
|
101
|
-
- `app-select
|
|
102
|
-
- `app-date-picker-multiple
|
|
103
|
-
- `app-panel
|
|
104
|
-
- `app-tabs
|
|
105
|
-
- `app-checkbox` (
|
|
106
|
-
- `app-message
|
|
107
|
-
-
|
|
108
|
-
- `translationChanges
|
|
109
|
-
-
|
|
94
|
+
- Selectors are `app-*` and classes end with `Component`.
|
|
95
|
+
- **Controls**: the engine renders each control (`text`, `number`, `select`, `date`, `dateMultiple`, `checkbox`) with a template from the `RecipeUi` registry. The host passes to `provideRecipeForms({ ui })` a component that declares one `<ng-template appRecipeTextControl let-field let-inputId="inputId" …>` (`appRecipeNumberControl`, `appRecipeSelectControl`, `appRecipeDateControl`, `appRecipeDateMultipleControl`, `appRecipeCheckboxControl`) per control to render with its design system, and binds its wrapper to it with `[formField]="field"`. A control it does not declare keeps the default template. `RecipeDefaultUiComponent` (`ui/recipe-default-ui.ts`) declares the six templates with the wrappers from `ui/` and serves as a model; the context of each template is typed (`RecipeTextControlContext`…). The registry creates these components once, outside the application tree; a template's view is refreshed with the field that inserts it, and updated in place when its context changes (the control keeps its focus). Learning tests: `specs/ui-seam.learning.spec.ts`.
|
|
96
|
+
- **Messages, buttons, panels and tabs**: the engine renders them through `app-recipe-message`, `app-recipe-button`, `app-recipe-panel` and `app-recipe-tabs`, which keep the id targeted by `aria-describedby`, the placement classes and the state (collapsed panel, active tab), and render the registry template inside: `appRecipeMessage` (translated text, `severity`, `inline`), `appRecipeButton` (label, `variant`, `severity`, `click`), `appRecipePanel` (`let-content` to render with `ngTemplateOutlet`, texts, `collapsed` and `toggle`), `appRecipeTabs` (`let-panels`, one `{ value, template }` per section, to render without ever destroying it, `options`, `value`, `select`, `fill`). The tabs template tracks panels by `value`: the list is recreated on each computation of the context.
|
|
97
|
+
- For a single field, a `SLOT` control renders the template provided by the caller. The wrappers in `ui/` remain those of the default templates. Contracts expected from the wrappers:
|
|
98
|
+
- every control: Signal Forms contract (`value` or `checked`, `disabled`, `invalid`, `touched`, `touch` output), `inputId` and `describedBy` inputs (`aria-describedby` set on the element that receives focus), a `focus(options?: FocusOptions)` method that passes `options` to the native focus (focus of the first field in error, called with `preventScroll: true`: the engine then scrolls `app-recipe-field` to the center with `scrollIntoView({ block: 'center' })`);
|
|
99
|
+
- `app-input-text`: `placeholder` (`''` by default), `inputmode` (`'text'` by default), `maxLength` (a `FormValueControl` input, bound by `[formField]` to the `MAX_LENGTH` rule), `icon` (trailing icon, none by default; the engine passes `TextControlDef.icon` as is, an icon name of the host's wrapper, `string` by default and restricted to the host's names if it extends `RecipeIconTypes` (`declare module 'ngx-recipe-forms' { interface RecipeIconTypes { icon: IconEnum } }`); the default wrapper accepts it without drawing it);
|
|
100
|
+
- `app-input-number`: `step`, `minFractionDigits` (decimals always shown), `maxFractionDigits` (decimals allowed when typing, 3 by default);
|
|
101
|
+
- `app-select`: `options: SelectOption<T>[]` (`[]` by default; the field passes a copy, with `label` already translated for a recipe option using `labelKey`), `showClear`, `filter` (search in the list, `false` by default; the engine passes `filter ?? false`; the native `<select>` of the default wrapper ignores it and keeps the browser's first-letter search), `ariaLabelledBy` (id of the label: a design system's dropdown is often not a native field), `placeholder` (text shown when the value is `null`, translation of `SelectControlDef.placeholderKey`, `''` without a key). In `readonly` mode, the list stays focusable (never `disabled` for read-only), does not open, does not change value from the keyboard, has neither chevron nor pointer cursor and carries `aria-readonly="true"`; the `RecipeSelectControlContext` context passes `placeholder` and `readonly` to the template. Contract spec of the default template: `specs/recipe-select-readonly.spec.ts`;
|
|
102
|
+
- `app-date-picker-multiple`: `FormValueControl<readonly Date[]>`, `maxDate`, `numberOfMonths` (months shown side by side, 3 by default; the engine passes `months ?? 3`; the native field of the default wrapper ignores it), `ariaLabel` (name of the group, the translated label), `dateAdded` and `dateRemoved` outputs for each day checked or unchecked;
|
|
103
|
+
- `app-panel`: `header`, `collapsible`, `collapsed` (model), `badge` (number, absent at zero), `badgeLabel`, `collapseLabel` and `expandLabel` (name of the collapse button, with `aria-expanded`);
|
|
104
|
+
- `app-tabs`: `value` (model, `string`), `options: TabOption[]` (`label`, `value`, `disabled`, `badge` absent at zero, `badgeLabel`; same shape as `SelectOption<string>`), `fill` (`false` by default; when true: below 768 px, the tabs share the full width, `flex-1` on a zero basis, and their title wraps between words only, never inside a word, so no tab is out of view; smaller padding and text (`px-2`, `text-xs`); badge in the top right corner of the tab (`absolute`, tab `relative`), in a top space reserved even without a count (`pt-6`): the title gets the full width and the tab keeps the same height with or without a count; nothing changes above that width; the section group sets it to true); one panel per projected `<ng-template [appTabPanel]="value">` (`TabPanelDirective`, in template order), hidden (`hidden`) when its tab is inactive and never destroyed; the bar alone without a template; ARIA tabs pattern (`aria-controls`, `aria-labelledby`, roving focus, arrows, Home, End); sticky bar at the top of the scrolling container (`sticky z-10`, opaque white background), panels in the same block, at `top: var(--app-sticky-top, 0px)` (class `top-[var(--app-sticky-top,0px)]`): a scrolling container with a top padding sets `--app-sticky-top` to the negative of that padding (`-20px` for 20 px), otherwise content stays visible in the strip above the stuck bar; when the user changes tab (click or keyboard) while the bar is stuck (top of the host above the top of the bar), the host scrolls to the start of the area (`scrollIntoView({ block: 'start' })`, after rendering), nothing without prior scrolling, nothing when `value` is changed by the parent (tab of the first field in error: the field's focus takes over); name of the tab (and of the panel) = title only, `badgeLabel` in a `hidden` element targeted by the tab's `aria-describedby`, badge `aria-hidden`; same tab height with or without a badge (`leading-none` in an `h-5` container, the title's line);
|
|
105
|
+
- `app-checkbox` (and any `appRecipeCheckboxControl` template): `FormCheckboxControl`; in `readonly` mode, the box never changes state, neither on screen nor for assistive technologies (click, click on the label and Space are cancelled, the native box does not get checked), stays focusable (never `disabled` for read-only), carries `aria-readonly="true"` on the focusable element, and keeps the default cursor on the box and its label. The `RecipeCheckboxControlContext` context passes `readonly` to the template. Contract spec of the default template: `specs/recipe-readonly-field.spec.ts`;
|
|
106
|
+
- `app-message`: `severity` (`SeverityEnum`, including the `WARNING` key), `inline`, projected content; `[id]` set on the host element.
|
|
107
|
+
- Translator: `RECIPE_FORM_TRANSLATOR` and `RECIPE_FORM_TRANSLATION_CHANGES` are provided with `useFactory`: the factory can inject the application's i18n service (see "Providers" above). Without a translator, the key is shown as is. The `recipeTranslate` pipe is impure (lazily loaded scopes).
|
|
108
|
+
- `translationChanges`: the `labelKey` options of a `select`, tab titles and count texts are translated by the translator in a `computed`, not by the impure pipe: they are recomputed whenever their data changes and, with `translationChanges`, whenever translations load; without this option, the scope that holds their keys must be loaded before the form renders.
|
|
109
|
+
- Default keys: they are listed by the `RECIPE_FORM_DEFAULT_KEYS` constant (`constants/recipe-form-default-keys.constants.ts`); a host spec checks that its flattened dictionary (`forms.array.add`) contains each of them (model: `projects/playground/src/app/i18n/fr.spec.ts`): `forms.errors.*` (including `minItems`, `maxItems`, `unique`), `forms.warnings.validationUnavailable`, `forms.pending`, `forms.array.*`, `forms.display.errorCountOne` and `forms.display.errorCount` ("{{ count }} error", "{{ count }} errors": the engine uses the first one when `count` is 1 and the second otherwise, since the translator has no plural), `forms.display.collapsePanel` and `forms.display.expandPanel` ("Collapse panel {{ title }}", "Expand panel {{ title }}"), and, outside the constant, `errors.<code>` (or `<scope>.errors.<code>`) for server codes.
|
|
110
110
|
|
|
111
|
-
##
|
|
111
|
+
## In the host application
|
|
112
112
|
|
|
113
|
-
- Tailwind 4
|
|
114
|
-
-
|
|
115
|
-
-
|
|
116
|
-
- `npm run check:loose`
|
|
113
|
+
- Tailwind 4: the library's classes are literal. If the package is consumed from `node_modules`, add `@source "../node_modules/ngx-recipe-forms";` to the host's stylesheet.
|
|
114
|
+
- Server validators (`ServerValidator<T>`) return an `Observable<ServerValidationResult>`; the adapter to the application's HTTP services is written by the caller. A validator that needs other keys of the model (for example the start date and the format of a training course) is declared `ServerValidator<T, RootModel>`, receives `(value, ctx)` and reads through `ctx.root(key)` the keys its rule declares in `dependsOn`. The errors of a write (`RecipeServerError[]`: `fields`, `code`, `message?`) are passed as is to `serverErrors`.
|
|
115
|
+
- `server` rules call their validator through the resource of `RECIPE_FORM_RX_RESOURCE` (`rxResource` by default): an application that enforces its own resource wrapper passes it to `provideRecipeForms({ rxResource })`, with the signature of `rxResource`. The timing collector is a `@Service({ autoProvided: false })`.
|
|
116
|
+
- `npm run check:loose` compiles the library and its specs under less strict options, like an application that sets neither `strict` nor `strictTemplates`: the `@ts-expect-error` of `recipe-types.spec.ts` must hold. The specs use no API specific to Vitest 5. Those that submit an invalid form replace `Element.prototype.scrollIntoView`, which jsdom does not implement, with a `vi.fn` spy for each test; a host spec that submits an invalid recipe form must do the same.
|
|
117
117
|
|
|
118
|
-
##
|
|
118
|
+
## Commands
|
|
119
119
|
|
|
120
120
|
```bash
|
|
121
121
|
npm run build:lib # ng build recipe-forms
|
|
122
|
-
npm run pack:lib #
|
|
123
|
-
npm run publish:lib #
|
|
122
|
+
npm run pack:lib # builds then packs the package (dist/ngx-recipe-forms-<version>.tgz)
|
|
123
|
+
npm run publish:lib # builds then publishes dist/recipe-forms to npm
|
|
124
124
|
npm run test:lib # ng test recipe-forms --watch=false
|
|
125
|
-
npm run check:loose # tsc
|
|
125
|
+
npm run check:loose # tsc with less strict options
|
|
126
126
|
npm start # ng serve playground
|
|
127
|
-
npm run install:host -- <
|
|
128
|
-
npm run export:host -- <
|
|
127
|
+
npm run install:host -- <host folder> # installs the built package in a host (file:…tgz)
|
|
128
|
+
npm run export:host -- <folder> # copies the sources into a host, with the hash manifest
|
|
129
129
|
```
|
|
130
130
|
|
|
131
|
-
|
|
131
|
+
Both scripts are described in the [repository README](https://github.com/SrenoG/ngx-recipe-forms#readme) ("Trying it in an application before publication", "Copying it into an application").
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ngx-recipe-forms",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Generic recipe-based form engine for Angular Signal Forms, styled with Tailwind",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"angular",
|
|
8
8
|
"signal-forms",
|