@chepchik/bind-form 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,27 @@
1
1
  # bind-form
2
2
 
3
- Что: один помощник `bindForm`, который вешает обработчик `submit` на форму,
4
- валидирует поля по простой схеме (`required` / `pattern`) и вызывает
5
- `onSubmit` с собранными значениями, если всё валидно.
3
+ ![coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Egortex/spa-toolkit/main/packages/bind-form/coverage-badge.json) ![size](https://img.shields.io/bundlephobia/minzip/@chepchik/bind-form)
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)).
6
21
 
7
22
  Зачем: чтобы не дублировать в каждой форме одинаковый код —
8
- `preventDefault`, сбор `FormData`, проверку обязательных полей и regex,
9
- показ/скрытие текста ошибки. Отправка по Enter работает "из коробки",
23
+ `preventDefault`, сбор `FormData`, проверку полей, показ/скрытие ошибок,
24
+ доступность и фокус-менеджмент. Отправка по Enter работает "из коробки",
10
25
  т.к. используется стандартное поведение `<form>`.
11
26
 
12
27
  ## Установка
@@ -15,7 +30,153 @@
15
30
  npm install @chepchik/bind-form
16
31
  ```
17
32
 
18
- ## Использование
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
+ npm run test # tsc --noEmit && vitest run
172
+ npm run 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`
19
180
 
20
181
  ```ts
21
182
  import { bindForm } from "@chepchik/bind-form";
@@ -23,12 +184,16 @@ import { bindForm } from "@chepchik/bind-form";
23
184
  const form = document.querySelector("form")!;
24
185
  const errorElement = document.querySelector("#error")!;
25
186
 
26
- const unsubscribe = bindForm(form, {
187
+ const formHandle = bindForm(form, {
27
188
  schema: {
28
189
  email: { required: "Введите email", pattern: { value: /.+@.+/, message: "Неверный email" } },
29
- password: { required: "Введите пароль" },
190
+ password: {
191
+ required: "Введите пароль",
192
+ minLength: { value: 6, message: "Минимум 6 символов" },
193
+ },
30
194
  },
31
195
  errorElement,
196
+ validateOn: "blur",
32
197
  resetOnSuccess: true,
33
198
  onSubmit: async (values, form) => {
34
199
  await api.login(values.email, values.password);
@@ -36,12 +201,100 @@ const unsubscribe = bindForm(form, {
36
201
  });
37
202
 
38
203
  // позже, при размонтировании:
39
- unsubscribe();
204
+ formHandle();
205
+ ```
206
+
207
+ Для показа ошибки конкретного поля при `validateOn` добавьте рядом с полем
208
+ элемент `[data-error-for="<name>"]` (`<span data-error-for="email" hidden></span>`).
209
+
210
+ ## Пример: сложная форма (`bindForm`)
211
+
212
+ Более развёрнутый пример, использующий все возможности: `resolver` для
213
+ асинхронной проверки, `onStateChange` для индикации состояния, `watch` для
214
+ живого фидбека по отдельному полю и блокировку кнопки на время отправки.
215
+ Рабочая версия — страница `/form-demo` в `OOP_taskList`
216
+ (`app/pages/form-demo/index.page.ts`).
217
+
218
+ ```ts
219
+ import { bindForm, type FormErrors } from "@chepchik/bind-form";
220
+
221
+ type Field = "username" | "password" | "bio";
222
+
223
+ const submitButton = form.querySelector<HTMLButtonElement>('[type="submit"]')!;
224
+ const bioCount = document.querySelector("#bio-count")!;
225
+ const passwordStrength = document.querySelector("#password-strength")!;
226
+
227
+ const handle = bindForm<Field>(form, {
228
+ schema: {
229
+ username: {
230
+ required: "Введите имя пользователя",
231
+ minLength: { value: 3, message: "Минимум 3 символа" },
232
+ },
233
+ password: {
234
+ required: "Введите пароль",
235
+ minLength: { value: 6, message: "Минимум 6 символов" },
236
+ validate: (value) => (/\d/.test(value) ? undefined : "Пароль должен содержать цифру"),
237
+ },
238
+ bio: {
239
+ maxLength: { value: 200, message: "Максимум 200 символов" },
240
+ },
241
+ },
242
+ validateOn: "input",
243
+ // Асинхронная проверка, выполняется на submit после правил schema.
244
+ resolver: async (values): Promise<FormErrors<Field>> => {
245
+ const taken = await api.isUsernameTaken(values.username);
246
+ return taken ? { username: "Это имя уже занято" } : {};
247
+ },
248
+ // Отслеживание состояния формы.
249
+ onStateChange: (state) => {
250
+ submitButton.textContent = state.isSubmitting ? "Отправка..." : "Зарегистрироваться";
251
+ },
252
+ onSubmit: async (values) => {
253
+ await api.register(values);
254
+ },
255
+ resetOnSuccess: true,
256
+ });
257
+
258
+ // Живой фидбек по отдельным полям.
259
+ handle.watch("bio", (value) => {
260
+ bioCount.textContent = `${value.length}/200`;
261
+ });
262
+ handle.watch("password", (value) => {
263
+ passwordStrength.textContent = value.length >= 10 ? "сильный" : "слабый";
264
+ });
265
+
266
+ // Программное управление формой.
267
+ fillExampleButton.addEventListener("click", () => {
268
+ handle.setValue("username", "ivan_petrov");
269
+ handle.setValue("password", "secret123");
270
+ });
271
+ resetButton.addEventListener("click", () => handle.reset());
40
272
  ```
