@ilokesto/form 2.0.0 → 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.
package/README.ko.md CHANGED
@@ -1,61 +1,29 @@
1
1
  # @ilokesto/form
2
2
 
3
- [English](./README.md) | **한국어**
3
+ 값, 필드 메타데이터, 검증과 제출을 관리하는 프레임워크 독립적인 TypeScript 폼 코어입니다.
4
4
 
5
- `@ilokesto/form`은 프레임워크에 의존하지 않는 form state core다. 렌더링과 이벤트 바인딩은 framework adapter에 맡기고, core는 form values, field metadata, validation errors, submit attempts, array item keys를 하나의 정규화된 store 안에서 관리한다.
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
- 이 패키지는 다섯 가지 아이디어를 중심으로 설계되어 있다.
8
+ [English](./README.md)
8
9
 
9
- 1. **프레임워크 독립성**: core는 plain TypeScript class인 `CreateForm`을 노출하고 React, Vue, Svelte, Solid, DOM API를 import하지 않는다.
10
- 2. **dot path가 아닌 tuple path**: `"user.name"` 같은 문자열은 literal field name이고, nested path는 `["user", "name"]` 같은 tuple로 표현한다.
11
- 3. **정규화된 field state**: nested values는 leaf `FieldState` record로 분리되어 저장되고, `getValues()`를 호출할 때 다시 복원된다.
12
- 4. **Standard Schema validation**: core는 특정 schema library가 아니라 Standard Schema v1의 `~standard.validate` 계약에만 의존한다.
13
- 5. **Array rebasing**: array item이 move, swap, insert, remove될 때 `errors`, `touched`, `dirty`, `modified` 같은 child field metadata가 item과 함께 이동한다.
10
+ - 명시적인 tuple 경로와 정규화된 필드 상태로 중첩 필드를 관리합니다.
11
+ - 필드별 스키마와 비동기 결과를 포함한 Standard Schema v1 검증을 지원합니다.
12
+ - 배열 항목의 메타데이터를 보존하며 React, Vue, Solid, Svelte 어댑터로 연결합니다.
14
13
 
