@ilokesto/form 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +86 -13
  3. package/README.md +86 -15
  4. package/dist/FormInput-DuT7QFe-.d.ts +37 -0
  5. package/dist/chunk-EPQC3LKB.js +1649 -0
  6. package/dist/chunk-EPQC3LKB.js.map +1 -0
  7. package/dist/chunk-OBMSHDV2.js +215 -0
  8. package/dist/chunk-OBMSHDV2.js.map +1 -0
  9. package/dist/index.d.ts +58 -2
  10. package/dist/index.js +3 -4
  11. package/dist/index.js.map +1 -0
  12. package/dist/react/index.d.ts +87 -2
  13. package/dist/react/index.js +110 -70
  14. package/dist/react/index.js.map +1 -0
  15. package/dist/solid/index.d.ts +89 -2
  16. package/dist/solid/index.js +115 -62
  17. package/dist/solid/index.js.map +1 -0
  18. package/dist/svelte/index.d.ts +68 -2
  19. package/dist/svelte/index.js +162 -75
  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 +137 -62
  24. package/dist/vue/index.js.map +1 -0
  25. package/package.json +15 -8
  26. package/dist/CreateForm-hQ4cxAK-.js +0 -1283
  27. package/dist/FormStateSummary-gmEQdNXj.js +0 -140
  28. package/dist/adapters/FormInput.d.ts +0 -8
  29. package/dist/adapters/FormStateSummary.d.ts +0 -14
  30. package/dist/adapters/dom/FieldValue.d.ts +0 -2
  31. package/dist/adapters/dom/RegisterBinding.d.ts +0 -14
  32. package/dist/adapters/dom/SubmitHandler.d.ts +0 -9
  33. package/dist/adapters/dom/index.d.ts +0 -5
  34. package/dist/adapters/dom/types.d.ts +0 -22
  35. package/dist/core/array/ArrayItemReorder.d.ts +0 -6
  36. package/dist/core/array/ArrayKeyGenerator.d.ts +0 -4
  37. package/dist/core/array/FormArrayController.d.ts +0 -21
  38. package/dist/core/array/FormArrayFactory.d.ts +0 -8
  39. package/dist/core/array/FormArrayMutationPlanner.d.ts +0 -14
  40. package/dist/core/array/FormArrayPath.d.ts +0 -6
  41. package/dist/core/array/FormArrayRebaser.d.ts +0 -7
  42. package/dist/core/array/index.d.ts +0 -1
  43. package/dist/core/form/CreateForm.d.ts +0 -23
  44. package/dist/core/form/FormFieldCommands.d.ts +0 -15
  45. package/dist/core/form/FormSubmitter.d.ts +0 -9
  46. package/dist/core/form/index.d.ts +0 -1
  47. package/dist/core/index.d.ts +0 -2
  48. package/dist/core/path/FormPath.d.ts +0 -9
  49. package/dist/core/path/index.d.ts +0 -1
  50. package/dist/core/state/FieldStateFactory.d.ts +0 -6
  51. package/dist/core/state/FormStateInitializer.d.ts +0 -7
  52. package/dist/core/state/FormStateReader.d.ts +0 -11
  53. package/dist/core/state/FormStateStore.d.ts +0 -24
  54. package/dist/core/state/FormStateWriter.d.ts +0 -17
  55. package/dist/core/state/index.d.ts +0 -1
  56. package/dist/core/types.d.ts +0 -112
  57. package/dist/core/validation/StandardSchemaValidator.d.ts +0 -14
  58. package/dist/core/validation/ValidationEngine.d.ts +0 -25
  59. package/dist/core/validation/index.d.ts +0 -1
  60. package/dist/core/value/ValueHelper.d.ts +0 -7
  61. package/dist/core/value/index.d.ts +0 -1
  62. package/dist/react/RegisterBinding.d.ts +0 -5
  63. package/dist/react/types.d.ts +0 -73
  64. package/dist/react/useField.d.ts +0 -3
  65. package/dist/react/useFieldSchemaRegistration.d.ts +0 -4
  66. package/dist/react/useFieldState.d.ts +0 -3
  67. package/dist/react/useForm.d.ts +0 -4
  68. package/dist/react/useFormSnapshot.d.ts +0 -2
  69. package/dist/react/useFormState.d.ts +0 -3
  70. package/dist/react/useRegister.d.ts +0 -6
  71. package/dist/solid/RegisterBinding.d.ts +0 -5
  72. package/dist/solid/types.d.ts +0 -71
  73. package/dist/solid/useField.d.ts +0 -3
  74. package/dist/solid/useFieldSchemaRegistration.d.ts +0 -3
  75. package/dist/solid/useForm.d.ts +0 -4
  76. package/dist/solid/useFormSnapshot.d.ts +0 -3
  77. package/dist/solid/useFormState.d.ts +0 -3
  78. package/dist/solid/useRegister.d.ts +0 -6
  79. package/dist/svelte/RegisterAction.d.ts +0 -4
  80. package/dist/svelte/types.d.ts +0 -13
  81. package/dist/svelte/useForm.d.ts +0 -4
  82. package/dist/svelte/useFormState.d.ts +0 -4
  83. package/dist/vue/RegisterBinding.d.ts +0 -5
  84. package/dist/vue/types.d.ts +0 -71
  85. package/dist/vue/useField.d.ts +0 -3
  86. package/dist/vue/useFieldSchemaRegistration.d.ts +0 -3
  87. package/dist/vue/useForm.d.ts +0 -4
  88. package/dist/vue/useFormSnapshot.d.ts +0 -3
  89. package/dist/vue/useFormState.d.ts +0 -3
  90. package/dist/vue/useRegister.d.ts +0 -6
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeong Jinho <wpfekdml@me.com> and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
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
 