41
273
 
42
274
  ## API
43
275
 
44
- ### `bindForm<TField>(form, options): () => void`
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
+
297
+ ### `bindForm<TField>(form, options): BindFormHandle<TField>`
45
298
 
46
299
  - `form: HTMLFormElement` — форма, на которую вешается обработчик `submit`.
47
300
  - `options.schema: Record<TField, FieldRule>` — схема валидации, ключи
@@ -49,9 +302,56 @@ unsubscribe();
49
302
  - `required?: string` — текст ошибки, если поле пустое после `trim()`.
50
303
  - `pattern?: { value: RegExp; message: string }` — проверяется только
51
304
  если поле непустое.
52
- - `options.errorElement?: HTMLElement` — элемент для показа текста ошибки
305
+ - `minLength?: { value: number; message: string }` / `maxLength?: { ... }` —
306
+ длина строки после `trim()`.
307
+ - `min?: { value: number; message: string }` / `max?: { ... }` — проверяются,
308
+ только если значение поля парсится как число.
309
+ - `validate?: (value: string) => string | undefined` — кастомная проверка,
310
+ выполняется последней.
311
+ - `options.errorElement?: HTMLElement` — элемент для показа общей ошибки формы
53
312
  (должен поддерживать атрибут `hidden`).
313
+ - `options.validateOn?: "blur" | "input"` — дополнительно валидировать поле
314
+ при потере фокуса/вводе и показывать ошибку в `[data-error-for="<field>"]`.
315
+ - `options.resolver?: (values) => FormErrors<TField> | Promise<FormErrors<TField>>` —
316
+ доп. асинхронная/внешняя валидация (например, обёртка над zod/yup-схемой),
317
+ выполняется на submit после проверок из `schema`. Для поля, у которого
318
+ `schema` уже нашла ошибку, результат resolver'а игнорируется.
319
+ - `options.onStateChange?: (state: FormState<TField>) => void` — вызывается
320
+ при изменении значений/ошибок/`touched`/`dirty`/`isSubmitting`.
321
+ - `options.disableSubmitWhilePending?: boolean` — отключать `[type="submit"]`
322
+ на время выполнения `onSubmit`. По умолчанию `true`.
54
323
  - `options.onSubmit(values, form)` — вызывается после успешной валидации.
55
324
  - `options.resetOnSuccess?: boolean` — сбросить форму после успешного `onSubmit`.
56
325
 