15
- ## 문서
16
-
17
- - 전체 문서: [English](https://ilokesto.ayden94.com/en/form) · [한국어](https://ilokesto.ayden94.com/ko/form)
18
- - 소스: [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)
36
-
37
- ## Installation
38
-
39
- 이 패키지는 `@ilokesto/form` 이름으로 npm에 public access로 게시된다. workspace에서는 package manager 또는 workspace protocol을 통해 추가하면 된다. package가 publish되거나 link된 상태에서 import surface는 다음과 같다.
40
-
41
- ```ts
42
- import { CreateForm } from '@ilokesto/form';
43
- ```
44
-
45
- Local development commands:
14
+ ## 설치
46
15
 
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
- 이 package는 ESM JavaScript와 TypeScript declaration을 `dist/`로 emit한다.
20
+ ESM과 TypeScript 선언을 제공하며 CommonJS `require()`는 지원하지 않습니다.
21
+ ESM import나 동적 `import()`를 사용하세요. 어댑터 하위 경로를 사용할 때는
22
+ 해당 프레임워크도 설치하세요.
55
23
 
56
- > **ESM-only.** 이 package는 `"type": "module"`과 ESM-only `exports`를 제공한다. CommonJS `require()`는 지원하지 않는다. Vite, webpack 5+, esbuild, tsup 같은 현대 번들러 또는 Node.js ESM(`import`)을 사용하라. CJS 호환이 필요하면 dynamic `import()` 또는 번들러에서 `@ilokesto/form`을 transpile하도록 설정하라.
24
+ ## 빠른 시작
57
25
 
58
- ## Quick start
26
+ 폼을 만들고 중첩 필드를 변경한 뒤 현재 값을 제출합니다.
59
27
 
60
28
  ```ts
61
29
  import { CreateForm } from '@ilokesto/form';
@@ -79,1305 +47,44 @@ 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
- 중요한 path rule:
87
-
88
- ```ts
89
- form.setValue(['profile', 'name'], 'Grace');
90
- form.setValue('profile.name', 'literal field');
91
- ```
92
-
93
- 이 둘은 서로 다른 field다. `['profile', 'name']`은 nested `profile.name` value를 의미한다. `'profile.name'`은 실제 key에 dot이 들어간 top-level field를 의미한다.
94
-
95
- ## React adapter
96
-
97
- React binding은 `./react` subpath로 노출된다. 그래서 package root는 framework-agnostic core만 유지한다.
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
- Component가 form을 소유하는 경우 React adapter는 options로 form을 직접 만들 수도 있다.
147
-
148
- ```tsx
149
- const { form, useRegister, handleSubmit } = useForm({
150
- defaultValues: {
151
- email: '',
152
- remember: false,
153
- },
154
- });
155
- ```
156
-
157
- `defaultValues`와 다른 `CreateForm` options는 component-owned form을 한 번만 생성한다. `ReactFormOptions`는 현재 render의 `values`와 plain `resetOptions`도 받는다. 처음 정의된 값과 이후 `Object.is` identity가 달라진 값마다 `form.reset(values, resetOptions)`를 호출한다. `undefined`는 reset 없이 동기화를 중단하고, 마지막으로 정의되었던 같은 object를 다시 전달해도 no-op이다. `resetOptions`만 바꾸는 것도 no-op이며 새 `values` reference가 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
- Values effect는 component unmount 시 종료된다. `useForm(existingForm)` overload는 기존 동작을 유지하며 external-value synchronization을 설치하지 않는다.
171
-
172
- React adapter의 첫 버전 hook은 세 가지다. `useRegister`는 단일, 배열, rest-argument 등록을 모두 처리하도록 overload되어 있다.
173
-
174
- | Hook | Purpose |
175
- | --- | --- |
176
- | `useRegister(options)` | 단일 field의 input binding props를 반환한다: `name`, `type`, `value`, `checked`, `onChange`, `onBlur`, `onFocus`. 기본 input `type`은 `text`다. |
177
- | `useRegister<TElement>(options[])` | map-friendly rendering을 위해 여러 binding props를 입력 순서대로 반환한다. select/textarea에 spread할 때는 `HTMLSelectElement` 또는 `HTMLTextAreaElement` generic으로 좁힌다. |
178
- | `useRegister(optionA, optionB)` | 여러 binding을 rest arguments로 받는다. 내부적으로 options array처럼 처리한다. |
179
- | `useField(options)` | 한 field에 대해 `{ props, value, setValue, errors, dirty, touched }`를 반환한다. `field.register`는 의도적으로 노출하지 않는다. |
180
- | `useFormState()` | `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, `submitCount` 같은 form 전체 aggregate state를 반환한다. |
181
-
182
- Field-local schema는 `useRegister` 또는 `useField`에 전달할 수 있다. 해당 field에 대해서는 field-local schema가 form-level schema보다 우선한다.
183
-
184
- ```tsx
185
- const email = useField({
186
- name: 'email',
187
- schema: emailSchema,
188
- });
189
- ```
190
-
191
- Event model은 DOM event 중심이다. Custom component도 DOM-compatible `value`, `checked`, `onChange`, `onBlur`, `onFocus` props를 그대로 전달한다면 `useRegister`를 사용할 수 있다.
192
-
193
-
194
- ## Vue adapter
195
-
196
- Vue binding은 `./vue` subpath로 노출된다. React adapter와 같은 `useForm(form)` 형태를 쓰지만, Vue template의 `v-bind`에 바로 전달할 수 있도록 `onInput`, `onChange`, `onBlur`, `onFocus` handler를 가진 props를 반환한다.
197
-
198
- `useForm`은 `VueFormOptions`도 받는다. `values` source는 `MaybeRefOrGetter<TValues | undefined>`이고 `resetOptions`는 plain이다. 처음 정의된 값과 이후 `Object.is` identity가 달라진 값마다 `form.reset(values, resetOptions)`를 호출한다. `undefined`는 reset 없이 동기화를 중단하고, 마지막으로 정의되었던 같은 object를 다시 emit해도 no-op이다. 변경을 추적하려면 `ref`, `computed`, getter를 전달하라. 평면 값은 한 번만 평가된다. Reactive values에는 active Vue effect scope가 필요하며, scope가 없으면 adapter는 form을 만들기 전에 실패한다. Watcher는 해당 scope와 함께 중지되며 `useForm(existingForm)`은 watcher를 설치하지 않는다.
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'],
225
- });
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
- ```
262
-
263
- Vue adapter도 같은 세 가지 개념을 노출한다.
264
-
265
- | Composable | Purpose |
266
- | --- | --- |
267
- | `useRegister(options)` | 하나의 input 중심 `v-bind` binding object를 반환한다. `type`이 포함되고 기본값은 `text`다. Text input은 `input` event에서, checkbox/radio는 `change` event에서 값을 갱신한다. select/textarea 타입은 generic으로 좁힌다. |
268
- | `useRegister(options[])` / `useRegister(optionA, optionB)` | map-friendly rendering을 위해 여러 binding object를 반환한다. |
269
- | `useField(options)` | getter 기반 reactive read를 가진 `{ props, value, setValue, errors, dirty, touched }`를 반환한다. |
270
- | `useFormState()` | `errors`, `dirtyFields`, `touchedFields`, `focusedField`, `isDirty`, `isValid`, `submitCount` 같은 form 전체 aggregate getter를 반환한다. |
271
-
272
- Field-local schema는 React와 같은 방식으로 동작하고 현재 Vue effect scope가 정리될 때 함께 cleanup된다.
273
-
274
- ## Solid adapter
275
-
276
- Solid binding은 `./solid` subpath로 노출된다. React/Vue와 같은 `useForm(form)` 형태를 유지하되, Solid owner cleanup과 getter 기반 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
- ```
315
-
316
- Solid adapter는 Vue와 같은 의미의 `useRegister`, `useField`, `useFormState`를 제공한다. Text input은 `input` event에서, checkbox/radio/multiple select는 `change` event에서 갱신하고, field-local schema는 현재 Solid owner와 함께 dispose된다.
317
-
318
- Component-owned form에서는 `SolidFormOptions`가 `values`를 `Accessor<TValues | undefined>`로 받고 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
- 처음 정의된 accessor 값과 이후 `Object.is` identity가 달라진 값마다 form을 reset한다. `undefined`는 reset 없이 동기화를 중단하고, 마지막으로 정의되었던 같은 object를 다시 emit해도 no-op이며, `resetOptions`는 value-driven reset에만 적용된다. Reactive values에는 active Solid owner가 필요하며, owner가 없으면 adapter는 form을 만들기 전에 실패한다. Tracking은 해당 owner와 함께 dispose된다. `useForm(existingForm)`은 tracking을 설치하지 않는다.
330
-
331
- ## Svelte adapter
332
-
333
- Svelte binding은 `./svelte` subpath로 노출된다. Adapter는 register action과 함께 form-wide 및 field-local state를 위한 readable store를 제공한다.
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
- Svelte action은 DOM synchronization을 직접 담당한다. `useField`는 `$email`로 소비하는 `Readable<SvelteFieldSnapshot>`이며 최신 `value`, `errors`, `dirty`, `touched`를 emit하고 마지막 subscriber가 해제되면 core subscription도 정리한다.
372
-
373
- Component-owned form에서는 `SvelteFormOptions`가 `values`를 `Readable<TValues | undefined>`로 받고 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
- 처음 정의된 emission과 이후 `Object.is` identity가 달라진 emission마다 form을 reset한다. `undefined`는 reset 없이 동기화를 중단하고, 마지막으로 정의되었던 같은 object를 다시 emit해도 no-op이며, `resetOptions`는 value-driven reset에만 적용된다. 이 overload는 component initialization 중 호출해야 하며 subscription은 unmount 시 종료된다. `useForm(existingForm)`은 external values를 구독하지 않는다.
390
-
391
- ## Core concepts
392
-
393
- ### `FieldPathSegment`
394
-
395
- 하나의 path segment는 string object key 또는 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
- `FieldPath`는 form field path의 내부 tuple 표현이다.
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
- Root path는 primitive root value나 root-level schema error에 유용하다.
428
-
429
- ### `FieldPathInput`
430
-
431
- Public API는 string field name 또는 tuple path를 받는다.
432
-
433
- ```ts
434
- type FieldPathInput = string | FieldPath;
435
- ```
436
-
437
- String은 dot path로 파싱되지 않는다. 그래서 nested path와 `.` 문자를 실제로 포함한 object key가 충돌하지 않는다.
438
-
439
- ### `PathKey`
440
-
441
- `FormState.fields`와 `FormState.arrayKeys`는 string key가 필요하다. `FormPath`는 tuple path를 안정적인 string key로 변환한다.
442
-
443
- | FieldPath | PathKey |
444
- | --- | --- |
445
- | `[]` | `$` |
446
- | `['email']` | `["email"]` |
447
- | `['user', 'name']` | `["user","name"]` |
448
- | `['items', 0, 'title']` | `["items",0,"title"]` |
449
-
450
- 구현은 separator 기반 문자열 대신 JSON array string을 사용한다. 그래서 `"user.name"` 같은 literal field name도 안전하다.
451
-
452
- ### `FieldState`
453
-
454
- `FieldState`는 하나의 leaf field가 가진 value와 metadata를 저장한다.
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
- Flag의 의미:
468
-
469
- - `touched`: field가 한 번 이상 blur되었다.
470
- - `dirty`: 현재 value가 같은 path의 initial value와 `Object.is` 기준으로 다르다.
471
- - `modified`: `source: 'user'` write로 field가 변경되었다.
472
- - `isFocused`: field가 현재 focus 중이다. `focus()`가 `true`로, `blur()`가 (`validateOn`과 무관하게 항상) `false`로 설정한다.
473
- - `errors`: validation 또는 manual assignment로 붙은 field errors.
474
-
475
- ### `FormState`
476
-
477
- Internal snapshot은 정규화되어 있다.
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
- 다음 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
- Core는 leaf field states와 array container keys를 따로 저장한다.
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()`는 `fields`와 `arrayKeys`에서 nested object를 복원한다.
520
-
521
- ### `FormError`
522
-
523
- ```ts
524
- type FormError = {
525
- type?: string;
526
- message: string;
527
- };
528
- ```
529
-
530
- Schema error는 `type: 'standard_schema'`를 사용한다. `setErrors()`로 error를 직접 설정할 수도 있다.
531
-
532
- ### `ValidationTrigger`
533
-
534
- ```ts
535
- type ValidationTrigger = 'change' | 'blur' | 'submit' | 'manual';
536
- ```
537
-
538
- `validateOn`은 automatic validation을 제어한다. 생략하면 기본값은 `['submit']`이다. Manual validation은 `trigger()`로 언제든 실행할 수 있다.
539
-
540
- ### `StandardSchemaV1`
541
-
542
- Core는 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
- 실패 시 `validate()`는 `issues`를 반환한다. 각 issue path는 `FieldPath`로 변환되고, 다시 `PathKey`로 변환된 뒤 해당 `FieldState.errors`에 기록된다.
557
-
558
- ### Field-local schemas
559
-
560
- Framework adapter는 single field에 대한 schema를 등록할 수 있다.
561
-
562
- ```ts
563
- const cleanup = form.registerFieldSchema('email', {
564
- schema: emailSchema,
565
- });
566
- ```
567
-
568
- Field-local schema가 있으면 해당 field는 form-level schema 대신 그 schema를 사용한다.
569
-
570
- ```txt
571
- field-local schema > form-level schema
572
- ```
573
-
574
- Cleanup function은 자신이 등록한 schema가 여전히 해당 field의 최신 registration일 때만 제거한다.
575
-
576
- ### `ArrayKeys`
577
-
578
- Array item identity는 array values와 별도로 저장된다.
579
-
580
- - `defaultValues`에서 온 item은 deterministic key를 받는다: `initial-0`, `initial-1`, ...
581
- - Runtime insertion은 generated key를 받는다: `item-1`, `item-2`, ...
582
- - `move()`와 `swap()`은 value와 함께 key를 이동시킨다.
583
- - `replace()`는 모든 새 item에 새 key를 만들고 old child metadata를 보존하지 않는다.
584
-
585
- 이 key들은 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. reset/dirty 기준값으로도 사용된다.
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
- 현재 `FormState` snapshot을 반환한다.
610
-
611
- ```ts
612
- const state = form.getState();
613
- console.log(state.submitCount);
614
- ```
615
-
616
- 반환된 object는 read-only로 취급해야 한다.
617
-
618
- ### `subscribe(listener)`
619
-
620
- Store change를 구독하고 unsubscribe function을 반환한다.
621
-
622
- ```ts
623
- const unsubscribe = form.subscribe(() => {
624
- console.log(form.getValues());
625
- });
626
-
627
- unsubscribe();
628
- ```
629
-
630
- Framework adapter는 이 method를 사용해 core store와 reactive rendering을 연결한다.
631
-
632
- ### `registerFieldSchema(path, options)`
633
-
634
- Field-local schema를 등록하고 cleanup function을 반환한다.
635
-
636
- ```ts
637
- const cleanup = form.registerFieldSchema('email', {
638
- schema: emailSchema,
639
- });
640
-
641
- cleanup();
642
- ```
643
-
644
- 이 API는 주로 framework adapter를 위한 것이다. Field-local schema는 `blur()`, `trigger()`, `submit()` 동안 해당 field에서 form-level schema보다 우선한다.
645
-
646
- ### `getFieldState(path)`
647
-
648
- Path에 해당하는 `FieldState`를 반환한다. Field가 아직 존재하지 않아도 `undefined` 대신 default field state를 반환한다.
649
-
650
- ```ts
651
- const email = form.getFieldState('email');
652
- ```
653
-
654
- ### `getValue(path)`
655
-
656
- 현재 field value만 반환한다.
657
-
658
- ```ts
659
- const email = form.getValue('email');
660
- ```
661
-
662
- ### `getValues()`
663
-
664
- 전체 nested values object를 복원해 반환한다.
665
-
666
- ```ts
667
- const values = form.getValues();
668
- ```
669
-
670
- ### `setValue(path, value, options?)`
671
-
672
- 하나의 field value를 쓴다.
50
+ console.log(form.getFieldState('email').dirty); // true
51
+ console.log(form.getValues().profile.name); // Grace
673
52
 
674
- ```ts
675
- form.setValue(['user', 'name'], 'Grace', {
676
- source: 'user',
677
- validate: true,
53
+ await form.submit(values => {
54
+ console.log(values.email);
678
55
  });
679
56
  ```
680
57
 
681
- Effects:
682
-
683
- 1. Public path input을 internal tuple path로 변환한다.
684
- 2. 새 value를 해당 `FieldState`에 쓴다.
685
- 3. 같은 path의 `defaultValues`와 비교해 `dirty`를 다시 계산한다.
686
- 4. `source === 'user'`일 때만 `modified`를 `true`로 만든다.
687
- 5. `options.validate`가 true이거나 `validateOn`에 `'change'`가 있으면 change validation을 시작한다.
688
-
689
- `setValue()`는 `void`를 반환한다. Change validation은 async로 시작되며 method가 await하지 않는다.
690
-
691
- Async validation은 target-aware하게 동작한다. 새 validation은 겹치는 field만 supersede하며 서로 독립적인 field validation은 동시에 완료될 수 있다. Full-form submit validation은 자신이 검증한 value snapshot도 확인한다. stale submit은 authoritative result를 얻을 때까지 재검증하며 기본값으로 `onValid`를 호출하지 않는다.
692
-
693
- ### `blur(path)`
694
-
695
- Field를 touched 처리하고 필요하면 validate한다.
696
-
697
- ```ts
698
- const valid = await form.blur('email');
699
- ```
700
-
701
- `validateOn`에 `'blur'`가 없으면 field를 touch한 뒤 `true`를 반환한다.
702
-
703
- ### `focus(path)`
704
-
705
- `path`에 해당하는 field의 `isFocused`를 `true`로 바꾼다. 다른 field는 건드리지 않는다 — DOM이 이전에 focus 되어 있던 element에 자연스럽게 `blur` 이벤트를 발생시키므로, `blur()`를 통해 `isFocused`가 clearing된다. Array rebasing 시 `isFocused`는 `move`/`swap`/`insert`/`remove`에 대해 보존된다.
706
-
707
- core는 DOM과 독립적이므로 여러 field에 `focus()`를 호출하면 둘 이상이 동시에 `isFocused: true`가 될 수 있다. DOM 어댑터에서는 브라우저가 자연스럽게 한 번에 하나로 제한하지만, core를 직접 사용할 때는 이전 field를 `blur()` 하는 것은 호출자의 책임이다. `useFormState().focusedField` aggregate는 **`Object.entries` 순서상 첫 번째**로 발견된 focused field를 반환하며, "가장 최근에 focus 된 field"가 아니다. 모든 focused field를 알려면 `state.fields`를 직접 순회하라.
708
-
709
- ### `setErrors(path, errors)`
710
-
711
- 하나의 field error list를 교체한다.
712
-
713
- ```ts
714
- form.setErrors('email', [{ message: 'Email is required' }]);
715
- ```
716
-
717
- ### `clearErrors(...paths)`
718
-
719
- 특정 field들의 errors를 비우거나, path를 넘기지 않으면 existing field 전체 errors를 비운다.
720
-
721
- ```ts
722
- form.clearErrors('email');
723
- form.clearErrors();
724
- ```
725
-
726
- ### `trigger(...paths)`
727
-
728
- Manual validation을 실행한다.
729
-
730
- ```ts
731
- await form.trigger('email');
732
- await form.trigger();
733
- ```
734
-
735
- Path가 있으면 full schema result에서 해당 field errors만 update한다. Path가 없으면 registered fields와 schema error keys 전체를 update한다.
736
-
737
- ### `array(path)`
738
-
739
- Array field를 위한 `FormArray` controller를 반환한다.
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
- Array controller는 command가 실행될 때마다 store에서 최신 values와 keys를 읽는다.
750
-
751
- ### `reset(values?, options?)`
752
-
753
- Form을 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
- Argument가 없으면 현재 `defaultValues`를 재사용한다. Argument가 있으면 그 값이 새로운 `defaultValues`가 된다.
762
-
763
- Reset options는 새 normalized value shape에도 살아남은 field path에 대해 일부 상태를 보존한다.
764
-
765
- | Option | Behavior |
766
- | --- | --- |
767
- | `keepDirtyValues` | dirty field의 현재 value를 유지하고 새 `defaultValues` 기준으로 dirty를 다시 계산한다. |
768
- | `keepErrors` | 살아남은 field path의 errors를 유지한다. |
769
- | `keepTouched` | 살아남은 field path의 touched flag를 유지한다. |
770
- | `keepSubmitState` | `submitCount`, `isSubmitting`, `isSubmitted`, `isSubmitSuccessful`을 유지한다. |
771
-
772
- ### `submit(onValid, onInvalid?)`
773
-
774
- `submitCount`를 증가시키고 form을 validate한 뒤 알맞은 callback을 호출한다.
775
-
776
- ```ts
777
- const result = await form.submit(
778
- values => values,
779
- fields => {
780
- console.log(fields);
781
- },
782
- );
783
- ```
784
-
785
- Validation이 실패하면 `onInvalid`는 현재 `fields` object를 받고 `submit()`은 `undefined`를 반환한다. Validation이 성공하면 `onValid`는 복원된 values를 받는다.
786
-
787
- ### `FormArray.keys()`
788
-
789
- 현재 array items를 rendering하기 위한 stable keys를 반환한다.
790
-
791
- ```ts
792
- const keys = form.array('items').keys();
793
- ```
794
-
795
- ### `FormArray.insert(index, value)`
796
-
797
- Item을 삽입한다. Out-of-range index는 `0...length` 범위로 보정된다.
798
-
799
- ### `FormArray.push(value)`
800
-
801
- Item을 끝에 추가한다.
802
-
803
- ### `FormArray.remove(index)`
804
-
805
- Item을 제거한다. Invalid index는 무시된다.
806
-
807
- ### `FormArray.move(fromIndex, toIndex)`
808
-
809
- Item 하나를 이동한다. Invalid index 또는 no-op move는 무시된다.
810
-
811
- ### `FormArray.swap(leftIndex, rightIndex)`
812
-
813
- 두 item을 교환한다. Invalid index 또는 같은 index는 무시된다.
814
-
815
- ### `FormArray.replace(values)`
816
-
817
- Array 전체를 교체한다. 기존 item link를 의도적으로 끊기 때문에 child field metadata는 보존되지 않는다.
818
-
819
- ## Runtime flows
820
-
821
- ### Form creation flow
822
-
823
- ```txt
824
- new CreateForm(options)
825
- -> new FormStateStore(options.defaultValues)
826
- -> FormStateInitializer.initialize(defaultValues)
827
- -> fields for leaf values
828
- -> arrayKeys for array containers
829
- -> new ValidationEngine(store, options)
830
- -> new FormFieldCommands(store, validation)
831
- -> new FormArrayFactory(store)
832
- -> new FormSubmitter(store, validation)
833
- ```
834
-
835
- 핵심은 모든 collaborator가 같은 `FormStateStore`를 공유한다는 점이다.
836
-
837
- ### Value write flow
838
-
839
- ```txt
840
- form.setValue(path, value, options)
841
- -> FormFieldCommands.setValue()
842
- -> FormPath.toFieldPath(path)
843
- -> FormStateStore.setValue()
844
- -> FormStateWriter.setValue()
845
- -> compute dirty from defaultValues
846
- -> optionally mark modified
847
- -> optionally start change validation
848
- ```
849
-
850
- `dirty`와 `modified`는 의도적으로 분리되어 있다. Programmatic write는 field를 dirty하게 만들 수 있지만 user-modified로 표시하지 않을 수 있다.
851
-
852
- ### Blur flow
853
-
854
- ```txt
855
- form.blur(path)
856
- -> FormFieldCommands.blur()
857
- -> FormPath.pathInputToKey(path)
858
- -> FormStateStore.touchField(key)
859
- -> if validateOn includes 'blur': ValidationEngine.validateField(key, 'blur')
860
- -> otherwise return true
861
- ```
862
-
863
- ### Manual validation flow
864
-
865
- ```txt
866
- form.trigger(...paths)
867
- -> no paths: validateRegisteredFields('manual')
868
- -> with paths: validateFields(keys, 'manual')
869
- -> StandardSchemaValidator.validate(values)
870
- -> issue paths become PathKeys
871
- -> selected field errors are replaced
872
- ```
873
-
874
- Field-level validation도 full schema를 실행한 뒤 target field errors만 적용한다. 이렇게 하면 schema adapter가 단순하고 schema-library independent하게 유지된다.
875
-
876
- ### Submit flow
877
-
878
- ```txt
879
- form.submit(onValid, onInvalid)
880
- -> increment submitCount
881
- -> validateRegisteredFields('submit')
882
- -> invalid: onInvalid(fields), return undefined
883
- -> valid: onValid(getValues())
884
- ```
885
-
886
- `submitCount`는 successful submissions가 아니라 submit attempts를 기록한다.
887
-
888
- ### Array mutation flow
889
-
890
- ```txt
891
- form.array('items').move(1, 0)
892
- -> FormArrayController.move()
893
- -> read current array values and keys
894
- -> FormArrayMutationPlanner.move()
895
- -> next values
896
- -> next keys
897
- -> previous-index to next-index mapper
898
- -> FormArrayRebaser.rebase()
899
- -> write next array into values
900
- -> initialize a fresh FormState from next values
901
- -> preserve non-array fields
902
- -> move child metadata through the index mapper
903
- -> write next array keys
904
- ```
905
-
906
- 이 흐름이 `items[1].name` metadata를 동일한 logical item에 붙인 채 그 item이 `items[0].name`으로 이동하게 만드는 핵심 기능이다.
907
-
908
- ## Internal architecture
909
-
910
- ```txt
911
- src/index.ts
912
- -> src/core/index.ts
913
- -> form/CreateForm.ts
914
- -> state/FormStateStore.ts
915
- -> state/FormStateInitializer.ts
916
- -> state/FormStateReader.ts
917
- -> state/FormStateWriter.ts
918
- -> form/FormFieldCommands.ts
919
- -> validation/ValidationEngine.ts
920
- -> validation/StandardSchemaValidator.ts
921
- -> form/FormSubmitter.ts
922
- -> array/FormArrayFactory.ts
923
- -> array/FormArrayController.ts
924
- -> array/FormArrayMutationPlanner.ts
925
- -> array/FormArrayRebaser.ts
926
- -> array/FormArrayPath.ts
927
- -> array/ArrayItemReorder.ts
928
- -> array/ArrayKeyGenerator.ts
929
- -> path/FormPath.ts
930
- -> value/ValueHelper.ts
931
- -> types.ts
932
- -> src/adapters/
933
- -> dom/FieldValue.ts
934
- -> dom/RegisterBinding.ts
935
- -> FormStateSummary.ts
936
- -> src/react/index.ts
937
- -> shared adapter logic 위의 React hook adapter
938
- -> src/vue/index.ts
939
- -> shared adapter logic 위의 Vue composable adapter
940
- -> src/solid/index.ts
941
- -> shared adapter logic 위의 Solid helper adapter
942
- -> src/svelte/index.ts
943
- -> shared adapter logic 위의 Svelte action adapter
944
- ```
945
-
946
- Responsibility summary:
947
-
948
- | Area | Responsibility |
949
- | --- | --- |
950
- | `form/` | Public orchestration: field commands, submit flow, array controller access. |
951
- | `state/` | Normalized state initialization, reading, writing, and store facade. |
952
- | `path/` | Conversion between public path input, tuple paths, and string path keys. |
953
- | `value/` | Immutable nested get/set and reconstruction of values from field states. |
954
- | `validation/` | Standard Schema execution and error normalization. |
955
- | `array/` | Array item key management, mutation planning, and child field metadata rebasing. |
956
- | `adapters/` | 내부 shared adapter logic: DOM value extraction/binding, form-state aggregation. |
957
- | `react/` | Public `Form` interface를 감싸는 React hook adapter. |
958
- | `vue/` | Public `Form` interface를 감싸는 Vue composable adapter. |
959
- | `solid/` | Public `Form` interface를 감싸는 Solid helper adapter. |
960
- | `svelte/` | Public `Form` interface를 감싸는 Svelte action adapter. |
961
- | `types.ts` | Public and internal TypeScript contracts. |
962
-
963
- ## Core walkthrough
964
-
965
- ### `src/index.ts`
966
-
967
- Package root는 안정적인 framework-agnostic surface만 export한다.
968
-
969
- ```ts
970
- export { CreateForm } from './core/index';
971
- export type {
972
- CreateFormOptions,
973
- FieldPathInput,
974
- Form,
975
- FormError,
976
- StandardSchemaV1,
977
- } from './core/index';
978
- ```
979
-
980
- Internal state와 command helper 타입은 package root에서 내보내지 않는다. 이 문서에서는 구현 설명을 위해 다루지만, consumer는 `Form`, `CreateForm`, field path, errors, Standard Schema contract를 통해 사용해야 한다.
981
-
982
- ### `src/core/index.ts`
983
-
984
- 이 파일은 `types.ts`의 public types와 `CreateForm`을 re-export한다. Package root와 implementation folders 사이의 boundary다.
985
-
986
- ### `src/core/types.ts`
987
-
988
- `types.ts`는 core vocabulary를 정의한다.
989
-
990
- - public path type: `FieldPathInput`; internal path concepts: `FieldPathSegment`, `FieldPath`, `PathKey`
991
- - exported validation types: `FormError`, `StandardSchemaV1`; internal validation trigger type: `ValidationTrigger`
992
- - internal state types: `FieldState`, `ArrayKeys`, `FormState`
993
- - public API types: `CreateFormOptions`, `Form`; internal command helper types: `FormArray`, `SetValueOptions`
994
-
995
- 이 파일에서 가장 중요한 설계는 public string path가 literal field name이라는 점이다. Nested field에는 tuple path가 필요하다.
996
-
997
- ### `src/core/form/CreateForm.ts`
998
-
999
- `CreateForm`은 top-level controller이자 main public class다.
1000
-
1001
- 네 collaborator를 소유한다.
1002
-
1003
- ```txt
1004
- store -> state storage and state operations
1005
- fields -> setValue, blur, errors, trigger
1006
- arrays -> array(path) controller creation
1007
- submitter -> submitCount, validation, callbacks
1008
- ```
1009
-
1010
- Constructor는 하나의 `FormStateStore`를 만들고 모든 collaborator에 전달한다. 그래서 모든 command는 같은 snapshot 위에서 동작한다.
1011
-
1012
- 대부분의 method는 얇은 delegation이다.
1013
-
1014
- - `getState()`, `getFieldState()`, `getValue()`, `getValues()`, `reset()`은 `FormStateStore`에 위임한다.
1015
- - `setValue()`, `blur()`, `focus()`, `setErrors()`, `clearErrors()`, `trigger()`는 `FormFieldCommands`에 위임한다.
1016
- - `array()`는 path를 tuple로 변환하고 `FormArrayFactory`에 controller를 요청한다.
1017
- - `submit()`은 `FormSubmitter`에 위임한다.
1018
-
1019
- 이 구조는 public API를 stable하게 유지하면서 implementation responsibilities를 분리한다.
1020
-
1021
- ### `src/core/form/FormFieldCommands.ts`
1022
-
1023
- `FormFieldCommands`는 field-level operations를 묶는다.
1024
-
1025
- `setValue()`:
1026
-
1027
- 1. `FormPath.toFieldPath()`로 path를 tuple로 변환한다.
1028
- 2. `store.setValue()`로 value를 쓴다.
1029
- 3. 결과 `PathKey`를 받는다.
1030
- 4. `options.validate`가 true이거나 `validateOn`에 `'change'`가 있으면 change validation을 시작한다.
58
+ 문자열은 실제 필드 이름입니다. `'profile.name'`과 `['profile', 'name']`은
59
+ 서로 다른 필드를 가리킵니다. `getState()` 스냅샷은 읽기 전용으로 다루세요.
60
+ `dirty`는 기본값과의 비교이고 `modified`는 사용자 입력에 의한 변경 기록입니다.
1031
61
 
1032
- `blur()`:
62
+ 이 예제에는 스키마가 없습니다. 검증하려면 Standard Schema 호환 `schema`를 추가하세요.
63
+ 자동 검증의 기본 시점은 submit입니다. `setValue()`는 `void`를 반환하며
64
+ change 검증을 기다리지 않습니다. 검증 완료를 기다리려면 `trigger()`를 사용하세요.
65
+ 배열의 `move()`와 `swap()`은 메타데이터를 유지하고 `replace()`는 의도적으로 버립니다.
1033
66
 
1034
- 1. Public path를 `PathKey`로 변환한다.
1035
- 2. Field를 touched 처리한다.
1036
- 3. 설정된 경우에만 blur validation을 실행한다.
67
+ 어댑터는 `/react`, `/vue`, `/solid`, `/svelte`에 있으므로 루트는 프레임워크와
68
+ DOM을 import하지 않습니다. 어댑터 소유자가 해제될 때 구독도 정리하세요.
1037
69
 
1038
- `focus()`는 field의 `isFocused`를 `true`로 바꾼다. 대응되는 `blur()` command가 `isFocused`를 clearing하고 (`validateOn` 설정과 무관하게 항상), field를 `touched`로 표시한다. `isFocused` flag는 array rebasing 시 보존된다.
70
+ <details>
71
+ <summary>개발</summary>
1039
72
 
1040
- `setErrors()`, `clearErrors()`, `trigger()`는 path를 key로 normalize하고 store 또는 validation engine에 위임한다.
1041
-
1042
- ### `src/core/form/FormSubmitter.ts`
1043
-
1044
- `FormSubmitter`는 submit-specific sequencing을 분리한다.
1045
-
1046
- ```txt
1047
- increment submitCount
1048
- validate all registered fields
1049
- if invalid -> call onInvalid(fields) and return undefined
1050
- if valid -> call onValid(getValues())
1051
- ```
1052
-
1053
- Submit은 multi-step command이므로 `CreateForm`이 validation branching까지 책임지지 않게 별도 class로 분리되어 있다.
1054
-
1055
- ### `src/core/state/FieldStateFactory.ts`
1056
-
1057
- `FieldStateFactory`는 default field state shape을 중앙화한다.
1058
-
1059
- ```ts
1060
- {
1061
- value: undefined,
1062
- errors: [],
1063
- touched: false,
1064
- dirty: false,
1065
- modified: false,
1066
- }
1067
- ```
1068
-
1069
- Shared mutable reference를 피하기 위해 매번 새 `errors` array를 만든다. 같은 factory는 initial leaf fields와 missing-field fallback에 모두 사용된다.
1070
-
1071
- ### `src/core/state/FormStateInitializer.ts`
1072
-
1073
- `FormStateInitializer.initialize(defaultValues)`는 nested values를 normalized `FormState`로 변환한다.
1074
-
1075
- Rules:
1076
-
1077
- 1. Arrays는 leaf field가 아니라 containers다.
1078
- 2. Array containers는 `initial-0`, `initial-1` 같은 `arrayKeys`를 받는다.
1079
- 3. Array items는 recursive하게 방문된다.
1080
- 4. Plain objects는 traverse된다.
1081
- 5. Empty plain object는 더 내려갈 field가 없으므로 leaf value로 저장된다.
1082
- 6. `Date`, class instance 같은 non-plain objects는 leaf value로 취급된다.
1083
- 7. Primitive와 `null`은 leaf value다.
1084
-
1085
- 그래서 `getState().fields`는 원래 nested object가 아니라 leaf paths를 가진다.
1086
-
1087
- ### `src/core/state/FormStateReader.ts`
1088
-
1089
- `FormStateReader`는 read-only derived operations를 담당한다.
1090
-
1091
- - `getKnownFieldPaths()`는 저장된 모든 `PathKey`를 tuple path로 되돌린다.
1092
- - `getFieldStateByKey()`는 existing field 또는 default `FieldState`를 반환한다.
1093
- - `getFieldState()`와 `getValue()`는 path-input convenience methods다.
1094
- - `getValues()`는 `ValueHelper.getValuesFromFields()`로 full nested value tree를 복원한다.
1095
- - `getValueAtPath()`는 먼저 values를 복원한 뒤 nested path를 읽는다.
1096
-
1097
- Reader는 store를 직접 소유하지 않고 snapshot getter를 받기 때문에 항상 최신 state를 읽는다.
1098
-
1099
- ### `src/core/state/FormStateWriter.ts`
1100
-
1101
- `FormStateWriter`는 모든 state mutation을 `immer`로 수행한다.
1102
-
1103
- > **번들 참고:** `immer`는 컨슈머 번들에 ~5KB를 추가한다. `FormState`가 flat `Record<PathKey, FieldState>` 구조이므로 spread 기반 업데이트(`{ ...state, [key]: nextField }`)로 immer를 대체해도 동작이 동일하다. 마이그레이션 전에 벤치마크하라 — immer는 구조 공유와 가독성 이점을 제공하며, array rebasing 경로에서는 크기 비용을 상회할 수 있다.
1104
-
1105
- `setValue()`:
1106
-
1107
- - Tuple path를 `PathKey`로 변환한다.
1108
- - 해당 tuple path의 initial value를 읽는다.
1109
- - 가능하면 existing field metadata를 보존한다.
1110
- - `value`를 교체한다.
1111
- - `Object.is`로 `dirty`를 계산한다.
1112
- - `source: 'user'`일 때만 `modified`를 설정한다.
1113
- - Validation이 재사용할 수 있도록 `PathKey`를 반환한다.
1114
-
1115
- Other methods:
1116
-
1117
- - `touchField()`는 `touched: true`를 설정한다.
1118
- - `setErrorsByKey()`는 error array를 교체한다.
1119
- - `clearErrors()`는 target fields 또는 existing fields 전체 errors를 비운다.
1120
- - `reset()`은 현재 또는 replacement initial values로 state를 다시 초기화한다.
1121
- - `incrementSubmitCount()`는 attempts를 증가시킨다.
1122
- - `replaceState()`는 array rebasing 같은 whole-state operation을 위한 escape hatch다.
1123
-
1124
- ### `src/core/state/FormStateStore.ts`
1125
-
1126
- `FormStateStore`는 core의 다른 부분들이 사용하는 facade다.
1127
-
1128
- 소유하는 것:
1129
-
1130
- - `@ilokesto/store`의 `Store<FormState<TValues>>`
1131
- - `FormStateReader`
1132
- - `FormStateWriter`
1133
-
1134
- Collaborator들은 operation이 reader, writer, underlying store 중 어디에서 구현되는지 알 필요가 없다. Facade만 호출하면 된다.
1135
-
1136
- ### `src/core/path/FormPath.ts`
1137
-
1138
- `FormPath`는 path conversion rules를 정의한다.
1139
-
1140
- Key methods:
1141
-
1142
- - `path(...segments)`: tuple path helper.
1143
- - `toFieldPath(input)`: string은 `[input]`이 되고 tuple path는 그대로 통과한다.
1144
- - `pathInputToKey(input)`: public path input을 `PathKey`로 변환한다.
1145
- - `pathToKey(path)`: `[]`는 `$`, 나머지는 tuple을 JSON stringify한다.
1146
- - `keyToPath(key)`: key를 tuple segments로 parse하고 validate한다.
1147
-
1148
- JSON encoding이 path collision을 방지한다.
1149
-
1150
- > **성능 참고:** `pathToKey`는 `JSON.stringify`를, `keyToPath`는 `JSON.parse`를 사용한다. 큰 폼(수백 필드)에서 잦은 업데이트 시 NUL separator 기반 커스텀 인코딩으로 hot path 오버헤드를 줄일 수 있다. 마이그레이션 전에 벤치마크하라 — 현재 접근은 정확하고 읽기 쉬우며 실제 영향은 보통 미미하다.
1151
-
1152
- ### `src/core/value/ValueHelper.ts`
1153
-
1154
- `ValueHelper`는 immutable nested value operations를 제공한다.
1155
-
1156
- `getValueAtPath(source, path)`는 object/array를 안전하게 walk한다. 중간 value가 nullish이거나 primitive이면 `undefined`를 반환한다.
1157
-
1158
- `setValueAtPath(source, path, value)`는 new root value를 반환하고 path를 따라 container를 shallow-clone한다. Missing container는 next segment로 추론한다. Number면 array를 만들고 string이면 object를 만든다.
1159
-
1160
- `getValuesFromFields(state, fieldPaths)`는 public values를 두 단계로 복원한다.
1161
-
1162
- 1. `arrayKeys`에서 empty array containers를 만든다.
1163
- 2. 모든 leaf field value를 tuple path 위치에 쓴다.
1164
-
1165
- 이 과정을 통해 normalized `fields`가 다시 nested object가 된다.
1166
-
1167
- ### `src/core/validation/ValidationEngine.ts`
1168
-
1169
- `ValidationEngine`은 validation triggers와 store writes를 조율한다.
1170
-
1171
- - Default `validateOn`은 `['submit']`이다.
1172
- - Schema가 없으면 validation은 error 없이 성공한다.
1173
- - `validateField(key, trigger)`는 full schema를 실행하고 해당 field errors만 적용한다.
1174
- - `validateFields(keys, trigger)`는 full schema를 실행하고 selected fields errors만 적용한다.
1175
- - `validateRegisteredFields(trigger)`는 full schema를 실행하고 current fields와 schema error keys 전체를 update한다.
1176
-
1177
- Engine은 schema를 호출할 때 trigger value를 전달하지 않는다. Trigger는 engine이 언제 실행될지를 제어하지 schema API를 바꾸지 않는다.
1178
-
1179
- `ValidationSequencer`는 full-form revision과 field별 revision을 추적한다. 겹치는 작업만 stale 처리하고 독립 field 작업은 유지하며, error나 submit callback을 적용하기 전에 captured field-value 및 array-shape snapshot이 최신인지 확인한다.
1180
-
1181
- ### `src/core/validation/StandardSchemaValidator.ts`
1182
-
1183
- `StandardSchemaValidator`는 Standard Schema result를 core errors로 adapt한다.
1184
-
1185
- Success:
1186
-
1187
- ```ts
1188
- { valid: true, errorsByKey: {} }
1189
- ```
1190
-
1191
- Failure:
1192
-
1193
- ```ts
1194
- {
1195
- valid: false,
1196
- errorsByKey: {
1197
- '["email"]': [{ type: 'standard_schema', message: 'Email is invalid' }],
1198
- },
1199
- }
1200
- ```
1201
-
1202
- Issue path conversion rules:
1203
-
1204
- - Missing path 또는 empty path는 root path `[]`와 key `$`가 된다.
1205
- - String과 number path segment는 그대로 보존된다.
1206
- - Object path segment는 `.key` property를 사용한다.
1207
- - Symbol 같은 unsupported key는 root error로 fallback된다.
1208
-
1209
- ### `src/core/array/ArrayKeyGenerator.ts`
1210
-
1211
- `ArrayKeyGenerator`는 runtime item keys를 만든다.
1212
-
1213
- ```txt
1214
- item-1
1215
- item-2
1216
- item-3
1217
- ```
1218
-
1219
- 하나의 `FormArrayFactory`는 form instance마다 하나의 generator를 공유한다. 이렇게 하면 여러 controller 사이에서 accidental key collision 가능성을 줄인다.
1220
-
1221
- ### `src/core/array/ArrayItemReorder.ts`
1222
-
1223
- `ArrayItemReorder`는 array order operations를 위한 pure helper다.
1224
-
1225
- - `moveItem(items, from, to)`는 reordered copy를 반환한다.
1226
- - `swapItems(items, left, right)`는 swapped copy를 반환한다.
1227
- - `createIndexMapper(previousLength, nextOrder)`는 previous index를 next index로 mapping하는 function을 반환한다.
1228
-
1229
- `nextOrder`는 "각 next position에는 어떤 previous index가 있는가?"로 표현된다. New item은 `-1`을 사용하고 removed item은 아예 등장하지 않는다.
1230
-
1231
- ### `src/core/array/FormArrayMutationPlanner.ts`
1232
-
1233
- `FormArrayMutationPlanner`는 store를 몰라도 array mutations를 계산한다.
1234
-
1235
- 각 mutation은 다음 형태를 반환한다.
1236
-
1237
- ```ts
1238
- type FormArrayMutation = {
1239
- values: readonly unknown[];
1240
- keys: readonly string[];
1241
- mapPreviousIndex: (index: number) => number | undefined;
1242
- };
1243
- ```
1244
-
1245
- Command behavior:
1246
-
1247
- - `insert()`는 target index를 보정하고 새 value/key를 삽입한다. New item은 `-1`에서 온 것으로 처리되어 previous metadata가 붙지 않는다.
1248
- - `push()`는 value/key를 끝에 추가한다.
1249
- - `remove()`는 value/key를 제거하고 removed index는 `undefined`로 map한다.
1250
- - `move()`는 같은 rule로 values와 keys를 이동한다.
1251
- - `swap()`은 같은 rule로 values와 keys를 교환한다.
1252
- - `replace()`는 모두 새 values/keys를 반환하고 모든 previous index를 `undefined`로 map한다.
1253
-
1254
- 이 planner는 pure하기 때문에 store와 독립적으로 test하기 쉽다.
1255
-
1256
- ### `src/core/array/FormArrayPath.ts`
1257
-
1258
- `FormArrayPath`는 rebasing 중 필요한 path helpers를 담는다.
1259
-
1260
- - `hasPathPrefix(fieldPath, prefix)`는 tuple prefix equality를 확인한다.
1261
- - `isArrayChildPath(fieldPath, arrayPath)`는 `['items']` 아래의 `['items', 0, 'name']`처럼 field가 array item 아래에 있는지 확인한다.
1262
- - `replaceArrayIndex(fieldPath, arrayPath, nextIndex)`는 item index가 교체된 새 child path를 만든다.
1263
-
1264
- ### `src/core/array/FormArrayController.ts`
1265
-
1266
- `FormArrayController`는 `form.array(path)`가 반환하는 public command object다.
1267
-
1268
- 보유하는 것:
1269
-
1270
- - shared `FormStateStore`
1271
- - shared `ArrayKeyGenerator`
1272
- - controlled array `FieldPath`
1273
- - `FormArrayMutationPlanner`
1274
-
1275
- 각 command는 같은 pattern을 따른다.
1276
-
1277
- ```txt
1278
- read current array value
1279
- read current keys
1280
- ask planner for next values, keys, and index mapper
1281
- if mutation exists, rebase the whole FormState
1282
- ```
1283
-
1284
- `getArray()`는 array path의 현재 value를 읽는다. Value가 array가 아니면 empty array를 사용한다.
1285
-
1286
- `getKeys()`는 stored `arrayKeys`를 읽는다. 없으면 current array length만큼 key를 만든다.
1287
-
1288
- ### `src/core/array/FormArrayFactory.ts`
1289
-
1290
- `FormArrayFactory`는 `FormArrayController` instances를 만들고 form instance를 위한 하나의 `ArrayKeyGenerator`를 공유한다.
1291
-
1292
- 이 덕분에 `form.array('items')`를 반복 호출해서 fresh controller를 만들어도 key sequence가 reset되지 않는다.
1293
-
1294
- ### `src/core/array/FormArrayRebaser.ts`
1295
-
1296
- `FormArrayRebaser`는 가장 중요한 array component다. Array mutation 뒤 values, field states, array keys, submit count를 정렬한다.
1297
-
1298
- Detailed sequence:
1299
-
1300
- 1. Current store에서 known field paths를 읽는다.
1301
- 2. `store.getValues()`로 current values를 복원한다.
1302
- 3. `ValueHelper.setValueAtPath()`로 next array를 values에 쓴다.
1303
- 4. Next values에서 fresh `FormState`를 initialize한다.
1304
- 5. Freshly initialized fields에서 시작한다.
1305
- 6. Previous fields를 순회한다.
1306
- 7. Changed array 밖의 fields는 보존한다.
1307
- 8. Changed array 안의 child fields는 previous item index를 next item index로 mapping한다.
1308
- 9. Item이 아직 존재하면 child path의 index를 교체하고 metadata를 new field로 copy한다.
1309
- 10. Array path에 next `arrayKeys`를 쓴다.
1310
- 11. `submitCount`를 보존한다.
1311
-
1312
- Rebased child field에 copy되는 것은 metadata뿐이다.
1313
-
1314
- ```txt
1315
- errors
1316
- touched
1317
- dirty
1318
- modified
1319
- ```
1320
-
1321
- Value 자체는 next values로부터 freshly initialized state에서 온다. 그래서 stale value를 방지하면서 user interaction metadata는 보존한다.
1322
-
1323
- ## Design decisions
1324
-
1325
- ### Strings are literal paths
1326
-
1327
- Dot-path parsing은 편하지만 모호하다. 이 core는 unambiguous tuple paths를 선택한다.
1328
-
1329
- ```ts
1330
- 'user.name' // one field named "user.name"
1331
- ['user', 'name'] // nested user.name field
1332
- ```
1333
-
1334
- ### State is normalized
1335
-
1336
- Normalized fields는 whole nested value object를 mutate하지 않고도 개별 metadata를 update하기 쉽게 만든다. `ValueHelper`는 필요할 때 public value shape을 복원한다.
1337
-
1338
- ### Validation is schema-library independent
1339
-
1340
- Core는 Standard Schema만 안다. 그래서 여러 validation library와 호환되고 특정 validator를 import하지 않는다.
1341
-
1342
- ### Array mutation is split into planning and rebasing
1343
-
1344
- `FormArrayMutationPlanner`는 next array가 어떤 모습인지 결정한다. `FormArrayRebaser`는 전체 form state가 어떻게 따라가야 하는지 결정한다. 이 분리는 mutation math를 pure하게 만들고 store updates를 중앙화한다.
1345
-
1346
- ### `dirty` and `modified` are different
1347
-
1348
- `dirty`는 current value와 initial value를 비교한다. `modified`는 user-originated writes를 추적한다. Programmatic update는 dirty일 수 있지만 user modified는 아닐 수 있다.
1349
-
1350
- ## Testing and development
1351
-
1352
- ### Commands
73
+ Node 24.22.1과 pnpm 10.17.1을 사용하고 저장소 루트에서 실행하세요.
1353
74
 
1354
75
  ```sh
1355
- pnpm build
76
+ pnpm install --frozen-lockfile
1356
77
  pnpm typecheck
1357
78
  pnpm test
1358
79
  ```
1359
80
 
1360
- `pnpm build`는 TypeScript로 declaration files를 emit하고, NodeNext 호환성을 위해 declaration-file relative specifier만 보정한 뒤, Vite로 ESM JavaScript를 bundle한다. 그래서 source import는 extensionless로 유지하면서도 `dist/index.js`, `dist/react/index.js`, `dist/vue/index.js`, `dist/solid/index.js`, `dist/svelte/index.js` 같은 adapter subpath는 ESM runtime에서 직접 import할 수 있다.
1361
-
1362
- `pnpm test`는 Vitest suite를 실행한다.
1363
-
1364
- ### Current test coverage themes
1365
-
1366
- Existing tests는 다음을 cover한다.
1367
-
1368
- 1. Tuple paths와 literal string names의 차이.
1369
- 2. Blur, manual trigger, submit에서의 Standard Schema validation.
1370
- 3. Move와 remove 시 array value/key/metadata rebasing.
1371
- 4. React adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema precedence.
1372
- 5. Vue adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema cleanup.
1373
- 6. Solid adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema cleanup.
1374
- 7. Svelte register action의 text input, checkbox, radio, select, multiple select, readable `useFormState`, field-local schema cleanup.
1375
-
1376
- ### Suggested future documentation/tests
81
+ `typecheck`는 라이브러리 코드를 검사합니다. `test`는 한 번 빌드한 뒤 `test:unit`, `test:tooling`, `test:pack`, 다섯 예제의 빌드·타입 검사를 실행합니다. 런타임 테스트는 `tests/unit`, fixture·setup은 `tests/fixtures`, Node 도구 테스트는 `tests/tooling`에 있습니다. `test:pack`을 단독 실행할 때는 먼저 `pnpm build`를 실행하세요.
1377
82
 
1378
- 좋은 추가 항목:
83
+ 빌드 결과는 `dist/`에 생성됩니다. `test:pack`은 레지스트리 Store를 사용하는 격리된
84
+ 소비자를 검사하고 예제 명령은 다섯 private 예제를 모두 확인합니다.
85
+ PR은 Verify CI를 실행합니다. main 병합은 Changesets 릴리스 PR을 생성·갱신하며,
86
+ 릴리스 PR을 병합하면 GitHub Actions가 성공한 Verify의 정확한 아티팩트만 게시합니다.
87
+ 적용 전에 `Allow GitHub Actions to create and approve pull requests`를 켜고
88
+ `Production` 환경에 `NPM_TOKEN`을 설정하세요. 로컬에서는 게시하지 않습니다.
1379
89
 
1380
- - `insert()` index bounding test.
1381
- - `replace()`가 child metadata를 의도적으로 drop하는지에 대한 test.
1382
- - Root-level schema errors test.
1383
- - Custom DOM-event-compatible component를 위한 adapter examples.
90
+ </details>