@@ -968,7 +1035,7 @@ Constructor는 하나의 `FormStateStore`를 만들고 모든 collaborator에
968
1035
  2. Field를 touched 처리한다.
969
1036
  3. 설정된 경우에만 blur validation을 실행한다.
970
1037
 
971
- `focus()`는 현재 no-op이다. Minimal core state가 focus를 추적하지 않기 때문이다. Adapter-level consistency를 위해 method는 유지한다.
1038
+ `focus()`는 field의 `isFocused`를 `true`로 바꾼다. 대응되는 `blur()` command가 `isFocused`를 clearing하고 (`validateOn` 설정과 무관하게 항상), field를 `touched`로 표시한다. `isFocused` flag는 array rebasing 시 보존된다.
972
1039
 
973
1040
  `setErrors()`, `clearErrors()`, `trigger()`는 path를 key로 normalize하고 store 또는 validation engine에 위임한다.
974
1041
 
@@ -1033,6 +1100,8 @@ Reader는 store를 직접 소유하지 않고 snapshot getter를 받기 때문
1033
1100
 
1034
1101
  `FormStateWriter`는 모든 state mutation을 `immer`로 수행한다.
1035
1102
 
1103
+ > **번들 참고:** `immer`는 컨슈머 번들에 ~5KB를 추가한다. `FormState`가 flat `Record<PathKey, FieldState>` 구조이므로 spread 기반 업데이트(`{ ...state, [key]: nextField }`)로 immer를 대체해도 동작이 동일하다. 마이그레이션 전에 벤치마크하라 — immer는 구조 공유와 가독성 이점을 제공하며, array rebasing 경로에서는 크기 비용을 상회할 수 있다.
1104
+
1036
1105
  `setValue()`:
1037
1106
 
1038
1107
  - Tuple path를 `PathKey`로 변환한다.
@@ -1078,6 +1147,8 @@ Key methods:
1078
1147
 
1079
1148
  JSON encoding이 path collision을 방지한다.
1080
1149
 