57
- Возвращает функцию отписки от события `submit`.
326
+ ### `FormState<TField>`
327
+
328
+ - `values: FormValues<TField>` — текущие значения.
329
+ - `errors: FormErrors<TField>` — текущие ошибки по полям.
330
+ - `touched: Record<TField, boolean>` — было ли поле в фокусе/изменено
331
+ (`blur`/`input`) с момента привязки или последнего `reset()`.
332
+ - `dirty: Record<TField, boolean>` — отличается ли значение поля от значения
333
+ на момент привязки/последнего `reset()`.
334
+ - `isDirty: boolean` — true, если хотя бы одно поле `dirty`.
335
+ - `isSubmitting: boolean` — true во время выполнения `onSubmit`.
336
+
337
+ ### `BindFormHandle<TField>`
338
+
339
+ Сама функция — отписка от обработчиков (вызовите `formHandle()` при размонтировании).
340
+ Дополнительно доступны методы:
341
+
342
+ - `getValues(): FormValues<TField>` — текущие (обрезанные) значения полей.
343
+ - `setValue(field, value: string)` — записать значение в поле формы.
344
+ - `setError(field, message?: string)` — показать/скрыть ошибку поля
345
+ (`[data-error-for="<field>"]`).
346
+ - `reset()` — сбросить форму, очистить все отображённые ошибки и пересчитать
347
+ базовые значения для `dirty`/`touched`.
348
+ - `getState(): FormState<TField>` — снимок текущего состояния формы.
349
+ - `watch(field, callback)` — вызывать `callback(value, values)` при каждом
350
+ изменении значения `field`. Возвращает функцию отписки.
351
+
352
+ ### `mapServerErrors(response, knownFields, errorMessages?)`
353
+
354
+ Превращает `ServerErrorResponse` (`{ field?, code?, message? }[]`) в
355
+ `{ fieldErrors, formError }`. Используется автоматически внутри `createForm`
356
+ при `FormSubmitError`, но экспортируется и для ручного использования (в том
357
+ числе вместе с `bindForm`).
package/dist/index.js CHANGED
@@ -1,29 +1,283 @@
1
- //#region src/index.ts
2
- function e(e, r) {
3
- let i = (i) => {
4
- i.preventDefault();
5
- let a = new FormData(e), o = {}, s;
6
- for (let e of Object.keys(r.schema)) {
7
- let t = String(a.get(e) ?? "").trim();
8
- o[e] = t;
9
- let n = r.schema[e];
10
- !s && n.required && !t ? s = n.required : !s && t && n.pattern && !n.pattern.value.test(t) && (s = n.pattern.message);
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(",") : "";
11
65
  }
12
- if (s) {
13
- t(r.errorElement, s);
14
- return;
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;
79
+ }
80
+ case "checkbox": return n !== "";
81
+ default: return n;
15
82
  }
16
- n(r.errorElement), Promise.resolve(r.onSubmit(o, e)).then(() => {
17
- r.resetOnSuccess && e.reset();
83
+ }, w = () => {
84
+ let e = {};
85
+ for (let t of d) e[t] = C(t);
86
+ return e;
87
+ }, T = () => {
88
+ _ = w();
89
+ };
90
+ T();
91
+ let E = () => {
92
+ let e = {};
93
+ for (let t of d) e[t] = y(t) !== D(t);
94
+ return e;
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 },
112
+ dirty: e,
113
+ isDirty: d.some((t) => e[t]),
114
+ isSubmitting: v
18
115
  });
