@ilokesto/form 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.ko.md +39 -925
  2. package/README.md +38 -925
  3. package/package.json +35 -23
package/README.md CHANGED
@@ -1,62 +1,30 @@
1
1
  # @ilokesto/form
2
2
 
3
- **English** | [한국어](./README.ko.md)
3
+ A framework-independent TypeScript form core for values, field metadata, validation, and submission.
4
4
 
5
- `@ilokesto/form` is a framework-agnostic form state core. It keeps form values, field metadata, validation errors, submit attempts, and array item keys in one normalized store, while leaving rendering and event binding to framework adapters.
5
+ [![npm](https://img.shields.io/npm/v/@ilokesto/form?style=flat&color=555)](https://www.npmjs.com/package/@ilokesto/form)
6
+ [![MIT](https://img.shields.io/badge/license-MIT-555?style=flat)](./LICENSE)
6
7
 
7
- The package is designed around five ideas:
8
+ [한국어](./README.ko.md)
8
9
 
9
- 1. **Framework independence**: the core exposes a plain TypeScript class, `CreateForm`, and does not import React, Vue, Svelte, Solid, or DOM APIs.
10
- 2. **Tuple paths, not dot paths**: a string such as `"user.name"` is a literal field name; nested paths are expressed as tuples such as `["user", "name"]`.
11
- 3. **Normalized field state**: nested values are split into leaf `FieldState` records and reconstructed when `getValues()` is called.
12
- 4. **Standard Schema validation**: the core depends only on the Standard Schema v1 `~standard.validate` contract, not on a specific schema library.
13
- 5. **Array rebasing**: when array items move, swap, insert, or disappear, child field metadata such as `errors`, `touched`, `dirty`, and `modified` is moved with the item.
14
-
15
- ## Documentation
16
-
17
- - Full docs: [English](https://ilokesto.ayden94.com/en/form) · [한국어](https://ilokesto.ayden94.com/ko/form)
18
- - Source: [packages/form](https://github.com/ilokesto/ilokesto/tree/main/packages/form)
19
- - npm: [@ilokesto/form](https://www.npmjs.com/package/@ilokesto/form)
20
-
21
- ## Table of contents
22
-
23
- - [Installation](#installation)
24
- - [Quick start](#quick-start)
25
- - [React adapter](#react-adapter)
26
- - [Vue adapter](#vue-adapter)
27
- - [Solid adapter](#solid-adapter)
28
- - [Svelte adapter](#svelte-adapter)
29
- - [Core concepts](#core-concepts)
30
- - [API guide](#api-guide)
31
- - [Runtime flows](#runtime-flows)
32
- - [Internal architecture](#internal-architecture)
33
- - [Core walkthrough](#core-walkthrough)
34
- - [Design decisions](#design-decisions)
35
- - [Testing and development](#testing-and-development)
10
+ - Manage nested fields with explicit tuple paths and normalized field state.
11
+ - Validate with Standard Schema v1, including field-local schemas and async results.
12
+ - Preserve array item metadata and connect React, Vue, Solid, or Svelte adapters.
36
13
 
37
14
  ## Installation
38
15
 
39
- This package is published to npm under the `@ilokesto/form` name with public access. In a workspace, add it through your package manager or workspace protocol. When the package is published or linked, the import surface is:
40
-
41
- ```ts
42
- import { CreateForm } from '@ilokesto/form';
43
- ```
44
-
45
- Local development commands:
46
-
47
16
  ```sh
48
- pnpm install
49
- pnpm build
50
- pnpm typecheck
51
- pnpm test
17
+ pnpm add @ilokesto/form
52
18
  ```
53
19
 
54
- The package emits ESM JavaScript and TypeScript declarations to `dist/`.
55
-
56
- > **ESM-only.** This package ships `"type": "module"` with ESM-only `exports`. CommonJS `require()` is not supported. Use a modern bundler (Vite, webpack 5+, esbuild, tsup) or Node.js ESM (`import`). If you need CJS compatibility, use dynamic `import()` or configure your bundler to transpile `@ilokesto/form`.
20
+ The package ships ESM and TypeScript declarations; CommonJS `require()` is not
21
+ supported. Use ESM imports or dynamic `import()`. Install your chosen framework
22
+ when using its adapter subpath.
57
23
 
58
24
  ## Quick start
59
25
 
26
+ Create a form, update a nested field, and submit its current values:
27
+
60
28
  ```ts
61
29
  import { CreateForm } from '@ilokesto/form';
62
30
 
@@ -79,900 +47,45 @@ const form = new CreateForm<LoginValues>({
79
47
  form.setValue('email', 'ada@example.com', { source: 'user' });
80
48
  form.setValue(['profile', 'name'], 'Grace', { source: 'user' });
81
49
 
82
- console.log(form.getFieldState('email'));
83
- console.log(form.getValues());
84
- ```
85
-
86
- Important path rule:
87
-
88
- ```ts
89
- form.setValue(['profile', 'name'], 'Grace');
90
- form.setValue('profile.name', 'literal field');
91
- ```
92
-
93
- These are different fields. `['profile', 'name']` means the nested `profile.name` value. `'profile.name'` means a top-level field whose actual key contains a dot.
94
-
95
- ## React adapter
96
-
97
- React bindings are exposed through the `./react` subpath so the root package stays framework-agnostic.
98
-
99
- ```tsx
100
- import { CreateForm } from '@ilokesto/form';
101
- import { useForm } from '@ilokesto/form/react';
102
-
103
- const form = new CreateForm({
104
- defaultValues: {
105
- email: '',
106
- remember: false,
107
- },
108
- validateOn: ['blur', 'submit'],
109
- });
110
-
111
- function LoginForm() {
112
- const {
113
- useRegister,
114
- useField,
115
- useFormState,
116
- } = useForm(form);
117
-
118
- const email = useField({ name: 'email', schema: emailSchema });
119
- const remember = useRegister({ name: 'remember', type: 'checkbox' });
120
- const [role] = useRegister<HTMLSelectElement>([{ name: 'role' }]);
121
- const state = useFormState();
122
-
123
- return (
124
- <form>
125
- <input {...email.props} />
126
- {email.errors.map(error => <p key={error.message}>{error.message}</p>)}
127
-
128
- <label>
129
- <input type="checkbox" {...remember} />
130
- Remember me
131
- </label>
132
-
133
- <select {...role}>
134
- <option value="user">User</option>
135
- <option value="admin">Admin</option>
136
- </select>
137
-
138
- <button disabled={!state.isDirty || !state.isValid}>
139
- Submit
140
- </button>
141
- </form>
142
- );
143
- }
144
- ```
145
-
146
- For component-owned forms, the React adapter can also create the form from options directly:
147
-
148
- ```tsx
149
- const { form, useRegister, handleSubmit } = useForm({
150
- defaultValues: {
151
- email: '',
152
- remember: false,
153
- },
154
- });
155
- ```
156
-
157
- `defaultValues` and the other `CreateForm` options create the component-owned form once. `ReactFormOptions` also accepts the current render `values` and plain `resetOptions`. The first defined value and each later value with a different `Object.is` identity call `form.reset(values, resetOptions)`. `undefined` pauses synchronization without resetting; passing the last defined object again remains a no-op. Changing only `resetOptions` is also a no-op because it applies only when a new `values` reference drives a reset.
158
-
159
- ```tsx
160
- const { useRegister } = useForm({
161
- defaultValues: emptyUser,
162
- values: query.data,
163
- resetOptions: {
164
- keepDirtyValues: true,
165
- keepErrors: true,
166
- },
167
- });
168
- ```
169
-
170
- The values effect ends on component unmount. `useForm(existingForm)` keeps its existing overload behavior and does not install external-value synchronization.
171
-
172
- The React adapter has three first-version hooks. `useRegister` is overloaded for single, array, and rest-argument registration:
173
-
174
- | Hook | Purpose |
175
- | --- | --- |
176
- | `useRegister(options)` | Returns input binding props for one field: `name`, `type`, `value`, `checked`, `onChange`, `onBlur`, `onFocus`. Default input `type` is `text`. |
177
- | `useRegister<TElement>(options[])` | Returns multiple binding props in input order for map-friendly rendering. Use `HTMLSelectElement` or `HTMLTextAreaElement` as the generic when spreading into select/textarea. |
178
- | `useRegister(optionA, optionB)` | Rest-argument form for multiple bindings; internally handled like an options array. |
179
- | `useField(options)` | Returns `{ props, value, setValue, errors, dirty, touched }` for one field. It intentionally does not expose `field.register`. |
180
- | `useFormState()` | Returns whole-form aggregate state such as `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, and `submitCount`. |
181
-
182
- Field-local schemas can be passed to `useRegister` or `useField`. For that field, the field-local schema takes precedence over the form-level schema.
183
-
184
- ```tsx
185
- const email = useField({
186
- name: 'email',
187
- schema: emailSchema,
188
- });
189
- ```
190
-
191
- The event model is DOM-event centered. Custom components can use `useRegister` when they pass through DOM-compatible `value`, `checked`, `onChange`, `onBlur`, and `onFocus` props.
192
-
193
-
194
- ## Vue adapter
50
+ console.log(form.getFieldState('email').dirty); // true
51
+ console.log(form.getValues().profile.name); // Grace
195
52
 
196
- Vue bindings are exposed through the `./vue` subpath. They use the same `useForm(form)` shape as the React adapter, but return Vue-friendly `v-bind` props with `onInput`, `onChange`, `onBlur`, and `onFocus` handlers.
197
-
198
- `useForm` also accepts `VueFormOptions`. Its `values` source is `MaybeRefOrGetter<TValues | undefined>` and `resetOptions` stays plain. The first defined value and each later value with a different `Object.is` identity call `form.reset(values, resetOptions)`. `undefined` pauses synchronization without resetting, and re-emitting the last defined object remains a no-op. Pass `ref`, `computed`, or a getter to track changes; a plain value is evaluated once. Reactive values require an active Vue effect scope; the adapter fails before creating a form when none exists. The watcher stops with that scope, and `useForm(existingForm)` does not install it.
199
-
200
- ```vue
201
- <script setup lang="ts">
202
- import { ref } from 'vue';
203
- import { useForm } from '@ilokesto/form/vue';
204
-
205
- const serverValues = ref({ email: 'initial@example.com' });
206
- const { form, useRegister } = useForm({
207
- defaultValues: { email: '' },
208
- values: serverValues,
209
- });
210
- </script>
211
- ```
212
-
213
- ```vue
214
- <script setup lang="ts">
215
- import { CreateForm } from '@ilokesto/form';
216
- import { useForm } from '@ilokesto/form/vue';
217
-
218
- const form = new CreateForm({
219
- defaultValues: {
220
- email: '',
221
- remember: false,
222
- role: 'user',
223
- },
224
- validateOn: ['blur', 'submit'],
53
+ await form.submit(values => {
54
+ console.log(values.email);
225
55
  });
226
-
227
- const {
228
- useRegister,
229
- useField,
230
- useFormState,
231
- } = useForm(form);
232
-
233
- const email = useField({ name: 'email', schema: emailSchema });
234
- const remember = useRegister({ name: 'remember', type: 'checkbox' });
235
- const [role] = useRegister<HTMLSelectElement>([{ name: 'role' }]);
236
- const state = useFormState();
237
- </script>
238
-
239
- <template>
240
- <form>
241
- <input v-bind="email.props" />
242
- <p v-for="error in email.errors" :key="error.message">
243
- {{ error.message }}
244
- </p>
245
-
246
- <label>
247
- <input type="checkbox" v-bind="remember" />
248
- Remember me
249
- </label>
250
-
251
- <select v-bind="role">
252
- <option value="user">User</option>
253
- <option value="admin">Admin</option>
254
- </select>
255
-
256
- <button :disabled="!state.isDirty || !state.isValid">
257
- Submit
258
- </button>
259
- </form>
260
- </template>
261
56
  ```
262
57
 
263
- The Vue adapter exposes the same three concepts:
264
-
265
- | Composable | Purpose |
266
- | --- | --- |
267
- | `useRegister(options)` | Returns one input-oriented `v-bind` binding object. It includes `type` and defaults to `text`; text inputs update on `input`; checkbox/radio update on `change`. Use a generic for select/textarea binding types. |
268
- | `useRegister(options[])` / `useRegister(optionA, optionB)` | Returns multiple binding objects for map-friendly rendering. |
269
- | `useField(options)` | Returns `{ props, value, setValue, errors, dirty, touched }` with getter-backed reactive reads. |
270
- | `useFormState()` | Returns form-wide aggregate getters such as `errors`, `dirtyFields`, `touchedFields`, `focusedField`, `isDirty`, `isValid`, and `submitCount`. |
271
-
272
- Field-local schemas work the same way as React and are cleaned up with the current Vue effect scope.
273
-
274
- ## Solid adapter
275
-
276
- Solid bindings are exposed through the `./solid` subpath. They keep the same `useForm(form)` shape as React and Vue, but use Solid owner cleanup and getter-backed props.
277
-
278
- ```tsx
279
- import { CreateForm } from '@ilokesto/form';
280
- import { useForm } from '@ilokesto/form/solid';
281
-
282
- const form = new CreateForm({
283
- defaultValues: {
284
- email: '',
285
- remember: false,
286
- role: 'user',
287
- },
288
- validateOn: ['blur', 'submit'],
289
- });
290
-
291
- function LoginForm() {
292
- const { useRegister, useField, useFormState } = useForm(form);
293
- const email = useField({ name: 'email', schema: emailSchema });
294
- const remember = useRegister({ name: 'remember', type: 'checkbox' });
295
- const role = useRegister<HTMLSelectElement>({ name: 'role' });
296
- const state = useFormState();
297
-
298
- return (
299
- <form>
300
- <input {...email.props} />
301
- {email.errors.map(error => <p>{error.message}</p>)}
302
-
303
- <input type="checkbox" {...remember} />
304
-
305
- <select {...role}>
306
- <option value="user">User</option>
307
- <option value="admin">Admin</option>
308
- </select>
309
-
310
- <button disabled={!state.isDirty || !state.isValid}>Submit</button>
311
- </form>
312
- );
313
- }
314
- ```
58
+ Strings are literal field names: `'profile.name'` and `['profile', 'name']`
59
+ refer to different fields. Treat `getState()` snapshots as read-only.
60
+ `dirty` compares against defaults; `modified` records user-sourced writes.
315
61
 
316
- The Solid adapter exposes `useRegister`, `useField`, and `useFormState` with the same semantics as Vue: text inputs update on `input`, checkbox/radio/multiple select update on `change`, and field-local schemas are disposed with the current Solid owner.
317
-
318
- For component-owned forms, `SolidFormOptions` accepts `values` as `Accessor<TValues | undefined>` and plain `resetOptions`:
319
-
320
- ```tsx
321
- const [serverValues, setServerValues] = createSignal<User | undefined>();
322
- const { form } = useForm({
323
- defaultValues: emptyUser,
324
- values: serverValues,
325
- resetOptions: { keepDirtyValues: true },
326
- });
327
- ```
328
-
329
- The first defined accessor value and each later value with a different `Object.is` identity reset the form. `undefined` pauses without resetting, re-emitting the last defined object is a no-op, and `resetOptions` applies only to value-driven resets. Reactive values require an active Solid owner; the adapter fails before creating a form when none exists. Tracking is disposed with that owner. `useForm(existingForm)` does not install it.
330
-
331
- ## Svelte adapter
332
-
333
- Svelte bindings are exposed through the `./svelte` subpath. The adapter exposes register actions plus readable stores for both form-wide and field-local state.
334
-
335
- ```svelte
336
- <script lang="ts">
337
- import { CreateForm } from '@ilokesto/form';
338
- import { useForm } from '@ilokesto/form/svelte';
339
-
340
- const form = new CreateForm({
341
- defaultValues: {
342
- email: '',
343
- remember: false,
344
- role: 'user',
345
- },
346
- validateOn: ['blur', 'submit'],
347
- });
348
-
349
- const { register, useField, useFormState } = useForm(form);
350
- const email = useField({ name: 'email', schema: emailSchema });
351
- const emailProps = email.props;
352
- const state = useFormState();
353
- </script>
354
-
355
- <form>
356
- <input use:emailProps />
357
- {#each $email.errors as error}
358
- <p>{error.message}</p>
359
- {/each}
360
- <input type="checkbox" use:register={{ name: 'remember', type: 'checkbox' }} />
361
-
362
- <select use:register={{ name: 'role' }}>
363
- <option value="user">User</option>
364
- <option value="admin">Admin</option>
365
- </select>
366
-
367
- <button disabled={!$state.isDirty || !$state.isValid}>Submit</button>
368
- </form>
369
- ```
370
-
371
- The Svelte action owns DOM synchronization directly. `useField` is a `Readable<SvelteFieldSnapshot>` consumed as `$email`; it emits current `value`, `errors`, `dirty`, and `touched` state and releases its core subscription when the last subscriber leaves.
372
-
373
- For component-owned forms, `SvelteFormOptions` accepts `values` as `Readable<TValues | undefined>` and plain `resetOptions`:
374
-
375
- ```svelte
376
- <script lang="ts">
377
- import { writable } from 'svelte/store';
378
- import { useForm } from '@ilokesto/form/svelte';
379
-
380
- const serverValues = writable<User | undefined>(undefined);
381
- const { form } = useForm({
382
- defaultValues: emptyUser,
383
- values: serverValues,
384
- resetOptions: { keepDirtyValues: true },
385
- });
386
- </script>
387
- ```
388
-
389
- The first defined emission and each later emission with a different `Object.is` identity reset the form. `undefined` pauses without resetting, re-emitting the last defined object is a no-op, and `resetOptions` applies only to value-driven resets. Call this overload during component initialization; its subscription ends on unmount. `useForm(existingForm)` does not subscribe.
390
-
391
- ## Core concepts
392
-
393
- ### `FieldPathSegment`
394
-
395
- A single path segment is either a string object key or a numeric array index.
396
-
397
- ```ts
398
- type FieldPathSegment = string | number;
399
- ```
400
-
401
- Examples:
402
-
403
- ```ts
404
- 'user'
405
- 'name'
406
- 0
407
- 1
408
- ```
409
-
410
- ### `FieldPath`
411
-
412
- A `FieldPath` is the internal tuple representation of a form field path.
413
-
414
- ```ts
415
- type FieldPath = readonly FieldPathSegment[];
416
- ```
417
-
418
- Examples:
419
-
420
- ```ts
421
- ['email']
422
- ['user', 'name']
423
- ['items', 0, 'title']
424
- [] // root value
425
- ```
426
-
427
- The root path is useful for primitive root values or root-level schema errors.
428
-
429
- ### `FieldPathInput`
430
-
431
- Public APIs accept either a string field name or a tuple path.
432
-
433
- ```ts
434
- type FieldPathInput = string | FieldPath;
435
- ```
436
-
437
- A string is not parsed as a dot path. This prevents collisions between a nested path and an actual object key containing `.`.
438
-
439
- ### `PathKey`
440
-
441
- `FormState.fields` and `FormState.arrayKeys` need string keys. `FormPath` converts tuple paths to stable string keys.
442
-
443
- | FieldPath | PathKey |
444
- | --- | --- |
445
- | `[]` | `$` |
446
- | `['email']` | `["email"]` |
447
- | `['user', 'name']` | `["user","name"]` |
448
- | `['items', 0, 'title']` | `["items",0,"title"]` |
449
-
450
- The implementation uses JSON array strings instead of separator-based strings, so literal field names such as `"user.name"` are safe.
451
-
452
- ### `FieldState`
453
-
454
- A `FieldState` stores the value and metadata for one leaf field.
455
-
456
- ```ts
457
- type FieldState<TValue = unknown> = {
458
- value: TValue;
459
- errors: FormError[];
460
- touched: boolean;
461
- dirty: boolean;
462
- modified: boolean;
463
- isFocused: boolean;
464
- };
465
- ```
466
-
467
- The flags mean:
468
-
469
- - `touched`: the field was blurred at least once.
470
- - `dirty`: the current value is not `Object.is`-equal to the initial value at the same path.
471
- - `modified`: the field was changed by a user-sourced write, `source: 'user'`.
472
- - `isFocused`: the field currently has focus. Set to `true` by `focus()` and cleared by `blur()` (always, regardless of `validateOn`).
473
- - `errors`: validation or manually assigned field errors.
474
-
475
- ### `FormState`
476
-
477
- The internal snapshot is normalized.
478
-
479
- ```ts
480
- type FormState<TValues> = {
481
- defaultValues: TValues;
482
- fields: Record<PathKey, FieldState>;
483
- submitCount: number;
484
- arrayKeys: Record<PathKey, string[]>;
485
- };
486
- ```
487
-
488
- For this input:
489
-
490
- ```ts
491
- const form = new CreateForm({
492
- defaultValues: {
493
- user: { name: 'Ada' },
494
- items: [{ title: 'A' }, { title: 'B' }],
495
- },
496
- });
497
- ```
498
-
499
- The core stores leaf field states and array container keys separately:
500
-
501
- ```ts
502
- {
503
- defaultValues: {
504
- user: { name: 'Ada' },
505
- items: [{ title: 'A' }, { title: 'B' }],
506
- },
507
- fields: {
508
- '["user","name"]': { value: 'Ada', errors: [], touched: false, dirty: false, modified: false, isFocused: false },
509
- '["items",0,"title"]': { value: 'A', errors: [], touched: false, dirty: false, modified: false, isFocused: false },
510
- '["items",1,"title"]': { value: 'B', errors: [], touched: false, dirty: false, modified: false, isFocused: false },
511
- },
512
- submitCount: 0,
513
- arrayKeys: {
514
- '["items"]': ['initial-0', 'initial-1'],
515
- },
516
- }
517
- ```
518
-
519
- `getValues()` reconstructs the nested object from `fields` and `arrayKeys`.
520
-
521
- ### `FormError`
522
-
523
- ```ts
524
- type FormError = {
525
- type?: string;
526
- message: string;
527
- };
528
- ```
529
-
530
- Schema errors use `type: 'standard_schema'`. You can also set errors manually with `setErrors()`.
531
-
532
- ### `ValidationTrigger`
533
-
534
- ```ts
535
- type ValidationTrigger = 'change' | 'blur' | 'submit' | 'manual';
536
- ```
62
+ This example has no schema. Add a Standard Schema-compatible `schema` for
63
+ validation; automatic validation defaults to submit. `setValue()` returns `void`
64
+ and does not await change validation. Use `trigger()` for awaited validation.
65
+ Array `move()` and `swap()` retain item metadata; `replace()` intentionally drops it.
537
66
 
538
- `validateOn` controls automatic validation. If omitted, the default is `['submit']`. Manual validation is always available through `trigger()`.
67
+ Adapters live at `/react`, `/vue`, `/solid`, and `/svelte`, keeping the root free
68
+ of framework and DOM imports. Dispose adapter subscriptions when their owner unmounts.
539
69
 
540
- ### `StandardSchemaV1`
70
+ <details>
71
+ <summary>Development</summary>
541
72
 
542
- The core accepts a Standard Schema compatible object:
543
-
544
- ```ts
545
- const schema = {
546
- '~standard': {
547
- version: 1,
548
- vendor: 'example',
549
- validate(value) {
550
- return { value };
551
- },
552
- },
553
- };
554
- ```
555
-
556
- On failure, `validate()` returns `issues`. Each issue path is converted into a `FieldPath`, then into a `PathKey`, then written to the corresponding `FieldState.errors`.
557
-
558
- ### Field-local schemas
559
-
560
- Framework adapters can register a schema for a single field.
561
-
562
- ```ts
563
- const cleanup = form.registerFieldSchema('email', {
564
- schema: emailSchema,
565
- });
566
- ```
567
-
568
- When a field-local schema exists, that field uses it instead of the form-level schema:
569
-
570
- ```txt
571
- field-local schema > form-level schema
572
- ```
573
-
574
- The cleanup function removes the schema registration if it is still the latest registration for that field.
575
-
576
- ### `ArrayKeys`
577
-
578
- Array item identity is stored separately from array values.
579
-
580
- - Items from `defaultValues` get deterministic keys: `initial-0`, `initial-1`, ...
581
- - Runtime insertions get generated keys: `item-1`, `item-2`, ...
582
- - `move()` and `swap()` move keys with values.
583
- - `replace()` creates a new key for every new item and does not preserve old child metadata.
584
-
585
- These keys are intended for framework list rendering.
586
-
587
- ## API guide
588
-
589
- ### `new CreateForm(options)`
590
-
591
- ```ts
592
- const form = new CreateForm({
593
- defaultValues,
594
- schema,
595
- schemaOptions,
596
- validateOn,
597
- });
598
- ```
599
-
600
- Options:
601
-
602
- - `defaultValues`: required default value tree. This is also the reset/dirty baseline.
603
- - `schema`: optional Standard Schema v1 compatible schema.
604
- - `schemaOptions`: optional Standard Schema validation options.
605
- - `validateOn`: optional automatic validation triggers. Defaults to `['submit']`.
606
-
607
- ### `getState()`
608
-
609
- Returns the current `FormState` snapshot.
610
-
611
- ```ts
612
- const state = form.getState();
613
- console.log(state.submitCount);
614
- ```
615
-
616
- Treat the returned object as read-only.
617
-
618
- ### `subscribe(listener)`
619
-
620
- Subscribes to store changes and returns an unsubscribe function.
621
-
622
- ```ts
623
- const unsubscribe = form.subscribe(() => {
624
- console.log(form.getValues());
625
- });
626
-
627
- unsubscribe();
628
- ```
629
-
630
- Framework adapters use this method to connect the core store to reactive rendering.
631
-
632
- ### `registerFieldSchema(path, options)`
633
-
634
- Registers a field-local schema and returns a cleanup function.
635
-
636
- ```ts
637
- const cleanup = form.registerFieldSchema('email', {
638
- schema: emailSchema,
639
- });
640
-
641
- cleanup();
642
- ```
643
-
644
- This is mostly intended for framework adapters. A field-local schema overrides the form-level schema for that field during `blur()`, `trigger()`, and `submit()`.
645
-
646
- ### `getFieldState(path)`
647
-
648
- Returns the `FieldState` for a path. If the field does not exist yet, the method returns a default field state instead of `undefined`.
649
-
650
- ```ts
651
- const email = form.getFieldState('email');
652
- ```
653
-
654
- ### `getValue(path)`
655
-
656
- Returns only the current field value.
657
-
658
- ```ts
659
- const email = form.getValue('email');
660
- ```
661
-
662
- ### `getValues()`
663
-
664
- Reconstructs and returns the full nested values object.
665
-
666
- ```ts
667
- const values = form.getValues();
668
- ```
669
-
670
- ### `setValue(path, value, options?)`
671
-
672
- Writes one field value.
673
-
674
- ```ts
675
- form.setValue(['user', 'name'], 'Grace', {
676
- source: 'user',
677
- validate: true,
678
- });
679
- ```
680
-
681
- Effects:
682
-
683
- 1. Converts the public path input to an internal tuple path.
684
- 2. Writes the new value to the corresponding `FieldState`.
685
- 3. Recomputes `dirty` by comparing with `defaultValues` at the same path.
686
- 4. Sets `modified` to `true` only when `source === 'user'`.
687
- 5. Starts change validation if `options.validate` is true or `validateOn` contains `'change'`.
688
-
689
- `setValue()` returns `void`; change validation is started asynchronously and is not awaited by the method.
690
-
691
- Async validation is target-aware. New validation supersedes only overlapping fields, while independent field validations may complete concurrently. Full-form submit validation also verifies the value snapshot it validated; stale submit attempts retry until they obtain an authoritative result and never call `onValid` by default.
692
-
693
- ### `blur(path)`
694
-
695
- Marks the field as touched and optionally validates it.
696
-
697
- ```ts
698
- const valid = await form.blur('email');
699
- ```
700
-
701
- If `validateOn` does not contain `'blur'`, it returns `true` after touching the field.
702
-
703
- ### `focus(path)`
704
-
705
- Sets `isFocused: true` on the field at `path`. Other fields are not touched — DOM naturally fires a `blur` event on the previously focused element, which clears `isFocused` via `blur()`. Array rebasing preserves `isFocused` across `move`/`swap`/`insert`/`remove`.
706
-
707
- The core is DOM-independent, so calling `focus()` on multiple fields can leave more than one field with `isFocused: true`. In DOM adapters this is naturally bounded to one by the browser; in direct core usage it is the caller's responsibility to `blur()` the previous field. The `useFormState().focusedField` aggregate returns the **first** focused field found in `Object.entries` order, not the most recently focused one — to enumerate all focused fields, iterate `state.fields` directly.
708
-
709
- ### `setErrors(path, errors)`
710
-
711
- Replaces the error list for one field.
712
-
713
- ```ts
714
- form.setErrors('email', [{ message: 'Email is required' }]);
715
- ```
716
-
717
- ### `clearErrors(...paths)`
718
-
719
- Clears errors for specific fields, or all existing fields when no path is passed.
720
-
721
- ```ts
722
- form.clearErrors('email');
723
- form.clearErrors();
724
- ```
725
-
726
- ### `trigger(...paths)`
727
-
728
- Runs manual validation.
729
-
730
- ```ts
731
- await form.trigger('email');
732
- await form.trigger();
733
- ```
734
-
735
- With paths, only those fields' errors are updated from the full schema result. Without paths, all registered fields and all schema error keys are updated.
736
-
737
- ### `array(path)`
738
-
739
- Returns a `FormArray` controller for an array field.
740
-
741
- ```ts
742
- const items = form.array('items');
743
-
744
- items.push({ title: 'C' });
745
- items.move(2, 0);
746
- console.log(items.keys());
747
- ```
748
-
749
- The array controller reads the latest values and keys from the store each time a command runs.
750
-
751
- ### `reset(values?, options?)`
752
-
753
- Resets the form to initial state.
754
-
755
- ```ts
756
- form.reset();
757
- form.reset({ email: 'new@example.com' });
758
- form.reset({ email: 'new@example.com' }, { keepDirtyValues: true });
759
- ```
760
-
761
- Without an argument, it reuses the current `defaultValues`. With an argument, the argument becomes the new `defaultValues`.
762
-
763
- Reset options can preserve selected state for fields that still exist in the new normalized value shape:
764
-
765
- | Option | Behavior |
766
- | --- | --- |
767
- | `keepDirtyValues` | Keeps current values for dirty fields and recomputes dirty against the new `defaultValues`. |
768
- | `keepErrors` | Keeps existing errors for surviving field paths. |
769
- | `keepTouched` | Keeps touched flags for surviving field paths. |
770
- | `keepSubmitState` | Keeps `submitCount`, `isSubmitting`, `isSubmitted`, and `isSubmitSuccessful`. |
771
-
772
- ### `submit(onValid, onInvalid?)`
773
-
774
- Increments `submitCount`, validates the form, and calls the matching callback.
775
-
776
- ```ts
777
- const result = await form.submit(
778
- values => values,
779
- fields => {
780
- console.log(fields);
781
- },
782
- );
783
- ```
784
-
785
- If validation fails, `onInvalid` receives the current `fields` object and `submit()` returns `undefined`. If validation succeeds, `onValid` receives reconstructed values.
786
-
787
- ### `FormArray.keys()`
788
-
789
- Returns stable keys for rendering the current array items.
790
-
791
- ```ts
792
- const keys = form.array('items').keys();
793
- ```
794
-
795
- ### `FormArray.insert(index, value)`
796
-
797
- Inserts an item. Out-of-range indexes are bounded to `0...length`.
798
-
799
- ### `FormArray.push(value)`
800
-
801
- Appends an item.
802
-
803
- ### `FormArray.remove(index)`
804
-
805
- Removes an item. Invalid indexes are ignored.
806
-
807
- ### `FormArray.move(fromIndex, toIndex)`
808
-
809
- Moves one item. Invalid indexes or a no-op move are ignored.
810
-
811
- ### `FormArray.swap(leftIndex, rightIndex)`
812
-
813
- Swaps two items. Invalid indexes or identical indexes are ignored.
814
-
815
- ### `FormArray.replace(values)`
816
-
817
- Replaces the whole array. Existing item links are intentionally broken, so child field metadata is not preserved.
818
-
819
- ## Runtime flows
820
-
821
- ### Field commands
822
-
823
- Start with `src/core/form/CreateForm.ts`. It shows the complete orchestration:
824
-
825
- ```txt
826
- setValue -> normalize path -> store.setValue -> optional change validation
827
- blur -> normalize path -> unfocus -> touch -> optional blur validation
828
- trigger -> normalize paths -> selected-field or full validation
829
- array -> create controller with the form's shared key generator
830
- submit -> submit queue -> validation -> callback -> completion
831
- ```
832
-
833
- Writes notify synchronously. Blur retains separate unfocus and touch notifications.
834
- `dirty` compares against the default value with `Object.is`; `modified` records
835
- user-originated writes. These flags have different meanings.
836
-
837
- ### Validation and submission
838
-
839
- Selected-field validation runs local schemas first, then the form schema for
840
- remaining targets. Full validation runs the form schema first, then registered
841
- local schemas. A local result, including an empty error list, takes precedence.
842
- Without a local schema, selected-field validation executes the whole form schema
843
- but writes only the selected errors.
844
-
845
- Every asynchronous phase checks both its validation revision and captured values
846
- before writing errors. Independent field validations may finish in either order;
847
- overlapping work must not overwrite newer results. Errors are applied through the
848
- existing per-field write boundaries, not a new batch update.
849
-
850
- `FormSubmitter` queues concurrent submissions. It increments the attempt count
851
- immediately, retries stale validation, calls `onInvalid` for invalid results or
852
- `onValid` with current values, and completes submit state when the queue drains.
853
-
854
- ### Array mutations
855
-
856
- ```txt
857
- controller reads values and keys
858
- -> static planner computes { values, keys, mapPreviousIndex }
859
- -> store.replaceState(previousState => rebase(previousState, path, mutation))
860
- -> one next snapshot
861
- ```
862
-
863
- Rebasing reconstructs values from the supplied snapshot, initializes the next
864
- state, and moves surviving child metadata and nested array keys to their new
865
- paths. Errors, touched, dirty, modified and focus follow the item. Unrelated
866
- fields and submit state are preserved. Replace intentionally drops old child
867
- metadata and creates fresh keys. The existing defaultValues behavior is retained.
868
-
869
- ## Internal architecture
870
-
871
- ```txt
872
- CreateForm public command order and shared array keys
873
- FormStateStore state ownership and writes
874
- FormStateInitializer nested defaults -> normalized snapshot
875
- FormStateReader snapshot -> fields and nested values
876
- ValidationEngine schema registration and validation phases
877
- StandardSchemaValidator schema results -> field errors
878
- ValidationSequencer overlapping validation revisions
879
- ValidationSnapshot captured values and array-key comparison
880
- FormSubmitter submit queue and callback lifecycle
881
- FormArrayController array reads and state application
882
- FormArrayMutationPlanner pure array mutation calculation
883
- FormArrayRebaser previous snapshot + mutation -> next snapshot
884
- ```
885
-
886
- React, Vue, Solid and Svelte adapters depend on the public `Form` contract.
887
- `adapters/` shares DOM value/binding and aggregate-state logic; subscriptions and
888
- component lifecycle ownership remain in each framework directory.
889
-
890
- ## Core walkthrough
891
-
892
- Read in this order rather than following every import:
893
-
894
- | Question | File under `src/core/` | Responsibility |
895
- | --- | --- | --- |
896
- | What happens after a public command? | `form/CreateForm.ts` | Normalize paths, write state, request validation. |
897
- | Where does state change? | `state/FormStateStore.ts` | Own the store and apply writes with immer, including reset and submit flags. |
898
- | How are values reconstructed? | `state/FormStateReader.ts` | Static calculations over an explicit snapshot; no store or getter ownership. |
899
- | How is initial state built? | `state/FormStateInitializer.ts` | Traverse arrays/plain objects; keep empty objects, non-plain objects and primitive values as leaves. |
900
- | What is an absent field? | `state/FieldStateFactory.ts` | Fresh metadata with undefined value, empty errors and false flags, including isFocused. |
901
- | How do paths work? | `path/FormPath.ts` | Literal strings become one segment; tuple paths encode as JSON keys, with root key `$`. |
902
- | How are nested values changed? | `value/ValueHelper.ts` | Immutable nested get/set and reconstruction from fields and array containers. |
903
- | When may validation apply? | `validation/ValidationEngine.ts` | Local-schema precedence, selected/full execution and stale-result checks. |
904
- | Which validation supersedes which? | `validation/ValidationSequencer.ts` | Full and per-field revisions, including schema registration invalidation. |
905
- | Did values change during validation? | `validation/ValidationSnapshot.ts` | Capture and compare field values and array-key identities. |
906
- | How are schema issues converted? | `validation/StandardSchemaValidator.ts` | Normalize Standard Schema issues; missing/unsupported paths become root errors. |
907
- | How are submissions serialized? | `form/FormSubmitter.ts` | Queue submissions, retry stale validation and settle lifecycle state. |
908
- | What is the next array order? | `array/FormArrayMutationPlanner.ts` | Static insert/push/remove/move/swap/replace calculations; no instance or store. |
909
- | How does metadata follow items? | `array/FormArrayRebaser.ts` | Pure snapshot transformation with no store access or notifications. |
910
- | Who applies an array mutation? | `array/FormArrayController.ts` | Read current array state and pass the updater snapshot to the rebaser. |
911
- | Where do array keys come from? | `array/ArrayKeyGenerator.ts` | One generator per CreateForm, shared across newly created controllers. |
912
- | How are indexes and paths mapped? | `array/ArrayItemReorder.ts`, `array/FormArrayPath.ts` | Pure ordering/index mapping and child-path replacement. |
913
-
914
- `src/index.ts` and the framework entry points define the published surface.
915
- `core/types.ts` describes the existing path, state, schema and command contracts.
916
- Internal modules are implementation details, not additional package exports.
917
-
918
- ## Design decisions
919
-
920
- ### Strings are literal paths
921
-
922
- Dot-path parsing is convenient but ambiguous. This core chooses unambiguous tuple paths instead.
923
-
924
- ```ts
925
- 'user.name' // one field named "user.name"
926
- ['user', 'name'] // nested user.name field
927
- ```
928
-
929
- ### State is normalized
930
-
931
- Normalized fields make it easy to update individual metadata without mutating the whole nested value object. `ValueHelper` reconstructs the public value shape when needed.
932
-
933
- ### Validation is schema-library independent
934
-
935
- The core only knows Standard Schema. This keeps validation compatible with multiple libraries and avoids importing a specific validator.
936
-
937
- ### Array mutation is split into planning and rebasing
938
-
939
- `FormArrayMutationPlanner` decides what the next array looks like. `FormArrayRebaser` decides how the whole form state should follow. This separation keeps mutation math pure and store updates centralized.
940
-
941
- ### `dirty` and `modified` are different
942
-
943
- `dirty` compares current value with the initial value. `modified` tracks user-originated writes. A programmatic update can be dirty without being modified by the user.
944
-
945
- ## Testing and development
946
-
947
- ### Commands
73
+ Use Node 24.22.1 and pnpm 10.17.1. Run these commands from this repository root:
948
74
 
949
75
  ```sh
950
- pnpm build
76
+ pnpm install --frozen-lockfile
951
77
  pnpm typecheck
952
78
  pnpm test
953
79
  ```
954
80
 
955
- `pnpm build` uses tsup to bundle ESM JavaScript and declaration files for the core and four framework entry points. `pnpm test:pack` checks the packed package's runtime imports and TypeScript contracts in a separate consumer.
956
-
957
- `pnpm test` runs the Vitest suite.
958
-
959
- ### Current test coverage themes
960
-
961
- The existing tests cover:
962
-
963
- 1. Tuple paths versus literal string names.
964
- 2. Standard Schema validation on blur, manual trigger, and submit.
965
- 3. Array value/key/metadata rebasing when moving and removing items.
966
- 4. React adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema precedence.
967
- 5. Vue adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema cleanup.
968
- 6. Solid adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema cleanup.
969
- 7. Svelte register action bindings for text input, checkbox, radio, select, multiple select, readable `useFormState`, and field-local schema cleanup.
81
+ `typecheck` checks library code. `test` builds once and runs `test:unit` and `test:tooling`, `test:pack`, and all five example build/type checks. Runtime tests live in `tests/unit`, fixtures/setup in `tests/fixtures`, and Node tooling tests in `tests/tooling`. Run `pnpm build` before standalone `pnpm test:pack`.
970
82
 
971
- ### Suggested future documentation/tests
83
+ Build output goes to `dist/`. `test:pack` checks an isolated consumer using registry
84
+ Store; the example commands check all five private examples.
972
85
 
973
- Good additions would be:
86
+ Pull requests run Verify CI. Main merges create or update a Changesets release PR; merging
87
+ that PR publishes only the exact successful Verify artifact through GitHub Actions. Enable
88
+ `Allow GitHub Actions to create and approve pull requests` and configure `NPM_TOKEN` in the
89
+ `Production` environment before rollout. Never publish locally.
974
90
 
975
- - A test for `insert()` index bounding.
976
- - A test for `replace()` intentionally dropping child metadata.
977
- - A test for root-level schema errors.
978
- - More adapter examples for custom DOM-event-compatible components.
91
+ </details>