1150
+ > **성능 참고:** `pathToKey`는 `JSON.stringify`를, `keyToPath`는 `JSON.parse`를 사용한다. 큰 폼(수백 필드)에서 잦은 업데이트 시 NUL separator 기반 커스텀 인코딩으로 hot path 오버헤드를 줄일 수 있다. 마이그레이션 전에 벤치마크하라 — 현재 접근은 정확하고 읽기 쉬우며 실제 영향은 보통 미미하다.
1151
+
1081
1152
  ### `src/core/value/ValueHelper.ts`
1082
1153
 
1083
1154
  `ValueHelper`는 immutable nested value operations를 제공한다.
@@ -1105,6 +1176,8 @@ JSON encoding이 path collision을 방지한다.
1105
1176
 
1106
1177
  Engine은 schema를 호출할 때 trigger value를 전달하지 않는다. Trigger는 engine이 언제 실행될지를 제어하지 schema API를 바꾸지 않는다.
1107
1178
 
1179
+ `ValidationSequencer`는 full-form revision과 field별 revision을 추적한다. 겹치는 작업만 stale 처리하고 독립 field 작업은 유지하며, error나 submit callback을 적용하기 전에 captured field-value 및 array-shape snapshot이 최신인지 확인한다.
1180
+
1108
1181
  ### `src/core/validation/StandardSchemaValidator.ts`
1109
1182
 
1110
1183
  `StandardSchemaValidator`는 Standard Schema result를 core errors로 adapt한다.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ilokesto/form
2
2
 
3
- English | [한국어](./README.ko.md)
3
+ **English** | [한국어](./README.ko.md)
4
4
 
5
5
  `@ilokesto/form` is a framework-agnostic form state core. It keeps form values, field metadata, validation errors, submit attempts, and array item keys in one normalized store, while leaving rendering and event binding to framework adapters.
6
6
 
@@ -12,6 +12,12 @@ The package is designed around five ideas:
12
12
  4. **Standard Schema validation**: the core depends only on the Standard Schema v1 `~standard.validate` contract, not on a specific schema library.
13
13
  5. **Array rebasing**: when array items move, swap, insert, or disappear, child field metadata such as `errors`, `touched`, `dirty`, and `modified` is moved with the item.
14
14
 