116
+ }, N = (t) => {
117
+ let n = e.querySelectorAll("[type=\"submit\"]");
118
+ for (let e of n) e.disabled = t;
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]);
124
+ }
125
+ let r, i = !1;
126
+ for (let e of d) A(e, t[e]), t[e] && (i = !0, r ||= t[e]);
127
+ return {
128
+ values: e,
129
+ firstError: r,
130
+ hasError: i
131
+ };
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);
143
+ return;
144
+ }
145
+ F(void 0), v = !0, c.disableSubmitWhilePending !== !1 && N(!0), M();
146
+ try {
147
+ if (await c.onSubmit(t, e), c.resetOnSuccess) {
148
+ e.reset(), I();
149
+ for (let e of d) g[e] = !1;
150
+ T();
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);
157
+ } finally {
158
+ v = !1, c.disableSubmitWhilePending !== !1 && N(!1), M();
159
+ }
160
+ })();
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
+ A(r, await t(p(r), x(r), C(r), w(), S(r))), M();
167
+ })());
168
+ };
169
+ e.addEventListener("submit", L), c.validateOn && e.addEventListener(c.validateOn, R, !0);
170
+ for (let t of d) {
171
+ k(t);
172
+ let n = O(t);
173
+ n && i(n), c.skipLabelWarning || o(e, t);
174
+ }
175
+ let z = (() => {
176
+ e.removeEventListener("submit", L), c.validateOn && e.removeEventListener(c.validateOn, R, !0);
177
+ });
178
+ return z.getValues = w, z.setValue = (t, n) => {
179
+ let r = e.elements.namedItem(t);
180
+ s(r) && (r.value = n), k(t), M();
181
+ }, z.setError = (e, t) => {
182
+ A(e, t), M();
183
+ }, z.setFormError = (e) => {
184
+ j(e), M();
185
+ }, z.reset = () => {
186
+ e.reset(), I();
187
+ for (let e of d) g[e] = !1;
188
+ T(), M();
189
+ }, z.getState = () => {
190
+ let e = E();
191
+ return {
192
+ values: w(),
193
+ errors: { ...m },
194
+ formError: h,
195
+ touched: { ...g },
196
+ dirty: e,
197
+ isDirty: d.some((t) => e[t]),
198
+ isSubmitting: v
199
+ };
200
+ }, z.watch = (t, n) => {
201
+ let r = (e) => {
202
+ let r = e.target;
203
+ r instanceof HTMLElement && r.getAttribute("name") === t && n(C(t), w());
204
+ };
205
+ return e.addEventListener("input", r), () => e.removeEventListener("input", r);
206
+ }, z;
207
+ }
208
+ function l(e, t) {
209
+ e && (t ? (e.textContent = t, e.removeAttribute("hidden")) : e.setAttribute("hidden", ""));
210
+ }
211
+ function u(e, t) {
212
+ 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 ?? "");
213
+ }
214
+ //#endregion
215
+ //#region src/serverErrors.ts
216
+ var d = class extends Error {
217
+ errors;
218
+ constructor(e, t = "Form submit failed") {
219
+ super(t), this.name = "FormSubmitError", this.errors = e;
220
+ }
221
+ };
222
+ function f(e, t, n) {
223
+ let r = {}, i;
224
+ for (let a of e) {
225
+ let e = p(a, n), o = a.field;
226
+ o && t.includes(o) ? r[o] = e : i ||= e;
227
+ }
228
+ return {
229
+ fieldErrors: r,
230
+ formError: i
19
231
  };
20
- return e.addEventListener("submit", i), () => e.removeEventListener("submit", i);
21
232
  }
