@ilokesto/form 1.0.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.ko.md +1276 -0
- package/README.md +1277 -0
- package/dist/FormStateSummary-YyGT9nfY.js +124 -0
- package/dist/adapters/FormStateSummary.d.ts +12 -0
- package/dist/adapters/dom/FieldValue.d.ts +2 -0
- package/dist/adapters/dom/RegisterBinding.d.ts +14 -0
- package/dist/adapters/dom/index.d.ts +3 -0
- package/dist/adapters/dom/types.d.ts +22 -0
- package/dist/core/array/ArrayItemReorder.d.ts +6 -0
- package/dist/core/array/ArrayKeyGenerator.d.ts +4 -0
- package/dist/core/array/FormArrayController.d.ts +21 -0
- package/dist/core/array/FormArrayFactory.d.ts +8 -0
- package/dist/core/array/FormArrayMutationPlanner.d.ts +14 -0
- package/dist/core/array/FormArrayPath.d.ts +6 -0
- package/dist/core/array/FormArrayRebaser.d.ts +7 -0
- package/dist/core/array/index.d.ts +1 -0
- package/dist/core/form/CreateForm.d.ts +23 -0
- package/dist/core/form/FormFieldCommands.d.ts +15 -0
- package/dist/core/form/FormSubmitter.d.ts +9 -0
- package/dist/core/form/index.d.ts +1 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/path/FormPath.d.ts +9 -0
- package/dist/core/path/index.d.ts +1 -0
- package/dist/core/state/FieldStateFactory.d.ts +6 -0
- package/dist/core/state/FormStateInitializer.d.ts +7 -0
- package/dist/core/state/FormStateReader.d.ts +11 -0
- package/dist/core/state/FormStateStore.d.ts +23 -0
- package/dist/core/state/FormStateWriter.d.ts +16 -0
- package/dist/core/state/index.d.ts +1 -0
- package/dist/core/types.d.ts +96 -0
- package/dist/core/validation/StandardSchemaValidator.d.ts +14 -0
- package/dist/core/validation/ValidationEngine.d.ts +25 -0
- package/dist/core/validation/index.d.ts +1 -0
- package/dist/core/value/ValueHelper.d.ts +7 -0
- package/dist/core/value/index.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1245 -0
- package/dist/react/RegisterBinding.d.ts +5 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +83 -0
- package/dist/react/types.d.ts +64 -0
- package/dist/react/useField.d.ts +3 -0
- package/dist/react/useFieldSchemaRegistration.d.ts +4 -0
- package/dist/react/useForm.d.ts +3 -0
- package/dist/react/useFormSnapshot.d.ts +2 -0
- package/dist/react/useFormState.d.ts +3 -0
- package/dist/react/useRegister.d.ts +6 -0
- package/dist/solid/RegisterBinding.d.ts +5 -0
- package/dist/solid/index.d.ts +2 -0
- package/dist/solid/index.js +110 -0
- package/dist/solid/types.d.ts +68 -0
- package/dist/solid/useField.d.ts +3 -0
- package/dist/solid/useFieldSchemaRegistration.d.ts +3 -0
- package/dist/solid/useForm.d.ts +3 -0
- package/dist/solid/useFormSnapshot.d.ts +3 -0
- package/dist/solid/useFormState.d.ts +3 -0
- package/dist/solid/useRegister.d.ts +6 -0
- package/dist/svelte/RegisterAction.d.ts +4 -0
- package/dist/svelte/index.d.ts +2 -0
- package/dist/svelte/index.js +107 -0
- package/dist/svelte/types.d.ts +12 -0
- package/dist/svelte/useForm.d.ts +3 -0
- package/dist/svelte/useFormState.d.ts +4 -0
- package/dist/vue/RegisterBinding.d.ts +5 -0
- package/dist/vue/index.d.ts +2 -0
- package/dist/vue/index.js +110 -0
- package/dist/vue/types.d.ts +68 -0
- package/dist/vue/useField.d.ts +3 -0
- package/dist/vue/useFieldSchemaRegistration.d.ts +3 -0
- package/dist/vue/useForm.d.ts +3 -0
- package/dist/vue/useFormSnapshot.d.ts +3 -0
- package/dist/vue/useFormState.d.ts +3 -0
- package/dist/vue/useRegister.d.ts +6 -0
- package/package.json +93 -0
package/README.md
ADDED
|
@@ -0,0 +1,1277 @@
|
|
|
1
|
+
# @ilokesto/form
|
|
2
|
+
|
|
3
|
+
English | [한국어](./README.ko.md)
|
|
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.
|
|
6
|
+
|
|
7
|
+
The package is designed around five ideas:
|
|
8
|
+
|
|
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
|
+
## Table of contents
|
|
16
|
+
|
|
17
|
+
- [Installation](#installation)
|
|
18
|
+
- [Quick start](#quick-start)
|
|
19
|
+
- [React adapter](#react-adapter)
|
|
20
|
+
- [Vue adapter](#vue-adapter)
|
|
21
|
+
- [Solid adapter](#solid-adapter)
|
|
22
|
+
- [Svelte adapter](#svelte-adapter)
|
|
23
|
+
- [Core concepts](#core-concepts)
|
|
24
|
+
- [API guide](#api-guide)
|
|
25
|
+
- [Runtime flows](#runtime-flows)
|
|
26
|
+
- [Internal architecture](#internal-architecture)
|
|
27
|
+
- [Core walkthrough](#core-walkthrough)
|
|
28
|
+
- [Design decisions](#design-decisions)
|
|
29
|
+
- [Testing and development](#testing-and-development)
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
This repository currently marks the package as private in `package.json`. In a workspace, add it through your package manager or workspace protocol. When the package is published or linked, the import surface is:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { CreateForm } from '@ilokesto/form';
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Local development commands:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
pnpm install
|
|
43
|
+
pnpm build
|
|
44
|
+
pnpm typecheck
|
|
45
|
+
pnpm test
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The package emits ESM JavaScript and TypeScript declarations to `dist/`.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { CreateForm } from '@ilokesto/form';
|
|
54
|
+
|
|
55
|
+
type LoginValues = {
|
|
56
|
+
email: string;
|
|
57
|
+
profile: {
|
|
58
|
+
name: string;
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const form = new CreateForm<LoginValues>({
|
|
63
|
+
initialValues: {
|
|
64
|
+
email: '',
|
|
65
|
+
profile: {
|
|
66
|
+
name: 'Ada',
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
form.setValue('email', 'ada@example.com', { source: 'user' });
|
|
72
|
+
form.setValue(['profile', 'name'], 'Grace', { source: 'user' });
|
|
73
|
+
|
|
74
|
+
console.log(form.getFieldState('email'));
|
|
75
|
+
console.log(form.getValues());
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Important path rule:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
form.setValue(['profile', 'name'], 'Grace');
|
|
82
|
+
form.setValue('profile.name', 'literal field');
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
## React adapter
|
|
88
|
+
|
|
89
|
+
React bindings are exposed through the `./react` subpath so the root package stays framework-agnostic.
|
|
90
|
+
|
|
91
|
+
```tsx
|
|
92
|
+
import { CreateForm } from '@ilokesto/form';
|
|
93
|
+
import { useForm } from '@ilokesto/form/react';
|
|
94
|
+
|
|
95
|
+
const form = new CreateForm({
|
|
96
|
+
initialValues: {
|
|
97
|
+
email: '',
|
|
98
|
+
remember: false,
|
|
99
|
+
},
|
|
100
|
+
validateOn: ['blur', 'submit'],
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
function LoginForm() {
|
|
104
|
+
const {
|
|
105
|
+
useRegister,
|
|
106
|
+
useField,
|
|
107
|
+
useFormState,
|
|
108
|
+
} = useForm(form);
|
|
109
|
+
|
|
110
|
+
const email = useField({ name: 'email', schema: emailSchema });
|
|
111
|
+
const remember = useRegister({ name: 'remember', type: 'checkbox' });
|
|
112
|
+
const [role] = useRegister<HTMLSelectElement>([{ name: 'role' }]);
|
|
113
|
+
const state = useFormState();
|
|
114
|
+
|
|
115
|
+
return (
|
|
116
|
+
<form>
|
|
117
|
+
<input {...email.props} />
|
|
118
|
+
{email.errors.map(error => <p key={error.message}>{error.message}</p>)}
|
|
119
|
+
|
|
120
|
+
<label>
|
|
121
|
+
<input type="checkbox" {...remember} />
|
|
122
|
+
Remember me
|
|
123
|
+
</label>
|
|
124
|
+
|
|
125
|
+
<select {...role}>
|
|
126
|
+
<option value="user">User</option>
|
|
127
|
+
<option value="admin">Admin</option>
|
|
128
|
+
</select>
|
|
129
|
+
|
|
130
|
+
<button disabled={!state.isDirty || !state.isValid}>
|
|
131
|
+
Submit
|
|
132
|
+
</button>
|
|
133
|
+
</form>
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The React adapter has three first-version hooks. `useRegister` is overloaded for single, array, and rest-argument registration:
|
|
139
|
+
|
|
140
|
+
| Hook | Purpose |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| `useRegister(options)` | Returns input binding props for one field: `name`, `type`, `value`, `checked`, `onChange`, `onBlur`, `onFocus`. Default input `type` is `text`. |
|
|
143
|
+
| `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. |
|
|
144
|
+
| `useRegister(optionA, optionB)` | Rest-argument form for multiple bindings; internally handled like an options array. |
|
|
145
|
+
| `useField(options)` | Returns `{ props, value, setValue, errors, dirty, touched }` for one field. It intentionally does not expose `field.register`. |
|
|
146
|
+
| `useFormState()` | Returns whole-form aggregate state such as `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, and `submitCount`. |
|
|
147
|
+
|
|
148
|
+
Field-local schemas can be passed to `useRegister` or `useField`. For that field, the field-local schema takes precedence over the form-level schema.
|
|
149
|
+
|
|
150
|
+
```tsx
|
|
151
|
+
const email = useField({
|
|
152
|
+
name: 'email',
|
|
153
|
+
schema: emailSchema,
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
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.
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
## Vue adapter
|
|
161
|
+
|
|
162
|
+
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.
|
|
163
|
+
|
|
164
|
+
```vue
|
|
165
|
+
<script setup lang="ts">
|
|
166
|
+
import { CreateForm } from '@ilokesto/form';
|
|
167
|
+
import { useForm } from '@ilokesto/form/vue';
|
|
168
|
+
|
|
169
|
+
const form = new CreateForm({
|
|
170
|
+
initialValues: {
|
|
171
|
+
email: '',
|
|
172
|
+
remember: false,
|
|
173
|
+
role: 'user',
|
|
174
|
+
},
|
|
175
|
+
validateOn: ['blur', 'submit'],
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const {
|
|
179
|
+
useRegister,
|
|
180
|
+
useField,
|
|
181
|
+
useFormState,
|
|
182
|
+
} = useForm(form);
|
|
183
|
+
|
|
184
|
+
const email = useField({ name: 'email', schema: emailSchema });
|
|
185
|
+
const remember = useRegister({ name: 'remember', type: 'checkbox' });
|
|
186
|
+
const [role] = useRegister<HTMLSelectElement>([{ name: 'role' }]);
|
|
187
|
+
const state = useFormState();
|
|
188
|
+
</script>
|
|
189
|
+
|
|
190
|
+
<template>
|
|
191
|
+
<form>
|
|
192
|
+
<input v-bind="email.props" />
|
|
193
|
+
<p v-for="error in email.errors" :key="error.message">
|
|
194
|
+
{{ error.message }}
|
|
195
|
+
</p>
|
|
196
|
+
|
|
197
|
+
<label>
|
|
198
|
+
<input type="checkbox" v-bind="remember" />
|
|
199
|
+
Remember me
|
|
200
|
+
</label>
|
|
201
|
+
|
|
202
|
+
<select v-bind="role">
|
|
203
|
+
<option value="user">User</option>
|
|
204
|
+
<option value="admin">Admin</option>
|
|
205
|
+
</select>
|
|
206
|
+
|
|
207
|
+
<button :disabled="!state.isDirty || !state.isValid">
|
|
208
|
+
Submit
|
|
209
|
+
</button>
|
|
210
|
+
</form>
|
|
211
|
+
</template>
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
The Vue adapter exposes the same three concepts:
|
|
215
|
+
|
|
216
|
+
| Composable | Purpose |
|
|
217
|
+
| --- | --- |
|
|
218
|
+
| `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. |
|
|
219
|
+
| `useRegister(options[])` / `useRegister(optionA, optionB)` | Returns multiple binding objects for map-friendly rendering. |
|
|
220
|
+
| `useField(options)` | Returns `{ props, value, setValue, errors, dirty, touched }` with getter-backed reactive reads. |
|
|
221
|
+
| `useFormState()` | Returns form-wide aggregate getters such as `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, and `submitCount`. |
|
|
222
|
+
|
|
223
|
+
Field-local schemas work the same way as React and are cleaned up with the current Vue effect scope.
|
|
224
|
+
|
|
225
|
+
## Solid adapter
|
|
226
|
+
|
|
227
|
+
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.
|
|
228
|
+
|
|
229
|
+
```tsx
|
|
230
|
+
import { CreateForm } from '@ilokesto/form';
|
|
231
|
+
import { useForm } from '@ilokesto/form/solid';
|
|
232
|
+
|
|
233
|
+
const form = new CreateForm({
|
|
234
|
+
initialValues: {
|
|
235
|
+
email: '',
|
|
236
|
+
remember: false,
|
|
237
|
+
role: 'user',
|
|
238
|
+
},
|
|
239
|
+
validateOn: ['blur', 'submit'],
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
function LoginForm() {
|
|
243
|
+
const { useRegister, useField, useFormState } = useForm(form);
|
|
244
|
+
const email = useField({ name: 'email', schema: emailSchema });
|
|
245
|
+
const remember = useRegister({ name: 'remember', type: 'checkbox' });
|
|
246
|
+
const role = useRegister<HTMLSelectElement>({ name: 'role' });
|
|
247
|
+
const state = useFormState();
|
|
248
|
+
|
|
249
|
+
return (
|
|
250
|
+
<form>
|
|
251
|
+
<input {...email.props} />
|
|
252
|
+
{email.errors.map(error => <p>{error.message}</p>)}
|
|
253
|
+
|
|
254
|
+
<input type="checkbox" {...remember} />
|
|
255
|
+
|
|
256
|
+
<select {...role}>
|
|
257
|
+
<option value="user">User</option>
|
|
258
|
+
<option value="admin">Admin</option>
|
|
259
|
+
</select>
|
|
260
|
+
|
|
261
|
+
<button disabled={!state.isDirty || !state.isValid}>Submit</button>
|
|
262
|
+
</form>
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
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.
|
|
268
|
+
|
|
269
|
+
## Svelte adapter
|
|
270
|
+
|
|
271
|
+
Svelte bindings are exposed through the `./svelte` subpath. Svelte does not use hook-style rendering, so the adapter exposes a `register` action and a Svelte readable form-state store.
|
|
272
|
+
|
|
273
|
+
```svelte
|
|
274
|
+
<script lang="ts">
|
|
275
|
+
import { CreateForm } from '@ilokesto/form';
|
|
276
|
+
import { useForm } from '@ilokesto/form/svelte';
|
|
277
|
+
|
|
278
|
+
const form = new CreateForm({
|
|
279
|
+
initialValues: {
|
|
280
|
+
email: '',
|
|
281
|
+
remember: false,
|
|
282
|
+
role: 'user',
|
|
283
|
+
},
|
|
284
|
+
validateOn: ['blur', 'submit'],
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
const { register, useFormState } = useForm(form);
|
|
288
|
+
const state = useFormState();
|
|
289
|
+
</script>
|
|
290
|
+
|
|
291
|
+
<form>
|
|
292
|
+
<input use:register={{ name: 'email', schema: emailSchema }} />
|
|
293
|
+
<input type="checkbox" use:register={{ name: 'remember', type: 'checkbox' }} />
|
|
294
|
+
|
|
295
|
+
<select use:register={{ name: 'role' }}>
|
|
296
|
+
<option value="user">User</option>
|
|
297
|
+
<option value="admin">Admin</option>
|
|
298
|
+
</select>
|
|
299
|
+
|
|
300
|
+
<button disabled={!$state.isDirty || !$state.isValid}>Submit</button>
|
|
301
|
+
</form>
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
The Svelte action owns DOM synchronization directly: it sets the DOM `name`, keeps `value`/`checked` in sync from form state, writes user changes back to the core form, and cleans up field-local schemas when the action is destroyed.
|
|
305
|
+
|
|
306
|
+
## Core concepts
|
|
307
|
+
|
|
308
|
+
### `FieldPathSegment`
|
|
309
|
+
|
|
310
|
+
A single path segment is either a string object key or a numeric array index.
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
type FieldPathSegment = string | number;
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
Examples:
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
'user'
|
|
320
|
+
'name'
|
|
321
|
+
0
|
|
322
|
+
1
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### `FieldPath`
|
|
326
|
+
|
|
327
|
+
A `FieldPath` is the internal tuple representation of a form field path.
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
type FieldPath = readonly FieldPathSegment[];
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
Examples:
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
['email']
|
|
337
|
+
['user', 'name']
|
|
338
|
+
['items', 0, 'title']
|
|
339
|
+
[] // root value
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
The root path is useful for primitive root values or root-level schema errors.
|
|
343
|
+
|
|
344
|
+
### `FieldPathInput`
|
|
345
|
+
|
|
346
|
+
Public APIs accept either a string field name or a tuple path.
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
type FieldPathInput = string | FieldPath;
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
A string is not parsed as a dot path. This prevents collisions between a nested path and an actual object key containing `.`.
|
|
353
|
+
|
|
354
|
+
### `PathKey`
|
|
355
|
+
|
|
356
|
+
`FormState.fields` and `FormState.arrayKeys` need string keys. `FormPath` converts tuple paths to stable string keys.
|
|
357
|
+
|
|
358
|
+
| FieldPath | PathKey |
|
|
359
|
+
| --- | --- |
|
|
360
|
+
| `[]` | `$` |
|
|
361
|
+
| `['email']` | `["email"]` |
|
|
362
|
+
| `['user', 'name']` | `["user","name"]` |
|
|
363
|
+
| `['items', 0, 'title']` | `["items",0,"title"]` |
|
|
364
|
+
|
|
365
|
+
The implementation uses JSON array strings instead of separator-based strings, so literal field names such as `"user.name"` are safe.
|
|
366
|
+
|
|
367
|
+
### `FieldState`
|
|
368
|
+
|
|
369
|
+
A `FieldState` stores the value and metadata for one leaf field.
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
type FieldState<TValue = unknown> = {
|
|
373
|
+
value: TValue;
|
|
374
|
+
errors: FormError[];
|
|
375
|
+
touched: boolean;
|
|
376
|
+
dirty: boolean;
|
|
377
|
+
modified: boolean;
|
|
378
|
+
};
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
The flags mean:
|
|
382
|
+
|
|
383
|
+
- `touched`: the field was blurred at least once.
|
|
384
|
+
- `dirty`: the current value is not `Object.is`-equal to the initial value at the same path.
|
|
385
|
+
- `modified`: the field was changed by a user-sourced write, `source: 'user'`.
|
|
386
|
+
- `errors`: validation or manually assigned field errors.
|
|
387
|
+
|
|
388
|
+
### `FormState`
|
|
389
|
+
|
|
390
|
+
The internal snapshot is normalized.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
type FormState<TValues> = {
|
|
394
|
+
initialValues: TValues;
|
|
395
|
+
fields: Record<PathKey, FieldState>;
|
|
396
|
+
submitCount: number;
|
|
397
|
+
arrayKeys: Record<PathKey, string[]>;
|
|
398
|
+
};
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
For this input:
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
const form = new CreateForm({
|
|
405
|
+
initialValues: {
|
|
406
|
+
user: { name: 'Ada' },
|
|
407
|
+
items: [{ title: 'A' }, { title: 'B' }],
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
The core stores leaf field states and array container keys separately:
|
|
413
|
+
|
|
414
|
+
```ts
|
|
415
|
+
{
|
|
416
|
+
initialValues: {
|
|
417
|
+
user: { name: 'Ada' },
|
|
418
|
+
items: [{ title: 'A' }, { title: 'B' }],
|
|
419
|
+
},
|
|
420
|
+
fields: {
|
|
421
|
+
'["user","name"]': { value: 'Ada', errors: [], touched: false, dirty: false, modified: false },
|
|
422
|
+
'["items",0,"title"]': { value: 'A', errors: [], touched: false, dirty: false, modified: false },
|
|
423
|
+
'["items",1,"title"]': { value: 'B', errors: [], touched: false, dirty: false, modified: false },
|
|
424
|
+
},
|
|
425
|
+
submitCount: 0,
|
|
426
|
+
arrayKeys: {
|
|
427
|
+
'["items"]': ['initial-0', 'initial-1'],
|
|
428
|
+
},
|
|
429
|
+
}
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
`getValues()` reconstructs the nested object from `fields` and `arrayKeys`.
|
|
433
|
+
|
|
434
|
+
### `FormError`
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
type FormError = {
|
|
438
|
+
type?: string;
|
|
439
|
+
message: string;
|
|
440
|
+
};
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
Schema errors use `type: 'standard_schema'`. You can also set errors manually with `setErrors()`.
|
|
444
|
+
|
|
445
|
+
### `ValidationTrigger`
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
type ValidationTrigger = 'change' | 'blur' | 'submit' | 'manual';
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
`validateOn` controls automatic validation. If omitted, the default is `['submit']`. Manual validation is always available through `trigger()`.
|
|
452
|
+
|
|
453
|
+
### `StandardSchemaV1`
|
|
454
|
+
|
|
455
|
+
The core accepts a Standard Schema compatible object:
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
const schema = {
|
|
459
|
+
'~standard': {
|
|
460
|
+
version: 1,
|
|
461
|
+
vendor: 'example',
|
|
462
|
+
validate(value) {
|
|
463
|
+
return { value };
|
|
464
|
+
},
|
|
465
|
+
},
|
|
466
|
+
};
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
On failure, `validate()` returns `issues`. Each issue path is converted into a `FieldPath`, then into a `PathKey`, then written to the corresponding `FieldState.errors`.
|
|
470
|
+
|
|
471
|
+
### Field-local schemas
|
|
472
|
+
|
|
473
|
+
Framework adapters can register a schema for a single field.
|
|
474
|
+
|
|
475
|
+
```ts
|
|
476
|
+
const cleanup = form.registerFieldSchema('email', {
|
|
477
|
+
schema: emailSchema,
|
|
478
|
+
});
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
When a field-local schema exists, that field uses it instead of the form-level schema:
|
|
482
|
+
|
|
483
|
+
```txt
|
|
484
|
+
field-local schema > form-level schema
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
The cleanup function removes the schema registration if it is still the latest registration for that field.
|
|
488
|
+
|
|
489
|
+
### `ArrayKeys`
|
|
490
|
+
|
|
491
|
+
Array item identity is stored separately from array values.
|
|
492
|
+
|
|
493
|
+
- Items from `initialValues` get deterministic keys: `initial-0`, `initial-1`, ...
|
|
494
|
+
- Runtime insertions get generated keys: `item-1`, `item-2`, ...
|
|
495
|
+
- `move()` and `swap()` move keys with values.
|
|
496
|
+
- `replace()` creates a new key for every new item and does not preserve old child metadata.
|
|
497
|
+
|
|
498
|
+
These keys are intended for framework list rendering.
|
|
499
|
+
|
|
500
|
+
## API guide
|
|
501
|
+
|
|
502
|
+
### `new CreateForm(options)`
|
|
503
|
+
|
|
504
|
+
```ts
|
|
505
|
+
const form = new CreateForm({
|
|
506
|
+
initialValues,
|
|
507
|
+
schema,
|
|
508
|
+
schemaOptions,
|
|
509
|
+
validateOn,
|
|
510
|
+
});
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
Options:
|
|
514
|
+
|
|
515
|
+
- `initialValues`: required initial value tree.
|
|
516
|
+
- `schema`: optional Standard Schema v1 compatible schema.
|
|
517
|
+
- `schemaOptions`: optional Standard Schema validation options.
|
|
518
|
+
- `validateOn`: optional automatic validation triggers. Defaults to `['submit']`.
|
|
519
|
+
|
|
520
|
+
### `getState()`
|
|
521
|
+
|
|
522
|
+
Returns the current `FormState` snapshot.
|
|
523
|
+
|
|
524
|
+
```ts
|
|
525
|
+
const state = form.getState();
|
|
526
|
+
console.log(state.submitCount);
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
Treat the returned object as read-only.
|
|
530
|
+
|
|
531
|
+
### `subscribe(listener)`
|
|
532
|
+
|
|
533
|
+
Subscribes to store changes and returns an unsubscribe function.
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
const unsubscribe = form.subscribe(() => {
|
|
537
|
+
console.log(form.getValues());
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
unsubscribe();
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
Framework adapters use this method to connect the core store to reactive rendering.
|
|
544
|
+
|
|
545
|
+
### `registerFieldSchema(path, options)`
|
|
546
|
+
|
|
547
|
+
Registers a field-local schema and returns a cleanup function.
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
const cleanup = form.registerFieldSchema('email', {
|
|
551
|
+
schema: emailSchema,
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
cleanup();
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
This is mostly intended for framework adapters. A field-local schema overrides the form-level schema for that field during `blur()`, `trigger()`, and `submit()`.
|
|
558
|
+
|
|
559
|
+
### `getFieldState(path)`
|
|
560
|
+
|
|
561
|
+
Returns the `FieldState` for a path. If the field does not exist yet, the method returns a default field state instead of `undefined`.
|
|
562
|
+
|
|
563
|
+
```ts
|
|
564
|
+
const email = form.getFieldState('email');
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
### `getValue(path)`
|
|
568
|
+
|
|
569
|
+
Returns only the current field value.
|
|
570
|
+
|
|
571
|
+
```ts
|
|
572
|
+
const email = form.getValue('email');
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
### `getValues()`
|
|
576
|
+
|
|
577
|
+
Reconstructs and returns the full nested values object.
|
|
578
|
+
|
|
579
|
+
```ts
|
|
580
|
+
const values = form.getValues();
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
### `setValue(path, value, options?)`
|
|
584
|
+
|
|
585
|
+
Writes one field value.
|
|
586
|
+
|
|
587
|
+
```ts
|
|
588
|
+
form.setValue(['user', 'name'], 'Grace', {
|
|
589
|
+
source: 'user',
|
|
590
|
+
validate: true,
|
|
591
|
+
});
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
Effects:
|
|
595
|
+
|
|
596
|
+
1. Converts the public path input to an internal tuple path.
|
|
597
|
+
2. Writes the new value to the corresponding `FieldState`.
|
|
598
|
+
3. Recomputes `dirty` by comparing with `initialValues` at the same path.
|
|
599
|
+
4. Sets `modified` to `true` only when `source === 'user'`.
|
|
600
|
+
5. Starts change validation if `options.validate` is true or `validateOn` contains `'change'`.
|
|
601
|
+
|
|
602
|
+
`setValue()` returns `void`; change validation is started asynchronously and is not awaited by the method.
|
|
603
|
+
|
|
604
|
+
### `blur(path)`
|
|
605
|
+
|
|
606
|
+
Marks the field as touched and optionally validates it.
|
|
607
|
+
|
|
608
|
+
```ts
|
|
609
|
+
const valid = await form.blur('email');
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
If `validateOn` does not contain `'blur'`, it returns `true` after touching the field.
|
|
613
|
+
|
|
614
|
+
### `focus(path)`
|
|
615
|
+
|
|
616
|
+
Currently a no-op. It exists so framework adapters can expose a stable command surface for focus events even though the minimal core state does not store a focused field.
|
|
617
|
+
|
|
618
|
+
### `setErrors(path, errors)`
|
|
619
|
+
|
|
620
|
+
Replaces the error list for one field.
|
|
621
|
+
|
|
622
|
+
```ts
|
|
623
|
+
form.setErrors('email', [{ message: 'Email is required' }]);
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
### `clearErrors(...paths)`
|
|
627
|
+
|
|
628
|
+
Clears errors for specific fields, or all existing fields when no path is passed.
|
|
629
|
+
|
|
630
|
+
```ts
|
|
631
|
+
form.clearErrors('email');
|
|
632
|
+
form.clearErrors();
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
### `trigger(...paths)`
|
|
636
|
+
|
|
637
|
+
Runs manual validation.
|
|
638
|
+
|
|
639
|
+
```ts
|
|
640
|
+
await form.trigger('email');
|
|
641
|
+
await form.trigger();
|
|
642
|
+
```
|
|
643
|
+
|
|
644
|
+
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.
|
|
645
|
+
|
|
646
|
+
### `array(path)`
|
|
647
|
+
|
|
648
|
+
Returns a `FormArray` controller for an array field.
|
|
649
|
+
|
|
650
|
+
```ts
|
|
651
|
+
const items = form.array('items');
|
|
652
|
+
|
|
653
|
+
items.push({ title: 'C' });
|
|
654
|
+
items.move(2, 0);
|
|
655
|
+
console.log(items.keys());
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
The array controller reads the latest values and keys from the store each time a command runs.
|
|
659
|
+
|
|
660
|
+
### `reset(values?)`
|
|
661
|
+
|
|
662
|
+
Resets the form to initial state.
|
|
663
|
+
|
|
664
|
+
```ts
|
|
665
|
+
form.reset();
|
|
666
|
+
form.reset({ email: 'new@example.com' });
|
|
667
|
+
```
|
|
668
|
+
|
|
669
|
+
Without an argument, it reuses the current `initialValues`. With an argument, the argument becomes the new `initialValues`.
|
|
670
|
+
|
|
671
|
+
### `submit(onValid, onInvalid?)`
|
|
672
|
+
|
|
673
|
+
Increments `submitCount`, validates the form, and calls the matching callback.
|
|
674
|
+
|
|
675
|
+
```ts
|
|
676
|
+
const result = await form.submit(
|
|
677
|
+
values => values,
|
|
678
|
+
fields => {
|
|
679
|
+
console.log(fields);
|
|
680
|
+
},
|
|
681
|
+
);
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
If validation fails, `onInvalid` receives the current `fields` object and `submit()` returns `undefined`. If validation succeeds, `onValid` receives reconstructed values.
|
|
685
|
+
|
|
686
|
+
### `FormArray.keys()`
|
|
687
|
+
|
|
688
|
+
Returns stable keys for rendering the current array items.
|
|
689
|
+
|
|
690
|
+
```ts
|
|
691
|
+
const keys = form.array('items').keys();
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
### `FormArray.insert(index, value)`
|
|
695
|
+
|
|
696
|
+
Inserts an item. Out-of-range indexes are bounded to `0...length`.
|
|
697
|
+
|
|
698
|
+
### `FormArray.push(value)`
|
|
699
|
+
|
|
700
|
+
Appends an item.
|
|
701
|
+
|
|
702
|
+
### `FormArray.remove(index)`
|
|
703
|
+
|
|
704
|
+
Removes an item. Invalid indexes are ignored.
|
|
705
|
+
|
|
706
|
+
### `FormArray.move(fromIndex, toIndex)`
|
|
707
|
+
|
|
708
|
+
Moves one item. Invalid indexes or a no-op move are ignored.
|
|
709
|
+
|
|
710
|
+
### `FormArray.swap(leftIndex, rightIndex)`
|
|
711
|
+
|
|
712
|
+
Swaps two items. Invalid indexes or identical indexes are ignored.
|
|
713
|
+
|
|
714
|
+
### `FormArray.replace(values)`
|
|
715
|
+
|
|
716
|
+
Replaces the whole array. Existing item links are intentionally broken, so child field metadata is not preserved.
|
|
717
|
+
|
|
718
|
+
## Runtime flows
|
|
719
|
+
|
|
720
|
+
### Form creation flow
|
|
721
|
+
|
|
722
|
+
```txt
|
|
723
|
+
new CreateForm(options)
|
|
724
|
+
-> new FormStateStore(options.initialValues)
|
|
725
|
+
-> FormStateInitializer.initialize(initialValues)
|
|
726
|
+
-> fields for leaf values
|
|
727
|
+
-> arrayKeys for array containers
|
|
728
|
+
-> new ValidationEngine(store, options)
|
|
729
|
+
-> new FormFieldCommands(store, validation)
|
|
730
|
+
-> new FormArrayFactory(store)
|
|
731
|
+
-> new FormSubmitter(store, validation)
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
The important point is that all collaborators share the same `FormStateStore`.
|
|
735
|
+
|
|
736
|
+
### Value write flow
|
|
737
|
+
|
|
738
|
+
```txt
|
|
739
|
+
form.setValue(path, value, options)
|
|
740
|
+
-> FormFieldCommands.setValue()
|
|
741
|
+
-> FormPath.toFieldPath(path)
|
|
742
|
+
-> FormStateStore.setValue()
|
|
743
|
+
-> FormStateWriter.setValue()
|
|
744
|
+
-> compute dirty from initialValues
|
|
745
|
+
-> optionally mark modified
|
|
746
|
+
-> optionally start change validation
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
`dirty` and `modified` are intentionally separate. Programmatic writes can make a field dirty without marking it as user-modified.
|
|
750
|
+
|
|
751
|
+
### Blur flow
|
|
752
|
+
|
|
753
|
+
```txt
|
|
754
|
+
form.blur(path)
|
|
755
|
+
-> FormFieldCommands.blur()
|
|
756
|
+
-> FormPath.pathInputToKey(path)
|
|
757
|
+
-> FormStateStore.touchField(key)
|
|
758
|
+
-> if validateOn includes 'blur': ValidationEngine.validateField(key, 'blur')
|
|
759
|
+
-> otherwise return true
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
### Manual validation flow
|
|
763
|
+
|
|
764
|
+
```txt
|
|
765
|
+
form.trigger(...paths)
|
|
766
|
+
-> no paths: validateRegisteredFields('manual')
|
|
767
|
+
-> with paths: validateFields(keys, 'manual')
|
|
768
|
+
-> field-local schema exists: validate that field value and replace that field's errors
|
|
769
|
+
-> otherwise: StandardSchemaValidator.validate(values)
|
|
770
|
+
-> issue paths become PathKeys
|
|
771
|
+
-> selected field errors are replaced
|
|
772
|
+
```
|
|
773
|
+
|
|
774
|
+
Without a field-local schema, field-level validation still runs the whole form schema, then applies only the target field errors. This keeps the schema adapter simple and schema-library independent. With a field-local schema, that schema overrides form-level errors for the same field.
|
|
775
|
+
|
|
776
|
+
### Submit flow
|
|
777
|
+
|
|
778
|
+
```txt
|
|
779
|
+
form.submit(onValid, onInvalid)
|
|
780
|
+
-> increment submitCount
|
|
781
|
+
-> validateRegisteredFields('submit')
|
|
782
|
+
-> invalid: onInvalid(fields), return undefined
|
|
783
|
+
-> valid: onValid(getValues())
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
`submitCount` records submit attempts, not successful submissions.
|
|
787
|
+
|
|
788
|
+
### Array mutation flow
|
|
789
|
+
|
|
790
|
+
```txt
|
|
791
|
+
form.array('items').move(1, 0)
|
|
792
|
+
-> FormArrayController.move()
|
|
793
|
+
-> read current array values and keys
|
|
794
|
+
-> FormArrayMutationPlanner.move()
|
|
795
|
+
-> next values
|
|
796
|
+
-> next keys
|
|
797
|
+
-> previous-index to next-index mapper
|
|
798
|
+
-> FormArrayRebaser.rebase()
|
|
799
|
+
-> write next array into values
|
|
800
|
+
-> initialize a fresh FormState from next values
|
|
801
|
+
-> preserve non-array fields
|
|
802
|
+
-> move child metadata through the index mapper
|
|
803
|
+
-> write next array keys
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
This is the core feature that keeps `items[1].name` metadata attached to the same logical item when that item moves to `items[0].name`.
|
|
807
|
+
|
|
808
|
+
## Internal architecture
|
|
809
|
+
|
|
810
|
+
```txt
|
|
811
|
+
src/index.ts
|
|
812
|
+
-> src/core/index.ts
|
|
813
|
+
-> form/CreateForm.ts
|
|
814
|
+
-> state/FormStateStore.ts
|
|
815
|
+
-> state/FormStateInitializer.ts
|
|
816
|
+
-> state/FormStateReader.ts
|
|
817
|
+
-> state/FormStateWriter.ts
|
|
818
|
+
-> form/FormFieldCommands.ts
|
|
819
|
+
-> validation/ValidationEngine.ts
|
|
820
|
+
-> validation/StandardSchemaValidator.ts
|
|
821
|
+
-> form/FormSubmitter.ts
|
|
822
|
+
-> array/FormArrayFactory.ts
|
|
823
|
+
-> array/FormArrayController.ts
|
|
824
|
+
-> array/FormArrayMutationPlanner.ts
|
|
825
|
+
-> array/FormArrayRebaser.ts
|
|
826
|
+
-> array/FormArrayPath.ts
|
|
827
|
+
-> array/ArrayItemReorder.ts
|
|
828
|
+
-> array/ArrayKeyGenerator.ts
|
|
829
|
+
-> path/FormPath.ts
|
|
830
|
+
-> value/ValueHelper.ts
|
|
831
|
+
-> types.ts
|
|
832
|
+
-> src/adapters/
|
|
833
|
+
-> dom/FieldValue.ts
|
|
834
|
+
-> dom/RegisterBinding.ts
|
|
835
|
+
-> FormStateSummary.ts
|
|
836
|
+
-> src/react/index.ts
|
|
837
|
+
-> React hook adapter over shared adapter logic
|
|
838
|
+
-> src/vue/index.ts
|
|
839
|
+
-> Vue composable adapter over shared adapter logic
|
|
840
|
+
-> src/solid/index.ts
|
|
841
|
+
-> Solid helper adapter over shared adapter logic
|
|
842
|
+
-> src/svelte/index.ts
|
|
843
|
+
-> Svelte action adapter over shared adapter logic
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
Responsibility summary:
|
|
847
|
+
|
|
848
|
+
| Area | Responsibility |
|
|
849
|
+
| --- | --- |
|
|
850
|
+
| `form/` | Public orchestration: field commands, submit flow, array controller access. |
|
|
851
|
+
| `state/` | Normalized state initialization, reading, writing, and store facade. |
|
|
852
|
+
| `path/` | Conversion between public path input, tuple paths, and string path keys. |
|
|
853
|
+
| `value/` | Immutable nested get/set and reconstruction of values from field states. |
|
|
854
|
+
| `validation/` | Standard Schema execution and error normalization. |
|
|
855
|
+
| `array/` | Array item key management, mutation planning, and child field metadata rebasing. |
|
|
856
|
+
| `adapters/` | Internal shared adapter logic: DOM value extraction/binding and form-state aggregation. |
|
|
857
|
+
| `react/` | React hook adapter around the public `Form` interface. |
|
|
858
|
+
| `vue/` | Vue composable adapter around the public `Form` interface. |
|
|
859
|
+
| `solid/` | Solid helper adapter around the public `Form` interface. |
|
|
860
|
+
| `svelte/` | Svelte action adapter around the public `Form` interface. |
|
|
861
|
+
| `types.ts` | Public and internal TypeScript contracts. |
|
|
862
|
+
|
|
863
|
+
## Core walkthrough
|
|
864
|
+
|
|
865
|
+
### `src/index.ts`
|
|
866
|
+
|
|
867
|
+
The package root exports only the stable framework-agnostic surface:
|
|
868
|
+
|
|
869
|
+
```ts
|
|
870
|
+
export { CreateForm } from './core/index';
|
|
871
|
+
export type {
|
|
872
|
+
CreateFormOptions,
|
|
873
|
+
FieldPathInput,
|
|
874
|
+
Form,
|
|
875
|
+
FormError,
|
|
876
|
+
StandardSchemaV1,
|
|
877
|
+
} from './core/index';
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
Internal state and command helper types stay out of the package root. They are documented here to explain the implementation, but consumers should interact through `Form`, `CreateForm`, field paths, errors, and Standard Schema contracts.
|
|
881
|
+
|
|
882
|
+
### `src/core/index.ts`
|
|
883
|
+
|
|
884
|
+
This file re-exports `CreateForm` and public types from `types.ts`. It is the boundary between the package root and the implementation folders.
|
|
885
|
+
|
|
886
|
+
### `src/core/types.ts`
|
|
887
|
+
|
|
888
|
+
`types.ts` defines the core vocabulary:
|
|
889
|
+
|
|
890
|
+
- public path type: `FieldPathInput`; internal path concepts: `FieldPathSegment`, `FieldPath`, `PathKey`
|
|
891
|
+
- exported validation types: `FormError`, `StandardSchemaV1`; internal validation trigger type: `ValidationTrigger`
|
|
892
|
+
- internal state types: `FieldState`, `ArrayKeys`, `FormState`
|
|
893
|
+
- public API types: `CreateFormOptions`, `Form`; internal command helper types: `FormArray`, `SetValueOptions`
|
|
894
|
+
|
|
895
|
+
The most important design in this file is that public string paths are literal field names. Nested fields require tuple paths.
|
|
896
|
+
|
|
897
|
+
### `src/core/form/CreateForm.ts`
|
|
898
|
+
|
|
899
|
+
`CreateForm` is the top-level controller and the main public class.
|
|
900
|
+
|
|
901
|
+
It owns four collaborators:
|
|
902
|
+
|
|
903
|
+
```txt
|
|
904
|
+
store -> state storage and state operations
|
|
905
|
+
fields -> setValue, blur, errors, trigger
|
|
906
|
+
arrays -> array(path) controller creation
|
|
907
|
+
submitter -> submitCount, validation, callbacks
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
The constructor creates one `FormStateStore`, then passes it to all collaborators. That makes every command operate on the same snapshot.
|
|
911
|
+
|
|
912
|
+
Most methods are thin delegations:
|
|
913
|
+
|
|
914
|
+
- `getState()`, `getFieldState()`, `getValue()`, `getValues()`, `reset()` delegate to `FormStateStore`.
|
|
915
|
+
- `setValue()`, `blur()`, `focus()`, `setErrors()`, `clearErrors()`, `trigger()` delegate to `FormFieldCommands`.
|
|
916
|
+
- `array()` converts the path to a tuple and asks `FormArrayFactory` for a controller.
|
|
917
|
+
- `submit()` delegates to `FormSubmitter`.
|
|
918
|
+
|
|
919
|
+
This keeps the public API stable while implementation responsibilities stay separated.
|
|
920
|
+
|
|
921
|
+
### `src/core/form/FormFieldCommands.ts`
|
|
922
|
+
|
|
923
|
+
`FormFieldCommands` groups field-level operations.
|
|
924
|
+
|
|
925
|
+
`setValue()`:
|
|
926
|
+
|
|
927
|
+
1. Converts the path to a tuple through `FormPath.toFieldPath()`.
|
|
928
|
+
2. Writes the value through `store.setValue()`.
|
|
929
|
+
3. Receives the resulting `PathKey`.
|
|
930
|
+
4. Starts change validation if `options.validate` is true or `validateOn` contains `'change'`.
|
|
931
|
+
|
|
932
|
+
`blur()`:
|
|
933
|
+
|
|
934
|
+
1. Converts the public path to a `PathKey`.
|
|
935
|
+
2. Marks the field as touched.
|
|
936
|
+
3. Runs blur validation only when configured.
|
|
937
|
+
|
|
938
|
+
`focus()` is currently a no-op because the minimal core state does not track focus. The method exists for adapter-level consistency.
|
|
939
|
+
|
|
940
|
+
`setErrors()`, `clearErrors()`, and `trigger()` normalize paths to keys and delegate to the store or validation engine.
|
|
941
|
+
|
|
942
|
+
### `src/core/form/FormSubmitter.ts`
|
|
943
|
+
|
|
944
|
+
`FormSubmitter` isolates submit-specific sequencing:
|
|
945
|
+
|
|
946
|
+
```txt
|
|
947
|
+
increment submitCount
|
|
948
|
+
validate all registered fields
|
|
949
|
+
if invalid -> call onInvalid(fields) and return undefined
|
|
950
|
+
if valid -> call onValid(getValues())
|
|
951
|
+
```
|
|
952
|
+
|
|
953
|
+
The class exists because submit is a multi-step command and should not make `CreateForm` responsible for validation branching.
|
|
954
|
+
|
|
955
|
+
### `src/core/state/FieldStateFactory.ts`
|
|
956
|
+
|
|
957
|
+
`FieldStateFactory` centralizes the default field state shape:
|
|
958
|
+
|
|
959
|
+
```ts
|
|
960
|
+
{
|
|
961
|
+
value: undefined,
|
|
962
|
+
errors: [],
|
|
963
|
+
touched: false,
|
|
964
|
+
dirty: false,
|
|
965
|
+
modified: false,
|
|
966
|
+
}
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
It creates a new `errors` array each time to avoid shared mutable references. The same factory is used for initial leaf fields and missing-field fallbacks.
|
|
970
|
+
|
|
971
|
+
### `src/core/state/FormStateInitializer.ts`
|
|
972
|
+
|
|
973
|
+
`FormStateInitializer.initialize(initialValues)` converts nested values into normalized `FormState`.
|
|
974
|
+
|
|
975
|
+
Rules:
|
|
976
|
+
|
|
977
|
+
1. Arrays are containers, not leaf fields.
|
|
978
|
+
2. Array containers receive `arrayKeys` such as `initial-0`, `initial-1`.
|
|
979
|
+
3. Array items are visited recursively.
|
|
980
|
+
4. Plain objects are traversed.
|
|
981
|
+
5. Empty plain objects are stored as leaf values because there is no deeper field.
|
|
982
|
+
6. Non-plain objects such as `Date` and class instances are treated as leaf values.
|
|
983
|
+
7. Primitives and `null` are leaf values.
|
|
984
|
+
|
|
985
|
+
This is why `getState().fields` contains leaf paths rather than the original nested object.
|
|
986
|
+
|
|
987
|
+
### `src/core/state/FormStateReader.ts`
|
|
988
|
+
|
|
989
|
+
`FormStateReader` handles read-only derived operations.
|
|
990
|
+
|
|
991
|
+
- `getKnownFieldPaths()` converts every stored `PathKey` back to a tuple path.
|
|
992
|
+
- `getFieldStateByKey()` returns an existing field or a default `FieldState`.
|
|
993
|
+
- `getFieldState()` and `getValue()` are path-input convenience methods.
|
|
994
|
+
- `getValues()` reconstructs the full nested value tree with `ValueHelper.getValuesFromFields()`.
|
|
995
|
+
- `getValueAtPath()` reconstructs values first, then reads a nested path from them.
|
|
996
|
+
|
|
997
|
+
The reader receives a snapshot getter rather than owning the store directly, so it always reads the latest state.
|
|
998
|
+
|
|
999
|
+
### `src/core/state/FormStateWriter.ts`
|
|
1000
|
+
|
|
1001
|
+
`FormStateWriter` performs all state mutations through `immer`.
|
|
1002
|
+
|
|
1003
|
+
`setValue()`:
|
|
1004
|
+
|
|
1005
|
+
- Converts the tuple path to a `PathKey`.
|
|
1006
|
+
- Reads the initial value at that tuple path.
|
|
1007
|
+
- Preserves existing field metadata when possible.
|
|
1008
|
+
- Replaces `value`.
|
|
1009
|
+
- Computes `dirty` with `Object.is`.
|
|
1010
|
+
- Sets `modified` only for `source: 'user'`.
|
|
1011
|
+
- Returns the `PathKey` so validation can reuse it.
|
|
1012
|
+
|
|
1013
|
+
Other methods:
|
|
1014
|
+
|
|
1015
|
+
- `touchField()` sets `touched: true`.
|
|
1016
|
+
- `setErrorsByKey()` replaces the error array.
|
|
1017
|
+
- `clearErrors()` clears target fields or all existing fields.
|
|
1018
|
+
- `reset()` reinitializes state from the current or replacement initial values.
|
|
1019
|
+
- `incrementSubmitCount()` increments attempts.
|
|
1020
|
+
- `replaceState()` is an escape hatch for whole-state operations such as array rebasing.
|
|
1021
|
+
|
|
1022
|
+
### `src/core/state/FormStateStore.ts`
|
|
1023
|
+
|
|
1024
|
+
`FormStateStore` is the facade used by the rest of the core.
|
|
1025
|
+
|
|
1026
|
+
It owns:
|
|
1027
|
+
|
|
1028
|
+
- `Store<FormState<TValues>>` from `@ilokesto/store`
|
|
1029
|
+
- `FormStateReader`
|
|
1030
|
+
- `FormStateWriter`
|
|
1031
|
+
|
|
1032
|
+
Collaborators do not need to know whether an operation is implemented by the reader, writer, or underlying store. They call the facade.
|
|
1033
|
+
|
|
1034
|
+
### `src/core/path/FormPath.ts`
|
|
1035
|
+
|
|
1036
|
+
`FormPath` defines path conversion rules.
|
|
1037
|
+
|
|
1038
|
+
Key methods:
|
|
1039
|
+
|
|
1040
|
+
- `path(...segments)`: helper for tuple paths.
|
|
1041
|
+
- `toFieldPath(input)`: string becomes `[input]`; tuple path passes through.
|
|
1042
|
+
- `pathInputToKey(input)`: public path input to `PathKey`.
|
|
1043
|
+
- `pathToKey(path)`: `[]` becomes `$`, otherwise JSON stringifies the tuple.
|
|
1044
|
+
- `keyToPath(key)`: parses and validates a key back into tuple segments.
|
|
1045
|
+
|
|
1046
|
+
The JSON encoding is what prevents path collisions.
|
|
1047
|
+
|
|
1048
|
+
### `src/core/value/ValueHelper.ts`
|
|
1049
|
+
|
|
1050
|
+
`ValueHelper` provides immutable nested value operations.
|
|
1051
|
+
|
|
1052
|
+
`getValueAtPath(source, path)` walks an object/array safely. If an intermediate value is nullish or primitive, it returns `undefined`.
|
|
1053
|
+
|
|
1054
|
+
`setValueAtPath(source, path, value)` returns a new root value and shallow-clones containers along the path. Missing containers are inferred from the next segment: a number creates an array, a string creates an object.
|
|
1055
|
+
|
|
1056
|
+
`getValuesFromFields(state, fieldPaths)` reconstructs public values in two phases:
|
|
1057
|
+
|
|
1058
|
+
1. Create empty array containers from `arrayKeys`.
|
|
1059
|
+
2. Write every leaf field value into its tuple path.
|
|
1060
|
+
|
|
1061
|
+
This lets normalized `fields` become a nested object again.
|
|
1062
|
+
|
|
1063
|
+
### `src/core/validation/ValidationEngine.ts`
|
|
1064
|
+
|
|
1065
|
+
`ValidationEngine` coordinates validation triggers and store writes.
|
|
1066
|
+
|
|
1067
|
+
- Default `validateOn` is `['submit']`.
|
|
1068
|
+
- If no schema is provided, validation succeeds with no errors.
|
|
1069
|
+
- `validateField(key, trigger)` runs the full schema and applies only that field's errors.
|
|
1070
|
+
- `validateFields(keys, trigger)` runs the full schema and applies only selected fields' errors.
|
|
1071
|
+
- `validateRegisteredFields(trigger)` runs the full schema and updates all current fields plus all schema error keys.
|
|
1072
|
+
|
|
1073
|
+
The engine deliberately ignores the trigger value when calling the schema. The trigger controls when the engine runs, not the schema API.
|
|
1074
|
+
|
|
1075
|
+
### `src/core/validation/StandardSchemaValidator.ts`
|
|
1076
|
+
|
|
1077
|
+
`StandardSchemaValidator` adapts Standard Schema results to core errors.
|
|
1078
|
+
|
|
1079
|
+
Success:
|
|
1080
|
+
|
|
1081
|
+
```ts
|
|
1082
|
+
{ valid: true, errorsByKey: {} }
|
|
1083
|
+
```
|
|
1084
|
+
|
|
1085
|
+
Failure:
|
|
1086
|
+
|
|
1087
|
+
```ts
|
|
1088
|
+
{
|
|
1089
|
+
valid: false,
|
|
1090
|
+
errorsByKey: {
|
|
1091
|
+
'["email"]': [{ type: 'standard_schema', message: 'Email is invalid' }],
|
|
1092
|
+
},
|
|
1093
|
+
}
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
Issue path conversion rules:
|
|
1097
|
+
|
|
1098
|
+
- Missing or empty path becomes the root path `[]` and key `$`.
|
|
1099
|
+
- String and number path segments are preserved.
|
|
1100
|
+
- Object path segments use their `.key` property.
|
|
1101
|
+
- Unsupported keys such as symbols fall back to root errors.
|
|
1102
|
+
|
|
1103
|
+
### `src/core/array/ArrayKeyGenerator.ts`
|
|
1104
|
+
|
|
1105
|
+
`ArrayKeyGenerator` creates runtime item keys:
|
|
1106
|
+
|
|
1107
|
+
```txt
|
|
1108
|
+
item-1
|
|
1109
|
+
item-2
|
|
1110
|
+
item-3
|
|
1111
|
+
```
|
|
1112
|
+
|
|
1113
|
+
A single `FormArrayFactory` shares one generator per form instance, reducing accidental key collisions across controllers.
|
|
1114
|
+
|
|
1115
|
+
### `src/core/array/ArrayItemReorder.ts`
|
|
1116
|
+
|
|
1117
|
+
`ArrayItemReorder` is a pure helper for array order operations.
|
|
1118
|
+
|
|
1119
|
+
- `moveItem(items, from, to)` returns a reordered copy.
|
|
1120
|
+
- `swapItems(items, left, right)` returns a swapped copy.
|
|
1121
|
+
- `createIndexMapper(previousLength, nextOrder)` returns a function that maps a previous index to its next index.
|
|
1122
|
+
|
|
1123
|
+
`nextOrder` is expressed as "for each next position, which previous index is here?" New items use `-1`, and removed items simply do not appear.
|
|
1124
|
+
|
|
1125
|
+
### `src/core/array/FormArrayMutationPlanner.ts`
|
|
1126
|
+
|
|
1127
|
+
`FormArrayMutationPlanner` calculates array mutations without knowing about the store.
|
|
1128
|
+
|
|
1129
|
+
Each mutation returns:
|
|
1130
|
+
|
|
1131
|
+
```ts
|
|
1132
|
+
type FormArrayMutation = {
|
|
1133
|
+
values: readonly unknown[];
|
|
1134
|
+
keys: readonly string[];
|
|
1135
|
+
mapPreviousIndex: (index: number) => number | undefined;
|
|
1136
|
+
};
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
Command behavior:
|
|
1140
|
+
|
|
1141
|
+
- `insert()` bounds the target index and inserts a new value/key. The new item maps from `-1`, so no previous metadata is attached to it.
|
|
1142
|
+
- `push()` appends a value/key.
|
|
1143
|
+
- `remove()` drops a value/key and maps removed indexes to `undefined`.
|
|
1144
|
+
- `move()` moves values and keys with the same rule.
|
|
1145
|
+
- `swap()` swaps values and keys with the same rule.
|
|
1146
|
+
- `replace()` returns all new values/keys and maps every previous index to `undefined`.
|
|
1147
|
+
|
|
1148
|
+
Because this planner is pure, it is easy to test independently from the store.
|
|
1149
|
+
|
|
1150
|
+
### `src/core/array/FormArrayPath.ts`
|
|
1151
|
+
|
|
1152
|
+
`FormArrayPath` contains path helpers used during rebasing.
|
|
1153
|
+
|
|
1154
|
+
- `hasPathPrefix(fieldPath, prefix)` checks tuple prefix equality.
|
|
1155
|
+
- `isArrayChildPath(fieldPath, arrayPath)` checks whether a field is below an array item, such as `['items', 0, 'name']` below `['items']`.
|
|
1156
|
+
- `replaceArrayIndex(fieldPath, arrayPath, nextIndex)` creates a new child path with the item index replaced.
|
|
1157
|
+
|
|
1158
|
+
### `src/core/array/FormArrayController.ts`
|
|
1159
|
+
|
|
1160
|
+
`FormArrayController` is the public command object returned by `form.array(path)`.
|
|
1161
|
+
|
|
1162
|
+
It holds:
|
|
1163
|
+
|
|
1164
|
+
- the shared `FormStateStore`
|
|
1165
|
+
- the shared `ArrayKeyGenerator`
|
|
1166
|
+
- the controlled array `FieldPath`
|
|
1167
|
+
- a `FormArrayMutationPlanner`
|
|
1168
|
+
|
|
1169
|
+
Each command follows the same pattern:
|
|
1170
|
+
|
|
1171
|
+
```txt
|
|
1172
|
+
read current array value
|
|
1173
|
+
read current keys
|
|
1174
|
+
ask planner for next values, keys, and index mapper
|
|
1175
|
+
if mutation exists, rebase the whole FormState
|
|
1176
|
+
```
|
|
1177
|
+
|
|
1178
|
+
`getArray()` reads the current value at the array path. If the value is not an array, it uses an empty array.
|
|
1179
|
+
|
|
1180
|
+
`getKeys()` reads stored `arrayKeys`; if none exist, it creates keys for the current array length.
|
|
1181
|
+
|
|
1182
|
+
### `src/core/array/FormArrayFactory.ts`
|
|
1183
|
+
|
|
1184
|
+
`FormArrayFactory` creates `FormArrayController` instances and shares one `ArrayKeyGenerator` for the form instance.
|
|
1185
|
+
|
|
1186
|
+
This allows repeated calls such as `form.array('items')` to create fresh controllers without resetting the key sequence.
|
|
1187
|
+
|
|
1188
|
+
### `src/core/array/FormArrayRebaser.ts`
|
|
1189
|
+
|
|
1190
|
+
`FormArrayRebaser` is the most important array component. It aligns values, field states, array keys, and submit count after an array mutation.
|
|
1191
|
+
|
|
1192
|
+
Detailed sequence:
|
|
1193
|
+
|
|
1194
|
+
1. Read known field paths from the current store.
|
|
1195
|
+
2. Reconstruct current values with `store.getValues()`.
|
|
1196
|
+
3. Write the next array into those values with `ValueHelper.setValueAtPath()`.
|
|
1197
|
+
4. Initialize a fresh `FormState` from the next values.
|
|
1198
|
+
5. Start with the freshly initialized fields.
|
|
1199
|
+
6. Iterate over previous fields.
|
|
1200
|
+
7. Preserve fields outside the changed array.
|
|
1201
|
+
8. For child fields inside the changed array, map the previous item index to the next item index.
|
|
1202
|
+
9. If the item still exists, replace the index in the child path and copy metadata to the new field.
|
|
1203
|
+
10. Write the next `arrayKeys` for the array path.
|
|
1204
|
+
11. Preserve `submitCount`.
|
|
1205
|
+
|
|
1206
|
+
Only metadata is copied for rebased child fields:
|
|
1207
|
+
|
|
1208
|
+
```txt
|
|
1209
|
+
errors
|
|
1210
|
+
touched
|
|
1211
|
+
dirty
|
|
1212
|
+
modified
|
|
1213
|
+
```
|
|
1214
|
+
|
|
1215
|
+
The value itself comes from the freshly initialized state based on the new values. This prevents stale values while preserving user interaction metadata.
|
|
1216
|
+
|
|
1217
|
+
## Design decisions
|
|
1218
|
+
|
|
1219
|
+
### Strings are literal paths
|
|
1220
|
+
|
|
1221
|
+
Dot-path parsing is convenient but ambiguous. This core chooses unambiguous tuple paths instead.
|
|
1222
|
+
|
|
1223
|
+
```ts
|
|
1224
|
+
'user.name' // one field named "user.name"
|
|
1225
|
+
['user', 'name'] // nested user.name field
|
|
1226
|
+
```
|
|
1227
|
+
|
|
1228
|
+
### State is normalized
|
|
1229
|
+
|
|
1230
|
+
Normalized fields make it easy to update individual metadata without mutating the whole nested value object. `ValueHelper` reconstructs the public value shape when needed.
|
|
1231
|
+
|
|
1232
|
+
### Validation is schema-library independent
|
|
1233
|
+
|
|
1234
|
+
The core only knows Standard Schema. This keeps validation compatible with multiple libraries and avoids importing a specific validator.
|
|
1235
|
+
|
|
1236
|
+
### Array mutation is split into planning and rebasing
|
|
1237
|
+
|
|
1238
|
+
`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.
|
|
1239
|
+
|
|
1240
|
+
### `dirty` and `modified` are different
|
|
1241
|
+
|
|
1242
|
+
`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.
|
|
1243
|
+
|
|
1244
|
+
## Testing and development
|
|
1245
|
+
|
|
1246
|
+
### Commands
|
|
1247
|
+
|
|
1248
|
+
```sh
|
|
1249
|
+
pnpm build
|
|
1250
|
+
pnpm typecheck
|
|
1251
|
+
pnpm test
|
|
1252
|
+
```
|
|
1253
|
+
|
|
1254
|
+
`pnpm build` emits declaration files with TypeScript, rewrites only declaration-file relative specifiers for NodeNext compatibility, and bundles ESM JavaScript with Vite so source imports can stay extensionless while `dist/index.js` and adapter subpaths such as `dist/react/index.js`, `dist/vue/index.js`, `dist/solid/index.js`, and `dist/svelte/index.js` remain directly importable by ESM runtimes.
|
|
1255
|
+
|
|
1256
|
+
`pnpm test` runs the Vitest suite.
|
|
1257
|
+
|
|
1258
|
+
### Current test coverage themes
|
|
1259
|
+
|
|
1260
|
+
The existing tests cover:
|
|
1261
|
+
|
|
1262
|
+
1. Tuple paths versus literal string names.
|
|
1263
|
+
2. Standard Schema validation on blur, manual trigger, and submit.
|
|
1264
|
+
3. Array value/key/metadata rebasing when moving and removing items.
|
|
1265
|
+
4. React adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema precedence.
|
|
1266
|
+
5. Vue adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema cleanup.
|
|
1267
|
+
6. Solid adapter bindings for text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, and field-local schema cleanup.
|
|
1268
|
+
7. Svelte register action bindings for text input, checkbox, radio, select, multiple select, readable `useFormState`, and field-local schema cleanup.
|
|
1269
|
+
|
|
1270
|
+
### Suggested future documentation/tests
|
|
1271
|
+
|
|
1272
|
+
Good additions would be:
|
|
1273
|
+
|
|
1274
|
+
- A test for `insert()` index bounding.
|
|
1275
|
+
- A test for `replace()` intentionally dropping child metadata.
|
|
1276
|
+
- A test for root-level schema errors.
|
|
1277
|
+
- More adapter examples for custom DOM-event-compatible components.
|