@chepchik/bind-form 0.1.2 → 0.2.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 +196 -12
- package/dist/accessibility.d.ts +24 -0
- package/dist/createForm.d.ts +49 -0
- package/dist/engine.d.ts +47 -0
- package/dist/index.d.ts +19 -94
- package/dist/index.js +248 -91
- package/dist/serverErrors.d.ts +34 -0
- package/dist/types.d.ts +159 -0
- package/dist/validation.d.ts +20 -0
- package/package.json +17 -4
package/README.md
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
# bind-form
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
(`
|
|
3
|
+
 
|
|
4
|
+
|
|
5
|
+
Что: dependency-free typed form engine поверх настоящего `<form>`/`FormData`.
|
|
6
|
+
Два входа в один и тот же движок:
|
|
7
|
+
|
|
8
|
+
- `createForm({ schema, initialValues })` — `form.values`/`form.errors`
|
|
9
|
+
выводятся из `schema` типами (без ручного `TField`), значения полей могут
|
|
10
|
+
быть не только `string` (`number`/`boolean`/`string[]`), валидация идёт по
|
|
11
|
+
пайплайну `sync → async(на поле) → resolver(на форму) → server`, а сервер
|
|
12
|
+
ошибки `{ field, code }[]` автоматически маппятся в `form.errors`/`form.formError`.
|
|
13
|
+
- `bindForm(form, options)` — прежний API (submit handling, `schema`,
|
|
14
|
+
`resolver`, `validateOn`, `onStateChange`, `watch`...), работает без
|
|
15
|
+
изменений сигнатуры и построен поверх того же движка.
|
|
16
|
+
|
|
17
|
+
Оба API автоматически проставляют accessibility-атрибуты (`aria-invalid`,
|
|
18
|
+
`aria-describedby`, `role="alert"`) и переносят фокус на первое невалидное
|
|
19
|
+
поле после неуспешного submit — это не опция, а поведение "из коробки"
|
|
20
|
+
(см. раздел [Accessibility](#accessibility)).
|
|
11
21
|
|
|
12
22
|
Зачем: чтобы не дублировать в каждой форме одинаковый код —
|
|
13
|
-
`preventDefault`, сбор `FormData`, проверку
|
|
14
|
-
|
|
23
|
+
`preventDefault`, сбор `FormData`, проверку полей, показ/скрытие ошибок,
|
|
24
|
+
доступность и фокус-менеджмент. Отправка по Enter работает "из коробки",
|
|
15
25
|
т.к. используется стандартное поведение `<form>`.
|
|
16
26
|
|
|
17
27
|
## Установка
|
|
@@ -20,7 +30,153 @@
|
|
|
20
30
|
npm install @chepchik/bind-form
|
|
21
31
|
```
|
|
22
32
|
|
|
23
|
-
##
|
|
33
|
+
## Typed forms
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { createForm } from "@chepchik/bind-form";
|
|
37
|
+
|
|
38
|
+
const form = document.querySelector("form")!;
|
|
39
|
+
|
|
40
|
+
const handle = createForm(form, {
|
|
41
|
+
schema: {
|
|
42
|
+
name: { required: "Введите имя" },
|
|
43
|
+
age: { type: "number", min: { value: 18, message: "Минимум 18" } },
|
|
44
|
+
agree: { type: "checkbox", required: "Нужно согласие" },
|
|
45
|
+
},
|
|
46
|
+
initialValues: { age: 18 },
|
|
47
|
+
onSubmit: async (values) => {
|
|
48
|
+
// values.name: string, values.age: number, values.agree: boolean —
|
|
49
|
+
// выведено из schema, без ручного указания generic-параметра.
|
|
50
|
+
await api.register(values);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
handle.getValues().age; // number
|
|
55
|
+
handle.setValue("age", 21); // типизировано по конкретному полю
|
|
56
|
+
|
|
57
|
+
// позже, при размонтировании:
|
|
58
|
+
handle();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`FieldSchema.type` определяет, как строковое значение `FormData` приводится
|
|
62
|
+
к типу `form.values[field]`:
|
|
63
|
+
|
|
64
|
+
- `"text"` (по умолчанию) → `string`
|
|
65
|
+
- `"number"` → `number` (непарсибельное значение — ошибка валидации, а не `NaN`)
|
|
66
|
+
- `"checkbox"` → `boolean`
|
|
67
|
+
- `"multiselect"` → `string[]` (все значения `name`, например группа чекбоксов)
|
|
68
|
+
|
|
69
|
+
Свой парсинг/сериализация — через `parse`/`serialize` в `FieldSchema` вместо `type`.
|
|
70
|
+
|
|
71
|
+
## Validation pipeline
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
submit
|
|
75
|
+
│
|
|
76
|
+
▼
|
|
77
|
+
sync (required/pattern/minLength/maxLength/min/max) — на каждое поле
|
|
78
|
+
│ ошибка → стоп для этого поля, async не запускается (REQ-006)
|
|
79
|
+
▼
|
|
80
|
+
async (per field, например uniqueness-проверка)
|
|
81
|
+
│
|
|
82
|
+
▼
|
|
83
|
+
resolver (form-level, только для полей без ошибок sync/async)
|
|
84
|
+
│
|
|
85
|
+
▼
|
|
86
|
+
onSubmit(values) — если ошибок нет
|
|
87
|
+
│ бросает FormSubmitError → server-стадия
|
|
88
|
+
▼
|
|
89
|
+
server errors → form.errors / form.formError
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const handle = createForm(form, {
|
|
94
|
+
schema: {
|
|
95
|
+
email: {
|
|
96
|
+
required: "Введите email",
|
|
97
|
+
pattern: { value: /.+@.+/, message: "Неверный формат" },
|
|
98
|
+
// async выполняется, только если email прошёл sync-проверки выше.
|
|
99
|
+
async: async (value) => ((await api.isEmailTaken(value)) ? "Email уже занят" : undefined),
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
onSubmit: async (values) => api.register(values),
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Если поле не прошло sync-стадию, его `async`-правило не вызывается вообще —
|
|
107
|
+
это можно проверить шпионом/счётчиком вызовов (см. `tests/validation.test.ts`).
|
|
108
|
+
|
|
109
|
+
## Server errors
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { createForm, FormSubmitError } from "@chepchik/bind-form";
|
|
113
|
+
|
|
114
|
+
const handle = createForm(form, {
|
|
115
|
+
schema: { email: {} },
|
|
116
|
+
errorMessages: { EMAIL_EXISTS: "Такой email уже зарегистрирован" },
|
|
117
|
+
onSubmit: async (values) => {
|
|
118
|
+
const res = await fetch("/api/register", { method: "POST", body: JSON.stringify(values) });
|
|
119
|
+
if (res.status === 422) {
|
|
120
|
+
throw new FormSubmitError(await res.json()); // [{ field: "email", code: "EMAIL_EXISTS" }]
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `code` резолвится через `errorMessages`, при отсутствии — фолбэк на `message`,
|
|
127
|
+
затем на сырой `code`, затем на общий fallback-текст.
|
|
128
|
+
- Ошибка с `field`, которого нет в `schema` (или без `field` вообще), попадает
|
|
129
|
+
в `handle.getState().formError`, а не теряется и не бросает исключение.
|
|
130
|
+
|
|
131
|
+
## Accessibility
|
|
132
|
+
|
|
133
|
+
Применяется автоматически и к `createForm`, и к `bindForm` — не требует
|
|
134
|
+
настройки со стороны потребителя:
|
|
135
|
+
|
|
136
|
+
```html
|
|
137
|
+
<input name="email" aria-invalid="true" aria-describedby="email-error" />
|
|
138
|
+
<span data-error-for="email" id="email-error" role="alert" aria-live="polite">
|
|
139
|
+
Неверный формат
|
|
140
|
+
</span>
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
- `aria-invalid="true"` появляется на поле при ошибке и снимается, когда её нет.
|
|
144
|
+
- `[data-error-for="<field>"]` получает `role="alert"`, стабильный `id`
|
|
145
|
+
(генерируется как `${field}-error`, если отсутствует), и этот `id`
|
|
146
|
+
прописывается в `aria-describedby` поля.
|
|
147
|
+
- После неуспешного submit фокус переходит на первое невалидное поле в
|
|
148
|
+
DOM-порядке (`form.elements`, а не порядок ключей `schema`) — обычная
|
|
149
|
+
Tab/Shift+Tab навигация после этого не нарушается (никакого focus trap).
|
|
150
|
+
- В dev-режиме (`process.env.NODE_ENV !== "production"`) в консоль выводится
|
|
151
|
+
предупреждение, если у поля схемы нет связанного `<label>` (`for`/wrapping
|
|
152
|
+
`<label>`/`aria-label`/`aria-labelledby`). Проверка не попадает в
|
|
153
|
+
production-сборку по стоимости выполнения — только вызов вырезается вручную
|
|
154
|
+
через `NODE_ENV`, поэтому убедитесь, что ваш бандлер минифицирует `if (false)`.
|
|
155
|
+
|
|
156
|
+
## Migrating from `bindForm` to `createForm`
|
|
157
|
+
|
|
158
|
+
`bindForm` продолжает работать без изменений — мигрировать не обязательно.
|
|
159
|
+
|
|
160
|
+
| `bindForm` | `createForm` |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `schema: Record<TField, FieldRule>` | `schema: Record<TField, FieldSchema<TValue>>` (+ `type`/`parse`/`serialize`/`async`) |
|
|
163
|
+
| `values: FormValues<TField>` (всегда `string`) | `values: InferValues<TSchema>` (типы из схемы) |
|
|
164
|
+
| нет серверных ошибок | `errorMessages` + `FormSubmitError` → `form.errors`/`form.formError` |
|
|
165
|
+
| `resolver` — form-level async | тот же `resolver`, плюс per-field `async` в схеме |
|
|
166
|
+
| нет accessibility-контракта | `aria-*`/`role="alert"`/focus management — из коробки (и для `bindForm` тоже) |
|
|
167
|
+
|
|
168
|
+
## Testing
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
pnpm test # tsc --noEmit && vitest run
|
|
172
|
+
pnpm test:coverage # то же самое + отчёт покрытия, порог 100% по lines/branches/functions/statements
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Любой вклад в пакет должен сохранять 100% покрытие (`vitest.config.ts`,
|
|
176
|
+
`coverage.thresholds`) — `vitest run --coverage` завершается с ненулевым
|
|
177
|
+
кодом, если покрытие `src/**/*.ts` падает ниже 100% хотя бы по одной метрике.
|
|
178
|
+
|
|
179
|
+
## Пример использования `bindForm`
|
|
24
180
|
|
|
25
181
|
```ts
|
|
26
182
|
import { bindForm } from "@chepchik/bind-form";
|
|
@@ -51,7 +207,7 @@ formHandle();
|
|
|
51
207
|
Для показа ошибки конкретного поля при `validateOn` добавьте рядом с полем
|
|
52
208
|
элемент `[data-error-for="<name>"]` (`<span data-error-for="email" hidden></span>`).
|
|
53
209
|
|
|
54
|
-
## Пример: сложная форма
|
|
210
|
+
## Пример: сложная форма (`bindForm`)
|
|
55
211
|
|
|
56
212
|
Более развёрнутый пример, использующий все возможности: `resolver` для
|
|
57
213
|
асинхронной проверки, `onStateChange` для индикации состояния, `watch` для
|
|
@@ -117,6 +273,27 @@ resetButton.addEventListener("click", () => handle.reset());
|
|
|
117
273
|
|
|
118
274
|
## API
|
|
119
275
|
|
|
276
|
+
### `createForm<TSchema>(form, options): FormHandle<InferValues<TSchema>, keyof TSchema & string>`
|
|
277
|
+
|
|
278
|
+
- `options.schema: Record<TField, FieldSchema<TValue>>` — валидация + типизация.
|
|
279
|
+
- Наследует `required`/`pattern`/`minLength`/`maxLength`/`min`/`max` из `FieldRule`.
|
|
280
|
+
- `type?: "text" | "number" | "checkbox" | "multiselect"` — как приводится значение.
|
|
281
|
+
- `parse?`/`serialize?` — свой парсинг/сериализация вместо `type`.
|
|
282
|
+
- `validate?: (value: TValue, values) => string | undefined` — sync, после built-in правил.
|
|
283
|
+
- `async?: (value: TValue, values) => string | undefined | Promise<...>` — только если sync прошёл (REQ-006).
|
|
284
|
+
- `options.initialValues?: Partial<InferValues<TSchema>>` — записываются в поля формы при вызове `createForm`.
|
|
285
|
+
- `options.errorElement?`, `options.validateOn?`, `options.resolver?`,
|
|
286
|
+
`options.onStateChange?`, `options.disableSubmitWhilePending?`,
|
|
287
|
+
`options.resetOnSuccess?` — как в `bindForm`, но типизированы по `TSchema`.
|
|
288
|
+
- `options.onSubmit(values, form)` — может бросить/вернуть `FormSubmitError`
|
|
289
|
+
для server-стадии пайплайна.
|
|
290
|
+
- `options.errorMessages?: Record<string, string>` — словарь `code → message`
|
|
291
|
+
для `mapServerErrors`.
|
|
292
|
+
|
|
293
|
+
Возвращает `FormHandle`: `getValues()`, `setValue(field, value)`,
|
|
294
|
+
`setError(field, message?)`, `setFormError(message?)`, `reset()`,
|
|
295
|
+
`getState()`, `watch(field, callback)` — все типизированы по `TSchema`.
|
|
296
|
+
|
|
120
297
|
### `bindForm<TField>(form, options): BindFormHandle<TField>`
|
|
121
298
|
|
|
122
299
|
- `form: HTMLFormElement` — форма, на которую вешается обработчик `submit`.
|
|
@@ -171,3 +348,10 @@ resetButton.addEventListener("click", () => handle.reset());
|
|
|
171
348
|
- `getState(): FormState<TField>` — снимок текущего состояния формы.
|
|
172
349
|
- `watch(field, callback)` — вызывать `callback(value, values)` при каждом
|
|
173
350
|
изменении значения `field`. Возвращает функцию отписки.
|
|
351
|
+
|
|
352
|
+
### `mapServerErrors(response, knownFields, errorMessages?)`
|
|
353
|
+
|
|
354
|
+
Превращает `ServerErrorResponse` (`{ field?, code?, message? }[]`) в
|
|
355
|
+
`{ fieldErrors, formError }`. Используется автоматически внутри `createForm`
|
|
356
|
+
при `FormSubmitError`, но экспортируется и для ручного использования (в том
|
|
357
|
+
числе вместе с `bindForm`).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type FieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
2
|
+
/**
|
|
3
|
+
* Applies `aria-invalid` to `input` based on `hasError`, and (when `hasError` is true) links it to
|
|
4
|
+
* `errorElement` via `aria-describedby`, generating a stable `id` for `errorElement` if it doesn't
|
|
5
|
+
* have one yet (`${field}-error`). When `hasError` is false, `aria-invalid` is removed and the
|
|
6
|
+
* `aria-describedby` reference to the error element is removed (without touching other ids the
|
|
7
|
+
* consumer may have added there) (REQ-010/REQ-011).
|
|
8
|
+
*/
|
|
9
|
+
export declare function applyFieldAccessibility(input: FieldElement, field: string, errorElement: HTMLElement | null, hasError: boolean): void;
|
|
10
|
+
/** Marks a field's error element as an accessible live region (`role="alert"`, `aria-live="polite"`), once. */
|
|
11
|
+
export declare function ensureErrorElementA11y(errorElement: HTMLElement): void;
|
|
12
|
+
/**
|
|
13
|
+
* Focuses the first field (in DOM order, via `form.elements`, not schema key order) that has an
|
|
14
|
+
* entry in `errors`. Does nothing beyond a single `.focus()` call — it never sets `tabindex` or
|
|
15
|
+
* otherwise affects subsequent Tab/Shift+Tab navigation (REQ-012/REQ-013).
|
|
16
|
+
*/
|
|
17
|
+
export declare function focusFirstInvalidField(form: HTMLFormElement, errors: Record<string, string | undefined>): void;
|
|
18
|
+
/**
|
|
19
|
+
* Dev-only check (skipped when `process.env.NODE_ENV === "production"`): warns via `console.warn`
|
|
20
|
+
* if a schema field's input has no associated `<label for="...">` in the form (REQ-014). Intended
|
|
21
|
+
* to be tree-shaken out of production builds together with its call site.
|
|
22
|
+
*/
|
|
23
|
+
export declare function warnIfLabelMissing(form: HTMLFormElement, field: string): void;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { FieldSchema, FormHandle, InferValues, TypedFormState } from './types';
|
|
2
|
+
export interface CreateFormOptions<TSchema extends Record<string, FieldSchema<any>>> {
|
|
3
|
+
/** Validation + typing schema: keys must match the `name` attributes of the form fields. */
|
|
4
|
+
schema: TSchema;
|
|
5
|
+
/** Initial values written into the form's fields when `createForm` is called. */
|
|
6
|
+
initialValues?: Partial<InferValues<TSchema>>;
|
|
7
|
+
/** Element used to display the form-level error message (must support `hidden`). */
|
|
8
|
+
errorElement?: HTMLElement;
|
|
9
|
+
/**
|
|
10
|
+
* Run validation for a field as the user interacts with it, in addition to on submit.
|
|
11
|
+
* Per-field errors are shown in elements matching `[data-error-for="<field>"]` inside the form.
|
|
12
|
+
*/
|
|
13
|
+
validateOn?: "blur" | "input";
|
|
14
|
+
/**
|
|
15
|
+
* Additional form-level async validation, run on submit after each field's own
|
|
16
|
+
* `sync -> async` pipeline. Only consulted for fields that passed their own pipeline.
|
|
17
|
+
*/
|
|
18
|
+
resolver?: (values: InferValues<TSchema>) => Partial<Record<keyof TSchema & string, string>> | Promise<Partial<Record<keyof TSchema & string, string>>>;
|
|
19
|
+
/** Called whenever the form's values/errors/formError/touched/dirty/submitting state changes. */
|
|
20
|
+
onStateChange?: (state: TypedFormState<InferValues<TSchema>, keyof TSchema & string>) => void;
|
|
21
|
+
/**
|
|
22
|
+
* Disable `[type="submit"]` elements inside the form while `onSubmit` is pending.
|
|
23
|
+
* Defaults to `true`.
|
|
24
|
+
*/
|
|
25
|
+
disableSubmitWhilePending?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Called with the validated, typed values after a successful sync/async/resolver pipeline.
|
|
28
|
+
* Throw (or reject with) a `FormSubmitError` to report server-side validation errors — they
|
|
29
|
+
* are mapped through `mapServerErrors`/`errorMessages` automatically instead of propagating
|
|
30
|
+
* as an unhandled exception (REQ-007/TASK-013).
|
|
31
|
+
*/
|
|
32
|
+
onSubmit: (values: InferValues<TSchema>, form: HTMLFormElement) => void | Promise<void>;
|
|
33
|
+
/** Reset the form after a successful onSubmit. */
|
|
34
|
+
resetOnSuccess?: boolean;
|
|
35
|
+
/** Maps a server error `code` (see `ServerError`) to a human-readable message (REQ-008). */
|
|
36
|
+
errorMessages?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Creates a typed form engine over a real `<form>`: `form.values`/`form.errors` are inferred
|
|
40
|
+
* from `schema` (REQ-001/REQ-002), field values are parsed/serialized per `FieldSchema.type`
|
|
41
|
+
* (REQ-003), and the `sync -> async(per field) -> resolver(form-level) -> server` validation
|
|
42
|
+
* pipeline (see `validation.ts`) runs on every submit. Accessibility (`aria-invalid`,
|
|
43
|
+
* `aria-describedby`, `role="alert"`, focus management on failed submit) is applied automatically,
|
|
44
|
+
* same as `bindForm` (ASSUMPTION-001).
|
|
45
|
+
*
|
|
46
|
+
* Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
|
|
47
|
+
* `setFormError`/`reset`/`getState`/`watch`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createForm<TSchema extends Record<string, FieldSchema<any>>>(form: HTMLFormElement, options: CreateFormOptions<TSchema>): FormHandle<InferValues<TSchema>, keyof TSchema & string>;
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { FieldSchema, TypedFormState } from './types';
|
|
2
|
+
/** One schema field as seen by the engine: its name and its typed validation/parsing schema. */
|
|
3
|
+
export interface EngineField<TField extends string> {
|
|
4
|
+
name: TField;
|
|
5
|
+
schema: FieldSchema<any>;
|
|
6
|
+
}
|
|
7
|
+
export interface EngineOptions<TValues extends Record<string, unknown>, TField extends string> {
|
|
8
|
+
fields: EngineField<TField>[];
|
|
9
|
+
errorElement?: HTMLElement;
|
|
10
|
+
validateOn?: "blur" | "input";
|
|
11
|
+
resolver?: (values: TValues) => Partial<Record<TField, string>> | Promise<Partial<Record<TField, string>>>;
|
|
12
|
+
onStateChange?: (state: TypedFormState<TValues, TField>) => void;
|
|
13
|
+
disableSubmitWhilePending?: boolean;
|
|
14
|
+
onSubmit: (values: TValues, form: HTMLFormElement) => void | Promise<void>;
|
|
15
|
+
resetOnSuccess?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Called when `onSubmit` throws/rejects. Return mapped errors to display them as the "server"
|
|
18
|
+
* pipeline stage (REQ-004); return `undefined` to let the error propagate (e.g. unhandled
|
|
19
|
+
* rejection), matching the behavior of the legacy `bindForm` (which has no such hook).
|
|
20
|
+
*/
|
|
21
|
+
mapSubmitError?: (error: unknown) => {
|
|
22
|
+
fieldErrors: Partial<Record<TField, string>>;
|
|
23
|
+
formError?: string;
|
|
24
|
+
} | undefined;
|
|
25
|
+
/** Skip the dev-only missing-`<label>` warning (used internally by tests). */
|
|
26
|
+
skipLabelWarning?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Handle shared by `bindForm` and `createForm`; each wraps it with its own public, typed surface. */
|
|
29
|
+
export interface EngineHandle<TValues extends Record<string, unknown>, TField extends string> {
|
|
30
|
+
(): void;
|
|
31
|
+
getValues(): TValues;
|
|
32
|
+
setValue(field: TField, raw: string): void;
|
|
33
|
+
setError(field: TField, message: string | undefined): void;
|
|
34
|
+
setFormError(message: string | undefined): void;
|
|
35
|
+
reset(): void;
|
|
36
|
+
getState(): TypedFormState<TValues, TField>;
|
|
37
|
+
watch(field: TField, callback: (value: unknown, values: TValues) => void): () => void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Shared internal engine behind both `bindForm` and `createForm`: subscribes to `submit` (and
|
|
41
|
+
* optionally `blur`/`input`), runs the `sync -> async(per field) -> resolver(form-level) -> server`
|
|
42
|
+
* validation pipeline, applies accessibility attributes (REQ-010/011) and focus management
|
|
43
|
+
* (REQ-012/013) to every bound field, and reports state via `onStateChange`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function createEngine<TValues extends Record<string, unknown>, TField extends string>(form: HTMLFormElement, options: EngineOptions<TValues, TField>): EngineHandle<TValues, TField>;
|
|
46
|
+
/** Converts a typed field value back into the raw string a DOM field element expects, using `FieldSchema.serialize`/`type`. */
|
|
47
|
+
export declare function serializeFieldValue(schema: FieldSchema<any>, value: unknown): string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,97 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
minLength?: {
|
|
12
|
-
value: number;
|
|
13
|
-
message: string;
|
|
14
|
-
};
|
|
15
|
-
/** Maximum string length (after trim()). */
|
|
16
|
-
maxLength?: {
|
|
17
|
-
value: number;
|
|
18
|
-
message: string;
|
|
19
|
-
};
|
|
20
|
-
/** Minimum numeric value, checked only when the field parses as a number. */
|
|
21
|
-
min?: {
|
|
22
|
-
value: number;
|
|
23
|
-
message: string;
|
|
24
|
-
};
|
|
25
|
-
/** Maximum numeric value, checked only when the field parses as a number. */
|
|
26
|
-
max?: {
|
|
27
|
-
value: number;
|
|
28
|
-
message: string;
|
|
29
|
-
};
|
|
30
|
-
/** Custom validator, run last. Return an error message, or undefined/empty string if valid. */
|
|
31
|
-
validate?: (value: string) => string | undefined;
|
|
32
|
-
}
|
|
33
|
-
/** Form values: field name -> string value taken from FormData. */
|
|
34
|
-
export type FormValues<TField extends string> = Record<TField, string>;
|
|
35
|
-
/** Validation errors keyed by field name. */
|
|
36
|
-
export type FormErrors<TField extends string> = Partial<Record<TField, string>>;
|
|
37
|
-
/** When to run per-field validation in addition to submit. */
|
|
38
|
-
export type ValidateTrigger = "blur" | "input";
|
|
39
|
-
/** Snapshot of the form's current state, passed to `onStateChange`. */
|
|
40
|
-
export interface FormState<TField extends string> {
|
|
41
|
-
values: FormValues<TField>;
|
|
42
|
-
errors: FormErrors<TField>;
|
|
43
|
-
/** Whether a field has been interacted with (blur/input) since bind or last reset. */
|
|
44
|
-
touched: Record<TField, boolean>;
|
|
45
|
-
/** Whether a field's value differs from its value at bind time (or last reset). */
|
|
46
|
-
dirty: Record<TField, boolean>;
|
|
47
|
-
/** True if any field is dirty. */
|
|
48
|
-
isDirty: boolean;
|
|
49
|
-
/** True while `onSubmit` is pending. */
|
|
50
|
-
isSubmitting: boolean;
|
|
51
|
-
}
|
|
52
|
-
export interface BindFormOptions<TField extends string> {
|
|
53
|
-
/** Validation schema: keys must match the `name` attributes of the form fields. */
|
|
54
|
-
schema: Record<TField, FieldRule>;
|
|
55
|
-
/** Element used to display the form-level error message (must support `hidden`). */
|
|
56
|
-
errorElement?: HTMLElement;
|
|
57
|
-
/**
|
|
58
|
-
* Run validation for a field as the user interacts with it, in addition to on submit.
|
|
59
|
-
* Per-field errors are shown in elements matching `[data-error-for="<field>"]` inside the form.
|
|
60
|
-
*/
|
|
61
|
-
validateOn?: ValidateTrigger;
|
|
62
|
-
/**
|
|
63
|
-
* Additional async/external validation (e.g. a zod/yup schema adapter), run on submit
|
|
64
|
-
* after the `schema` rules. Only consulted for fields that passed `schema` validation.
|
|
65
|
-
*/
|
|
66
|
-
resolver?: (values: FormValues<TField>) => FormErrors<TField> | Promise<FormErrors<TField>>;
|
|
67
|
-
/** Called whenever the form's values/errors/touched/dirty/submitting state changes. */
|
|
68
|
-
onStateChange?: (state: FormState<TField>) => void;
|
|
69
|
-
/**
|
|
70
|
-
* Disable `[type="submit"]` elements inside the form while `onSubmit` is pending.
|
|
71
|
-
* Defaults to `true`.
|
|
72
|
-
*/
|
|
73
|
-
disableSubmitWhilePending?: boolean;
|
|
74
|
-
/** Called with the validated values after a successful submit. */
|
|
75
|
-
onSubmit: (values: FormValues<TField>, form: HTMLFormElement) => void | Promise<void>;
|
|
76
|
-
/** Reset the form after a successful onSubmit. */
|
|
77
|
-
resetOnSuccess?: boolean;
|
|
78
|
-
}
|
|
79
|
-
/** Handle returned by `bindForm`. Calling it directly unsubscribes (same as before). */
|
|
80
|
-
export interface BindFormHandle<TField extends string> {
|
|
81
|
-
(): void;
|
|
82
|
-
/** Reads and trims the current values of all schema fields from the form. */
|
|
83
|
-
getValues(): FormValues<TField>;
|
|
84
|
-
/** Writes a value into the form field with the given name. */
|
|
85
|
-
setValue(field: TField, value: string): void;
|
|
86
|
-
/** Shows (or, if `message` is undefined, hides) the error for `[data-error-for="<field>"]`. */
|
|
87
|
-
setError(field: TField, message: string | undefined): void;
|
|
88
|
-
/** Resets the form, clears all displayed errors and recaptures dirty/touched state. */
|
|
89
|
-
reset(): void;
|
|
90
|
-
/** Returns a snapshot of the current form state (values/errors/touched/dirty/isSubmitting). */
|
|
91
|
-
getState(): FormState<TField>;
|
|
92
|
-
/** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
|
|
93
|
-
watch(field: TField, callback: (value: string, values: FormValues<TField>) => void): () => void;
|
|
94
|
-
}
|
|
1
|
+
import { BindFormHandle, BindFormOptions } from './types';
|
|
2
|
+
export type { FieldRule, FieldSchema, FieldType, SyncFieldRules, FormValues, FormErrors, ValidateTrigger, FormState, TypedFormState, InferValues, InferErrors, BindFormOptions, BindFormHandle, FormHandle, } from './types';
|
|
3
|
+
export type { EngineField, EngineHandle, EngineOptions } from './engine';
|
|
4
|
+
export { createEngine, serializeFieldValue } from './engine';
|
|
5
|
+
export { runSyncRules, runFieldPipeline, runFormPipeline } from './validation';
|
|
6
|
+
export type { ServerError, ServerErrorResponse, MappedServerErrors } from './serverErrors';
|
|
7
|
+
export { FormSubmitError, mapServerErrors } from './serverErrors';
|
|
8
|
+
export { applyFieldAccessibility, ensureErrorElementA11y, focusFirstInvalidField, warnIfLabelMissing, } from './accessibility';
|
|
9
|
+
export type { CreateFormOptions } from './createForm';
|
|
10
|
+
export { createForm } from './createForm';
|
|
95
11
|
/**
|
|
96
12
|
* Subscribes to a form's submit event: prevents the page reload, validates fields
|
|
97
13
|
* against the schema (required/pattern/minLength/maxLength/min/max/validate, then
|
|
@@ -104,7 +20,16 @@ export interface BindFormHandle<TField extends string> {
|
|
|
104
20
|
* While `onSubmit` is pending, `[type="submit"]` elements are disabled (unless
|
|
105
21
|
* `disableSubmitWhilePending` is `false`) and `isSubmitting` is reported via `onStateChange`.
|
|
106
22
|
*
|
|
23
|
+
* Every bound field automatically gets accessibility wiring (aria-invalid,
|
|
24
|
+
* aria-describedby pointing at its `[data-error-for]` element, role="alert" on that
|
|
25
|
+
* element) and, on a failed submit, focus moves to the first invalid field in DOM
|
|
26
|
+
* order (see `createForm`'s Accessibility section in the README for details).
|
|
27
|
+
*
|
|
107
28
|
* Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
|
|
108
29
|
* `reset`/`getState`/`watch`.
|
|
30
|
+
*
|
|
31
|
+
* @deprecated Prefer `createForm`, which additionally infers typed `values`/`errors`
|
|
32
|
+
* from the schema and supports non-string field values, async per-field validation and
|
|
33
|
+
* automatic server error mapping. `bindForm` is not going away and keeps working as-is.
|
|
109
34
|
*/
|
|
110
35
|
export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): BindFormHandle<TField>;
|
package/dist/index.js
CHANGED
|
@@ -1,127 +1,284 @@
|
|
|
1
|
-
//#region src/
|
|
2
|
-
function e(e,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
if (
|
|
6
|
-
if (t)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
if (
|
|
11
|
-
|
|
12
|
-
if (
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
1
|
+
//#region src/validation.ts
|
|
2
|
+
function e(e, t) {
|
|
3
|
+
if (e.required && !t) return e.required;
|
|
4
|
+
if (t) {
|
|
5
|
+
if (e.pattern && !e.pattern.value.test(t)) return e.pattern.message;
|
|
6
|
+
if (e.minLength && t.length < e.minLength.value) return e.minLength.message;
|
|
7
|
+
if (e.maxLength && t.length > e.maxLength.value) return e.maxLength.message;
|
|
8
|
+
if (e.min || e.max) {
|
|
9
|
+
let n = Number(t);
|
|
10
|
+
if (!Number.isNaN(n)) {
|
|
11
|
+
if (e.min && n < e.min.value) return e.min.message;
|
|
12
|
+
if (e.max && n > e.max.value) return e.max.message;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function t(t, n, r, i, a) {
|
|
18
|
+
let o = e(t, n);
|
|
19
|
+
if (o) return o;
|
|
20
|
+
if (a) return a;
|
|
21
|
+
let s = t.validate?.(r, i) || void 0;
|
|
22
|
+
if (s) return s;
|
|
23
|
+
if (t.async) return await t.async(r, i) || void 0;
|
|
24
|
+
}
|
|
25
|
+
async function n(e, n, r, i, a, o) {
|
|
26
|
+
let s = await Promise.all(e.map(async (e) => [e, await t(n(e), r(e), i(e), a, o?.(e))])), c = {};
|
|
27
|
+
for (let [e, t] of s) t && (c[e] = t);
|
|
28
|
+
return c;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/accessibility.ts
|
|
32
|
+
function r(e, t, n, r) {
|
|
33
|
+
if (r ? e.setAttribute("aria-invalid", "true") : e.removeAttribute("aria-invalid"), !n) return;
|
|
34
|
+
n.id ||= `${t}-error`, i(n);
|
|
35
|
+
let a = (e.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean).filter((e) => e !== n.id);
|
|
36
|
+
r ? e.setAttribute("aria-describedby", [...a, n.id].join(" ")) : a.length > 0 ? e.setAttribute("aria-describedby", a.join(" ")) : e.removeAttribute("aria-describedby");
|
|
37
|
+
}
|
|
38
|
+
function i(e) {
|
|
39
|
+
e.hasAttribute("role") || e.setAttribute("role", "alert"), e.hasAttribute("aria-live") || e.setAttribute("aria-live", "polite");
|
|
40
|
+
}
|
|
41
|
+
function a(e, t) {
|
|
42
|
+
for (let n of Array.from(e.elements)) {
|
|
43
|
+
let e = n.getAttribute("name");
|
|
44
|
+
if (!e || !t[e]) continue;
|
|
45
|
+
let r = n;
|
|
46
|
+
typeof r.focus == "function" && r.focus();
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function o(e, t) {
|
|
51
|
+
if (typeof process < "u" && process.env.NODE_ENV === "production") return;
|
|
52
|
+
let n = e.elements.namedItem(t);
|
|
53
|
+
if (!n || !(n instanceof HTMLElement)) return;
|
|
54
|
+
let r = n.getAttribute("id"), i = r ? e.querySelector(`label[for="${r}"]`) !== null : !1, a = n.closest("label") !== null, o = n.hasAttribute("aria-label") || n.hasAttribute("aria-labelledby");
|
|
55
|
+
!i && !a && !o && console.warn(`[bind-form] Field "${t}" has no associated <label>. Add <label for="${r ?? t}"> for accessibility.`);
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/engine.ts
|
|
59
|
+
var s = (e) => e instanceof HTMLInputElement || e instanceof HTMLTextAreaElement || e instanceof HTMLSelectElement;
|
|
60
|
+
function c(e, c) {
|
|
61
|
+
let d = c.fields.map((e) => e.name), f = new Map(c.fields.map((e) => [e.name, e.schema])), p = (e) => f.get(e), m = {}, h, g = {}, _ = {}, v = !1, y = (t) => String(new FormData(e).get(t) ?? "").trim(), b = (t) => new FormData(e).getAll(t).map((e) => String(e)), x = (e) => {
|
|
62
|
+
if (p(e).type === "multiselect") {
|
|
63
|
+
let t = b(e);
|
|
64
|
+
return t.length > 0 ? t.join(",") : "";
|
|
65
|
+
}
|
|
66
|
+
return y(e);
|
|
67
|
+
}, S = (e) => {
|
|
68
|
+
let t = p(e), n = x(e);
|
|
69
|
+
if (t.type === "number" && n !== "" && Number.isNaN(Number(n))) return "Invalid number value";
|
|
70
|
+
}, C = (e) => {
|
|
71
|
+
let t = p(e), n = y(e);
|
|
72
|
+
if (t.type === "multiselect") return b(e);
|
|
73
|
+
if (t.parse) return t.parse(n);
|
|
74
|
+
switch (t.type) {
|
|
75
|
+
case "number": {
|
|
76
|
+
if (n === "") return;
|
|
77
|
+
let e = Number(n);
|
|
78
|
+
return Number.isNaN(e) ? void 0 : e;
|
|
16
79
|
}
|
|
17
|
-
return n
|
|
80
|
+
case "checkbox": return n !== "";
|
|
81
|
+
default: return n;
|
|
18
82
|
}
|
|
19
|
-
},
|
|
20
|
-
a[e] = t;
|
|
21
|
-
let n = u(e);
|
|
22
|
-
n && (t ? (n.textContent = t, n.removeAttribute("hidden")) : n.setAttribute("hidden", ""));
|
|
23
|
-
}, f = (t) => String(new FormData(e).get(t) ?? "").trim(), p = () => {
|
|
83
|
+
}, w = () => {
|
|
24
84
|
let e = {};
|
|
25
|
-
for (let t of
|
|
85
|
+
for (let t of d) e[t] = C(t);
|
|
26
86
|
return e;
|
|
27
|
-
},
|
|
28
|
-
|
|
87
|
+
}, T = () => {
|
|
88
|
+
_ = w();
|
|
29
89
|
};
|
|
30
|
-
|
|
31
|
-
let
|
|
90
|
+
T();
|
|
91
|
+
let E = () => {
|
|
32
92
|
let e = {};
|
|
33
|
-
for (let t of
|
|
93
|
+
for (let t of d) e[t] = y(t) !== D(t);
|
|
34
94
|
return e;
|
|
35
|
-
},
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
95
|
+
}, D = (e) => u(p(e), _[e]), O = (t) => e.querySelector(`[data-error-for="${t}"]`), k = (t) => {
|
|
96
|
+
let n = e.elements.namedItem(t);
|
|
97
|
+
s(n) && r(n, t, O(t), !!m[t]);
|
|
98
|
+
}, A = (e, t) => {
|
|
99
|
+
m[e] = t;
|
|
100
|
+
let n = O(e);
|
|
101
|
+
n && (t ? (n.textContent = t, n.removeAttribute("hidden")) : n.setAttribute("hidden", "")), k(e);
|
|
102
|
+
}, j = (e) => {
|
|
103
|
+
h = e, l(c.errorElement, e);
|
|
104
|
+
}, M = () => {
|
|
105
|
+
if (!c.onStateChange) return;
|
|
106
|
+
let e = E();
|
|
107
|
+
c.onStateChange({
|
|
108
|
+
values: w(),
|
|
109
|
+
errors: { ...m },
|
|
110
|
+
formError: h,
|
|
111
|
+
touched: { ...g },
|
|
42
112
|
dirty: e,
|
|
43
|
-
isDirty:
|
|
44
|
-
isSubmitting:
|
|
113
|
+
isDirty: d.some((t) => e[t]),
|
|
114
|
+
isSubmitting: v
|
|
45
115
|
});
|
|
46
|
-
},
|
|
116
|
+
}, N = (t) => {
|
|
47
117
|
let n = e.querySelectorAll("[type=\"submit\"]");
|
|
48
118
|
for (let e of n) e.disabled = t;
|
|
49
|
-
},
|
|
50
|
-
let e =
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
let n
|
|
54
|
-
for (let e of i) !t[e] && n[e] && (t[e] = n[e]);
|
|
119
|
+
}, P = async () => {
|
|
120
|
+
let e = w(), t = await n(d, p, x, C, e, S);
|
|
121
|
+
if (c.resolver) {
|
|
122
|
+
let n = await c.resolver(e);
|
|
123
|
+
for (let e of d) !t[e] && n[e] && (t[e] = n[e]);
|
|
55
124
|
}
|
|
56
|
-
let
|
|
57
|
-
for (let e of
|
|
125
|
+
let r, i = !1;
|
|
126
|
+
for (let e of d) A(e, t[e]), t[e] && (i = !0, r ||= t[e]);
|
|
58
127
|
return {
|
|
59
128
|
values: e,
|
|
60
|
-
firstError:
|
|
129
|
+
firstError: r,
|
|
130
|
+
hasError: i
|
|
61
131
|
};
|
|
62
|
-
},
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
132
|
+
}, F = (e) => {
|
|
133
|
+
l(c.errorElement, e);
|
|
134
|
+
}, I = () => {
|
|
135
|
+
for (let e of d) A(e, void 0);
|
|
136
|
+
j(void 0);
|
|
137
|
+
}, L = (t) => {
|
|
138
|
+
t.preventDefault(), (async () => {
|
|
139
|
+
h = void 0;
|
|
140
|
+
let { values: t, firstError: n, hasError: r } = await P();
|
|
141
|
+
if (M(), r) {
|
|
142
|
+
F(n), a(e, m);
|
|
70
143
|
return;
|
|
71
144
|
}
|
|
72
|
-
|
|
145
|
+
F(void 0), v = !0, c.disableSubmitWhilePending !== !1 && N(!0), M();
|
|
73
146
|
try {
|
|
74
|
-
if (await
|
|
75
|
-
e.reset(),
|
|
76
|
-
for (let e of
|
|
77
|
-
|
|
147
|
+
if (await c.onSubmit(t, e), c.resetOnSuccess) {
|
|
148
|
+
e.reset(), I();
|
|
149
|
+
for (let e of d) g[e] = !1;
|
|
150
|
+
T();
|
|
78
151
|
}
|
|
152
|
+
} catch (t) {
|
|
153
|
+
let n = c.mapSubmitError?.(t);
|
|
154
|
+
if (!n) throw t;
|
|
155
|
+
for (let e of d) A(e, n.fieldErrors[e]);
|
|
156
|
+
j(n.formError), a(e, m);
|
|
79
157
|
} finally {
|
|
80
|
-
|
|
158
|
+
v = !1, c.disableSubmitWhilePending !== !1 && N(!1), M();
|
|
81
159
|
}
|
|
82
160
|
})();
|
|
83
|
-
},
|
|
84
|
-
let
|
|
85
|
-
if (!(
|
|
86
|
-
let
|
|
87
|
-
|
|
161
|
+
}, R = (e) => {
|
|
162
|
+
let n = e.target;
|
|
163
|
+
if (!(n instanceof HTMLElement)) return;
|
|
164
|
+
let r = n.getAttribute("name");
|
|
165
|
+
r && d.includes(r) && (g[r] = !0, (async () => {
|
|
166
|
+
let e = await t(p(r), x(r), C(r), w(), S(r));
|
|
167
|
+
A(r, e), M();
|
|
168
|
+
})());
|
|
88
169
|
};
|
|
89
|
-
e.addEventListener("submit",
|
|
90
|
-
let
|
|
91
|
-
|
|
170
|
+
e.addEventListener("submit", L), c.validateOn && e.addEventListener(c.validateOn, R, !0);
|
|
171
|
+
for (let t of d) {
|
|
172
|
+
k(t);
|
|
173
|
+
let n = O(t);
|
|
174
|
+
n && i(n), c.skipLabelWarning || o(e, t);
|
|
175
|
+
}
|
|
176
|
+
let z = (() => {
|
|
177
|
+
e.removeEventListener("submit", L), c.validateOn && e.removeEventListener(c.validateOn, R, !0);
|
|
92
178
|
});
|
|
93
|
-
return
|
|
179
|
+
return z.getValues = w, z.setValue = (t, n) => {
|
|
94
180
|
let r = e.elements.namedItem(t);
|
|
95
|
-
(r
|
|
96
|
-
},
|
|
97
|
-
|
|
98
|
-
},
|
|
99
|
-
e
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
181
|
+
s(r) && (r.value = n), k(t), M();
|
|
182
|
+
}, z.setError = (e, t) => {
|
|
183
|
+
A(e, t), M();
|
|
184
|
+
}, z.setFormError = (e) => {
|
|
185
|
+
j(e), M();
|
|
186
|
+
}, z.reset = () => {
|
|
187
|
+
e.reset(), I();
|
|
188
|
+
for (let e of d) g[e] = !1;
|
|
189
|
+
T(), M();
|
|
190
|
+
}, z.getState = () => {
|
|
191
|
+
let e = E();
|
|
104
192
|
return {
|
|
105
|
-
values:
|
|
106
|
-
errors: { ...
|
|
107
|
-
|
|
193
|
+
values: w(),
|
|
194
|
+
errors: { ...m },
|
|
195
|
+
formError: h,
|
|
196
|
+
touched: { ...g },
|
|
108
197
|
dirty: e,
|
|
109
|
-
isDirty:
|
|
110
|
-
isSubmitting:
|
|
198
|
+
isDirty: d.some((t) => e[t]),
|
|
199
|
+
isSubmitting: v
|
|
111
200
|
};
|
|
112
|
-
},
|
|
201
|
+
}, z.watch = (t, n) => {
|
|
113
202
|
let r = (e) => {
|
|
114
203
|
let r = e.target;
|
|
115
|
-
r instanceof HTMLElement && r.getAttribute("name") === t && n(
|
|
204
|
+
r instanceof HTMLElement && r.getAttribute("name") === t && n(C(t), w());
|
|
116
205
|
};
|
|
117
206
|
return e.addEventListener("input", r), () => e.removeEventListener("input", r);
|
|
118
|
-
},
|
|
207
|
+
}, z;
|
|
208
|
+
}
|
|
209
|
+
function l(e, t) {
|
|
210
|
+
e && (t ? (e.textContent = t, e.removeAttribute("hidden")) : e.setAttribute("hidden", ""));
|
|
211
|
+
}
|
|
212
|
+
function u(e, t) {
|
|
213
|
+
return e.serialize ? e.serialize(t) : e.type === "number" ? t == null ? "" : String(t) : e.type === "checkbox" ? t ? "on" : "" : e.type === "multiselect" ? Array.isArray(t) ? t.join(",") : "" : typeof t == "string" ? t : String(t ?? "");
|
|
214
|
+
}
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/serverErrors.ts
|
|
217
|
+
var d = class extends Error {
|
|
218
|
+
errors;
|
|
219
|
+
constructor(e, t = "Form submit failed") {
|
|
220
|
+
super(t), this.name = "FormSubmitError", this.errors = e;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
function f(e, t, n) {
|
|
224
|
+
let r = {}, i;
|
|
225
|
+
for (let a of e) {
|
|
226
|
+
let e = p(a, n), o = a.field;
|
|
227
|
+
o && t.includes(o) ? r[o] = e : i ||= e;
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
fieldErrors: r,
|
|
231
|
+
formError: i
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
function p(e, t) {
|
|
235
|
+
return e.code && t?.[e.code] ? t[e.code] : e.message ? e.message : e.code ? e.code : "Invalid value";
|
|
119
236
|
}
|
|
120
|
-
|
|
121
|
-
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/createForm.ts
|
|
239
|
+
function m(e, t) {
|
|
240
|
+
let n = Object.keys(t.schema);
|
|
241
|
+
if (t.initialValues) for (let r of n) {
|
|
242
|
+
let n = t.initialValues[r];
|
|
243
|
+
if (n === void 0) continue;
|
|
244
|
+
let i = e.elements.namedItem(r);
|
|
245
|
+
(i instanceof HTMLInputElement || i instanceof HTMLTextAreaElement || i instanceof HTMLSelectElement) && (i.value = u(t.schema[r], n));
|
|
246
|
+
}
|
|
247
|
+
let r = c(e, {
|
|
248
|
+
fields: n.map((e) => ({
|
|
249
|
+
name: e,
|
|
250
|
+
schema: t.schema[e]
|
|
251
|
+
})),
|
|
252
|
+
errorElement: t.errorElement,
|
|
253
|
+
validateOn: t.validateOn,
|
|
254
|
+
resolver: t.resolver,
|
|
255
|
+
onStateChange: t.onStateChange,
|
|
256
|
+
disableSubmitWhilePending: t.disableSubmitWhilePending,
|
|
257
|
+
onSubmit: t.onSubmit,
|
|
258
|
+
resetOnSuccess: t.resetOnSuccess,
|
|
259
|
+
mapSubmitError: (e) => {
|
|
260
|
+
if (e instanceof d) return f(e.errors, n, t.errorMessages);
|
|
261
|
+
}
|
|
262
|
+
}), i = (() => r());
|
|
263
|
+
return i.getValues = () => r.getValues(), i.setValue = (e, n) => r.setValue(e, u(t.schema[e], n)), i.setError = (e, t) => r.setError(e, t), i.setFormError = (e) => r.setFormError(e), i.reset = () => r.reset(), i.getState = () => r.getState(), i.watch = (e, t) => r.watch(e, (e, n) => t(e, n)), i;
|
|
122
264
|
}
|
|
123
|
-
|
|
124
|
-
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region src/index.ts
|
|
267
|
+
function h(e, t) {
|
|
268
|
+
let n = c(e, {
|
|
269
|
+
fields: Object.keys(t.schema).map((e) => ({
|
|
270
|
+
name: e,
|
|
271
|
+
schema: t.schema[e]
|
|
272
|
+
})),
|
|
273
|
+
errorElement: t.errorElement,
|
|
274
|
+
validateOn: t.validateOn,
|
|
275
|
+
resolver: t.resolver,
|
|
276
|
+
onStateChange: t.onStateChange,
|
|
277
|
+
disableSubmitWhilePending: t.disableSubmitWhilePending,
|
|
278
|
+
onSubmit: t.onSubmit,
|
|
279
|
+
resetOnSuccess: t.resetOnSuccess
|
|
280
|
+
}), r = (() => n());
|
|
281
|
+
return r.getValues = () => n.getValues(), r.setValue = (e, t) => n.setValue(e, t), r.setError = (e, t) => n.setError(e, t), r.reset = () => n.reset(), r.getState = () => n.getState(), r.watch = (e, t) => n.watch(e, (e, n) => t(e, n)), r;
|
|
125
282
|
}
|
|
126
283
|
//#endregion
|
|
127
|
-
export {
|
|
284
|
+
export { d as FormSubmitError, r as applyFieldAccessibility, h as bindForm, c as createEngine, m as createForm, i as ensureErrorElementA11y, a as focusFirstInvalidField, f as mapServerErrors, t as runFieldPipeline, n as runFormPipeline, e as runSyncRules, u as serializeFieldValue, o as warnIfLabelMissing };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** A single server-side validation error returned after a failed submit (e.g. HTTP 422). */
|
|
2
|
+
export interface ServerError {
|
|
3
|
+
/** Name of the field the error applies to. If it doesn't match a schema field, it becomes `form.formError` (REQ-009). */
|
|
4
|
+
field?: string | null;
|
|
5
|
+
/** Machine-readable error code, resolved through `errorMessages` (REQ-008). */
|
|
6
|
+
code?: string;
|
|
7
|
+
/** Human-readable fallback message, used if `code` has no entry in `errorMessages`. */
|
|
8
|
+
message?: string;
|
|
9
|
+
}
|
|
10
|
+
/** Response shape expected from a failed submit: a list of per-field (or form-level) errors. */
|
|
11
|
+
export type ServerErrorResponse = ServerError[];
|
|
12
|
+
/**
|
|
13
|
+
* Thrown (or returned as a rejected promise) by `onSubmit` to report server-side validation errors.
|
|
14
|
+
* `createForm` catches it and maps `errors` through `mapServerErrors` instead of letting it propagate
|
|
15
|
+
* as an unhandled exception (TASK-013).
|
|
16
|
+
*/
|
|
17
|
+
export declare class FormSubmitError extends Error {
|
|
18
|
+
errors: ServerErrorResponse;
|
|
19
|
+
constructor(errors: ServerErrorResponse, message?: string);
|
|
20
|
+
}
|
|
21
|
+
/** Result of `mapServerErrors`: per-field messages plus an optional form-level (non-field) message. */
|
|
22
|
+
export interface MappedServerErrors<TField extends string> {
|
|
23
|
+
fieldErrors: Partial<Record<TField, string>>;
|
|
24
|
+
formError?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Maps a `ServerErrorResponse` into per-field errors plus a form-level error (REQ-007/REQ-009).
|
|
28
|
+
*
|
|
29
|
+
* For each entry: the message is resolved as `errorMessages[code]` (if `code` and a matching entry
|
|
30
|
+
* exist), else the raw `message`, else the raw `code`, else a generic fallback (REQ-008). Entries
|
|
31
|
+
* whose `field` is missing or not part of `knownFields` are collected into `formError` instead
|
|
32
|
+
* (the first one wins, matching the "first error" convention used elsewhere in this package).
|
|
33
|
+
*/
|
|
34
|
+
export declare function mapServerErrors<TField extends string>(response: ServerErrorResponse, knownFields: readonly TField[], errorMessages?: Record<string, string>): MappedServerErrors<TField>;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** Built-in synchronous rules shared by the legacy `FieldRule` and the typed `FieldSchema`. */
|
|
2
|
+
export interface SyncFieldRules {
|
|
3
|
+
/** Error message shown if the field is empty after trim(). */
|
|
4
|
+
required?: string;
|
|
5
|
+
/** Regex and error message checked only when the field is non-empty. */
|
|
6
|
+
pattern?: {
|
|
7
|
+
value: RegExp;
|
|
8
|
+
message: string;
|
|
9
|
+
};
|
|
10
|
+
/** Minimum string length (after trim()), checked only when the field is non-empty. */
|
|
11
|
+
minLength?: {
|
|
12
|
+
value: number;
|
|
13
|
+
message: string;
|
|
14
|
+
};
|
|
15
|
+
/** Maximum string length (after trim()). */
|
|
16
|
+
maxLength?: {
|
|
17
|
+
value: number;
|
|
18
|
+
message: string;
|
|
19
|
+
};
|
|
20
|
+
/** Minimum numeric value, checked only when the field parses as a number. */
|
|
21
|
+
min?: {
|
|
22
|
+
value: number;
|
|
23
|
+
message: string;
|
|
24
|
+
};
|
|
25
|
+
/** Maximum numeric value, checked only when the field parses as a number. */
|
|
26
|
+
max?: {
|
|
27
|
+
value: number;
|
|
28
|
+
message: string;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Validation rule for a single form field, as consumed by `bindForm`. */
|
|
32
|
+
export interface FieldRule extends SyncFieldRules {
|
|
33
|
+
/** Custom validator, run last. Return an error message, or undefined/empty string if valid. */
|
|
34
|
+
validate?: (value: string) => string | undefined;
|
|
35
|
+
}
|
|
36
|
+
/** How a field's raw (always-string) FormData value is converted to a typed `form.values[field]`. */
|
|
37
|
+
export type FieldType = "text" | "number" | "checkbox" | "multiselect";
|
|
38
|
+
/**
|
|
39
|
+
* Validation + typing schema for a single field, as consumed by `createForm`.
|
|
40
|
+
* `TValue` is the type exposed on `form.values[field]` (inferred via `InferValues`).
|
|
41
|
+
*/
|
|
42
|
+
export interface FieldSchema<TValue = string> extends SyncFieldRules {
|
|
43
|
+
/**
|
|
44
|
+
* How the raw FormData string is converted into `TValue`:
|
|
45
|
+
* - `"text"` (default) -> `string`
|
|
46
|
+
* - `"number"` -> `number` (raw parsed with `Number(...)`)
|
|
47
|
+
* - `"checkbox"` -> `boolean` (`true` if checked/present in FormData)
|
|
48
|
+
* - `"multiselect"` -> `string[]` (all values for fields with the same `name`, e.g. a multi-select or a group of checkboxes)
|
|
49
|
+
*/
|
|
50
|
+
type?: FieldType;
|
|
51
|
+
/** Custom parser overriding the default `type`-based conversion. Not used for `type: "multiselect"`. */
|
|
52
|
+
parse?: (raw: string) => TValue;
|
|
53
|
+
/** Custom serializer used by `setValue` to turn a typed value back into a string for the DOM element. */
|
|
54
|
+
serialize?: (value: TValue) => string;
|
|
55
|
+
/** Synchronous custom validator, run after the built-in sync rules. */
|
|
56
|
+
validate?: (value: TValue, values: Record<string, unknown>) => string | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* Asynchronous validator (e.g. a uniqueness check), run only if the field has no sync error
|
|
59
|
+
* (see `runFieldPipeline` / REQ-006).
|
|
60
|
+
*/
|
|
61
|
+
async?: (value: TValue, values: Record<string, unknown>) => string | undefined | Promise<string | undefined>;
|
|
62
|
+
}
|
|
63
|
+
/** Form values: field name -> string value taken from FormData. */
|
|
64
|
+
export type FormValues<TField extends string> = Record<TField, string>;
|
|
65
|
+
/** Validation errors keyed by field name. */
|
|
66
|
+
export type FormErrors<TField extends string> = Partial<Record<TField, string>>;
|
|
67
|
+
/** When to run per-field validation in addition to submit. */
|
|
68
|
+
export type ValidateTrigger = "blur" | "input";
|
|
69
|
+
/** Snapshot of the form's current state, passed to `onStateChange`. */
|
|
70
|
+
export interface FormState<TField extends string> {
|
|
71
|
+
values: FormValues<TField>;
|
|
72
|
+
errors: FormErrors<TField>;
|
|
73
|
+
/** Whether a field has been interacted with (blur/input) since bind or last reset. */
|
|
74
|
+
touched: Record<TField, boolean>;
|
|
75
|
+
/** Whether a field's value differs from its value at bind time (or last reset). */
|
|
76
|
+
dirty: Record<TField, boolean>;
|
|
77
|
+
/** True if any field is dirty. */
|
|
78
|
+
isDirty: boolean;
|
|
79
|
+
/** True while `onSubmit` is pending. */
|
|
80
|
+
isSubmitting: boolean;
|
|
81
|
+
}
|
|
82
|
+
/** Infers `form.values` shape from a `createForm` schema: field name -> its `FieldSchema<TValue>`'s `TValue`. */
|
|
83
|
+
export type InferValues<TSchema extends Record<string, FieldSchema<any>>> = {
|
|
84
|
+
[K in keyof TSchema]: TSchema[K] extends FieldSchema<infer TValue> ? TValue : never;
|
|
85
|
+
};
|
|
86
|
+
/** Infers `form.errors` shape from a `createForm` schema: every field maps to an optional error message. */
|
|
87
|
+
export type InferErrors<TSchema extends Record<string, FieldSchema<any>>> = Partial<Record<keyof TSchema & string, string>>;
|
|
88
|
+
/** Snapshot of a typed `createForm` form's current state, passed to `onStateChange`. */
|
|
89
|
+
export interface TypedFormState<TValues extends Record<string, unknown>, TField extends string> {
|
|
90
|
+
values: TValues;
|
|
91
|
+
errors: Partial<Record<TField, string>>;
|
|
92
|
+
/** Form-level error not tied to any known field (see `ServerError`/REQ-009). */
|
|
93
|
+
formError?: string;
|
|
94
|
+
touched: Record<TField, boolean>;
|
|
95
|
+
dirty: Record<TField, boolean>;
|
|
96
|
+
isDirty: boolean;
|
|
97
|
+
isSubmitting: boolean;
|
|
98
|
+
}
|
|
99
|
+
export interface BindFormOptions<TField extends string> {
|
|
100
|
+
/** Validation schema: keys must match the `name` attributes of the form fields. */
|
|
101
|
+
schema: Record<TField, FieldRule>;
|
|
102
|
+
/** Element used to display the form-level error message (must support `hidden`). */
|
|
103
|
+
errorElement?: HTMLElement;
|
|
104
|
+
/**
|
|
105
|
+
* Run validation for a field as the user interacts with it, in addition to on submit.
|
|
106
|
+
* Per-field errors are shown in elements matching `[data-error-for="<field>"]` inside the form.
|
|
107
|
+
*/
|
|
108
|
+
validateOn?: ValidateTrigger;
|
|
109
|
+
/**
|
|
110
|
+
* Additional async/external validation (e.g. a zod/yup schema adapter), run on submit
|
|
111
|
+
* after the `schema` rules. Only consulted for fields that passed `schema` validation.
|
|
112
|
+
*/
|
|
113
|
+
resolver?: (values: FormValues<TField>) => FormErrors<TField> | Promise<FormErrors<TField>>;
|
|
114
|
+
/** Called whenever the form's values/errors/touched/dirty/submitting state changes. */
|
|
115
|
+
onStateChange?: (state: FormState<TField>) => void;
|
|
116
|
+
/**
|
|
117
|
+
* Disable `[type="submit"]` elements inside the form while `onSubmit` is pending.
|
|
118
|
+
* Defaults to `true`.
|
|
119
|
+
*/
|
|
120
|
+
disableSubmitWhilePending?: boolean;
|
|
121
|
+
/** Called with the validated values after a successful submit. */
|
|
122
|
+
onSubmit: (values: FormValues<TField>, form: HTMLFormElement) => void | Promise<void>;
|
|
123
|
+
/** Reset the form after a successful onSubmit. */
|
|
124
|
+
resetOnSuccess?: boolean;
|
|
125
|
+
}
|
|
126
|
+
/** Handle returned by `bindForm`. Calling it directly unsubscribes (same as before). */
|
|
127
|
+
export interface BindFormHandle<TField extends string> {
|
|
128
|
+
(): void;
|
|
129
|
+
/** Reads and trims the current values of all schema fields from the form. */
|
|
130
|
+
getValues(): FormValues<TField>;
|
|
131
|
+
/** Writes a value into the form field with the given name. */
|
|
132
|
+
setValue(field: TField, value: string): void;
|
|
133
|
+
/** Shows (or, if `message` is undefined, hides) the error for `[data-error-for="<field>"]`. */
|
|
134
|
+
setError(field: TField, message: string | undefined): void;
|
|
135
|
+
/** Resets the form, clears all displayed errors and recaptures dirty/touched state. */
|
|
136
|
+
reset(): void;
|
|
137
|
+
/** Returns a snapshot of the current form state (values/errors/touched/dirty/isSubmitting). */
|
|
138
|
+
getState(): FormState<TField>;
|
|
139
|
+
/** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
|
|
140
|
+
watch(field: TField, callback: (value: string, values: FormValues<TField>) => void): () => void;
|
|
141
|
+
}
|
|
142
|
+
/** Handle returned by `createForm`. Calling it directly unsubscribes. */
|
|
143
|
+
export interface FormHandle<TValues extends Record<string, unknown>, TField extends string> {
|
|
144
|
+
(): void;
|
|
145
|
+
/** Reads the current, typed values of all schema fields from the form. */
|
|
146
|
+
getValues(): TValues;
|
|
147
|
+
/** Writes a value into the form field with the given name (serialized via `FieldSchema.serialize` if set). */
|
|
148
|
+
setValue<K extends TField>(field: K, value: TValues[K]): void;
|
|
149
|
+
/** Shows (or, if `message` is undefined, hides) the error for `[data-error-for="<field>"]`. */
|
|
150
|
+
setError(field: TField, message: string | undefined): void;
|
|
151
|
+
/** Sets (or, if `message` is undefined, clears) the form-level error (see REQ-009). */
|
|
152
|
+
setFormError(message: string | undefined): void;
|
|
153
|
+
/** Resets the form, clears all displayed errors and recaptures dirty/touched state. */
|
|
154
|
+
reset(): void;
|
|
155
|
+
/** Returns a snapshot of the current form state (values/errors/formError/touched/dirty/isSubmitting). */
|
|
156
|
+
getState(): TypedFormState<TValues, TField>;
|
|
157
|
+
/** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
|
|
158
|
+
watch<K extends TField>(field: K, callback: (value: TValues[K], values: TValues) => void): () => void;
|
|
159
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { FieldSchema, SyncFieldRules } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Runs the built-in synchronous rules (`required`/`pattern`/`minLength`/`maxLength`/`min`/`max`)
|
|
4
|
+
* against a field's raw (trimmed) string value. Used as stage 1 of the field pipeline
|
|
5
|
+
* (`sync -> async -> server`, see `runFieldPipeline`).
|
|
6
|
+
*/
|
|
7
|
+
export declare function runSyncRules(rule: SyncFieldRules, raw: string): string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Runs the full per-field pipeline: built-in sync rules -> `schema.validate` (sync) -> `schema.async`.
|
|
10
|
+
* As soon as a sync stage produces an error, later stages are skipped and that error is returned
|
|
11
|
+
* (REQ-006): the `async` rule never runs for a field that already failed sync validation.
|
|
12
|
+
*/
|
|
13
|
+
export declare function runFieldPipeline<TValue>(schema: FieldSchema<TValue>, raw: string, value: TValue, values: Record<string, unknown>,
|
|
14
|
+
/** Error from converting `raw` into `TValue` (e.g. an unparsable number), checked right after the sync rules. */
|
|
15
|
+
coercionError?: string): Promise<string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* Runs `runFieldPipeline` for every field in parallel and collects the resulting errors,
|
|
18
|
+
* keyed by field name (stage 2 of `sync -> async(per field) -> resolver(form-level) -> server`).
|
|
19
|
+
*/
|
|
20
|
+
export declare function runFormPipeline<TField extends string>(fields: TField[], getSchema: (field: TField) => FieldSchema<any>, getRaw: (field: TField) => string, getValue: (field: TField) => unknown, values: Record<string, unknown>, getCoercionError?: (field: TField) => string | undefined): Promise<Partial<Record<TField, string>>>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chepchik/bind-form",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Dependency-free typed form engine: createForm() with types inferred from schema, sync/async/server validation pipeline, automatic server error mapping and built-in accessibility (aria-invalid, focus management). Also exports the original bindForm() helper.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
@@ -15,18 +15,31 @@
|
|
|
15
15
|
"files": [
|
|
16
16
|
"dist"
|
|
17
17
|
],
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/Egortex/spa-toolkit.git",
|
|
21
|
+
"directory": "packages/bind-form"
|
|
22
|
+
},
|
|
18
23
|
"sideEffects": false,
|
|
19
24
|
"scripts": {
|
|
20
25
|
"build": "vite build",
|
|
21
|
-
"dev": "vite build --watch"
|
|
26
|
+
"dev": "vite build --watch",
|
|
27
|
+
"test": "tsc --noEmit && vitest run",
|
|
28
|
+
"test:coverage": "tsc --noEmit && vitest run --coverage"
|
|
22
29
|
},
|
|
23
30
|
"keywords": [
|
|
24
31
|
"form",
|
|
25
32
|
"validation",
|
|
26
|
-
"spa"
|
|
33
|
+
"spa",
|
|
34
|
+
"typed-forms",
|
|
35
|
+
"accessibility",
|
|
36
|
+
"form-validation"
|
|
27
37
|
],
|
|
28
38
|
"license": "MIT",
|
|
29
39
|
"devDependencies": {
|
|
40
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
41
|
+
"jsdom": "^30.0.1",
|
|
42
|
+
"vitest": "^5.0.0",
|
|
30
43
|
"typescript": "^6.0.3",
|
|
31
44
|
"vite": "^8.0.16",
|
|
32
45
|
"vite-plugin-dts": "^5.0.2"
|