@ilokesto/form 1.0.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +153 -487
  3. package/README.md +155 -490
  4. package/dist/FormInput-DuT7QFe-.d.ts +37 -0
  5. package/dist/chunk-4F4SAGQ5.js +1465 -0
  6. package/dist/chunk-4F4SAGQ5.js.map +1 -0
  7. package/dist/chunk-JK644RR7.js +215 -0
  8. package/dist/chunk-JK644RR7.js.map +1 -0
  9. package/dist/index.d.ts +58 -2
  10. package/dist/index.js +3 -1
  11. package/dist/index.js.map +1 -0
  12. package/dist/react/index.d.ts +87 -2
  13. package/dist/react/index.js +131 -1
  14. package/dist/react/index.js.map +1 -0
  15. package/dist/solid/index.d.ts +89 -2
  16. package/dist/solid/index.js +170 -1
  17. package/dist/solid/index.js.map +1 -0
  18. package/dist/svelte/index.d.ts +68 -2
  19. package/dist/svelte/index.js +198 -1
  20. package/dist/svelte/index.js.map +1 -0
  21. package/dist/types-DBlvL6AC.d.ts +229 -0
  22. package/dist/vue/index.d.ts +87 -2
  23. package/dist/vue/index.js +192 -1
  24. package/dist/vue/index.js.map +1 -0
  25. package/package.json +15 -8
  26. package/dist/adapters/FormInput.d.ts +0 -8
  27. package/dist/adapters/FormInput.js +0 -10
  28. package/dist/adapters/FormStateSummary.d.ts +0 -14
  29. package/dist/adapters/FormStateSummary.js +0 -27
  30. package/dist/adapters/dom/FieldValue.d.ts +0 -2
  31. package/dist/adapters/dom/FieldValue.js +0 -34
  32. package/dist/adapters/dom/RegisterBinding.d.ts +0 -14
  33. package/dist/adapters/dom/RegisterBinding.js +0 -110
  34. package/dist/adapters/dom/SubmitHandler.d.ts +0 -9
  35. package/dist/adapters/dom/SubmitHandler.js +0 -6
  36. package/dist/adapters/dom/index.d.ts +0 -5
  37. package/dist/adapters/dom/index.js +0 -3
  38. package/dist/adapters/dom/types.d.ts +0 -22
  39. package/dist/adapters/dom/types.js +0 -1
  40. package/dist/core/array/ArrayItemReorder.d.ts +0 -6
  41. package/dist/core/array/ArrayItemReorder.js +0 -24
  42. package/dist/core/array/ArrayKeyGenerator.d.ts +0 -4
  43. package/dist/core/array/ArrayKeyGenerator.js +0 -7
  44. package/dist/core/array/FormArrayController.d.ts +0 -21
  45. package/dist/core/array/FormArrayController.js +0 -54
  46. package/dist/core/array/FormArrayFactory.d.ts +0 -8
  47. package/dist/core/array/FormArrayFactory.js +0 -13
  48. package/dist/core/array/FormArrayMutationPlanner.d.ts +0 -14
  49. package/dist/core/array/FormArrayMutationPlanner.js +0 -68
  50. package/dist/core/array/FormArrayPath.d.ts +0 -6
  51. package/dist/core/array/FormArrayPath.js +0 -11
  52. package/dist/core/array/FormArrayRebaser.d.ts +0 -7
  53. package/dist/core/array/FormArrayRebaser.js +0 -54
  54. package/dist/core/array/index.d.ts +0 -1
  55. package/dist/core/array/index.js +0 -1
  56. package/dist/core/form/CreateForm.d.ts +0 -23
  57. package/dist/core/form/CreateForm.js +0 -64
  58. package/dist/core/form/FormFieldCommands.d.ts +0 -15
  59. package/dist/core/form/FormFieldCommands.js +0 -40
  60. package/dist/core/form/FormSubmitter.d.ts +0 -9
  61. package/dist/core/form/FormSubmitter.js +0 -26
  62. package/dist/core/form/index.d.ts +0 -1
  63. package/dist/core/form/index.js +0 -1
  64. package/dist/core/index.d.ts +0 -2
  65. package/dist/core/index.js +0 -1
  66. package/dist/core/path/FormPath.d.ts +0 -9
  67. package/dist/core/path/FormPath.js +0 -36
  68. package/dist/core/path/index.d.ts +0 -1
  69. package/dist/core/path/index.js +0 -1
  70. package/dist/core/state/FieldStateFactory.d.ts +0 -6
  71. package/dist/core/state/FieldStateFactory.js +0 -19
  72. package/dist/core/state/FormStateInitializer.d.ts +0 -7
  73. package/dist/core/state/FormStateInitializer.js +0 -45
  74. package/dist/core/state/FormStateReader.d.ts +0 -11
  75. package/dist/core/state/FormStateReader.js +0 -30
  76. package/dist/core/state/FormStateStore.d.ts +0 -24
  77. package/dist/core/state/FormStateStore.js +0 -66
  78. package/dist/core/state/FormStateWriter.d.ts +0 -17
  79. package/dist/core/state/FormStateWriter.js +0 -107
  80. package/dist/core/state/index.d.ts +0 -1
  81. package/dist/core/state/index.js +0 -1
  82. package/dist/core/types.d.ts +0 -112
  83. package/dist/core/types.js +0 -1
  84. package/dist/core/validation/StandardSchemaValidator.d.ts +0 -14
  85. package/dist/core/validation/StandardSchemaValidator.js +0 -63
  86. package/dist/core/validation/ValidationEngine.d.ts +0 -25
  87. package/dist/core/validation/ValidationEngine.js +0 -116
  88. package/dist/core/validation/index.d.ts +0 -1
  89. package/dist/core/validation/index.js +0 -1
  90. package/dist/core/value/ValueHelper.d.ts +0 -7
  91. package/dist/core/value/ValueHelper.js +0 -66
  92. package/dist/core/value/index.d.ts +0 -1
  93. package/dist/core/value/index.js +0 -1
  94. package/dist/react/RegisterBinding.d.ts +0 -5
  95. package/dist/react/RegisterBinding.js +0 -21
  96. package/dist/react/types.d.ts +0 -73
  97. package/dist/react/types.js +0 -1
  98. package/dist/react/useField.d.ts +0 -3
  99. package/dist/react/useField.js +0 -23
  100. package/dist/react/useFieldSchemaRegistration.d.ts +0 -4
  101. package/dist/react/useFieldSchemaRegistration.js +0 -25
  102. package/dist/react/useFieldState.d.ts +0 -3
  103. package/dist/react/useFieldState.js +0 -6
  104. package/dist/react/useForm.d.ts +0 -4
  105. package/dist/react/useForm.js +0 -30
  106. package/dist/react/useFormSnapshot.d.ts +0 -2
  107. package/dist/react/useFormSnapshot.js +0 -4
  108. package/dist/react/useFormState.d.ts +0 -3
  109. package/dist/react/useFormState.js +0 -7
  110. package/dist/react/useRegister.d.ts +0 -6
  111. package/dist/react/useRegister.js +0 -26
  112. package/dist/solid/RegisterBinding.d.ts +0 -5
  113. package/dist/solid/RegisterBinding.js +0 -28
  114. package/dist/solid/types.d.ts +0 -71
  115. package/dist/solid/types.js +0 -1
  116. package/dist/solid/useField.d.ts +0 -3
  117. package/dist/solid/useField.js +0 -28
  118. package/dist/solid/useFieldSchemaRegistration.d.ts +0 -3
  119. package/dist/solid/useFieldSchemaRegistration.js +0 -15
  120. package/dist/solid/useForm.d.ts +0 -4
  121. package/dist/solid/useForm.js +0 -13
  122. package/dist/solid/useFormSnapshot.d.ts +0 -3
  123. package/dist/solid/useFormSnapshot.js +0 -9
  124. package/dist/solid/useFormState.d.ts +0 -3
  125. package/dist/solid/useFormState.js +0 -38
  126. package/dist/solid/useRegister.d.ts +0 -6
  127. package/dist/solid/useRegister.js +0 -21
  128. package/dist/svelte/RegisterAction.d.ts +0 -4
  129. package/dist/svelte/RegisterAction.js +0 -121
  130. package/dist/svelte/types.d.ts +0 -13
  131. package/dist/svelte/types.js +0 -1
  132. package/dist/svelte/useForm.d.ts +0 -4
  133. package/dist/svelte/useForm.js +0 -17
  134. package/dist/svelte/useFormState.d.ts +0 -4
  135. package/dist/svelte/useFormState.js +0 -10
  136. package/dist/vue/RegisterBinding.d.ts +0 -5
  137. package/dist/vue/RegisterBinding.js +0 -28
  138. package/dist/vue/types.d.ts +0 -71
  139. package/dist/vue/types.js +0 -1
  140. package/dist/vue/useField.d.ts +0 -3
  141. package/dist/vue/useField.js +0 -28
  142. package/dist/vue/useFieldSchemaRegistration.d.ts +0 -3
  143. package/dist/vue/useFieldSchemaRegistration.js +0 -17
  144. package/dist/vue/useForm.d.ts +0 -4
  145. package/dist/vue/useForm.js +0 -13
  146. package/dist/vue/useFormSnapshot.d.ts +0 -3
  147. package/dist/vue/useFormSnapshot.js +0 -11
  148. package/dist/vue/useFormState.d.ts +0 -3
  149. package/dist/vue/useFormState.js +0 -38
  150. package/dist/vue/useRegister.d.ts +0 -6
  151. package/dist/vue/useRegister.js +0 -21