22
- function t(e, t) {
23
- e && (e.textContent = t, e.removeAttribute("hidden"));
233
+ function p(e, t) {
234
+ return e.code && t?.[e.code] ? t[e.code] : e.message ? e.message : e.code ? e.code : "Invalid value";
24
235
  }
25
- function n(e) {
26
- e && e.setAttribute("hidden", "");
236
+ //#endregion
237
+ //#region src/createForm.ts
238
+ function m(e, t) {
239
+ let n = Object.keys(t.schema);
240
+ if (t.initialValues) for (let r of n) {
241
+ let n = t.initialValues[r];
242
+ if (n === void 0) continue;
243
+ let i = e.elements.namedItem(r);
244
+ (i instanceof HTMLInputElement || i instanceof HTMLTextAreaElement || i instanceof HTMLSelectElement) && (i.value = u(t.schema[r], n));
245
+ }
246
+ let r = c(e, {
247
+ fields: n.map((e) => ({
248
+ name: e,
249
+ schema: t.schema[e]
250
+ })),
251
+ errorElement: t.errorElement,
252
+ validateOn: t.validateOn,
253
+ resolver: t.resolver,
254
+ onStateChange: t.onStateChange,
255
+ disableSubmitWhilePending: t.disableSubmitWhilePending,
256
+ onSubmit: t.onSubmit,
257
+ resetOnSuccess: t.resetOnSuccess,
258
+ mapSubmitError: (e) => {
259
+ if (e instanceof d) return f(e.errors, n, t.errorMessages);
260
+ }
261
+ }), i = (() => r());
262
+ 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;
263
+ }
264
+ //#endregion
265
+ //#region src/index.ts
266
+ function h(e, t) {
267
+ let n = c(e, {
268
+ fields: Object.keys(t.schema).map((e) => ({
269
+ name: e,
270
+ schema: t.schema[e]
271
+ })),
272
+ errorElement: t.errorElement,
273
+ validateOn: t.validateOn,
274
+ resolver: t.resolver,
275
+ onStateChange: t.onStateChange,
276
+ disableSubmitWhilePending: t.disableSubmitWhilePending,
277
+ onSubmit: t.onSubmit,
278
+ resetOnSuccess: t.resetOnSuccess
279
+ }), r = (() => n());
280
+ 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;
27
281
  }
28
282
  //#endregion
29
- export { e as bindForm };
283
+ 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,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>;
@@ -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;
@@ -0,0 +1,35 @@
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';
11
+ /**
12
+ * Subscribes to a form's submit event: prevents the page reload, validates fields
13
+ * against the schema (required/pattern/minLength/maxLength/min/max/validate, then
14
+ * an optional `resolver`) and calls onSubmit with the collected values.
15
+ * Submitting via Enter works out of the box (default <form> behavior).
16
+ *
17
+ * If `validateOn` is set, fields are additionally validated on "blur" or "input"
18
+ * and per-field errors are shown in `[data-error-for="<field>"]` elements.
19
+ *
20
+ * While `onSubmit` is pending, `[type="submit"]` elements are disabled (unless
21
+ * `disableSubmitWhilePending` is `false`) and `isSubmitting` is reported via `onStateChange`.
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
+ *
28
+ * Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
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.
34
+ */
35
+ export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): BindFormHandle<TField>;
@@ -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>;
@@ -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>>>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare function createForm(html: string): HTMLFormElement;
2
+ export declare function submit(form: HTMLFormElement): void;
3
+ export declare function flush(times?: number): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@chepchik/bind-form",
3
- "version": "0.1.1",
4
- "description": "Tiny dependency-free form binding helper: submit handling, validation schema and error display.",
3
+ "version": "0.2.0",
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"
package/dist/index.d.ts DELETED
@@ -1,29 +0,0 @@
1
- /** Validation rule for a single form field. */
2
- export interface FieldRule {
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
- }
11
- /** Form values: field name -> string value taken from FormData. */
12
- export type FormValues<TField extends string> = Record<TField, string>;
13
- export interface BindFormOptions<TField extends string> {
14
- /** Validation schema: keys must match the `name` attributes of the form fields. */
15
- schema: Record<TField, FieldRule>;
16
- /** Element used to display the validation error message (must support `hidden`). */
17
- errorElement?: HTMLElement;
18
- /** Called with the validated values after a successful submit. */
19
- onSubmit: (values: FormValues<TField>, form: HTMLFormElement) => void | Promise<void>;
20
- /** Reset the form after a successful onSubmit. */
21
- resetOnSuccess?: boolean;
22
- }
23
- /**
24
- * Subscribes to a form's submit event: prevents the page reload, validates fields
25
- * against the schema (required/pattern) and calls onSubmit with the collected values.
26
- * Submitting via Enter works out of the box (default <form> behavior).
27
- * Returns an unsubscribe function.
28
- */
29
- export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): () => void;