15
+ ## Documentation
16
+
17
+ - Full docs: [English](https://ilokesto.ayden94.com/en/form) · [한국어](https://ilokesto.ayden94.com/ko/form)
18
+ - Source: [packages/form](https://github.com/ilokesto/ilokesto/tree/main/packages/form)
19
+ - npm: [@ilokesto/form](https://www.npmjs.com/package/@ilokesto/form)
20
+
15
21
  ## Table of contents
16
22
 
17
23
  - [Installation](#installation)
@@ -30,7 +36,7 @@ The package is designed around five ideas:
30
36
 
31
37
  ## Installation
32
38
 
33
- This repository currently marks the package as private in `package.json`. In a workspace, add it through your package manager or workspace protocol. When the package is published or linked, the import surface is:
39
+ This package is published to npm under the `@ilokesto/form` name with public access. In a workspace, add it through your package manager or workspace protocol. When the package is published or linked, the import surface is:
34
40
 
35
41
  ```ts
36
42
  import { CreateForm } from '@ilokesto/form';
@@ -47,6 +53,8 @@ pnpm test
47
53
 
48
54
  The package emits ESM JavaScript and TypeScript declarations to `dist/`.
49
55
 
56
+ > **ESM-only.** This package ships `"type": "module"` with ESM-only `exports`. CommonJS `require()` is not supported. Use a modern bundler (Vite, webpack 5+, esbuild, tsup) or Node.js ESM (`import`). If you need CJS compatibility, use dynamic `import()` or configure your bundler to transpile `@ilokesto/form`.
57
+
50
58
  ## Quick start
51
59
 
52
60
  ```ts
@@ -146,9 +154,7 @@ const { form, useRegister, handleSubmit } = useForm({
146
154
  });
147
155
  ```
148
156
 
149
- Options passed to `useForm(options)` are used only to create the form instance for that component lifetime. They are not reactive. When hydrating values from async data such as a query result, initialize with safe defaults and call `form.reset(nextValues)` explicitly when you want that data to become the new default baseline.
150
-
151
- The React adapter also accepts reactive external `values`. When the `values` reference changes, the adapter calls `form.reset(values, resetOptions)` for you. This is useful for server/query data; use `keepDirtyValues` when refetches should not overwrite fields the user already edited.
157
+ `defaultValues` and the other `CreateForm` options create the component-owned form once. `ReactFormOptions` also accepts the current render `values` and plain `resetOptions`. The first defined value and each later value with a different `Object.is` identity call `form.reset(values, resetOptions)`. `undefined` pauses synchronization without resetting; passing the last defined object again remains a no-op. Changing only `resetOptions` is also a no-op because it applies only when a new `values` reference drives a reset.
152
158
 
153
159
  ```tsx
154
160
  const { useRegister } = useForm({
@@ -161,6 +167,8 @@ const { useRegister } = useForm({
161
167
  });
162
168
  ```
163
169
 
170
+ The values effect ends on component unmount. `useForm(existingForm)` keeps its existing overload behavior and does not install external-value synchronization.
171
+
164
172
  The React adapter has three first-version hooks. `useRegister` is overloaded for single, array, and rest-argument registration:
165
173
 
166
174
  | Hook | Purpose |
@@ -187,6 +195,21 @@ The event model is DOM-event centered. Custom components can use `useRegister` w
187
195
 
188
196
  Vue bindings are exposed through the `./vue` subpath. They use the same `useForm(form)` shape as the React adapter, but return Vue-friendly `v-bind` props with `onInput`, `onChange`, `onBlur`, and `onFocus` handlers.
189
197
 
198
+ `useForm` also accepts `VueFormOptions`. Its `values` source is `MaybeRefOrGetter<TValues | undefined>` and `resetOptions` stays plain. The first defined value and each later value with a different `Object.is` identity call `form.reset(values, resetOptions)`. `undefined` pauses synchronization without resetting, and re-emitting the last defined object remains a no-op. Pass `ref`, `computed`, or a getter to track changes; a plain value is evaluated once. Reactive values require an active Vue effect scope; the adapter fails before creating a form when none exists. The watcher stops with that scope, and `useForm(existingForm)` does not install it.
199
+
200
+ ```vue
201
+ <script setup lang="ts">
202
+ import { ref } from 'vue';
203
+ import { useForm } from '@ilokesto/form/vue';
204
+
205
+ const serverValues = ref({ email: 'initial@example.com' });
206
+ const { form, useRegister } = useForm({
207
+ defaultValues: { email: '' },
208
+ values: serverValues,
209
+ });
210
+ </script>
211
+ ```
212
+
190
213
  ```vue
191
214
  <script setup lang="ts">
192
215
  import { CreateForm } from '@ilokesto/form';
@@ -244,7 +267,7 @@ The Vue adapter exposes the same three concepts:
244
267
  | `useRegister(options)` | Returns one input-oriented `v-bind` binding object. It includes `type` and defaults to `text`; text inputs update on `input`; checkbox/radio update on `change`. Use a generic for select/textarea binding types. |
245
268
  | `useRegister(options[])` / `useRegister(optionA, optionB)` | Returns multiple binding objects for map-friendly rendering. |
246
269
  | `useField(options)` | Returns `{ props, value, setValue, errors, dirty, touched }` with getter-backed reactive reads. |
247
- | `useFormState()` | Returns form-wide aggregate getters such as `errors`, `dirtyFields`, `touchedFields`, `isDirty`, `isValid`, and `submitCount`. |
270
+ | `useFormState()` | Returns form-wide aggregate getters such as `errors`, `dirtyFields`, `touchedFields`, `focusedField`, `isDirty`, `isValid`, and `submitCount`. |
248
271
 
249
272
  Field-local schemas work the same way as React and are cleaned up with the current Vue effect scope.
250
273
 
@@ -292,9 +315,22 @@ function LoginForm() {
292
315
 
293
316
  The Solid adapter exposes `useRegister`, `useField`, and `useFormState` with the same semantics as Vue: text inputs update on `input`, checkbox/radio/multiple select update on `change`, and field-local schemas are disposed with the current Solid owner.
294
317
 
318
+ For component-owned forms, `SolidFormOptions` accepts `values` as `Accessor<TValues | undefined>` and plain `resetOptions`:
319
+
320
+ ```tsx
321
+ const [serverValues, setServerValues] = createSignal<User | undefined>();
322
+ const { form } = useForm({
323
+ defaultValues: emptyUser,
324
+ values: serverValues,
325
+ resetOptions: { keepDirtyValues: true },
326
+ });
327
+ ```
328
+
329
+ The first defined accessor value and each later value with a different `Object.is` identity reset the form. `undefined` pauses without resetting, re-emitting the last defined object is a no-op, and `resetOptions` applies only to value-driven resets. Reactive values require an active Solid owner; the adapter fails before creating a form when none exists. Tracking is disposed with that owner. `useForm(existingForm)` does not install it.
330
+
295
331
  ## Svelte adapter
296
332
 
297
- Svelte bindings are exposed through the `./svelte` subpath. Svelte does not use hook-style rendering, so the adapter exposes a `register` action and a Svelte readable form-state store.
333
+ Svelte bindings are exposed through the `./svelte` subpath. The adapter exposes register actions plus readable stores for both form-wide and field-local state.
298
334
 
299
335
  ```svelte
300
336
  <script lang="ts">
@@ -310,12 +346,17 @@ Svelte bindings are exposed through the `./svelte` subpath. Svelte does not use
310
346
  validateOn: ['blur', 'submit'],
311
347
  });
312
348
 
313
- 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;
314
352
  const state = useFormState();
315
353
  </script>
316
354
 
317
355
  <form>
318
- <input use:register={{ name: 'email', schema: emailSchema }} />
356
+ <input use:emailProps />
357
+ {#each $email.errors as error}
358
+ <p>{error.message}</p>
359
+ {/each}
319
360
  <input type="checkbox" use:register={{ name: 'remember', type: 'checkbox' }} />
320
361
 
321
362
  <select use:register={{ name: 'role' }}>
@@ -327,7 +368,25 @@ Svelte bindings are exposed through the `./svelte` subpath. Svelte does not use
327
368
  </form>
328
369
  ```
329
370
 
330
- The Svelte action owns DOM synchronization directly: it sets the DOM `name`, keeps `value`/`checked` in sync from form state, writes user changes back to the core form, and cleans up field-local schemas when the action is destroyed.
371
+ The Svelte action owns DOM synchronization directly. `useField` is a `Readable<SvelteFieldSnapshot>` consumed as `$email`; it emits current `value`, `errors`, `dirty`, and `touched` state and releases its core subscription when the last subscriber leaves.
372
+
373
+ For component-owned forms, `SvelteFormOptions` accepts `values` as `Readable<TValues | undefined>` and plain `resetOptions`:
374
+
375
+ ```svelte
376
+ <script lang="ts">
377
+ import { writable } from 'svelte/store';
378
+ import { useForm } from '@ilokesto/form/svelte';
379
+
380
+ const serverValues = writable<User | undefined>(undefined);
381
+ const { form } = useForm({
382
+ defaultValues: emptyUser,
383
+ values: serverValues,
384
+ resetOptions: { keepDirtyValues: true },
385
+ });
386
+ </script>
387
+ ```
388
+
389
+ The first defined emission and each later emission with a different `Object.is` identity reset the form. `undefined` pauses without resetting, re-emitting the last defined object is a no-op, and `resetOptions` applies only to value-driven resets. Call this overload during component initialization; its subscription ends on unmount. `useForm(existingForm)` does not subscribe.
331
390
 
332
391
  ## Core concepts
333
392
 
@@ -401,6 +460,7 @@ type FieldState<TValue = unknown> = {
401
460
  touched: boolean;
402
461
  dirty: boolean;
403
462
  modified: boolean;
463
+ isFocused: boolean;
404
464
  };
405
465
  ```
406
466
 
@@ -409,6 +469,7 @@ The flags mean:
409
469
  - `touched`: the field was blurred at least once.
410
470
  - `dirty`: the current value is not `Object.is`-equal to the initial value at the same path.
411
471
  - `modified`: the field was changed by a user-sourced write, `source: 'user'`.
472
+ - `isFocused`: the field currently has focus. Set to `true` by `focus()` and cleared by `blur()` (always, regardless of `validateOn`).
412
473
  - `errors`: validation or manually assigned field errors.
413
474
 
414
475
  ### `FormState`
@@ -444,9 +505,9 @@ The core stores leaf field states and array container keys separately:
444
505
  items: [{ title: 'A' }, { title: 'B' }],
445
506
  },
446
507
  fields: {
447
- '["user","name"]': { value: 'Ada', errors: [], touched: false, dirty: false, modified: false },
448
- '["items",0,"title"]': { value: 'A', errors: [], touched: false, dirty: false, modified: false },
449
- '["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 },
450
511
  },
451
512
  submitCount: 0,
452
513
  arrayKeys: {
@@ -627,6 +688,8 @@ Effects:
627
688
 
628
689
  `setValue()` returns `void`; change validation is started asynchronously and is not awaited by the method.
629
690
 
691
+ Async validation is target-aware. New validation supersedes only overlapping fields, while independent field validations may complete concurrently. Full-form submit validation also verifies the value snapshot it validated; stale submit attempts retry until they obtain an authoritative result and never call `onValid` by default.
692
+
630
693
  ### `blur(path)`
631
694
 
632
695
  Marks the field as touched and optionally validates it.
@@ -639,7 +702,9 @@ If `validateOn` does not contain `'blur'`, it returns `true` after touching the
639
702
 
640
703
  ### `focus(path)`
641
704
 
642
- Currently a no-op. It exists so framework adapters can expose a stable command surface for focus events even though the minimal core state does not store a focused field.
705
+ Sets `isFocused: true` on the field at `path`. Other fields are not touched — DOM naturally fires a `blur` event on the previously focused element, which clears `isFocused` via `blur()`. Array rebasing preserves `isFocused` across `move`/`swap`/`insert`/`remove`.
706
+
707
+ The core is DOM-independent, so calling `focus()` on multiple fields can leave more than one field with `isFocused: true`. In DOM adapters this is naturally bounded to one by the browser; in direct core usage it is the caller's responsibility to `blur()` the previous field. The `useFormState().focusedField` aggregate returns the **first** focused field found in `Object.entries` order, not the most recently focused one — to enumerate all focused fields, iterate `state.fields` directly.
643
708
 
644
709
  ### `setErrors(path, errors)`
645
710
 
@@ -971,7 +1036,7 @@ This keeps the public API stable while implementation responsibilities stay sepa
971
1036
  2. Marks the field as touched.
972
1037
  3. Runs blur validation only when configured.
973
1038
 
974
- `focus()` is currently a no-op because the minimal core state does not track focus. The method exists for adapter-level consistency.
1039
+ `focus()` sets `isFocused: true` on the field. The matching `blur()` command clears `isFocused` (always, regardless of `validateOn`) and marks the field as `touched`. The `isFocused` flag is preserved across array rebasing.
975
1040
 
976
1041
  `setErrors()`, `clearErrors()`, and `trigger()` normalize paths to keys and delegate to the store or validation engine.
977
1042
 
@@ -1036,6 +1101,8 @@ The reader receives a snapshot getter rather than owning the store directly, so
1036
1101
 
1037
1102
  `FormStateWriter` performs all state mutations through `immer`.
1038
1103
 
1104
+ > **Bundle note:** `immer` adds ~5KB to consumer bundles. Since `FormState` uses a flat `Record<PathKey, FieldState>`, spread-based updates (`{ ...state, [key]: nextField }`) could replace immer with no behavioral change. Benchmark before migrating — immer provides structural sharing and readability benefits that may outweigh the size cost for array rebasing paths.
1105
+
1039
1106
  `setValue()`:
1040
1107
 
1041
1108
  - Converts the tuple path to a `PathKey`.
@@ -1081,6 +1148,8 @@ Key methods:
1081
1148
 
1082
1149
  The JSON encoding is what prevents path collisions.
1083
1150
 
1151
+ > **Performance note:** `pathToKey` uses `JSON.stringify` and `keyToPath` uses `JSON.parse`. For large forms (hundreds of fields) with frequent updates, a custom separator-based encoding (e.g. NUL-joined) could reduce hot-path overhead. Benchmark before migrating — the current approach is correct and readable, and real-world impact is typically negligible.
1152
+
1084
1153
  ### `src/core/value/ValueHelper.ts`
1085
1154
 
1086
1155
  `ValueHelper` provides immutable nested value operations.
@@ -1108,6 +1177,8 @@ This lets normalized `fields` become a nested object again.
1108
1177
 
1109
1178
  The engine deliberately ignores the trigger value when calling the schema. The trigger controls when the engine runs, not the schema API.
1110
1179
 
1180
+ `ValidationSequencer` tracks full-form and per-field revisions. Overlapping work becomes stale, independent field work remains valid, and every result is checked against its captured field-value and array-shape snapshot before errors or submit callbacks are applied.
1181
+
1111
1182
  ### `src/core/validation/StandardSchemaValidator.ts`
1112
1183
 
1113
1184
  `StandardSchemaValidator` adapts Standard Schema results to core errors.
@@ -0,0 +1,37 @@
1
+ import { b as FieldPathInput, g as StandardSchemaV1, P as PathKey, d as FieldState, C as CreateFormOptions, R as ResetOptions } from './types-DBlvL6AC.js';
2
+
3
+ /** Framework adapters가 field binding에서 공통으로 받는 옵션이다. */
4
+ type FieldHookOptions = {
5
+ /** core form field path다. string은 하나의 field 이름으로 취급하고, tuple은 nested path를 표현한다. */
6
+ name: FieldPathInput;
7
+ /** 이 field에만 적용할 schema다. form-level schema보다 우선한다. */
8
+ schema?: StandardSchemaV1<unknown, unknown>;
9
+ /** field-local schema validate 함수에 넘길 옵션이다. */
10
+ schemaOptions?: StandardSchemaV1.Options;
11
+ };
12
+ /** DOM binding 보정 옵션이다. `type`은 input type으로만 쓰며 기본값은 `text`다. */
13
+ type RegisterOptions = FieldHookOptions & {
14
+ /** input type이다. checkbox/radio는 checked 처리에 사용하고, 생략 시 text로 반환한다. */
15
+ type?: string;
16
+ /** radio/checkbox처럼 DOM value와 form value를 구분해야 할 때 사용한다. */
17
+ value?: unknown;
18
+ /** checkbox가 check될 때 쓸 값이다. 생략하면 boolean checkbox로 동작한다. */
19
+ checkedValue?: unknown;
20
+ /** checkbox가 uncheck될 때 쓸 값이다. 생략하면 false로 동작한다. */
21
+ uncheckedValue?: unknown;
22
+ };
23
+ type DomValue = string | number | readonly string[];
24
+
25
+ type SubmitEventLike = {
26
+ preventDefault?: () => void;
27
+ };
28
+ type SubmitValidHandler<TValues, TResult> = (values: TValues) => TResult | Promise<TResult>;
29
+ type SubmitInvalidHandler = (fields: Readonly<Record<PathKey, FieldState>>) => void;
30
+ type SubmitHandler<TEvent extends SubmitEventLike, TResult> = (event?: TEvent) => Promise<TResult | undefined>;
31
+
32
+ type ReactiveFormOptions<TValues, TSource> = CreateFormOptions<TValues> & {
33
+ readonly values?: TSource;
34
+ readonly resetOptions?: ResetOptions;
35
+ };
36
+
37
+ export type { DomValue as D, ReactiveFormOptions as R, SubmitValidHandler as S, RegisterOptions as a, SubmitInvalidHandler as b, SubmitHandler as c };