package/README.ko.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ilokesto/form
2
2
 
3
- [English](./README.md) | 한국어
3
+ [English](./README.md) | **한국어**
4
4
 
5
5
  `@ilokesto/form`은 프레임워크에 의존하지 않는 form state core다. 렌더링과 이벤트 바인딩은 framework adapter에 맡기고, core는 form values, field metadata, validation errors, submit attempts, array item keys를 하나의 정규화된 store 안에서 관리한다.
6
6
 
@@ -12,6 +12,12 @@
12
12
  4. **Standard Schema validation**: core는 특정 schema library가 아니라 Standard Schema v1의 `~standard.validate` 계약에만 의존한다.
13
13
  5. **Array rebasing**: array item이 move, swap, insert, remove될 때 `errors`, `touched`, `dirty`, `modified` 같은 child field metadata가 item과 함께 이동한다.
14
14
 
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
+
15
21
  ## Table of contents
16
22
 
17
23
  - [Installation](#installation)
@@ -30,7 +36,7 @@
30
36
 
31
37
  ## Installation
32
38
 
33
- 현재 이 repository의 `package.json`은 package를 private으로 표시한다. workspace에서는 package manager 또는 workspace protocol을 통해 추가하면 된다. package가 publish되거나 link된 상태에서 import surface는 다음과 같다.
39
+ 이 패키지는 `@ilokesto/form` 이름으로 npm에 public access로 게시된다. workspace에서는 package manager 또는 workspace protocol을 통해 추가하면 된다. package가 publish되거나 link된 상태에서 import surface는 다음과 같다.
34
40
 
35
41
  ```ts
36
42
  import { CreateForm } from '@ilokesto/form';
@@ -47,6 +53,8 @@ pnpm test
47
53
 
48
54
  이 package는 ESM JavaScript와 TypeScript declaration을 `dist/`로 emit한다.
49
55
 
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하도록 설정하라.
57
+
50
58
  ## Quick start
51
59
 
52
60
  ```ts
@@ -146,7 +154,7 @@ const { form, useRegister, handleSubmit } = useForm({
146
154
  });
147
155
  ```
148
156
 
149
- `useForm(options)`에 전달한 options는 해당 component lifetime 동안 form instance를 만들 때 사용된다. React adapter에서는 외부 `values`도 받을 수 있다. `values` reference가 바뀌면 adapter가 `form.reset(values, resetOptions)`를 대신 호출한다. `useQuery` 같은 async data로 값을 hydrate할 때 사용자 편집값을 덮어쓰고 싶지 않다면 `keepDirtyValues`를 사용한다.
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을 일으킬 때만 적용된다.
150
158
 
151
159
  ```tsx
152
160
  const { useRegister } = useForm({
@@ -159,6 +167,8 @@ const { useRegister } = useForm({
159
167
  });
160
168
  ```
161
169
 
170
+ Values effect는 component unmount 시 종료된다. `useForm(existingForm)` overload는 기존 동작을 유지하며 external-value synchronization을 설치하지 않는다.
171
+
162
172
  React adapter의 첫 버전 hook은 세 가지다. `useRegister`는 단일, 배열, rest-argument 등록을 모두 처리하도록 overload되어 있다.
163
173
 
164
174
  | Hook | Purpose |
@@ -185,6 +195,21 @@ Event model은 DOM event 중심이다. Custom component도 DOM-compatible `value
185
195
 
186
196
  Vue binding은 `./vue` subpath로 노출된다. React adapter와 같은 `useForm(form)` 형태를 쓰지만, Vue template의 `v-bind`에 바로 전달할 수 있도록 `onInput`, `onChange`, `onBlur`, `onFocus` handler를 가진 props를 반환한다.
187
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
+
188
213
  ```vue
189
214
  <script setup lang="ts">
190
215
  import { CreateForm } from '@ilokesto/form';
@@ -242,7 +267,7 @@ Vue adapter도 같은 세 가지 개념을 노출한다.
242
267
  | `useRegister(options)` | 하나의 input 중심 `v-bind` binding object를 반환한다. `type`이 포함되고 기본값은 `text`다. Text input은 `input` event에서, checkbox/radio는 `change` event에서 값을 갱신한다. select/textarea 타입은 generic으로 좁힌다. |
243
268
  | `useRegister(options[])` / `useRegister(optionA, optionB)` | map-friendly rendering을 위해 여러 binding object를 반환한다. |
244
269
  | `useField(options)` | getter 기반 reactive read를 가진 `{ props, value, setValue, errors, dirty, touched }`를 반환한다. |
245
- | `useFormState()` | `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, `submitCount` 같은 form 전체 aggregate getter를 반환한다. |
270
+ | `useFormState()` | `errors`, `dirtyFields`, `touchedFields`, `focusedField`, `isDirty`, `isValid`, `submitCount` 같은 form 전체 aggregate getter를 반환한다. |
246
271
 
247
272
  Field-local schema는 React와 같은 방식으로 동작하고 현재 Vue effect scope가 정리될 때 함께 cleanup된다.
248
273
 
@@ -290,9 +315,22 @@ function LoginForm() {
290
315
 
291
316
  Solid adapter는 Vue와 같은 의미의 `useRegister`, `useField`, `useFormState`를 제공한다. Text input은 `input` event에서, checkbox/radio/multiple select는 `change` event에서 갱신하고, field-local schema는 현재 Solid owner와 함께 dispose된다.
292
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
+
293
331
  ## Svelte adapter
294
332
 
295
- Svelte binding은 `./svelte` subpath로 노출된다. Svelte는 hook-style rendering을 쓰지 않으므로 adapter는 `register` action과 Svelte readable form-state store를 제공한다.
333
+ Svelte binding은 `./svelte` subpath로 노출된다. Adapter는 register action과 함께 form-wide 및 field-local state를 위한 readable store를 제공한다.
296
334
 
297
335
  ```svelte
298
336
  <script lang="ts">
@@ -308,12 +346,17 @@ Svelte binding은 `./svelte` subpath로 노출된다. Svelte는 hook-style rende
308
346
  validateOn: ['blur', 'submit'],
309
347
  });
310
348
 
311
- const { register, useFormState } = useForm(form);
349
+ const { register, useField, useFormState } = useForm(form);
350
+ const email = useField({ name: 'email', schema: emailSchema });
351
+ const emailProps = email.props;
312
352
  const state = useFormState();
313
353
  </script>
314
354
 
315
355
  <form>
316
- <input use:register={{ name: 'email', schema: emailSchema }} />
356
+ <input use:emailProps />
357
+ {#each $email.errors as error}
358
+ <p>{error.message}</p>
359
+ {/each}
317
360
  <input type="checkbox" use:register={{ name: 'remember', type: 'checkbox' }} />
318
361
 
319
362
  <select use:register={{ name: 'role' }}>
@@ -325,7 +368,25 @@ Svelte binding은 `./svelte` subpath로 노출된다. Svelte는 hook-style rende
325
368
  </form>
326
369
  ```
327
370
 
328
- Svelte action은 DOM synchronization을 직접 담당한다. DOM `name`을 설정하고, form state에서 `value`/`checked`를 sync하고, user change를 core form에 쓰며, action이 destroy될 때 field-local schema를 cleanup한다.
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를 구독하지 않는다.
329
390
 
330
391
  ## Core concepts
331
392
 
@@ -399,6 +460,7 @@ type FieldState<TValue = unknown> = {
399
460
  touched: boolean;
400
461
  dirty: boolean;
401
462
  modified: boolean;
463
+ isFocused: boolean;
402
464
  };
403
465
  ```
404
466
 
@@ -407,6 +469,7 @@ Flag의 의미:
407
469
  - `touched`: field가 한 번 이상 blur되었다.
408
470
  - `dirty`: 현재 value가 같은 path의 initial value와 `Object.is` 기준으로 다르다.
409
471
  - `modified`: `source: 'user'` write로 field가 변경되었다.
472
+ - `isFocused`: field가 현재 focus 중이다. `focus()`가 `true`로, `blur()`가 (`validateOn`과 무관하게 항상) `false`로 설정한다.
410
473
  - `errors`: validation 또는 manual assignment로 붙은 field errors.
411
474
 
412
475
  ### `FormState`
@@ -442,9 +505,9 @@ Core는 leaf field states와 array container keys를 따로 저장한다.
442
505
  items: [{ title: 'A' }, { title: 'B' }],
443
506
  },
444
507
  fields: {
445
- '["user","name"]': { value: 'Ada', errors: [], touched: false, dirty: false, modified: false },
446
- '["items",0,"title"]': { value: 'A', errors: [], touched: false, dirty: false, modified: false },
447
- '["items",1,"title"]': { value: 'B', errors: [], touched: false, dirty: false, modified: false },
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 },
448
511
  },
449
512
  submitCount: 0,
450
513
  arrayKeys: {
@@ -625,6 +688,8 @@ Effects:
625
688
 
626
689
  `setValue()`는 `void`를 반환한다. Change validation은 async로 시작되며 method가 await하지 않는다.
627
690
 
691
+ Async validation은 target-aware하게 동작한다. 새 validation은 겹치는 field만 supersede하며 서로 독립적인 field validation은 동시에 완료될 수 있다. Full-form submit validation은 자신이 검증한 value snapshot도 확인한다. stale submit은 authoritative result를 얻을 때까지 재검증하며 기본값으로 `onValid`를 호출하지 않는다.
692
+
628
693
  ### `blur(path)`
629
694
 
630
695
  Field를 touched 처리하고 필요하면 validate한다.
@@ -637,7 +702,9 @@ const valid = await form.blur('email');
637
702
 
638
703
  ### `focus(path)`
639
704
 
640
- 현재는 no-op이다. Minimal core state가 focused field를 저장하지 않더라도 framework adapter가 stable command surface를 제공할 수 있도록 존재한다.
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`를 직접 순회하라.
641
708
 
642
709
  ### `setErrors(path, errors)`
643
710
 
@@ -751,501 +818,100 @@ Array 전체를 교체한다. 기존 item link를 의도적으로 끊기 때문
751
818
 
752
819
  ## Runtime flows
753
820
 
754
- ### Form creation flow
755
-
756
- ```txt
757
- new CreateForm(options)
758
- -> new FormStateStore(options.defaultValues)
759
- -> FormStateInitializer.initialize(defaultValues)
760
- -> fields for leaf values
761
- -> arrayKeys for array containers
762
- -> new ValidationEngine(store, options)
763
- -> new FormFieldCommands(store, validation)
764
- -> new FormArrayFactory(store)
765
- -> new FormSubmitter(store, validation)
766
- ```
767
-
768
- 핵심은 모든 collaborator가 같은 `FormStateStore`를 공유한다는 점이다.
769
-
770
- ### Value write flow
771
-
772
- ```txt
773
- form.setValue(path, value, options)
774
- -> FormFieldCommands.setValue()
775
- -> FormPath.toFieldPath(path)
776
- -> FormStateStore.setValue()
777
- -> FormStateWriter.setValue()
778
- -> compute dirty from defaultValues
779
- -> optionally mark modified
780
- -> optionally start change validation
781
- ```
782
-
783
- `dirty`와 `modified`는 의도적으로 분리되어 있다. Programmatic write는 field를 dirty하게 만들 수 있지만 user-modified로 표시하지 않을 수 있다.
821
+ ### 필드 명령
784
822
 
785
- ### Blur flow
823
+ `src/core/form/CreateForm.ts`부터 읽으면 명령의 전체 순서를 볼 수 있다.
786
824
 
787
825
  ```txt
788
- form.blur(path)
789
- -> FormFieldCommands.blur()
790
- -> FormPath.pathInputToKey(path)
791
- -> FormStateStore.touchField(key)
792
- -> if validateOn includes 'blur': ValidationEngine.validateField(key, 'blur')
793
- -> otherwise return true
826
+ setValue -> 경로 정규화 -> store.setValue -> 필요하면 change 검증
827
+ blur -> 경로 정규화 -> unfocus -> touch -> 필요하면 blur 검증
828
+ trigger -> 경로 정규화 -> 지정 필드 또는 전체 검증
829
+ array -> form이 공유하는 키 생성기로 controller 생성
830
+ submit -> 제출 큐 -> 검증 -> callback -> 완료 처리
794
831
  ```
795
832
 
796
- ### Manual validation flow
833
+ 상태 변경은 동기적으로 알린다. Blur의 unfocus와 touch 알림은 각각 유지한다.
834
+ `dirty`는 기본값과의 `Object.is` 비교 결과이고, `modified`는 사용자 입력으로
835
+ 변경되었는지를 기록한다. 두 flag의 의미는 다르다.
797
836
 
798
- ```txt
799
- form.trigger(...paths)
800
- -> no paths: validateRegisteredFields('manual')
801
- -> with paths: validateFields(keys, 'manual')
802
- -> StandardSchemaValidator.validate(values)
803
- -> issue paths become PathKeys
804
- -> selected field errors are replaced
805
- ```
806
-
807
- Field-level validation도 full schema를 실행한 뒤 target field errors만 적용한다. 이렇게 하면 schema adapter가 단순하고 schema-library independent하게 유지된다.
837
+ ### 검증과 제출
808
838
 
809
- ### Submit flow
839
+ 지정 필드 검증은 local schema를 먼저 실행한 뒤 나머지 대상에 form schema를
840
+ 적용한다. 전체 검증은 form schema 이후 등록된 local schema를 실행한다.
841
+ Local 결과는 빈 오류 목록을 포함해 form schema 결과보다 우선한다. Local schema가
842
+ 없는 지정 필드 검증은 form 전체 schema를 실행하지만 지정 필드 오류만 기록한다.
810
843
 
811
- ```txt
812
- form.submit(onValid, onInvalid)
813
- -> increment submitCount
814
- -> validateRegisteredFields('submit')
815
- -> invalid: onInvalid(fields), return undefined
816
- -> valid: onValid(getValues())
817
- ```
844
+ 비동기 단계마다 검증 revision과 캡처한 값이 유효한지 확인한다. 서로 다른 필드의
845
+ 검증은 순서가 바뀌어 완료되어도 반영되지만, 겹치는 검증은 최신 결과를 덮어쓰면
846
+ 안 된다. 오류는 기존처럼 필드별로 기록하며 새로운 일괄 알림을 도입하지 않는다.
818
847
 
819
- `submitCount`는 successful submissions가 아니라 submit attempts를 기록한다.
848
+ `FormSubmitter`는 동시 제출을 큐에 넣는다. 시도 횟수는 즉시 증가시키고,
849
+ stale 검증은 다시 실행한다. Invalid이면 `onInvalid`, valid이면 현재 값으로
850
+ `onValid`를 호출하고, 대기 중인 제출이 모두 끝나면 submit 상태를 완료한다.
820
851
 
821
- ### Array mutation flow
852
+ ### 배열 변경
822
853
 
823
854
  ```txt
824
- form.array('items').move(1, 0)
825
- -> FormArrayController.move()
826
- -> read current array values and keys
827
- -> FormArrayMutationPlanner.move()
828
- -> next values
829
- -> next keys
830
- -> previous-index to next-index mapper
831
- -> FormArrayRebaser.rebase()
832
- -> write next array into values
833
- -> initialize a fresh FormState from next values
834
- -> preserve non-array fields
835
- -> move child metadata through the index mapper
836
- -> write next array keys
855
+ controller가 현재 값과 키를 읽음
856
+ -> 정적 planner가 { values, keys, mapPreviousIndex } 계산
857
+ -> store.replaceState(previousState => rebase(previousState, path, mutation))
858
+ -> 다음 snapshot 한 번 반영
837
859
  ```
838
860
 
839
- 이 흐름이 `items[1].name` metadata를 동일한 logical item에 붙인 채 그 item이 `items[0].name`으로 이동하게 만드는 핵심 기능이다.
861
+ Rebaser는 전달받은 snapshot에서 값을 복원하고 다음 상태를 초기화한 뒤,
862
+ 살아남은 자식 필드 메타데이터와 중첩 배열 키를 새 경로로 옮긴다. Errors, touched,
863
+ dirty, modified, focus는 item을 따라간다. 배열 밖 필드와 submit 상태는 보존한다.
864
+ Replace는 기존 자식 메타데이터를 버리고 새 키를 만든다. 기존 defaultValues
865
+ 동작도 그대로 유지한다.
840
866
 
841
867
  ## Internal architecture
842
868
 
843
869
  ```txt
844
- src/index.ts
845
- -> src/core/index.ts
846
- -> form/CreateForm.ts
847
- -> state/FormStateStore.ts
848
- -> state/FormStateInitializer.ts
849
- -> state/FormStateReader.ts
850
- -> state/FormStateWriter.ts
851
- -> form/FormFieldCommands.ts
852
- -> validation/ValidationEngine.ts
853
- -> validation/StandardSchemaValidator.ts
854
- -> form/FormSubmitter.ts
855
- -> array/FormArrayFactory.ts
856
- -> array/FormArrayController.ts
857
- -> array/FormArrayMutationPlanner.ts
858
- -> array/FormArrayRebaser.ts
859
- -> array/FormArrayPath.ts
860
- -> array/ArrayItemReorder.ts
861
- -> array/ArrayKeyGenerator.ts
862
- -> path/FormPath.ts
863
- -> value/ValueHelper.ts
864
- -> types.ts
865
- -> src/adapters/
866
- -> dom/FieldValue.ts
867
- -> dom/RegisterBinding.ts
868
- -> FormStateSummary.ts
869
- -> src/react/index.ts
870
- -> shared adapter logic 위의 React hook adapter
871
- -> src/vue/index.ts
872
- -> shared adapter logic 위의 Vue composable adapter
873
- -> src/solid/index.ts
874
- -> shared adapter logic 위의 Solid helper adapter
875
- -> src/svelte/index.ts
876
- -> shared adapter logic 위의 Svelte action adapter
877
- ```
878
-
879
- Responsibility summary:
880
-
881
- | Area | Responsibility |
882
- | --- | --- |
883
- | `form/` | Public orchestration: field commands, submit flow, array controller access. |
884
- | `state/` | Normalized state initialization, reading, writing, and store facade. |
885
- | `path/` | Conversion between public path input, tuple paths, and string path keys. |
886
- | `value/` | Immutable nested get/set and reconstruction of values from field states. |
887
- | `validation/` | Standard Schema execution and error normalization. |
888
- | `array/` | Array item key management, mutation planning, and child field metadata rebasing. |
889
- | `adapters/` | 내부 shared adapter logic: DOM value extraction/binding, form-state aggregation. |
890
- | `react/` | Public `Form` interface를 감싸는 React hook adapter. |
891
- | `vue/` | Public `Form` interface를 감싸는 Vue composable adapter. |
892
- | `solid/` | Public `Form` interface를 감싸는 Solid helper adapter. |
893
- | `svelte/` | Public `Form` interface를 감싸는 Svelte action adapter. |
894
- | `types.ts` | Public and internal TypeScript contracts. |
870
+ CreateForm 공개 명령 순서와 공유 배열 키
871
+ FormStateStore 상태 소유와 쓰기
872
+ FormStateInitializer 중첩 기본값 -> 정규화된 snapshot
873
+ FormStateReader snapshot -> 필드와 중첩 값
874
+ ValidationEngine schema 등록과 검증 단계
875
+ StandardSchemaValidator schema 결과 -> 필드 오류
876
+ ValidationSequencer 겹치는 검증의 revision
877
+ ValidationSnapshot 캡처한 값과 배열 키 비교
878
+ FormSubmitter 제출 큐와 callback 수명
879
+ FormArrayController 배열 읽기와 상태 반영
880
+ FormArrayMutationPlanner 순수 배열 변경 계산
881
+ FormArrayRebaser 이전 snapshot + 변경 결과 -> 다음 snapshot
882
+ ```
883
+
884
+ React, Vue, Solid, Svelte adapter는 공개 `Form` 계약에 의존한다.
885
+ `adapters/`는 DOM 값·바인딩과 상태 집계를 공유하고, 구독과 컴포넌트 수명 관리는
886
+ 각 framework 디렉터리에 남긴다.
895
887
 
896
888
  ## Core walkthrough
897
889
 
898
- ### `src/index.ts`
899
-
900
- Package root는 안정적인 framework-agnostic surface만 export한다.
901
-
902
- ```ts
903
- export { CreateForm } from './core/index';
904
- export type {
905
- CreateFormOptions,
906
- FieldPathInput,
907
- Form,
908
- FormError,
909
- StandardSchemaV1,
910
- } from './core/index';
911
- ```
912
-
913
- Internal state와 command helper 타입은 package root에서 내보내지 않는다. 이 문서에서는 구현 설명을 위해 다루지만, consumer는 `Form`, `CreateForm`, field path, errors, Standard Schema contract를 통해 사용해야 한다.
914
-
915
- ### `src/core/index.ts`
916
-
917
- 이 파일은 `types.ts`의 public types와 `CreateForm`을 re-export한다. Package root와 implementation folders 사이의 boundary다.
918
-
919
- ### `src/core/types.ts`
920
-
921
- `types.ts`는 core vocabulary를 정의한다.
922
-
923
- - public path type: `FieldPathInput`; internal path concepts: `FieldPathSegment`, `FieldPath`, `PathKey`
924
- - exported validation types: `FormError`, `StandardSchemaV1`; internal validation trigger type: `ValidationTrigger`
925
- - internal state types: `FieldState`, `ArrayKeys`, `FormState`
926
- - public API types: `CreateFormOptions`, `Form`; internal command helper types: `FormArray`, `SetValueOptions`
927
-
928
- 이 파일에서 가장 중요한 설계는 public string path가 literal field name이라는 점이다. Nested field에는 tuple path가 필요하다.
929
-
930
- ### `src/core/form/CreateForm.ts`
931
-
932
- `CreateForm`은 top-level controller이자 main public class다.
933
-
934
- 네 collaborator를 소유한다.
935
-
936
- ```txt
937
- store -> state storage and state operations
938
- fields -> setValue, blur, errors, trigger
939
- arrays -> array(path) controller creation
940
- submitter -> submitCount, validation, callbacks
941
- ```
942
-
943
- Constructor는 하나의 `FormStateStore`를 만들고 모든 collaborator에 전달한다. 그래서 모든 command는 같은 snapshot 위에서 동작한다.
944
-
945
- 대부분의 method는 얇은 delegation이다.
946
-
947
- - `getState()`, `getFieldState()`, `getValue()`, `getValues()`, `reset()`은 `FormStateStore`에 위임한다.
948
- - `setValue()`, `blur()`, `focus()`, `setErrors()`, `clearErrors()`, `trigger()`는 `FormFieldCommands`에 위임한다.
949
- - `array()`는 path를 tuple로 변환하고 `FormArrayFactory`에 controller를 요청한다.
950
- - `submit()`은 `FormSubmitter`에 위임한다.
951
-
952
- 이 구조는 public API를 stable하게 유지하면서 implementation responsibilities를 분리한다.
953
-
954
- ### `src/core/form/FormFieldCommands.ts`
955
-
956
- `FormFieldCommands`는 field-level operations를 묶는다.
957
-
958
- `setValue()`:
959
-
960
- 1. `FormPath.toFieldPath()`로 path를 tuple로 변환한다.
961
- 2. `store.setValue()`로 value를 쓴다.
962
- 3. 결과 `PathKey`를 받는다.
963
- 4. `options.validate`가 true이거나 `validateOn`에 `'change'`가 있으면 change validation을 시작한다.
964
-
965
- `blur()`:
966
-
967
- 1. Public path를 `PathKey`로 변환한다.
968
- 2. Field를 touched 처리한다.
969
- 3. 설정된 경우에만 blur validation을 실행한다.
970
-
971
- `focus()`는 현재 no-op이다. Minimal core state가 focus를 추적하지 않기 때문이다. Adapter-level consistency를 위해 method는 유지한다.
972
-
973
- `setErrors()`, `clearErrors()`, `trigger()`는 path를 key로 normalize하고 store 또는 validation engine에 위임한다.
974
-
975
- ### `src/core/form/FormSubmitter.ts`
976
-
977
- `FormSubmitter`는 submit-specific sequencing을 분리한다.
978
-
979
- ```txt
980
- increment submitCount
981
- validate all registered fields
982
- if invalid -> call onInvalid(fields) and return undefined
983
- if valid -> call onValid(getValues())
984
- ```
985
-
986
- Submit은 multi-step command이므로 `CreateForm`이 validation branching까지 책임지지 않게 별도 class로 분리되어 있다.
987
-
988
- ### `src/core/state/FieldStateFactory.ts`
989
-
990
- `FieldStateFactory`는 default field state shape을 중앙화한다.
991
-
992
- ```ts
993
- {
994
- value: undefined,
995
- errors: [],
996
- touched: false,
997
- dirty: false,
998
- modified: false,
999
- }
1000
- ```
1001
-
1002
- Shared mutable reference를 피하기 위해 매번 새 `errors` array를 만든다. 같은 factory는 initial leaf fields와 missing-field fallback에 모두 사용된다.
1003
-
1004
- ### `src/core/state/FormStateInitializer.ts`
1005
-
1006
- `FormStateInitializer.initialize(defaultValues)`는 nested values를 normalized `FormState`로 변환한다.
1007
-
1008
- Rules:
1009
-
1010
- 1. Arrays는 leaf field가 아니라 containers다.
1011
- 2. Array containers는 `initial-0`, `initial-1` 같은 `arrayKeys`를 받는다.
1012
- 3. Array items는 recursive하게 방문된다.
1013
- 4. Plain objects는 traverse된다.
1014
- 5. Empty plain object는 더 내려갈 field가 없으므로 leaf value로 저장된다.
1015
- 6. `Date`, class instance 같은 non-plain objects는 leaf value로 취급된다.
1016
- 7. Primitive와 `null`은 leaf value다.
1017
-
1018
- 그래서 `getState().fields`는 원래 nested object가 아니라 leaf paths를 가진다.
1019
-
1020
- ### `src/core/state/FormStateReader.ts`
1021
-
1022
- `FormStateReader`는 read-only derived operations를 담당한다.
1023
-
1024
- - `getKnownFieldPaths()`는 저장된 모든 `PathKey`를 tuple path로 되돌린다.
1025
- - `getFieldStateByKey()`는 existing field 또는 default `FieldState`를 반환한다.
1026
- - `getFieldState()`와 `getValue()`는 path-input convenience methods다.
1027
- - `getValues()`는 `ValueHelper.getValuesFromFields()`로 full nested value tree를 복원한다.
1028
- - `getValueAtPath()`는 먼저 values를 복원한 뒤 nested path를 읽는다.
1029
-
1030
- Reader는 store를 직접 소유하지 않고 snapshot getter를 받기 때문에 항상 최신 state를 읽는다.
1031
-
1032
- ### `src/core/state/FormStateWriter.ts`
1033
-
1034
- `FormStateWriter`는 모든 state mutation을 `immer`로 수행한다.
1035
-
1036
- `setValue()`:
1037
-
1038
- - Tuple path를 `PathKey`로 변환한다.
1039
- - 해당 tuple path의 initial value를 읽는다.
1040
- - 가능하면 existing field metadata를 보존한다.
1041
- - `value`를 교체한다.
1042
- - `Object.is`로 `dirty`를 계산한다.
1043
- - `source: 'user'`일 때만 `modified`를 설정한다.
1044
- - Validation이 재사용할 수 있도록 `PathKey`를 반환한다.
1045
-
1046
- Other methods:
1047
-
1048
- - `touchField()`는 `touched: true`를 설정한다.
1049
- - `setErrorsByKey()`는 error array를 교체한다.
1050
- - `clearErrors()`는 target fields 또는 existing fields 전체 errors를 비운다.
1051
- - `reset()`은 현재 또는 replacement initial values로 state를 다시 초기화한다.
1052
- - `incrementSubmitCount()`는 attempts를 증가시킨다.
1053
- - `replaceState()`는 array rebasing 같은 whole-state operation을 위한 escape hatch다.
1054
-
1055
- ### `src/core/state/FormStateStore.ts`
1056
-
1057
- `FormStateStore`는 core의 다른 부분들이 사용하는 facade다.
1058
-
1059
- 소유하는 것:
1060
-
1061
- - `@ilokesto/store`의 `Store<FormState<TValues>>`
1062
- - `FormStateReader`
1063
- - `FormStateWriter`
1064
-
1065
- Collaborator들은 operation이 reader, writer, underlying store 중 어디에서 구현되는지 알 필요가 없다. Facade만 호출하면 된다.
1066
-
1067
- ### `src/core/path/FormPath.ts`
1068
-
1069
- `FormPath`는 path conversion rules를 정의한다.
1070
-
1071
- Key methods:
1072
-
1073
- - `path(...segments)`: tuple path helper.
1074
- - `toFieldPath(input)`: string은 `[input]`이 되고 tuple path는 그대로 통과한다.
1075
- - `pathInputToKey(input)`: public path input을 `PathKey`로 변환한다.
1076
- - `pathToKey(path)`: `[]`는 `$`, 나머지는 tuple을 JSON stringify한다.
1077
- - `keyToPath(key)`: key를 tuple segments로 parse하고 validate한다.
1078
-
1079
- JSON encoding이 path collision을 방지한다.
1080
-
1081
- ### `src/core/value/ValueHelper.ts`
1082
-
1083
- `ValueHelper`는 immutable nested value operations를 제공한다.
1084
-
1085
- `getValueAtPath(source, path)`는 object/array를 안전하게 walk한다. 중간 value가 nullish이거나 primitive이면 `undefined`를 반환한다.
1086
-
1087
- `setValueAtPath(source, path, value)`는 new root value를 반환하고 path를 따라 container를 shallow-clone한다. Missing container는 next segment로 추론한다. Number면 array를 만들고 string이면 object를 만든다.
1088
-
1089
- `getValuesFromFields(state, fieldPaths)`는 public values를 두 단계로 복원한다.
1090
-
1091
- 1. `arrayKeys`에서 empty array containers를 만든다.
1092
- 2. 모든 leaf field value를 tuple path 위치에 쓴다.
1093
-
1094
- 이 과정을 통해 normalized `fields`가 다시 nested object가 된다.
1095
-
1096
- ### `src/core/validation/ValidationEngine.ts`
1097
-
1098
- `ValidationEngine`은 validation triggers와 store writes를 조율한다.
1099
-
1100
- - Default `validateOn`은 `['submit']`이다.
1101
- - Schema가 없으면 validation은 error 없이 성공한다.
1102
- - `validateField(key, trigger)`는 full schema를 실행하고 해당 field errors만 적용한다.
1103
- - `validateFields(keys, trigger)`는 full schema를 실행하고 selected fields errors만 적용한다.
1104
- - `validateRegisteredFields(trigger)`는 full schema를 실행하고 current fields와 schema error keys 전체를 update한다.
1105
-
1106
- Engine은 schema를 호출할 때 trigger value를 전달하지 않는다. Trigger는 engine이 언제 실행될지를 제어하지 schema API를 바꾸지 않는다.
1107
-
1108
- ### `src/core/validation/StandardSchemaValidator.ts`
1109
-
1110
- `StandardSchemaValidator`는 Standard Schema result를 core errors로 adapt한다.
1111
-
1112
- Success:
1113
-
1114
- ```ts
1115
- { valid: true, errorsByKey: {} }
1116
- ```
1117
-
1118
- Failure:
1119
-
1120
- ```ts
1121
- {
1122
- valid: false,
1123
- errorsByKey: {
1124
- '["email"]': [{ type: 'standard_schema', message: 'Email is invalid' }],
1125
- },
1126
- }
1127
- ```
1128
-
1129
- Issue path conversion rules:
1130
-
1131
- - Missing path 또는 empty path는 root path `[]`와 key `$`가 된다.
1132
- - String과 number path segment는 그대로 보존된다.
1133
- - Object path segment는 `.key` property를 사용한다.
1134
- - Symbol 같은 unsupported key는 root error로 fallback된다.
1135
-
1136
- ### `src/core/array/ArrayKeyGenerator.ts`
1137
-
1138
- `ArrayKeyGenerator`는 runtime item keys를 만든다.
1139
-
1140
- ```txt
1141
- item-1
1142
- item-2
1143
- item-3
1144
- ```
1145
-
1146
- 하나의 `FormArrayFactory`는 form instance마다 하나의 generator를 공유한다. 이렇게 하면 여러 controller 사이에서 accidental key collision 가능성을 줄인다.
1147
-
1148
- ### `src/core/array/ArrayItemReorder.ts`
1149
-
1150
- `ArrayItemReorder`는 array order operations를 위한 pure helper다.
1151
-
1152
- - `moveItem(items, from, to)`는 reordered copy를 반환한다.
1153
- - `swapItems(items, left, right)`는 swapped copy를 반환한다.
1154
- - `createIndexMapper(previousLength, nextOrder)`는 previous index를 next index로 mapping하는 function을 반환한다.
1155
-
1156
- `nextOrder`는 "각 next position에는 어떤 previous index가 있는가?"로 표현된다. New item은 `-1`을 사용하고 removed item은 아예 등장하지 않는다.
1157
-
1158
- ### `src/core/array/FormArrayMutationPlanner.ts`
1159
-
1160
- `FormArrayMutationPlanner`는 store를 몰라도 array mutations를 계산한다.
1161
-
1162
- 각 mutation은 다음 형태를 반환한다.
1163
-
1164
- ```ts
1165
- type FormArrayMutation = {
1166
- values: readonly unknown[];
1167
- keys: readonly string[];
1168
- mapPreviousIndex: (index: number) => number | undefined;
1169
- };
1170
- ```
1171
-
1172
- Command behavior:
1173
-
1174
- - `insert()`는 target index를 보정하고 새 value/key를 삽입한다. New item은 `-1`에서 온 것으로 처리되어 previous metadata가 붙지 않는다.
1175
- - `push()`는 value/key를 끝에 추가한다.
1176
- - `remove()`는 value/key를 제거하고 removed index는 `undefined`로 map한다.
1177
- - `move()`는 같은 rule로 values와 keys를 이동한다.
1178
- - `swap()`은 같은 rule로 values와 keys를 교환한다.
1179
- - `replace()`는 모두 새 values/keys를 반환하고 모든 previous index를 `undefined`로 map한다.
1180
-
1181
- 이 planner는 pure하기 때문에 store와 독립적으로 test하기 쉽다.
1182
-
1183
- ### `src/core/array/FormArrayPath.ts`
1184
-
1185
- `FormArrayPath`는 rebasing 중 필요한 path helpers를 담는다.
1186
-
1187
- - `hasPathPrefix(fieldPath, prefix)`는 tuple prefix equality를 확인한다.
1188
- - `isArrayChildPath(fieldPath, arrayPath)`는 `['items']` 아래의 `['items', 0, 'name']`처럼 field가 array item 아래에 있는지 확인한다.
1189
- - `replaceArrayIndex(fieldPath, arrayPath, nextIndex)`는 item index가 교체된 새 child path를 만든다.
1190
-
1191
- ### `src/core/array/FormArrayController.ts`
1192
-
1193
- `FormArrayController`는 `form.array(path)`가 반환하는 public command object다.
1194
-
1195
- 보유하는 것:
1196
-
1197
- - shared `FormStateStore`
1198
- - shared `ArrayKeyGenerator`
1199
- - controlled array `FieldPath`
1200
- - `FormArrayMutationPlanner`
1201
-
1202
- 각 command는 같은 pattern을 따른다.
1203
-
1204
- ```txt
1205
- read current array value
1206
- read current keys
1207
- ask planner for next values, keys, and index mapper
1208
- if mutation exists, rebase the whole FormState
1209
- ```
1210
-
1211
- `getArray()`는 array path의 현재 value를 읽는다. Value가 array가 아니면 empty array를 사용한다.
1212
-
1213
- `getKeys()`는 stored `arrayKeys`를 읽는다. 없으면 current array length만큼 key를 만든다.
1214
-
1215
- ### `src/core/array/FormArrayFactory.ts`
1216
-
1217
- `FormArrayFactory`는 `FormArrayController` instances를 만들고 form instance를 위한 하나의 `ArrayKeyGenerator`를 공유한다.
1218
-
1219
- 이 덕분에 `form.array('items')`를 반복 호출해서 fresh controller를 만들어도 key sequence가 reset되지 않는다.
1220
-
1221
- ### `src/core/array/FormArrayRebaser.ts`
1222
-
1223
- `FormArrayRebaser`는 가장 중요한 array component다. Array mutation 뒤 values, field states, array keys, submit count를 정렬한다.
1224
-
1225
- Detailed sequence:
1226
-
1227
- 1. Current store에서 known field paths를 읽는다.
1228
- 2. `store.getValues()`로 current values를 복원한다.
1229
- 3. `ValueHelper.setValueAtPath()`로 next array를 values에 쓴다.
1230
- 4. Next values에서 fresh `FormState`를 initialize한다.
1231
- 5. Freshly initialized fields에서 시작한다.
1232
- 6. Previous fields를 순회한다.
1233
- 7. Changed array 밖의 fields는 보존한다.
1234
- 8. Changed array 안의 child fields는 previous item index를 next item index로 mapping한다.
1235
- 9. Item이 아직 존재하면 child path의 index를 교체하고 metadata를 new field로 copy한다.
1236
- 10. Array path에 next `arrayKeys`를 쓴다.
1237
- 11. `submitCount`를 보존한다.
1238
-
1239
- Rebased child field에 copy되는 것은 metadata뿐이다.
1240
-
1241
- ```txt
1242
- errors
1243
- touched
1244
- dirty
1245
- modified
1246
- ```
1247
-
1248
- Value 자체는 next values로부터 freshly initialized state에서 온다. 그래서 stale value를 방지하면서 user interaction metadata는 보존한다.
890
+ 모든 import를 따라가기보다 아래 순서로 읽으면 된다.
891
+
892
+ | 알고 싶은 내용 | `src/core/` 아래 파일 | 책임 |
893
+ | --- | --- | --- |
894
+ | 공개 명령 다음에 무슨 일이 일어나는가? | `form/CreateForm.ts` | 경로 변환, 상태 변경, 검증 요청. |
895
+ | 상태는 어디서 바뀌는가? | `state/FormStateStore.ts` | store 소유와 immer 쓰기, reset·submit flag 반영. |
896
+ | 값을 어떻게 복원하는가? | `state/FormStateReader.ts` | 명시적으로 받은 snapshot의 정적 계산. Store나 getter를 소유하지 않는다. |
897
+ | 초기 상태는 어떻게 만드는가? | `state/FormStateInitializer.ts` | 배열과 일반 객체를 순회하고 빈 객체·특수 객체·원시값은 leaf로 유지. |
898
+ | 없는 필드는 어떻게 읽는가? | `state/FieldStateFactory.ts` | undefined 값, 새 오류 배열, isFocused를 포함한 false flag 생성. |
899
+ | 경로는 어떻게 표현하는가? | `path/FormPath.ts` | 문자열은 단일 segment, tuple은 JSON key, root는 `$`. |
900
+ | 중첩 값을 어떻게 변경하는가? | `value/ValueHelper.ts` | 불변 nested get/set과 fields·배열 container에서 값 복원. |
901
+ | 검증 결과는 언제 적용하는가? | `validation/ValidationEngine.ts` | Local schema 우선순위, 지정·전체 검증 실행, stale 판별. |
902
+ | 어느 검증이 이전 검증을 대체하는가? | `validation/ValidationSequencer.ts` | 전체·필드별 revision과 schema 등록에 따른 무효화. |
903
+ | 검증 중 값이 달라졌는가? | `validation/ValidationSnapshot.ts` | 필드 값과 배열 키 identity 캡처·비교. |
904
+ | Schema issue는 어떻게 변환하는가? | `validation/StandardSchemaValidator.ts` | Standard Schema issue 정규화. 없거나 지원하지 않는 경로는 root 오류. |
905
+ | 제출 순서는 어떻게 보장하는가? | `form/FormSubmitter.ts` | 제출 큐, stale 검증 재시도, 완료 상태 처리. |
906
+ | 다음 배열 순서는 무엇인가? | `array/FormArrayMutationPlanner.ts` | 인스턴스나 store 없이 정적 insert/push/remove/move/swap/replace 계산. |
907
+ | 메타데이터는 어떻게 item을 따라가는가? | `array/FormArrayRebaser.ts` | Store 접근이나 알림 없는 순수 snapshot 변환. |
908
+ | 배열 변경은 누가 반영하는가? | `array/FormArrayController.ts` | 배열 상태를 읽고 updater의 snapshot을 rebaser에 전달. |
909
+ | 배열 키는 어디서 만드는가? | `array/ArrayKeyGenerator.ts` | CreateForm마다 하나를 소유하고 새 controller들과 공유. |
910
+ | Index와 경로는 어떻게 옮기는가? | `array/ArrayItemReorder.ts`, `array/FormArrayPath.ts` | 순수 정렬·index mapping·자식 경로 교체. |
911
+
912
+ 공개 surface는 `src/index.ts`와 framework entry point가 정의한다.
913
+ `core/types.ts`는 기존 경로·상태·schema·명령 계약을 설명한다.
914
+ 내부 모듈은 구현 상세이며 새로운 package export가 아니다.
1249
915
 
1250
916
  ## Design decisions
1251
917
 
@@ -1284,7 +950,7 @@ pnpm typecheck
1284
950
  pnpm test
1285
951
  ```
1286
952
 
1287
- `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할 수 있다.
953
+ `pnpm build`는 tsup으로 core와 네 framework entry point의 ESM JavaScript 및 declaration files를 bundle한다. `pnpm test:pack`은 별도 consumer에서 packed package의 runtime import와 TypeScript 계약을 확인한다.
1288
954
 
1289
955
  `pnpm test`는 Vitest suite를 실행한다.
1290
956