@ilokesto/form 2.0.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +39 -925
- package/README.md +38 -925
- package/package.json +35 -23
package/README.ko.md
CHANGED
|
@@ -1,61 +1,29 @@
|
|
|
1
1
|
# @ilokesto/form
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
값, 필드 메타데이터, 검증과 제출을 관리하는 프레임워크 독립적인 TypeScript 폼 코어입니다.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/@ilokesto/form)
|
|
6
|
+
[](./LICENSE)
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
[English](./README.md)
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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
|
|
49
|
-
pnpm build
|
|
50
|
-
pnpm typecheck
|
|
51
|
-
pnpm test
|
|
17
|
+
pnpm add @ilokesto/form
|
|
52
18
|
```
|
|
53
19
|
|
|
54
|
-
|
|
20
|
+
ESM과 TypeScript 선언을 제공하며 CommonJS `require()`는 지원하지 않습니다.
|
|
21
|
+
ESM import나 동적 `import()`를 사용하세요. 어댑터 하위 경로를 사용할 때는
|
|
22
|
+
해당 프레임워크도 설치하세요.
|
|
55
23
|
|
|
56
|
-
|
|
24
|
+
## 빠른 시작
|
|
57
25
|
|
|
58
|
-
|
|
26
|
+
폼을 만들고 중첩 필드를 변경한 뒤 현재 값을 제출합니다.
|
|
59
27
|
|
|
60
28
|
```ts
|
|
61
29
|
import { CreateForm } from '@ilokesto/form';
|
|
@@ -79,898 +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를 직접 설정할 수도 있다.
|
|
50
|
+
console.log(form.getFieldState('email').dirty); // true
|
|
51
|
+
console.log(form.getValues().profile.name); // Grace
|
|
531
52
|
|
|
532
|
-
|
|
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,
|
|
53
|
+
await form.submit(values => {
|
|
54
|
+
console.log(values.email);
|
|
597
55
|
});
|
|
598
56
|
```
|
|
599
57
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
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를 쓴다.
|
|
673
|
-
|
|
674
|
-
```ts
|
|
675
|
-
form.setValue(['user', 'name'], 'Grace', {
|
|
676
|
-
source: 'user',
|
|
677
|
-
validate: true,
|
|
678
|
-
});
|
|
679
|
-
```
|
|
680
|
-
|
|
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는 무시된다.
|
|
58
|
+
문자열은 실제 필드 이름입니다. `'profile.name'`과 `['profile', 'name']`은
|
|
59
|
+
서로 다른 필드를 가리킵니다. `getState()` 스냅샷은 읽기 전용으로 다루세요.
|
|
60
|
+
`dirty`는 기본값과의 비교이고 `modified`는 사용자 입력에 의한 변경 기록입니다.
|
|
806
61
|
|
|
807
|
-
|
|
62
|
+
이 예제에는 스키마가 없습니다. 검증하려면 Standard Schema 호환 `schema`를 추가하세요.
|
|
63
|
+
자동 검증의 기본 시점은 submit입니다. `setValue()`는 `void`를 반환하며
|
|
64
|
+
change 검증을 기다리지 않습니다. 검증 완료를 기다리려면 `trigger()`를 사용하세요.
|
|
65
|
+
배열의 `move()`와 `swap()`은 메타데이터를 유지하고 `replace()`는 의도적으로 버립니다.
|
|
808
66
|
|
|
809
|
-
|
|
67
|
+
어댑터는 `/react`, `/vue`, `/solid`, `/svelte`에 있으므로 루트는 프레임워크와
|
|
68
|
+
DOM을 import하지 않습니다. 어댑터 소유자가 해제될 때 구독도 정리하세요.
|
|
810
69
|
|
|
811
|
-
|
|
70
|
+
<details>
|
|
71
|
+
<summary>개발</summary>
|
|
812
72
|
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
### `FormArray.replace(values)`
|
|
816
|
-
|
|
817
|
-
Array 전체를 교체한다. 기존 item link를 의도적으로 끊기 때문에 child field metadata는 보존되지 않는다.
|
|
818
|
-
|
|
819
|
-
## Runtime flows
|
|
820
|
-
|
|
821
|
-
### 필드 명령
|
|
822
|
-
|
|
823
|
-
`src/core/form/CreateForm.ts`부터 읽으면 명령의 전체 순서를 볼 수 있다.
|
|
824
|
-
|
|
825
|
-
```txt
|
|
826
|
-
setValue -> 경로 정규화 -> store.setValue -> 필요하면 change 검증
|
|
827
|
-
blur -> 경로 정규화 -> unfocus -> touch -> 필요하면 blur 검증
|
|
828
|
-
trigger -> 경로 정규화 -> 지정 필드 또는 전체 검증
|
|
829
|
-
array -> form이 공유하는 키 생성기로 controller 생성
|
|
830
|
-
submit -> 제출 큐 -> 검증 -> callback -> 완료 처리
|
|
831
|
-
```
|
|
832
|
-
|
|
833
|
-
상태 변경은 동기적으로 알린다. Blur의 unfocus와 touch 알림은 각각 유지한다.
|
|
834
|
-
`dirty`는 기본값과의 `Object.is` 비교 결과이고, `modified`는 사용자 입력으로
|
|
835
|
-
변경되었는지를 기록한다. 두 flag의 의미는 다르다.
|
|
836
|
-
|
|
837
|
-
### 검증과 제출
|
|
838
|
-
|
|
839
|
-
지정 필드 검증은 local schema를 먼저 실행한 뒤 나머지 대상에 form schema를
|
|
840
|
-
적용한다. 전체 검증은 form schema 이후 등록된 local schema를 실행한다.
|
|
841
|
-
Local 결과는 빈 오류 목록을 포함해 form schema 결과보다 우선한다. Local schema가
|
|
842
|
-
없는 지정 필드 검증은 form 전체 schema를 실행하지만 지정 필드 오류만 기록한다.
|
|
843
|
-
|
|
844
|
-
비동기 단계마다 검증 revision과 캡처한 값이 유효한지 확인한다. 서로 다른 필드의
|
|
845
|
-
검증은 순서가 바뀌어 완료되어도 반영되지만, 겹치는 검증은 최신 결과를 덮어쓰면
|
|
846
|
-
안 된다. 오류는 기존처럼 필드별로 기록하며 새로운 일괄 알림을 도입하지 않는다.
|
|
847
|
-
|
|
848
|
-
`FormSubmitter`는 동시 제출을 큐에 넣는다. 시도 횟수는 즉시 증가시키고,
|
|
849
|
-
stale 검증은 다시 실행한다. Invalid이면 `onInvalid`, valid이면 현재 값으로
|
|
850
|
-
`onValid`를 호출하고, 대기 중인 제출이 모두 끝나면 submit 상태를 완료한다.
|
|
851
|
-
|
|
852
|
-
### 배열 변경
|
|
853
|
-
|
|
854
|
-
```txt
|
|
855
|
-
controller가 현재 값과 키를 읽음
|
|
856
|
-
-> 정적 planner가 { values, keys, mapPreviousIndex } 계산
|
|
857
|
-
-> store.replaceState(previousState => rebase(previousState, path, mutation))
|
|
858
|
-
-> 다음 snapshot 한 번 반영
|
|
859
|
-
```
|
|
860
|
-
|
|
861
|
-
Rebaser는 전달받은 snapshot에서 값을 복원하고 다음 상태를 초기화한 뒤,
|
|
862
|
-
살아남은 자식 필드 메타데이터와 중첩 배열 키를 새 경로로 옮긴다. Errors, touched,
|
|
863
|
-
dirty, modified, focus는 item을 따라간다. 배열 밖 필드와 submit 상태는 보존한다.
|
|
864
|
-
Replace는 기존 자식 메타데이터를 버리고 새 키를 만든다. 기존 defaultValues
|
|
865
|
-
동작도 그대로 유지한다.
|
|
866
|
-
|
|
867
|
-
## Internal architecture
|
|
868
|
-
|
|
869
|
-
```txt
|
|
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 디렉터리에 남긴다.
|
|
887
|
-
|
|
888
|
-
## Core walkthrough
|
|
889
|
-
|
|
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가 아니다.
|
|
915
|
-
|
|
916
|
-
## Design decisions
|
|
917
|
-
|
|
918
|
-
### Strings are literal paths
|
|
919
|
-
|
|
920
|
-
Dot-path parsing은 편하지만 모호하다. 이 core는 unambiguous tuple paths를 선택한다.
|
|
921
|
-
|
|
922
|
-
```ts
|
|
923
|
-
'user.name' // one field named "user.name"
|
|
924
|
-
['user', 'name'] // nested user.name field
|
|
925
|
-
```
|
|
926
|
-
|
|
927
|
-
### State is normalized
|
|
928
|
-
|
|
929
|
-
Normalized fields는 whole nested value object를 mutate하지 않고도 개별 metadata를 update하기 쉽게 만든다. `ValueHelper`는 필요할 때 public value shape을 복원한다.
|
|
930
|
-
|
|
931
|
-
### Validation is schema-library independent
|
|
932
|
-
|
|
933
|
-
Core는 Standard Schema만 안다. 그래서 여러 validation library와 호환되고 특정 validator를 import하지 않는다.
|
|
934
|
-
|
|
935
|
-
### Array mutation is split into planning and rebasing
|
|
936
|
-
|
|
937
|
-
`FormArrayMutationPlanner`는 next array가 어떤 모습인지 결정한다. `FormArrayRebaser`는 전체 form state가 어떻게 따라가야 하는지 결정한다. 이 분리는 mutation math를 pure하게 만들고 store updates를 중앙화한다.
|
|
938
|
-
|
|
939
|
-
### `dirty` and `modified` are different
|
|
940
|
-
|
|
941
|
-
`dirty`는 current value와 initial value를 비교한다. `modified`는 user-originated writes를 추적한다. Programmatic update는 dirty일 수 있지만 user modified는 아닐 수 있다.
|
|
942
|
-
|
|
943
|
-
## Testing and development
|
|
944
|
-
|
|
945
|
-
### Commands
|
|
73
|
+
Node 24.22.1과 pnpm 10.17.1을 사용하고 저장소 루트에서 실행하세요.
|
|
946
74
|
|
|
947
75
|
```sh
|
|
948
|
-
pnpm
|
|
76
|
+
pnpm install --frozen-lockfile
|
|
949
77
|
pnpm typecheck
|
|
950
78
|
pnpm test
|
|
951
79
|
```
|
|
952
80
|
|
|
953
|
-
`
|
|
954
|
-
|
|
955
|
-
`pnpm test`는 Vitest suite를 실행한다.
|
|
956
|
-
|
|
957
|
-
### Current test coverage themes
|
|
958
|
-
|
|
959
|
-
Existing tests는 다음을 cover한다.
|
|
960
|
-
|
|
961
|
-
1. Tuple paths와 literal string names의 차이.
|
|
962
|
-
2. Blur, manual trigger, submit에서의 Standard Schema validation.
|
|
963
|
-
3. Move와 remove 시 array value/key/metadata rebasing.
|
|
964
|
-
4. React adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema precedence.
|
|
965
|
-
5. Vue adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema cleanup.
|
|
966
|
-
6. Solid adapter의 text input, textarea, checkbox, radio, select, `useField`, overloaded `useRegister`, `useFormState`, field-local schema cleanup.
|
|
967
|
-
7. Svelte register action의 text input, checkbox, radio, select, multiple select, readable `useFormState`, field-local schema cleanup.
|
|
968
|
-
|
|
969
|
-
### 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`를 실행하세요.
|
|
970
82
|
|
|
971
|
-
|
|
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`을 설정하세요. 로컬에서는 게시하지 않습니다.
|
|
972
89
|
|
|
973
|
-
|
|
974
|
-
- `replace()`가 child metadata를 의도적으로 drop하는지에 대한 test.
|
|
975
|
-
- Root-level schema errors test.
|
|
976
|
-
- Custom DOM-event-compatible component를 위한 adapter examples.
|
|
90
|
+
</details>
|