@ilokesto/form 2.0.1 → 2.0.3
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 +40 -924
- package/README.md +39 -924
- package/dist/{FormInput-DuT7QFe-.d.ts → FormInput-BpDWf4hF.d.ts} +3 -0
- package/dist/chunk-M7Y4OJPP.js +2166 -0
- package/dist/chunk-M7Y4OJPP.js.map +1 -0
- package/dist/{chunk-JK644RR7.js → chunk-WO5TIXCR.js} +3 -3
- package/dist/chunk-WO5TIXCR.js.map +1 -0
- package/dist/index.d.ts +194 -23
- package/dist/index.js +1 -1
- package/dist/react/index.d.ts +104 -2
- package/dist/react/index.js +2 -2
- package/dist/react/index.js.map +1 -1
- package/dist/solid/index.d.ts +103 -2
- package/dist/solid/index.js +2 -2
- package/dist/solid/index.js.map +1 -1
- package/dist/svelte/index.d.ts +75 -2
- package/dist/svelte/index.js +2 -2
- package/dist/svelte/index.js.map +1 -1
- package/dist/vue/index.d.ts +103 -2
- package/dist/vue/index.js +2 -2
- package/dist/vue/index.js.map +1 -1
- package/package.json +36 -23
- package/dist/chunk-4F4SAGQ5.js +0 -1465
- package/dist/chunk-4F4SAGQ5.js.map +0 -1
- package/dist/chunk-JK644RR7.js.map +0 -1
|
@@ -0,0 +1,2166 @@
|
|
|
1
|
+
import { createStore } from '@ilokesto/store';
|
|
2
|
+
import { produce } from 'immer';
|
|
3
|
+
|
|
4
|
+
// src/core/array/ArrayKeyGenerator.ts
|
|
5
|
+
var ArrayKeyGenerator = class {
|
|
6
|
+
/** 다음 key에 사용할 증가 숫자다. */
|
|
7
|
+
id = 0;
|
|
8
|
+
/**
|
|
9
|
+
* @description Allocate the next item-N rendering key; numbering starts at item-1 for this generator.
|
|
10
|
+
* @returns {string} Next form-local key in item-N format.
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* const keys = new ArrayKeyGenerator();
|
|
14
|
+
* const key = keys.create();
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
create() {
|
|
18
|
+
this.id += 1;
|
|
19
|
+
return `item-${this.id}`;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// src/core/array/ArrayItemReorder.ts
|
|
24
|
+
var ArrayItemReorder = class {
|
|
25
|
+
/**
|
|
26
|
+
* @description Build an old-to-new index mapper; removed and out-of-range old indexes resolve to undefined.
|
|
27
|
+
* @param {number} previousLength - Array length before the reorder.
|
|
28
|
+
* @param {readonly number[]} nextOrder - Old item indexes in next order; -1 denotes a newly inserted item.
|
|
29
|
+
* @returns {IndexMapper} Mapper returning the next index, or undefined when the old item was removed.
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* ArrayItemReorder.createIndexMapper(2, [1, 0]);
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
static createIndexMapper(previousLength, nextOrder) {
|
|
36
|
+
const positions = /* @__PURE__ */ new Map();
|
|
37
|
+
nextOrder.forEach((previousIndex, nextIndex) => {
|
|
38
|
+
if (previousIndex >= 0 && previousIndex < previousLength) {
|
|
39
|
+
positions.set(previousIndex, nextIndex);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return (index) => positions.get(index);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* @description Return a copied array with one item moved to the destination index.
|
|
46
|
+
* @param {readonly T[]} items - Items to reorder without mutating the input.
|
|
47
|
+
* @param {number} fromIndex - Original index of the item to move.
|
|
48
|
+
* @param {number} toIndex - Destination index of the moved item.
|
|
49
|
+
* @returns {T[]} Copied array in the requested order; the input array is unchanged.
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* ArrayItemReorder.moveItem(["Ada", "Lin"], 0, 1);
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
static moveItem(items, fromIndex, toIndex) {
|
|
56
|
+
const nextItems = [...items];
|
|
57
|
+
const [item] = nextItems.splice(fromIndex, 1);
|
|
58
|
+
nextItems.splice(toIndex, 0, item);
|
|
59
|
+
return nextItems;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* @description Return a copied array with the two item positions exchanged.
|
|
63
|
+
* @param {readonly T[]} items - Items to reorder without mutating the input.
|
|
64
|
+
* @param {number} leftIndex - First item index.
|
|
65
|
+
* @param {number} rightIndex - Second item index.
|
|
66
|
+
* @returns {T[]} Copied array with the two positions exchanged.
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* ArrayItemReorder.swapItems(["Ada", "Lin"], 0, 1);
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
static swapItems(items, leftIndex, rightIndex) {
|
|
73
|
+
const nextItems = [...items];
|
|
74
|
+
const left = nextItems[leftIndex];
|
|
75
|
+
nextItems[leftIndex] = nextItems[rightIndex];
|
|
76
|
+
nextItems[rightIndex] = left;
|
|
77
|
+
return nextItems;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// src/core/array/FormArrayMutationPlanner.ts
|
|
82
|
+
var FormArrayMutationPlanner = class {
|
|
83
|
+
/**
|
|
84
|
+
* @description Compute a bounded insertion using the supplied new item key and preserve old item mappings.
|
|
85
|
+
* @param {readonly unknown[]} currentArray - Array values before the mutation.
|
|
86
|
+
* @param {readonly string[]} currentKeys - Stable item keys before the mutation.
|
|
87
|
+
* @param {number} index - Zero-based item index.
|
|
88
|
+
* @param {unknown} value - Value to store or inspect.
|
|
89
|
+
* @param {string} nextKey - Stable key allocated for the new item.
|
|
90
|
+
* @returns {FormArrayMutation} Next values, stable keys, and old-to-new index mapper.
|
|
91
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
92
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
93
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* FormArrayMutationPlanner.insert(["Ada", "Lin"], ["item-1", "item-2"], 0, "Ada", "item-3");
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
static insert(currentArray, currentKeys, index, value, nextKey) {
|
|
100
|
+
const boundedIndex = Math.max(0, Math.min(index, currentArray.length));
|
|
101
|
+
const nextArray = [...currentArray];
|
|
102
|
+
const nextKeys = [...currentKeys];
|
|
103
|
+
const nextOrder = [...currentArray.keys()];
|
|
104
|
+
nextArray.splice(boundedIndex, 0, value);
|
|
105
|
+
nextKeys.splice(boundedIndex, 0, nextKey);
|
|
106
|
+
nextOrder.splice(boundedIndex, 0, -1);
|
|
107
|
+
return {
|
|
108
|
+
values: nextArray,
|
|
109
|
+
keys: nextKeys,
|
|
110
|
+
mapPreviousIndex: ArrayItemReorder.createIndexMapper(currentArray.length, nextOrder)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* @description Compute an append using the supplied new item key and preserve old item mappings.
|
|
115
|
+
* @param {readonly unknown[]} currentArray - Array values before the mutation.
|
|
116
|
+
* @param {readonly string[]} currentKeys - Stable item keys before the mutation.
|
|
117
|
+
* @param {unknown} value - Value to store or inspect.
|
|
118
|
+
* @param {string} nextKey - Stable key allocated for the new item.
|
|
119
|
+
* @returns {FormArrayMutation} Next values, stable keys, and old-to-new index mapper.
|
|
120
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
121
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
122
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* FormArrayMutationPlanner.push(["Ada", "Lin"], ["item-1", "item-2"], "Ada", "item-3");
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
static push(currentArray, currentKeys, value, nextKey) {
|
|
129
|
+
return {
|
|
130
|
+
values: [...currentArray, value],
|
|
131
|
+
keys: [...currentKeys, nextKey],
|
|
132
|
+
mapPreviousIndex: ArrayItemReorder.createIndexMapper(currentArray.length, [...currentArray.keys(), -1])
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* @description Compute removal and remap surviving indexes; return undefined for an invalid index.
|
|
137
|
+
* @param {readonly unknown[]} currentArray - Array values before the mutation.
|
|
138
|
+
* @param {readonly string[]} currentKeys - Stable item keys before the mutation.
|
|
139
|
+
* @param {number} index - Zero-based item index.
|
|
140
|
+
* @returns {FormArrayMutation | undefined} Next array mutation, or undefined for invalid or unchanged indexes.
|
|
141
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
142
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
143
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
144
|
+
* @example
|
|
145
|
+
* ```ts
|
|
146
|
+
* FormArrayMutationPlanner.remove(["Ada", "Lin"], ["item-1", "item-2"], 0);
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
static remove(currentArray, currentKeys, index) {
|
|
150
|
+
if (index < 0 || index >= currentArray.length) {
|
|
151
|
+
return void 0;
|
|
152
|
+
}
|
|
153
|
+
const nextOrder = [...currentArray.keys()].filter((itemIndex) => itemIndex !== index);
|
|
154
|
+
return {
|
|
155
|
+
values: currentArray.filter((_, itemIndex) => itemIndex !== index),
|
|
156
|
+
keys: currentKeys.filter((_, itemIndex) => itemIndex !== index),
|
|
157
|
+
mapPreviousIndex: ArrayItemReorder.createIndexMapper(currentArray.length, nextOrder)
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* @description Compute reordered values, keys, and index mapping; return undefined for invalid or identical indexes.
|
|
162
|
+
* @param {readonly unknown[]} currentArray - Array values before the mutation.
|
|
163
|
+
* @param {readonly string[]} currentKeys - Stable item keys before the mutation.
|
|
164
|
+
* @param {number} fromIndex - Original index of the item to move.
|
|
165
|
+
* @param {number} toIndex - Destination index of the moved item.
|
|
166
|
+
* @returns {FormArrayMutation | undefined} Next array mutation, or undefined for invalid or unchanged indexes.
|
|
167
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
168
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
169
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
170
|
+
* @example
|
|
171
|
+
* ```ts
|
|
172
|
+
* FormArrayMutationPlanner.move(["Ada", "Lin"], ["item-1", "item-2"], 0, 1);
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
static move(currentArray, currentKeys, fromIndex, toIndex) {
|
|
176
|
+
if (fromIndex < 0 || fromIndex >= currentArray.length || toIndex < 0 || toIndex >= currentArray.length || fromIndex === toIndex) {
|
|
177
|
+
return void 0;
|
|
178
|
+
}
|
|
179
|
+
const nextOrder = ArrayItemReorder.moveItem([...currentArray.keys()], fromIndex, toIndex);
|
|
180
|
+
return {
|
|
181
|
+
values: ArrayItemReorder.moveItem(currentArray, fromIndex, toIndex),
|
|
182
|
+
keys: ArrayItemReorder.moveItem(currentKeys, fromIndex, toIndex),
|
|
183
|
+
mapPreviousIndex: ArrayItemReorder.createIndexMapper(currentArray.length, nextOrder)
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* @description Compute exchanged values, keys, and index mapping; return undefined for invalid or identical indexes.
|
|
188
|
+
* @param {readonly unknown[]} currentArray - Array values before the mutation.
|
|
189
|
+
* @param {readonly string[]} currentKeys - Stable item keys before the mutation.
|
|
190
|
+
* @param {number} leftIndex - First item index.
|
|
191
|
+
* @param {number} rightIndex - Second item index.
|
|
192
|
+
* @returns {FormArrayMutation | undefined} Next array mutation, or undefined for invalid or unchanged indexes.
|
|
193
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
194
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
195
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
196
|
+
* @example
|
|
197
|
+
* ```ts
|
|
198
|
+
* FormArrayMutationPlanner.swap(["Ada", "Lin"], ["item-1", "item-2"], 0, 1);
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
static swap(currentArray, currentKeys, leftIndex, rightIndex) {
|
|
202
|
+
if (leftIndex < 0 || rightIndex < 0 || leftIndex >= currentArray.length || rightIndex >= currentArray.length || leftIndex === rightIndex) {
|
|
203
|
+
return void 0;
|
|
204
|
+
}
|
|
205
|
+
const nextOrder = ArrayItemReorder.swapItems([...currentArray.keys()], leftIndex, rightIndex);
|
|
206
|
+
return {
|
|
207
|
+
values: ArrayItemReorder.swapItems(currentArray, leftIndex, rightIndex),
|
|
208
|
+
keys: ArrayItemReorder.swapItems(currentKeys, leftIndex, rightIndex),
|
|
209
|
+
mapPreviousIndex: ArrayItemReorder.createIndexMapper(currentArray.length, nextOrder)
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* @description Copy replacement values and supplied keys, disconnecting every previous item mapping.
|
|
214
|
+
* @param {readonly unknown[]} values - Replacement or current form values.
|
|
215
|
+
* @param {readonly string[]} nextKeys - Stable keys for the replacement array.
|
|
216
|
+
* @returns {FormArrayMutation} Replacement values and keys with all previous item mappings removed.
|
|
217
|
+
* - values `readonly unknown[]` - Array values after this mutation, in the same order as the stable keys.
|
|
218
|
+
* - keys `readonly string[]` - Stable item keys in array order.
|
|
219
|
+
* - mapPreviousIndex `IndexMapper` - Map an old item index to its new position, or undefined if removed.
|
|
220
|
+
* @example
|
|
221
|
+
* ```ts
|
|
222
|
+
* FormArrayMutationPlanner.replace(["Ada"], ["item-1"]);
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
static replace(values, nextKeys) {
|
|
226
|
+
return {
|
|
227
|
+
values: [...values],
|
|
228
|
+
keys: [...nextKeys],
|
|
229
|
+
mapPreviousIndex: () => void 0
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// src/core/path/FormPath.ts
|
|
235
|
+
var FormPath = class {
|
|
236
|
+
/**
|
|
237
|
+
* root path를 표현하는 특수 key다.
|
|
238
|
+
*
|
|
239
|
+
* @remarks
|
|
240
|
+
* 일반 path는 JSON.stringify 배열 문자열이므로 `$`와 충돌하지 않는다.
|
|
241
|
+
*/
|
|
242
|
+
static ROOT_PATH_KEY = "$";
|
|
243
|
+
/**
|
|
244
|
+
* @description Return the supplied segments as a tuple path without parsing strings.
|
|
245
|
+
* @param {FieldPath} segments - Path segments; numeric segments identify array indexes.
|
|
246
|
+
* @returns {FieldPath} Tuple containing the supplied path segments.
|
|
247
|
+
* @example
|
|
248
|
+
* ```ts
|
|
249
|
+
* FormPath.path("users", 0, "email");
|
|
250
|
+
* ```
|
|
251
|
+
*/
|
|
252
|
+
static path(...segments) {
|
|
253
|
+
return segments;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* @description Wrap a string as one literal field name or preserve the supplied tuple path.
|
|
257
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
258
|
+
* @returns {FieldPath} Tuple path; a string becomes exactly one segment.
|
|
259
|
+
* @example
|
|
260
|
+
* ```ts
|
|
261
|
+
* FormPath.toFieldPath(["email"]);
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
static toFieldPath(fieldPath) {
|
|
265
|
+
if (typeof fieldPath === "string") {
|
|
266
|
+
return [fieldPath];
|
|
267
|
+
}
|
|
268
|
+
return fieldPath;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* @description Normalize a literal name or tuple into a field-store key.
|
|
272
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
273
|
+
* @returns {string} Normalized key for field and array-key lookup.
|
|
274
|
+
* @example
|
|
275
|
+
* ```ts
|
|
276
|
+
* FormPath.pathInputToKey(["email"]);
|
|
277
|
+
* ```
|
|
278
|
+
*/
|
|
279
|
+
static pathInputToKey(fieldPath) {
|
|
280
|
+
return this.pathToKey(this.toFieldPath(fieldPath));
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* @description Serialize a tuple as JSON, using $ for the empty root path.
|
|
284
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
285
|
+
* @returns {string} $ for the root path, otherwise the JSON-serialized tuple.
|
|
286
|
+
* @example
|
|
287
|
+
* ```ts
|
|
288
|
+
* FormPath.pathToKey(["email"]);
|
|
289
|
+
* ```
|
|
290
|
+
*/
|
|
291
|
+
static pathToKey(fieldPath) {
|
|
292
|
+
if (fieldPath.length === 0) {
|
|
293
|
+
return this.ROOT_PATH_KEY;
|
|
294
|
+
}
|
|
295
|
+
return JSON.stringify(fieldPath);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* @description Parse a stored key back to tuple segments and throw for invalid keys or segment types.
|
|
299
|
+
* @param {string} key - Serialized path key produced by pathToKey.
|
|
300
|
+
* @returns {FieldPath} Decoded string and numeric path segments.
|
|
301
|
+
* @example
|
|
302
|
+
* ```ts
|
|
303
|
+
* FormPath.keyToPath(FormPath.pathToKey(["email"]));
|
|
304
|
+
* ```
|
|
305
|
+
*/
|
|
306
|
+
static keyToPath(key) {
|
|
307
|
+
if (key === this.ROOT_PATH_KEY) {
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
const parsed = JSON.parse(key);
|
|
311
|
+
if (!Array.isArray(parsed)) {
|
|
312
|
+
throw new Error(`Invalid form path key: ${key}`);
|
|
313
|
+
}
|
|
314
|
+
return parsed.map((segment) => {
|
|
315
|
+
if (typeof segment === "string" || typeof segment === "number") {
|
|
316
|
+
return segment;
|
|
317
|
+
}
|
|
318
|
+
throw new Error(`Invalid form path segment in key: ${key}`);
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// src/core/array/FormArrayPath.ts
|
|
324
|
+
var FormArrayPath = class {
|
|
325
|
+
/**
|
|
326
|
+
* @description Compare path segments with Object.is to check whether a tuple starts with the prefix.
|
|
327
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
328
|
+
* @param {FieldPath} prefix - Path prefix to compare segment by segment.
|
|
329
|
+
* @returns {boolean} Whether every prefix segment matches by Object.is.
|
|
330
|
+
* @example
|
|
331
|
+
* ```ts
|
|
332
|
+
* FormArrayPath.hasPathPrefix(["email"], ["users"]);
|
|
333
|
+
* ```
|
|
334
|
+
*/
|
|
335
|
+
static hasPathPrefix(fieldPath, prefix) {
|
|
336
|
+
return prefix.every((segment, index) => Object.is(fieldPath[index], segment));
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* @description Check that a path extends the array path with a numeric item-index segment.
|
|
340
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
341
|
+
* @param {FieldPath} arrayPath - Tuple path of the array container.
|
|
342
|
+
* @returns {boolean} Whether the next segment below the array container is a numeric index.
|
|
343
|
+
* @example
|
|
344
|
+
* ```ts
|
|
345
|
+
* FormArrayPath.isArrayChildPath(["users", 0, "email"], ["users"]);
|
|
346
|
+
* ```
|
|
347
|
+
*/
|
|
348
|
+
static isArrayChildPath(fieldPath, arrayPath) {
|
|
349
|
+
return fieldPath.length > arrayPath.length && this.hasPathPrefix(fieldPath, arrayPath) && typeof fieldPath[arrayPath.length] === "number";
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* @description Replace the item index beneath an array path while retaining the remaining child segments.
|
|
353
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
354
|
+
* @param {FieldPath} arrayPath - Tuple path of the array container.
|
|
355
|
+
* @param {number} nextIndex - Replacement item index.
|
|
356
|
+
* @returns {FieldPath} Copied child path containing the replacement array index.
|
|
357
|
+
* @example
|
|
358
|
+
* ```ts
|
|
359
|
+
* FormArrayPath.replaceArrayIndex(["users", 0, "email"], ["users"], 1);
|
|
360
|
+
* ```
|
|
361
|
+
*/
|
|
362
|
+
static replaceArrayIndex(fieldPath, arrayPath, nextIndex) {
|
|
363
|
+
return [...arrayPath, nextIndex, ...fieldPath.slice(arrayPath.length + 1)];
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// src/core/state/FieldStateFactory.ts
|
|
368
|
+
var FieldStateFactory = class {
|
|
369
|
+
/** 모든 field가 공통으로 갖는 기본 메타데이터 값이다. errors는 매번 새 배열로 복사해서 공유 참조를 피한다. */
|
|
370
|
+
static DEFAULT_FIELD_STATE = {
|
|
371
|
+
value: void 0,
|
|
372
|
+
errors: [],
|
|
373
|
+
touched: false,
|
|
374
|
+
dirty: false,
|
|
375
|
+
modified: false,
|
|
376
|
+
isFocused: false
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* @description Create a field snapshot with the supplied value, fresh errors, and false metadata flags.
|
|
380
|
+
* @param {unknown} value - Value to store or inspect.
|
|
381
|
+
* @returns {FieldState} Independent field snapshot with the supplied value and fresh errors.
|
|
382
|
+
* - value `unknown` - Current field value.
|
|
383
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
384
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
385
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
386
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
387
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
388
|
+
* @example
|
|
389
|
+
* ```ts
|
|
390
|
+
* FieldStateFactory.create("Ada");
|
|
391
|
+
* ```
|
|
392
|
+
*/
|
|
393
|
+
static create(value) {
|
|
394
|
+
return {
|
|
395
|
+
...this.DEFAULT_FIELD_STATE,
|
|
396
|
+
value,
|
|
397
|
+
errors: []
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* @description Create an empty field snapshot with undefined value and fresh errors.
|
|
402
|
+
* @returns {FieldState} Independent empty snapshot with undefined value and false metadata flags.
|
|
403
|
+
* - value `unknown` - Current field value.
|
|
404
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
405
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
406
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
407
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
408
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
409
|
+
* @example
|
|
410
|
+
* ```ts
|
|
411
|
+
* FieldStateFactory.createDefault();
|
|
412
|
+
* ```
|
|
413
|
+
*/
|
|
414
|
+
static createDefault() {
|
|
415
|
+
return this.create(void 0);
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
// src/core/state/FormStateInitializer.ts
|
|
420
|
+
var FormStateInitializer = class {
|
|
421
|
+
/**
|
|
422
|
+
* @description Normalize default values; arrays become key containers, plain objects recurse, and other values become leaves.
|
|
423
|
+
* @param {TValues} defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
424
|
+
* @returns {FormState<TValues>} Initial normalized state with deterministic initial-N array keys.
|
|
425
|
+
* - defaultValues `TValues` - Initial values and the baseline used for dirty checks and reset.
|
|
426
|
+
* - fields `Record<string, FieldState<unknown>>` - Field snapshots indexed by normalized path keys.
|
|
427
|
+
* - submitCount `number` - Number of submission attempts started by the form.
|
|
428
|
+
* - isSubmitting `boolean` - Whether queued validation or a submit callback is still pending.
|
|
429
|
+
* - isSubmitted `boolean` - Whether a submission has completed at least once.
|
|
430
|
+
* - isSubmitSuccessful `boolean` - Whether the latest completed submission reached a successful valid callback.
|
|
431
|
+
* - arrayKeys `ArrayKeys` - Stable rendering keys indexed by array path.
|
|
432
|
+
* @example
|
|
433
|
+
* ```ts
|
|
434
|
+
* FormStateInitializer.initialize({ email: "" });
|
|
435
|
+
* ```
|
|
436
|
+
*/
|
|
437
|
+
static initialize(defaultValues) {
|
|
438
|
+
const fields = {};
|
|
439
|
+
const arrayKeys = {};
|
|
440
|
+
this.visitInitialValue(defaultValues, [], fields, arrayKeys);
|
|
441
|
+
return {
|
|
442
|
+
defaultValues,
|
|
443
|
+
fields,
|
|
444
|
+
submitCount: 0,
|
|
445
|
+
isSubmitting: false,
|
|
446
|
+
isSubmitted: false,
|
|
447
|
+
isSubmitSuccessful: false,
|
|
448
|
+
arrayKeys
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* 순회 가능한 plain object인지 확인한다.
|
|
453
|
+
*
|
|
454
|
+
* @remarks
|
|
455
|
+
* class 인스턴스나 Date 같은 객체는 내부 프로퍼티를 form field로 쪼개지 않고 leaf value로 보존한다.
|
|
456
|
+
*
|
|
457
|
+
* @param value - 검사할 값.
|
|
458
|
+
* @returns plain object이면 true.
|
|
459
|
+
*/
|
|
460
|
+
static isTraversableObject(value) {
|
|
461
|
+
return Object.prototype.toString.call(value) === "[object Object]";
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* defaultValues 안에 이미 존재하는 배열 item의 deterministic key를 만든다.
|
|
465
|
+
*
|
|
466
|
+
* @param length - 배열 길이.
|
|
467
|
+
* @returns `initial-0`, `initial-1` 형태의 key 배열.
|
|
468
|
+
*/
|
|
469
|
+
static createInitialArrayKeys(length) {
|
|
470
|
+
return Array.from({ length }, (_, index) => `initial-${index}`);
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* initial value tree를 DFS로 순회하며 fields와 arrayKeys 누적 객체에 기록한다.
|
|
474
|
+
*
|
|
475
|
+
* @param value - 현재 방문 중인 값.
|
|
476
|
+
* @param fieldPath - 현재 값이 위치한 tuple path.
|
|
477
|
+
* @param fields - leaf field 상태를 기록할 mutable accumulator.
|
|
478
|
+
* @param arrayKeys - 배열 container key 목록을 기록할 mutable accumulator.
|
|
479
|
+
*/
|
|
480
|
+
static visitInitialValue(value, fieldPath, fields, arrayKeys) {
|
|
481
|
+
if (Array.isArray(value)) {
|
|
482
|
+
arrayKeys[FormPath.pathToKey(fieldPath)] = this.createInitialArrayKeys(value.length);
|
|
483
|
+
value.forEach((item, index) => {
|
|
484
|
+
this.visitInitialValue(item, [...fieldPath, index], fields, arrayKeys);
|
|
485
|
+
});
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
if (this.isTraversableObject(value)) {
|
|
489
|
+
const entries = Object.entries(value);
|
|
490
|
+
if (entries.length === 0) {
|
|
491
|
+
fields[FormPath.pathToKey(fieldPath)] = FieldStateFactory.create(value);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
entries.forEach(([key, childValue]) => {
|
|
495
|
+
this.visitInitialValue(childValue, [...fieldPath, key], fields, arrayKeys);
|
|
496
|
+
});
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
fields[FormPath.pathToKey(fieldPath)] = FieldStateFactory.create(value);
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
// src/core/value/ValueHelper.ts
|
|
504
|
+
var ValueHelper = class {
|
|
505
|
+
/**
|
|
506
|
+
* values 복원을 시작할 root container를 만든다.
|
|
507
|
+
*
|
|
508
|
+
* @param source - defaultValues의 root 값.
|
|
509
|
+
* @returns source가 배열이면 빈 배열, 객체면 빈 객체, primitive면 source 자체.
|
|
510
|
+
*/
|
|
511
|
+
static createEmptyRoot(source) {
|
|
512
|
+
if (Array.isArray(source)) {
|
|
513
|
+
return [];
|
|
514
|
+
}
|
|
515
|
+
if (typeof source === "object" && source !== null) {
|
|
516
|
+
return {};
|
|
517
|
+
}
|
|
518
|
+
return source;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* @description Read a nested tuple path, returning undefined when a traversed container is missing or primitive.
|
|
522
|
+
* @param {unknown} source - Root object or array to read or immutably update.
|
|
523
|
+
* @param {FieldPath} path - Tuple path identifying the target field or value.
|
|
524
|
+
* @returns {unknown} Value at the tuple path, or undefined for an unreachable path.
|
|
525
|
+
* @example
|
|
526
|
+
* ```ts
|
|
527
|
+
* ValueHelper.getValueAtPath({ email: "Ada" }, ["email"]);
|
|
528
|
+
* ```
|
|
529
|
+
*/
|
|
530
|
+
static getValueAtPath(source, path) {
|
|
531
|
+
let current = source;
|
|
532
|
+
for (const segment of path) {
|
|
533
|
+
if (current === null || current === void 0) {
|
|
534
|
+
return void 0;
|
|
535
|
+
}
|
|
536
|
+
if (typeof current !== "object" && typeof current !== "function") {
|
|
537
|
+
return void 0;
|
|
538
|
+
}
|
|
539
|
+
current = current[segment];
|
|
540
|
+
}
|
|
541
|
+
return current;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* @description Copy containers along a tuple path and write the value without mutating the original root.
|
|
545
|
+
* @param {TValues} source - Root object or array to read or immutably update.
|
|
546
|
+
* @param {FieldPath} path - Tuple path identifying the target field or value.
|
|
547
|
+
* @param {unknown} value - Value to store or inspect.
|
|
548
|
+
* @returns {TValues} New root with the path updated; untouched branches retain their references.
|
|
549
|
+
* @example
|
|
550
|
+
* ```ts
|
|
551
|
+
* ValueHelper.setValueAtPath({ email: "Ada" }, ["email"], "Ada");
|
|
552
|
+
* ```
|
|
553
|
+
*/
|
|
554
|
+
static setValueAtPath(source, path, value) {
|
|
555
|
+
if (path.length === 0) {
|
|
556
|
+
return value;
|
|
557
|
+
}
|
|
558
|
+
const cloneRoot = Array.isArray(source) ? [...source] : typeof source === "object" && source !== null ? { ...source } : {};
|
|
559
|
+
let current = cloneRoot;
|
|
560
|
+
path.forEach((segment, index) => {
|
|
561
|
+
if (index === path.length - 1) {
|
|
562
|
+
current[segment] = value;
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const nextSegment = path[index + 1];
|
|
566
|
+
const previous = current[segment];
|
|
567
|
+
const next = Array.isArray(previous) ? [...previous] : typeof previous === "object" && previous !== null ? { ...previous } : typeof nextSegment === "number" ? [] : {};
|
|
568
|
+
current[segment] = next;
|
|
569
|
+
current = next;
|
|
570
|
+
});
|
|
571
|
+
return cloneRoot;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* @description Rebuild nested values from normalized fields and array keys, using the supplied path lookup.
|
|
575
|
+
* @param {FormState<TValues>} state - Form snapshot used as the source of this calculation.
|
|
576
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
577
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
578
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
579
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
580
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
581
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
582
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
583
|
+
* @param {Readonly<Record<string, FieldPath>>} fieldPaths - Lookup from normalized keys to tuple paths.
|
|
584
|
+
* @returns {TValues} Nested values rebuilt from field values and array container lengths.
|
|
585
|
+
* @example
|
|
586
|
+
* ```ts
|
|
587
|
+
* ValueHelper.getValuesFromFields(state, FormStateReader.getKnownFieldPaths(state));
|
|
588
|
+
* ```
|
|
589
|
+
*/
|
|
590
|
+
static getValuesFromFields(state, fieldPaths) {
|
|
591
|
+
const valueWithArrays = Object.entries(state.arrayKeys).reduce((values, [key, keys]) => {
|
|
592
|
+
return this.setValueAtPath(values, FormPath.keyToPath(key), new Array(keys.length));
|
|
593
|
+
}, this.createEmptyRoot(state.defaultValues));
|
|
594
|
+
return Object.entries(state.fields).reduce((values, [key, field]) => {
|
|
595
|
+
const fieldPath = fieldPaths[key];
|
|
596
|
+
if (!fieldPath) {
|
|
597
|
+
return values;
|
|
598
|
+
}
|
|
599
|
+
return this.setValueAtPath(values, fieldPath, field.value);
|
|
600
|
+
}, valueWithArrays);
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
// src/core/state/FormStateReader.ts
|
|
605
|
+
var FormStateReader = class _FormStateReader {
|
|
606
|
+
/**
|
|
607
|
+
* @description Decode the snapshot field keys into a lookup of tuple paths.
|
|
608
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
609
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
610
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
611
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
612
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
613
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
614
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
615
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
616
|
+
* @returns {Record<string, FieldPath>} Lookup mapping each stored field key to its decoded tuple path.
|
|
617
|
+
* @example
|
|
618
|
+
* ```ts
|
|
619
|
+
* FormStateReader.getKnownFieldPaths(state);
|
|
620
|
+
* ```
|
|
621
|
+
*/
|
|
622
|
+
static getKnownFieldPaths(state) {
|
|
623
|
+
return Object.keys(state.fields).reduce((paths, key) => {
|
|
624
|
+
paths[key] = FormPath.keyToPath(key);
|
|
625
|
+
return paths;
|
|
626
|
+
}, {});
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* @description Read a normalized field key, returning an independent default snapshot when absent.
|
|
630
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
631
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
632
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
633
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
634
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
635
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
636
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
637
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
638
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
639
|
+
* @returns {Readonly<FieldState>} Stored field snapshot, or an empty snapshot for an absent key.
|
|
640
|
+
* - value `unknown` - Current field value.
|
|
641
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
642
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
643
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
644
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
645
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
646
|
+
* @example
|
|
647
|
+
* ```ts
|
|
648
|
+
* FormStateReader.getFieldStateByKey(state, FormPath.pathToKey(["email"]));
|
|
649
|
+
* ```
|
|
650
|
+
*/
|
|
651
|
+
static getFieldStateByKey(state, fieldKey) {
|
|
652
|
+
return state.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* @description Read field metadata and use a default snapshot when the field is not present.
|
|
656
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
657
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
658
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
659
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
660
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
661
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
662
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
663
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
664
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
665
|
+
* @returns {Readonly<FieldState>} Field snapshot, with a default shape when the leaf field is absent.
|
|
666
|
+
* - value `unknown` - Current field value.
|
|
667
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
668
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
669
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
670
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
671
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
672
|
+
* @example
|
|
673
|
+
* ```ts
|
|
674
|
+
* FormStateReader.getFieldState(state, ["email"]);
|
|
675
|
+
* ```
|
|
676
|
+
*/
|
|
677
|
+
static getFieldState(state, fieldPath) {
|
|
678
|
+
return _FormStateReader.getFieldStateByKey(state, FormPath.pathInputToKey(fieldPath));
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* @description Read only the current value of the selected field.
|
|
682
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
683
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
684
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
685
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
686
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
687
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
688
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
689
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
690
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
691
|
+
* @returns {unknown} Stored field value, or undefined when the field has no value.
|
|
692
|
+
* @example
|
|
693
|
+
* ```ts
|
|
694
|
+
* FormStateReader.getValue(state, ["email"]);
|
|
695
|
+
* ```
|
|
696
|
+
*/
|
|
697
|
+
static getValue(state, fieldPath) {
|
|
698
|
+
return _FormStateReader.getFieldState(state, fieldPath).value;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* @description Reconstruct the nested values object from leaf fields and array containers.
|
|
702
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
703
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
704
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
705
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
706
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
707
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
708
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
709
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
710
|
+
* @returns {TValues} Nested values reconstructed in the shape of the supplied defaults.
|
|
711
|
+
* @example
|
|
712
|
+
* ```ts
|
|
713
|
+
* FormStateReader.getValues(state);
|
|
714
|
+
* ```
|
|
715
|
+
*/
|
|
716
|
+
static getValues(state) {
|
|
717
|
+
return ValueHelper.getValuesFromFields(state, _FormStateReader.getKnownFieldPaths(state));
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* @description Read a nested tuple path, returning undefined when a traversed container is missing or primitive.
|
|
721
|
+
* @param {Readonly<FormState<TValues>>} state - Form snapshot used as the source of this calculation.
|
|
722
|
+
* @param {TValues} state.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
723
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
724
|
+
* @param {number} state.submitCount - Number of submission attempts started by the form.
|
|
725
|
+
* @param {boolean} state.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
726
|
+
* @param {boolean} state.isSubmitted - Whether a submission has completed at least once.
|
|
727
|
+
* @param {boolean} state.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
728
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
729
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
730
|
+
* @returns {unknown} Value at the tuple path, or undefined for an unreachable path.
|
|
731
|
+
* @example
|
|
732
|
+
* ```ts
|
|
733
|
+
* FormStateReader.getValueAtPath(state, ["email"]);
|
|
734
|
+
* ```
|
|
735
|
+
*/
|
|
736
|
+
static getValueAtPath(state, fieldPath) {
|
|
737
|
+
return ValueHelper.getValueAtPath(_FormStateReader.getValues(state), fieldPath);
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
// src/core/array/FormArrayRebaser.ts
|
|
742
|
+
var FormArrayRebaser = class {
|
|
743
|
+
/**
|
|
744
|
+
* @description Apply next array values and move surviving child metadata and nested array keys to their new indexes.
|
|
745
|
+
* @param {Readonly<FormState<TValues>>} previousState - Snapshot before the array mutation.
|
|
746
|
+
* @param {TValues} previousState.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
747
|
+
* @param {Record<string, FieldState<unknown>>} previousState.fields - Field snapshots indexed by normalized path keys.
|
|
748
|
+
* @param {number} previousState.submitCount - Number of submission attempts started by the form.
|
|
749
|
+
* @param {boolean} previousState.isSubmitting - Whether queued validation or a submit callback is still pending.
|
|
750
|
+
* @param {boolean} previousState.isSubmitted - Whether a submission has completed at least once.
|
|
751
|
+
* @param {boolean} previousState.isSubmitSuccessful - Whether the latest completed submission reached a successful valid callback.
|
|
752
|
+
* @param {ArrayKeys} previousState.arrayKeys - Stable rendering keys indexed by array path.
|
|
753
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
754
|
+
* @param {FormArrayMutation} mutation - Next array values, stable keys, and old-to-new index mapper.
|
|
755
|
+
* @param {readonly unknown[]} mutation.values - Array values after this mutation, in the same order as the stable keys.
|
|
756
|
+
* @param {readonly string[]} mutation.keys - Stable item keys in array order.
|
|
757
|
+
* @param {IndexMapper} mutation.mapPreviousIndex - Map an old item index to its new position, or undefined if removed.
|
|
758
|
+
* @returns {FormState<TValues>} Next form snapshot with surviving child metadata and submission state preserved.
|
|
759
|
+
* - defaultValues `TValues` - Initial values and the baseline used for dirty checks and reset.
|
|
760
|
+
* - fields `Record<string, FieldState<unknown>>` - Field snapshots indexed by normalized path keys.
|
|
761
|
+
* - submitCount `number` - Number of submission attempts started by the form.
|
|
762
|
+
* - isSubmitting `boolean` - Whether queued validation or a submit callback is still pending.
|
|
763
|
+
* - isSubmitted `boolean` - Whether a submission has completed at least once.
|
|
764
|
+
* - isSubmitSuccessful `boolean` - Whether the latest completed submission reached a successful valid callback.
|
|
765
|
+
* - arrayKeys `ArrayKeys` - Stable rendering keys indexed by array path.
|
|
766
|
+
* @example
|
|
767
|
+
* ```ts
|
|
768
|
+
* const mutation = FormArrayMutationPlanner.push([], [], "Ada", "item-1");
|
|
769
|
+
* const next = FormArrayRebaser.rebase(state, ["users"], mutation);
|
|
770
|
+
* ```
|
|
771
|
+
*/
|
|
772
|
+
static rebase(previousState, fieldPath, mutation) {
|
|
773
|
+
const fieldPaths = FormStateReader.getKnownFieldPaths(previousState);
|
|
774
|
+
const nextValues = ValueHelper.setValueAtPath(FormStateReader.getValues(previousState), fieldPath, [...mutation.values]);
|
|
775
|
+
const initializedState = FormStateInitializer.initialize(nextValues);
|
|
776
|
+
const arrayKey = FormPath.pathToKey(fieldPath);
|
|
777
|
+
const rebasedFields = { ...initializedState.fields };
|
|
778
|
+
const rebasedArrayKeys = { ...initializedState.arrayKeys };
|
|
779
|
+
Object.entries(previousState.fields).forEach(([fieldKey, previousField]) => {
|
|
780
|
+
const currentFieldPath = fieldPaths[fieldKey];
|
|
781
|
+
if (!currentFieldPath) {
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (!FormArrayPath.isArrayChildPath(currentFieldPath, fieldPath)) {
|
|
785
|
+
rebasedFields[fieldKey] = previousField;
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
const previousIndex = currentFieldPath[fieldPath.length];
|
|
789
|
+
if (typeof previousIndex !== "number") {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
const nextIndex = mutation.mapPreviousIndex(previousIndex);
|
|
793
|
+
if (nextIndex === void 0) {
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const nextFieldPath = FormArrayPath.replaceArrayIndex(currentFieldPath, fieldPath, nextIndex);
|
|
797
|
+
const nextFieldKey = FormPath.pathToKey(nextFieldPath);
|
|
798
|
+
const nextField = initializedState.fields[nextFieldKey] ?? FieldStateFactory.createDefault();
|
|
799
|
+
rebasedFields[nextFieldKey] = {
|
|
800
|
+
...nextField,
|
|
801
|
+
errors: previousField.errors,
|
|
802
|
+
touched: previousField.touched,
|
|
803
|
+
dirty: previousField.dirty,
|
|
804
|
+
modified: previousField.modified,
|
|
805
|
+
isFocused: previousField.isFocused
|
|
806
|
+
};
|
|
807
|
+
});
|
|
808
|
+
Object.entries(previousState.arrayKeys).forEach(([previousArrayKey, previousKeys]) => {
|
|
809
|
+
if (previousArrayKey === arrayKey) {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const previousArrayPath = FormPath.keyToPath(previousArrayKey);
|
|
813
|
+
let nextArrayPath = previousArrayPath;
|
|
814
|
+
if (FormArrayPath.isArrayChildPath(previousArrayPath, fieldPath)) {
|
|
815
|
+
const previousIndex = previousArrayPath[fieldPath.length];
|
|
816
|
+
if (typeof previousIndex !== "number") {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
const nextIndex = mutation.mapPreviousIndex(previousIndex);
|
|
820
|
+
if (nextIndex === void 0) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
nextArrayPath = FormArrayPath.replaceArrayIndex(previousArrayPath, fieldPath, nextIndex);
|
|
824
|
+
}
|
|
825
|
+
const nextArrayKey = FormPath.pathToKey(nextArrayPath);
|
|
826
|
+
const initializedKeys = initializedState.arrayKeys[nextArrayKey];
|
|
827
|
+
if (initializedKeys?.length === previousKeys.length) {
|
|
828
|
+
rebasedArrayKeys[nextArrayKey] = [...previousKeys];
|
|
829
|
+
}
|
|
830
|
+
});
|
|
831
|
+
rebasedArrayKeys[arrayKey] = [...mutation.keys];
|
|
832
|
+
return {
|
|
833
|
+
...initializedState,
|
|
834
|
+
fields: rebasedFields,
|
|
835
|
+
arrayKeys: rebasedArrayKeys,
|
|
836
|
+
submitCount: previousState.submitCount,
|
|
837
|
+
isSubmitting: previousState.isSubmitting,
|
|
838
|
+
isSubmitted: previousState.isSubmitted,
|
|
839
|
+
isSubmitSuccessful: previousState.isSubmitSuccessful
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
// src/core/array/FormArrayController.ts
|
|
845
|
+
var FormArrayController = class {
|
|
846
|
+
/** 배열 값과 arrayKeys를 읽고, 최종 FormState를 교체할 store다. */
|
|
847
|
+
store;
|
|
848
|
+
/** 새 배열 item에 부여할 안정적인 render key를 만든다. */
|
|
849
|
+
keyGenerator;
|
|
850
|
+
/** 이 controller가 담당하는 배열 field의 내부 tuple path다. */
|
|
851
|
+
fieldPath;
|
|
852
|
+
/**
|
|
853
|
+
* @description Create an array controller for one tuple path with the shared form key generator.
|
|
854
|
+
* @param {FormStateStore<TValues>} store - Shared form state store to read and update.
|
|
855
|
+
* @param {ArrayKeyGenerator} keys - Item key generator shared by controllers in this form.
|
|
856
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
857
|
+
* @example
|
|
858
|
+
* ```ts
|
|
859
|
+
* const items = new FormArrayController(store, new ArrayKeyGenerator(), ["users"]);
|
|
860
|
+
* ```
|
|
861
|
+
*/
|
|
862
|
+
constructor(store, keys, fieldPath) {
|
|
863
|
+
this.store = store;
|
|
864
|
+
this.keyGenerator = keys;
|
|
865
|
+
this.fieldPath = fieldPath;
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* @description Read stable rendering keys in current item order.
|
|
869
|
+
* @returns {readonly string[]} Stable rendering keys corresponding to current array items.
|
|
870
|
+
* @example
|
|
871
|
+
* ```ts
|
|
872
|
+
* items.keys();
|
|
873
|
+
* ```
|
|
874
|
+
*/
|
|
875
|
+
keys() {
|
|
876
|
+
return this.getKeys();
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* @description Insert an item at a bounded index and allocate its stable key.
|
|
880
|
+
* @param {number} index - Zero-based item index.
|
|
881
|
+
* @param {unknown} value - Value to store or inspect.
|
|
882
|
+
* @example
|
|
883
|
+
* ```ts
|
|
884
|
+
* items.insert(0, "Ada");
|
|
885
|
+
* ```
|
|
886
|
+
*/
|
|
887
|
+
insert(index, value) {
|
|
888
|
+
this.applyMutation(FormArrayMutationPlanner.insert(this.getArray(), this.getKeys(), index, value, this.keyGenerator.create()));
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* @description Append an item and allocate its stable key.
|
|
892
|
+
* @param {unknown} value - Value to store or inspect.
|
|
893
|
+
* @example
|
|
894
|
+
* ```ts
|
|
895
|
+
* items.push("Ada");
|
|
896
|
+
* ```
|
|
897
|
+
*/
|
|
898
|
+
push(value) {
|
|
899
|
+
this.applyMutation(FormArrayMutationPlanner.push(this.getArray(), this.getKeys(), value, this.keyGenerator.create()));
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* @description Remove a valid item and its child state; an invalid index leaves the state unchanged.
|
|
903
|
+
* @param {number} index - Zero-based item index.
|
|
904
|
+
* @example
|
|
905
|
+
* ```ts
|
|
906
|
+
* items.remove(0);
|
|
907
|
+
* ```
|
|
908
|
+
*/
|
|
909
|
+
remove(index) {
|
|
910
|
+
this.applyMutation(FormArrayMutationPlanner.remove(this.getArray(), this.getKeys(), index));
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* @description Move an item and its metadata; invalid or identical indexes leave the state unchanged.
|
|
914
|
+
* @param {number} fromIndex - Original index of the item to move.
|
|
915
|
+
* @param {number} toIndex - Destination index of the moved item.
|
|
916
|
+
* @example
|
|
917
|
+
* ```ts
|
|
918
|
+
* items.move(0, 1);
|
|
919
|
+
* ```
|
|
920
|
+
*/
|
|
921
|
+
move(fromIndex, toIndex) {
|
|
922
|
+
this.applyMutation(FormArrayMutationPlanner.move(this.getArray(), this.getKeys(), fromIndex, toIndex));
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* @description Swap two items with their keys and metadata; invalid or identical indexes leave the state unchanged.
|
|
926
|
+
* @param {number} leftIndex - First item index.
|
|
927
|
+
* @param {number} rightIndex - Second item index.
|
|
928
|
+
* @example
|
|
929
|
+
* ```ts
|
|
930
|
+
* items.swap(0, 1);
|
|
931
|
+
* ```
|
|
932
|
+
*/
|
|
933
|
+
swap(leftIndex, rightIndex) {
|
|
934
|
+
this.applyMutation(FormArrayMutationPlanner.swap(this.getArray(), this.getKeys(), leftIndex, rightIndex));
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* @description Replace all items and regenerate their keys and child field state.
|
|
938
|
+
* @param {readonly unknown[]} values - Replacement or current form values.
|
|
939
|
+
* @example
|
|
940
|
+
* ```ts
|
|
941
|
+
* items.replace(["Ada", "Lin"]);
|
|
942
|
+
* ```
|
|
943
|
+
*/
|
|
944
|
+
replace(values) {
|
|
945
|
+
this.applyMutation(FormArrayMutationPlanner.replace(values, values.map(() => this.keyGenerator.create())));
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* store에서 현재 배열 값을 읽는다.
|
|
949
|
+
*
|
|
950
|
+
* @returns path의 값이 배열이면 그 배열, 아니면 빈 배열.
|
|
951
|
+
*/
|
|
952
|
+
getArray() {
|
|
953
|
+
const value = this.store.getValueAtPath(this.fieldPath);
|
|
954
|
+
return Array.isArray(value) ? value : [];
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* 현재 배열에 대응하는 render key 목록을 읽는다.
|
|
958
|
+
*
|
|
959
|
+
* @returns store에 저장된 arrayKeys가 있으면 그것을 사용하고, 없으면 현재 배열 길이만큼 새 key를 만든다.
|
|
960
|
+
*/
|
|
961
|
+
getKeys() {
|
|
962
|
+
const arrayKey = FormPath.pathToKey(this.fieldPath);
|
|
963
|
+
const currentArray = this.getArray();
|
|
964
|
+
return this.store.getState().arrayKeys[arrayKey] ?? currentArray.map(() => this.keyGenerator.create());
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* planner가 만든 mutation이 있으면 rebase를 실행한다.
|
|
968
|
+
*
|
|
969
|
+
* @param mutation - 유효하지 않은 조작이면 undefined일 수 있다.
|
|
970
|
+
*/
|
|
971
|
+
applyMutation(mutation) {
|
|
972
|
+
if (!mutation) {
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
this.store.replaceState(
|
|
976
|
+
(previousState) => FormArrayRebaser.rebase(previousState, this.fieldPath, mutation)
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
// src/core/form/FormSubmitter.ts
|
|
982
|
+
var FormSubmitter = class {
|
|
983
|
+
/**
|
|
984
|
+
* @description Create a submit queue over the same store and validation engine.
|
|
985
|
+
* @param {FormStateStore<TValues>} store - Shared form state store to read and update.
|
|
986
|
+
* @param {ValidationEngine<TValues>} validation - Validation engine sharing the same state store.
|
|
987
|
+
* @example
|
|
988
|
+
* ```ts
|
|
989
|
+
* const submitter = new FormSubmitter(store, validation);
|
|
990
|
+
* ```
|
|
991
|
+
*/
|
|
992
|
+
constructor(store, validation) {
|
|
993
|
+
this.store = store;
|
|
994
|
+
this.validation = validation;
|
|
995
|
+
}
|
|
996
|
+
store;
|
|
997
|
+
validation;
|
|
998
|
+
submissionQueue = Promise.resolve();
|
|
999
|
+
pendingSubmissionCount = 0;
|
|
1000
|
+
/**
|
|
1001
|
+
* @description Queue a submission, retry stale validation, and return the valid callback result or undefined after invalid validation.
|
|
1002
|
+
* @param {(values: TValues) => TResult | Promise<TResult>} onValid - Callback receiving current values after successful validation.
|
|
1003
|
+
* @param {((fields: Readonly<Record<PathKey, FieldState>>) => void) | undefined} [onInvalid] - Callback receiving field snapshots when validation fails.
|
|
1004
|
+
* @returns {Promise<TResult | undefined>} Promise of the valid callback result, or undefined when validation fails; callback errors reject.
|
|
1005
|
+
* @example
|
|
1006
|
+
* ```ts
|
|
1007
|
+
* await submitter.submit(values => save(values), fields => showErrors(fields));
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
submit(onValid, onInvalid) {
|
|
1011
|
+
this.pendingSubmissionCount += 1;
|
|
1012
|
+
this.store.beginSubmit();
|
|
1013
|
+
const submission = this.submissionQueue.then(() => this.executeSubmission(onValid, onInvalid));
|
|
1014
|
+
this.submissionQueue = submission.then(
|
|
1015
|
+
() => void 0,
|
|
1016
|
+
() => void 0
|
|
1017
|
+
);
|
|
1018
|
+
return submission;
|
|
1019
|
+
}
|
|
1020
|
+
async executeSubmission(onValid, onInvalid) {
|
|
1021
|
+
let successful = false;
|
|
1022
|
+
try {
|
|
1023
|
+
while (true) {
|
|
1024
|
+
const outcome = await this.validation.validateRegisteredFieldsOutcome("submit");
|
|
1025
|
+
switch (outcome.kind) {
|
|
1026
|
+
case "stale":
|
|
1027
|
+
continue;
|
|
1028
|
+
case "invalid":
|
|
1029
|
+
onInvalid?.(this.store.getState().fields);
|
|
1030
|
+
return void 0;
|
|
1031
|
+
case "valid": {
|
|
1032
|
+
const result = await onValid(this.store.getValues());
|
|
1033
|
+
successful = true;
|
|
1034
|
+
return result;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
} finally {
|
|
1039
|
+
this.pendingSubmissionCount -= 1;
|
|
1040
|
+
if (this.pendingSubmissionCount === 0) {
|
|
1041
|
+
this.store.completeSubmit(successful);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
var FormStateStore = class {
|
|
1047
|
+
store;
|
|
1048
|
+
/**
|
|
1049
|
+
* @description Create a store by normalizing the supplied default values.
|
|
1050
|
+
* @param {TValues} defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
1051
|
+
* @example
|
|
1052
|
+
* ```ts
|
|
1053
|
+
* const store = new FormStateStore({ email: "" });
|
|
1054
|
+
* ```
|
|
1055
|
+
*/
|
|
1056
|
+
constructor(defaultValues) {
|
|
1057
|
+
this.store = createStore(FormStateInitializer.initialize(defaultValues));
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* @description Read the current immutable form snapshot without cloning it.
|
|
1061
|
+
* @returns {Readonly<FormState<TValues>>} Current read-only snapshot; callers must not mutate it.
|
|
1062
|
+
* - defaultValues `TValues` - Initial values and the baseline used for dirty checks and reset.
|
|
1063
|
+
* - fields `Record<string, FieldState<unknown>>` - Field snapshots indexed by normalized path keys.
|
|
1064
|
+
* - submitCount `number` - Number of submission attempts started by the form.
|
|
1065
|
+
* - isSubmitting `boolean` - Whether queued validation or a submit callback is still pending.
|
|
1066
|
+
* - isSubmitted `boolean` - Whether a submission has completed at least once.
|
|
1067
|
+
* - isSubmitSuccessful `boolean` - Whether the latest completed submission reached a successful valid callback.
|
|
1068
|
+
* - arrayKeys `ArrayKeys` - Stable rendering keys indexed by array path.
|
|
1069
|
+
* @example
|
|
1070
|
+
* ```ts
|
|
1071
|
+
* store.getState();
|
|
1072
|
+
* ```
|
|
1073
|
+
*/
|
|
1074
|
+
getState() {
|
|
1075
|
+
return this.store.getState();
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* @description Subscribe to form state changes and return the callback that unsubscribes this listener.
|
|
1079
|
+
* @param {() => void} listener - Callback invoked synchronously after a state change.
|
|
1080
|
+
* @returns {() => void} Cleanup callback for this subscription or registration.
|
|
1081
|
+
* @example
|
|
1082
|
+
* ```ts
|
|
1083
|
+
* store.subscribe(() => render());
|
|
1084
|
+
* ```
|
|
1085
|
+
*/
|
|
1086
|
+
subscribe(listener) {
|
|
1087
|
+
return this.store.subscribe(listener);
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* @description Read a normalized field key, returning an independent default snapshot when absent.
|
|
1091
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1092
|
+
* @returns {Readonly<FieldState>} Stored field snapshot, or an empty snapshot for an absent key.
|
|
1093
|
+
* - value `unknown` - Current field value.
|
|
1094
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
1095
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
1096
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
1097
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
1098
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
1099
|
+
* @example
|
|
1100
|
+
* ```ts
|
|
1101
|
+
* store.getFieldStateByKey(FormPath.pathToKey(["email"]));
|
|
1102
|
+
* ```
|
|
1103
|
+
*/
|
|
1104
|
+
getFieldStateByKey(fieldKey) {
|
|
1105
|
+
return FormStateReader.getFieldStateByKey(this.store.getState(), fieldKey);
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* @description Read field metadata and use a default snapshot when the field is not present.
|
|
1109
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
1110
|
+
* @returns {Readonly<FieldState>} Field snapshot, with a default shape when the leaf field is absent.
|
|
1111
|
+
* - value `unknown` - Current field value.
|
|
1112
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
1113
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
1114
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
1115
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
1116
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
1117
|
+
* @example
|
|
1118
|
+
* ```ts
|
|
1119
|
+
* store.getFieldState(["email"]);
|
|
1120
|
+
* ```
|
|
1121
|
+
*/
|
|
1122
|
+
getFieldState(fieldPath) {
|
|
1123
|
+
return FormStateReader.getFieldState(this.store.getState(), fieldPath);
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* @description Read only the current value of the selected field.
|
|
1127
|
+
* @param {FieldPathInput} fieldPath - Literal field name or tuple path; strings are not split on dots.
|
|
1128
|
+
* @returns {unknown} Stored field value, or undefined when the field has no value.
|
|
1129
|
+
* @example
|
|
1130
|
+
* ```ts
|
|
1131
|
+
* store.getValue(["email"]);
|
|
1132
|
+
* ```
|
|
1133
|
+
*/
|
|
1134
|
+
getValue(fieldPath) {
|
|
1135
|
+
return FormStateReader.getValue(this.store.getState(), fieldPath);
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* @description Reconstruct the nested values object from leaf fields and array containers.
|
|
1139
|
+
* @returns {TValues} Nested values reconstructed in the shape of the supplied defaults.
|
|
1140
|
+
* @example
|
|
1141
|
+
* ```ts
|
|
1142
|
+
* store.getValues();
|
|
1143
|
+
* ```
|
|
1144
|
+
*/
|
|
1145
|
+
getValues() {
|
|
1146
|
+
return FormStateReader.getValues(this.store.getState());
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* @description Read a nested tuple path, returning undefined when a traversed container is missing or primitive.
|
|
1150
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
1151
|
+
* @returns {unknown} Value at the tuple path, or undefined for an unreachable path.
|
|
1152
|
+
* @example
|
|
1153
|
+
* ```ts
|
|
1154
|
+
* store.getValueAtPath(["email"]);
|
|
1155
|
+
* ```
|
|
1156
|
+
*/
|
|
1157
|
+
getValueAtPath(fieldPath) {
|
|
1158
|
+
return FormStateReader.getValueAtPath(this.store.getState(), fieldPath);
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* @description Write a field value, compare dirty state with its default, and mark user-originated changes as modified. Return the normalized key for subsequent validation.
|
|
1162
|
+
* @param {FieldPath} fieldPath - Tuple path identifying the target field or value.
|
|
1163
|
+
* @param {unknown} value - Value to store or inspect.
|
|
1164
|
+
* @param {SetValueOptions} [options] - Write origin and optional immediate validation request.
|
|
1165
|
+
* @param {"user" | "program" | undefined} [options.source] - Write origin; user writes mark the field as modified.
|
|
1166
|
+
* @param {boolean | undefined} [options.validate] - Validation request for the controller; the state store itself does not run validation.
|
|
1167
|
+
* @returns {string} Normalized field key for the updated value.
|
|
1168
|
+
* @example
|
|
1169
|
+
* ```ts
|
|
1170
|
+
* store.setValue(["email"], "Ada", { source: "user" });
|
|
1171
|
+
* ```
|
|
1172
|
+
*/
|
|
1173
|
+
setValue(fieldPath, value, options = {}) {
|
|
1174
|
+
const fieldKey = FormPath.pathToKey(fieldPath);
|
|
1175
|
+
const defaultValue = ValueHelper.getValueAtPath(this.store.getState().defaultValues, fieldPath);
|
|
1176
|
+
this.store.setState(
|
|
1177
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1178
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1179
|
+
draft.fields[fieldKey] = {
|
|
1180
|
+
...previousField,
|
|
1181
|
+
value,
|
|
1182
|
+
dirty: !Object.is(value, defaultValue),
|
|
1183
|
+
modified: options.source === "user" ? true : previousField.modified
|
|
1184
|
+
};
|
|
1185
|
+
})
|
|
1186
|
+
);
|
|
1187
|
+
return fieldKey;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* @description Mark a field touched, creating default metadata if the field does not yet exist.
|
|
1191
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1192
|
+
* @example
|
|
1193
|
+
* ```ts
|
|
1194
|
+
* store.touchField(FormPath.pathToKey(["email"]));
|
|
1195
|
+
* ```
|
|
1196
|
+
*/
|
|
1197
|
+
touchField(fieldKey) {
|
|
1198
|
+
this.store.setState(
|
|
1199
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1200
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1201
|
+
draft.fields[fieldKey] = {
|
|
1202
|
+
...previousField,
|
|
1203
|
+
touched: true
|
|
1204
|
+
};
|
|
1205
|
+
})
|
|
1206
|
+
);
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* @description Record focus, creating a default snapshot for an unknown field without clearing other fields.
|
|
1210
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1211
|
+
* @example
|
|
1212
|
+
* ```ts
|
|
1213
|
+
* store.focusField(FormPath.pathToKey(["email"]));
|
|
1214
|
+
* ```
|
|
1215
|
+
*/
|
|
1216
|
+
focusField(fieldKey) {
|
|
1217
|
+
this.store.setState(
|
|
1218
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1219
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1220
|
+
draft.fields[fieldKey] = {
|
|
1221
|
+
...previousField,
|
|
1222
|
+
isFocused: true
|
|
1223
|
+
};
|
|
1224
|
+
})
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* @description Clear focus, creating a default snapshot for an unknown field if necessary.
|
|
1229
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1230
|
+
* @example
|
|
1231
|
+
* ```ts
|
|
1232
|
+
* store.unfocusField(FormPath.pathToKey(["email"]));
|
|
1233
|
+
* ```
|
|
1234
|
+
*/
|
|
1235
|
+
unfocusField(fieldKey) {
|
|
1236
|
+
this.store.setState(
|
|
1237
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1238
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1239
|
+
draft.fields[fieldKey] = {
|
|
1240
|
+
...previousField,
|
|
1241
|
+
isFocused: false
|
|
1242
|
+
};
|
|
1243
|
+
})
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* @description Replace the errors for a normalized field key, creating a default field if necessary.
|
|
1248
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1249
|
+
* @param {readonly FormError[]} errors - Current validation errors for the field.
|
|
1250
|
+
* @example
|
|
1251
|
+
* ```ts
|
|
1252
|
+
* store.setErrorsByKey(FormPath.pathToKey(["email"]), errors);
|
|
1253
|
+
* ```
|
|
1254
|
+
*/
|
|
1255
|
+
setErrorsByKey(fieldKey, errors) {
|
|
1256
|
+
this.store.setState(
|
|
1257
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1258
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1259
|
+
draft.fields[fieldKey] = {
|
|
1260
|
+
...previousField,
|
|
1261
|
+
errors: [...errors]
|
|
1262
|
+
};
|
|
1263
|
+
})
|
|
1264
|
+
);
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* @description Clear selected fields or all fields when no paths are provided.
|
|
1268
|
+
* @param {readonly string[] | undefined} [fieldKeys] - Normalized path keys to target.
|
|
1269
|
+
* @example
|
|
1270
|
+
* ```ts
|
|
1271
|
+
* store.clearErrors([FormPath.pathToKey(["email"])]);
|
|
1272
|
+
* ```
|
|
1273
|
+
*/
|
|
1274
|
+
clearErrors(fieldKeys) {
|
|
1275
|
+
this.store.setState(
|
|
1276
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1277
|
+
const keys = fieldKeys && fieldKeys.length > 0 ? fieldKeys : Object.keys(draft.fields);
|
|
1278
|
+
keys.forEach((fieldKey) => {
|
|
1279
|
+
const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
|
|
1280
|
+
draft.fields[fieldKey] = {
|
|
1281
|
+
...previousField,
|
|
1282
|
+
errors: []
|
|
1283
|
+
};
|
|
1284
|
+
});
|
|
1285
|
+
})
|
|
1286
|
+
);
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* @description Reinitialize values and metadata, optionally retaining dirty values, errors, touched flags, and submission state.
|
|
1290
|
+
* @param {TValues | undefined} [values] - Replacement or current form values.
|
|
1291
|
+
* @param {ResetOptions} [options] - State preservation flags for this reset.
|
|
1292
|
+
* @param {boolean | undefined} [options.keepDirtyValues] - Preserve current values and modified flags of dirty fields.
|
|
1293
|
+
* @param {boolean | undefined} [options.keepErrors] - Preserve errors on surviving field paths.
|
|
1294
|
+
* @param {boolean | undefined} [options.keepTouched] - Preserve touched flags on surviving field paths.
|
|
1295
|
+
* @param {boolean | undefined} [options.keepSubmitState] - Preserve submission counters and lifecycle flags.
|
|
1296
|
+
* @example
|
|
1297
|
+
* ```ts
|
|
1298
|
+
* store.reset({ email: "Ada" }, { keepTouched: true });
|
|
1299
|
+
* ```
|
|
1300
|
+
*/
|
|
1301
|
+
reset(values, options = {}) {
|
|
1302
|
+
const previousState = this.store.getState();
|
|
1303
|
+
const nextDefaultValues = values ?? previousState.defaultValues;
|
|
1304
|
+
const initializedState = FormStateInitializer.initialize(nextDefaultValues);
|
|
1305
|
+
this.store.setState(
|
|
1306
|
+
produce(initializedState, (draft) => {
|
|
1307
|
+
Object.entries(draft.fields).forEach(([fieldKey, nextField]) => {
|
|
1308
|
+
const previousField = previousState.fields[fieldKey];
|
|
1309
|
+
if (!previousField) {
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
if (options.keepDirtyValues && previousField.dirty) {
|
|
1313
|
+
const fieldPath = FormPath.keyToPath(fieldKey);
|
|
1314
|
+
const defaultValue = ValueHelper.getValueAtPath(nextDefaultValues, fieldPath);
|
|
1315
|
+
nextField.value = previousField.value;
|
|
1316
|
+
nextField.dirty = !Object.is(previousField.value, defaultValue);
|
|
1317
|
+
nextField.modified = previousField.modified;
|
|
1318
|
+
}
|
|
1319
|
+
if (options.keepErrors) {
|
|
1320
|
+
nextField.errors = [...previousField.errors];
|
|
1321
|
+
}
|
|
1322
|
+
if (options.keepTouched) {
|
|
1323
|
+
nextField.touched = previousField.touched;
|
|
1324
|
+
}
|
|
1325
|
+
});
|
|
1326
|
+
if (options.keepSubmitState) {
|
|
1327
|
+
draft.submitCount = previousState.submitCount;
|
|
1328
|
+
draft.isSubmitting = previousState.isSubmitting;
|
|
1329
|
+
draft.isSubmitted = previousState.isSubmitted;
|
|
1330
|
+
draft.isSubmitSuccessful = previousState.isSubmitSuccessful;
|
|
1331
|
+
}
|
|
1332
|
+
})
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* @description Increment the attempt counter, mark submission pending, and clear the previous success flag.
|
|
1337
|
+
* @example
|
|
1338
|
+
* ```ts
|
|
1339
|
+
* store.beginSubmit();
|
|
1340
|
+
* ```
|
|
1341
|
+
*/
|
|
1342
|
+
beginSubmit() {
|
|
1343
|
+
this.store.setState(
|
|
1344
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1345
|
+
draft.submitCount += 1;
|
|
1346
|
+
draft.isSubmitting = true;
|
|
1347
|
+
draft.isSubmitSuccessful = false;
|
|
1348
|
+
})
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* @description Finish the submission lifecycle and record whether the valid callback succeeded.
|
|
1353
|
+
* @param {boolean} successful - Whether the final submission callback completed successfully.
|
|
1354
|
+
* @example
|
|
1355
|
+
* ```ts
|
|
1356
|
+
* store.completeSubmit(true);
|
|
1357
|
+
* ```
|
|
1358
|
+
*/
|
|
1359
|
+
completeSubmit(successful) {
|
|
1360
|
+
this.store.setState(
|
|
1361
|
+
(prevState) => produce(prevState, (draft) => {
|
|
1362
|
+
draft.isSubmitting = false;
|
|
1363
|
+
draft.isSubmitted = true;
|
|
1364
|
+
draft.isSubmitSuccessful = successful;
|
|
1365
|
+
})
|
|
1366
|
+
);
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* @description Apply a complete normalized state updater through the underlying store.
|
|
1370
|
+
* @param {(previousState: FormState<TValues>) => FormState<TValues>} updater - State updater that replaces the complete normalized snapshot.
|
|
1371
|
+
* @example
|
|
1372
|
+
* ```ts
|
|
1373
|
+
* store.replaceState(previous => ({ ...previous, submitCount: 0 }));
|
|
1374
|
+
* ```
|
|
1375
|
+
*/
|
|
1376
|
+
replaceState(updater) {
|
|
1377
|
+
this.store.setState(updater);
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
|
|
1381
|
+
// src/core/validation/StandardSchemaValidator.ts
|
|
1382
|
+
var StandardSchemaValidator = class _StandardSchemaValidator {
|
|
1383
|
+
/**
|
|
1384
|
+
* @description Create a Standard Schema adapter with optional library validation settings.
|
|
1385
|
+
* @param {StandardSchemaV1<unknown, TValues>} schema - Standard Schema validator to execute.
|
|
1386
|
+
* @param {StandardSchemaV1.Props<unknown, TValues>} schema.~standard - Standard Schema version, vendor, type metadata, and validation entry point.
|
|
1387
|
+
* @param {1} schema.~standard.version - Standard Schema major version, which must be 1.
|
|
1388
|
+
* @param {string} schema.~standard.vendor - Name of the schema library implementation.
|
|
1389
|
+
* @param {StandardSchemaV1.Types<unknown, TValues> | undefined} [schema.~standard.types] - Optional compile-time input and output metadata.
|
|
1390
|
+
* @param {unknown} [schema.~standard.types.input] - Schema input type metadata.
|
|
1391
|
+
* @param {TValues} [schema.~standard.types.output] - Schema output type metadata.
|
|
1392
|
+
* @param {(value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<TValues> | Promise<StandardSchemaV1.Result<TValues>>} schema.~standard.validate - Validate unknown input and return accepted values or issues, synchronously or asynchronously.
|
|
1393
|
+
* @param {StandardSchemaV1.Options | undefined} [options] - Optional library-specific Standard Schema validation settings.
|
|
1394
|
+
* @param {Record<string, unknown> | undefined} [options.libraryOptions] - Library-specific validation options; keys are defined by the schema library.
|
|
1395
|
+
* @example
|
|
1396
|
+
* ```ts
|
|
1397
|
+
* const validator = new StandardSchemaValidator(schema);
|
|
1398
|
+
* ```
|
|
1399
|
+
*/
|
|
1400
|
+
constructor(schema, options) {
|
|
1401
|
+
this.schema = schema;
|
|
1402
|
+
this.options = options;
|
|
1403
|
+
}
|
|
1404
|
+
schema;
|
|
1405
|
+
options;
|
|
1406
|
+
/**
|
|
1407
|
+
* @description Validate all values and group schema issues by normalized field key.
|
|
1408
|
+
* @param {TValues} values - Replacement or current form values.
|
|
1409
|
+
* @returns {Promise<StandardSchemaValidationResult>} Promise of schema validity and errors grouped by normalized path.
|
|
1410
|
+
* - valid `boolean` - Whether the schema accepted the supplied values.
|
|
1411
|
+
* - errorsByKey `Record<string, FormError[]>` - Validation errors grouped by normalized field path.
|
|
1412
|
+
* @example
|
|
1413
|
+
* ```ts
|
|
1414
|
+
* await validator.validate({ email: "Ada" });
|
|
1415
|
+
* ```
|
|
1416
|
+
*/
|
|
1417
|
+
async validate(values) {
|
|
1418
|
+
const result = await this.schema["~standard"].validate(values, this.options);
|
|
1419
|
+
if (!result.issues) {
|
|
1420
|
+
return {
|
|
1421
|
+
valid: true,
|
|
1422
|
+
errorsByKey: {}
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return {
|
|
1426
|
+
valid: false,
|
|
1427
|
+
errorsByKey: result.issues.reduce((errorsByKey, issue) => {
|
|
1428
|
+
const fieldKey = FormPath.pathToKey(_StandardSchemaValidator.issuePathToFieldPath(issue.path));
|
|
1429
|
+
errorsByKey[fieldKey] = [
|
|
1430
|
+
...errorsByKey[fieldKey] ?? [],
|
|
1431
|
+
{
|
|
1432
|
+
type: "standard_schema",
|
|
1433
|
+
message: issue.message
|
|
1434
|
+
}
|
|
1435
|
+
];
|
|
1436
|
+
return errorsByKey;
|
|
1437
|
+
}, {})
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* @description Validate one field value and flatten every issue into errors for that field.
|
|
1442
|
+
* @param {unknown} value - Value to store or inspect.
|
|
1443
|
+
* @returns {Promise<FormError[]>} Promise of the errors for this value, or an empty array on success.
|
|
1444
|
+
* @example
|
|
1445
|
+
* ```ts
|
|
1446
|
+
* await validator.validateValue("Ada");
|
|
1447
|
+
* ```
|
|
1448
|
+
*/
|
|
1449
|
+
async validateValue(value) {
|
|
1450
|
+
const result = await this.schema["~standard"].validate(value, this.options);
|
|
1451
|
+
if (!result.issues) {
|
|
1452
|
+
return [];
|
|
1453
|
+
}
|
|
1454
|
+
return result.issues.map((issue) => ({
|
|
1455
|
+
type: "standard_schema",
|
|
1456
|
+
message: issue.message
|
|
1457
|
+
}));
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Standard Schema issue path를 core FieldPath로 변환한다.
|
|
1461
|
+
*
|
|
1462
|
+
* @remarks
|
|
1463
|
+
* Standard Schema path segment는 PropertyKey 또는 `{ key }` 형태일 수 있다.
|
|
1464
|
+
* core FieldPath는 string/number만 지원하므로 symbol 등 표현할 수 없는 segment가 있으면 root error로 돌린다.
|
|
1465
|
+
*
|
|
1466
|
+
* @param issuePath - Standard Schema issue path.
|
|
1467
|
+
* @returns core에서 사용하는 FieldPath.
|
|
1468
|
+
*/
|
|
1469
|
+
static issuePathToFieldPath(issuePath) {
|
|
1470
|
+
if (!issuePath || issuePath.length === 0) {
|
|
1471
|
+
return [];
|
|
1472
|
+
}
|
|
1473
|
+
const fieldPath = [];
|
|
1474
|
+
for (const segment of issuePath) {
|
|
1475
|
+
const key = _StandardSchemaValidator.issuePathSegmentToKey(segment);
|
|
1476
|
+
if (key === void 0) {
|
|
1477
|
+
return [];
|
|
1478
|
+
}
|
|
1479
|
+
fieldPath.push(key);
|
|
1480
|
+
}
|
|
1481
|
+
return fieldPath;
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Standard Schema path segment 하나를 core path segment로 변환한다.
|
|
1485
|
+
*
|
|
1486
|
+
* @param segment - PropertyKey 또는 `{ key }` 형태의 path segment.
|
|
1487
|
+
* @returns string/number key면 그대로 반환하고, symbol처럼 표현할 수 없으면 undefined.
|
|
1488
|
+
*/
|
|
1489
|
+
static issuePathSegmentToKey(segment) {
|
|
1490
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
1491
|
+
if (typeof key === "string" || typeof key === "number") {
|
|
1492
|
+
return key;
|
|
1493
|
+
}
|
|
1494
|
+
return void 0;
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
|
|
1498
|
+
// src/core/validation/ValidationSequencer.ts
|
|
1499
|
+
var ValidationSequencer = class {
|
|
1500
|
+
revision = 0;
|
|
1501
|
+
fullRevision = 0;
|
|
1502
|
+
targetRevisions = /* @__PURE__ */ new Map();
|
|
1503
|
+
/**
|
|
1504
|
+
* @description Start a full validation revision, invalidating earlier full and field requests.
|
|
1505
|
+
* @returns {ValidationToken} Token capturing this full validation revision.
|
|
1506
|
+
* - kind `"full" | "fields"` - Validation scope: full-form or selected fields.
|
|
1507
|
+
* - revision `number` - Global validation revision captured when full validation starts.
|
|
1508
|
+
* - fullRevision `number` - Full-validation revision captured when field validation starts.
|
|
1509
|
+
* - targetRevisions `ReadonlyMap<string, number>` - Per-field revisions captured for this validation request.
|
|
1510
|
+
* @example
|
|
1511
|
+
* ```ts
|
|
1512
|
+
* sequencer.startFull();
|
|
1513
|
+
* ```
|
|
1514
|
+
*/
|
|
1515
|
+
startFull() {
|
|
1516
|
+
this.revision += 1;
|
|
1517
|
+
this.fullRevision += 1;
|
|
1518
|
+
return { kind: "full", revision: this.revision };
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* @description Start revisions for the selected fields without invalidating unrelated field requests.
|
|
1522
|
+
* @param {readonly string[]} fieldKeys - Normalized path keys to target.
|
|
1523
|
+
* @returns {ValidationToken} Token capturing the full revision and selected field revisions.
|
|
1524
|
+
* - kind `"full" | "fields"` - Validation scope: full-form or selected fields.
|
|
1525
|
+
* - revision `number` - Global validation revision captured when full validation starts.
|
|
1526
|
+
* - fullRevision `number` - Full-validation revision captured when field validation starts.
|
|
1527
|
+
* - targetRevisions `ReadonlyMap<string, number>` - Per-field revisions captured for this validation request.
|
|
1528
|
+
* @example
|
|
1529
|
+
* ```ts
|
|
1530
|
+
* sequencer.startFields([FormPath.pathToKey(["email"])]);
|
|
1531
|
+
* ```
|
|
1532
|
+
*/
|
|
1533
|
+
startFields(fieldKeys) {
|
|
1534
|
+
this.revision += 1;
|
|
1535
|
+
const targetRevisions = /* @__PURE__ */ new Map();
|
|
1536
|
+
for (const fieldKey of fieldKeys) {
|
|
1537
|
+
const revision = (this.targetRevisions.get(fieldKey) ?? 0) + 1;
|
|
1538
|
+
this.targetRevisions.set(fieldKey, revision);
|
|
1539
|
+
targetRevisions.set(fieldKey, revision);
|
|
1540
|
+
}
|
|
1541
|
+
return {
|
|
1542
|
+
fullRevision: this.fullRevision,
|
|
1543
|
+
kind: "fields",
|
|
1544
|
+
targetRevisions
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* @description Invalidate outstanding validation for the selected fields and any pending full request.
|
|
1549
|
+
* @param {readonly string[]} fieldKeys - Normalized path keys to target.
|
|
1550
|
+
* @example
|
|
1551
|
+
* ```ts
|
|
1552
|
+
* sequencer.invalidateFields([FormPath.pathToKey(["email"])]);
|
|
1553
|
+
* ```
|
|
1554
|
+
*/
|
|
1555
|
+
invalidateFields(fieldKeys) {
|
|
1556
|
+
this.revision += 1;
|
|
1557
|
+
for (const fieldKey of fieldKeys) {
|
|
1558
|
+
this.targetRevisions.set(fieldKey, (this.targetRevisions.get(fieldKey) ?? 0) + 1);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* @description Compare a captured token with current revisions to detect superseded validation.
|
|
1563
|
+
* @param {ValidationToken} token - Validation revision token to compare with current revisions.
|
|
1564
|
+
* @param {"full" | "fields"} token.kind - Validation scope: full-form or selected fields.
|
|
1565
|
+
* @param {number} token.revision - Global validation revision captured when full validation starts.
|
|
1566
|
+
* @param {number} token.fullRevision - Full-validation revision captured when field validation starts.
|
|
1567
|
+
* @param {ReadonlyMap<string, number>} token.targetRevisions - Per-field revisions captured for this validation request.
|
|
1568
|
+
* @returns {boolean} Whether any relevant revision has superseded the captured token.
|
|
1569
|
+
* @example
|
|
1570
|
+
* ```ts
|
|
1571
|
+
* const token = sequencer.startFull();
|
|
1572
|
+
* sequencer.startFields([FormPath.pathToKey(["email"])]);
|
|
1573
|
+
* const stale = sequencer.isStale(token);
|
|
1574
|
+
* ```
|
|
1575
|
+
*/
|
|
1576
|
+
isStale(token) {
|
|
1577
|
+
switch (token.kind) {
|
|
1578
|
+
case "full":
|
|
1579
|
+
return token.revision !== this.revision;
|
|
1580
|
+
case "fields":
|
|
1581
|
+
if (token.fullRevision !== this.fullRevision) return true;
|
|
1582
|
+
for (const [fieldKey, revision] of token.targetRevisions) {
|
|
1583
|
+
if (this.targetRevisions.get(fieldKey) !== revision) return true;
|
|
1584
|
+
}
|
|
1585
|
+
return false;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
};
|
|
1589
|
+
|
|
1590
|
+
// src/core/validation/ValidationSnapshot.ts
|
|
1591
|
+
var ValidationSnapshot = class _ValidationSnapshot {
|
|
1592
|
+
constructor(fieldValues, arrayKeys) {
|
|
1593
|
+
this.fieldValues = fieldValues;
|
|
1594
|
+
this.arrayKeys = arrayKeys;
|
|
1595
|
+
}
|
|
1596
|
+
fieldValues;
|
|
1597
|
+
arrayKeys;
|
|
1598
|
+
/**
|
|
1599
|
+
* @description Capture current field-value and array-key references without retaining a store.
|
|
1600
|
+
* @param {ValidationState} state - Form snapshot used as the source of this calculation.
|
|
1601
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
1602
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
1603
|
+
* @returns {ValidationSnapshot} Identity snapshot independent of validation revisions and the live store.
|
|
1604
|
+
* @example
|
|
1605
|
+
* ```ts
|
|
1606
|
+
* ValidationSnapshot.capture(state);
|
|
1607
|
+
* ```
|
|
1608
|
+
*/
|
|
1609
|
+
static capture(state) {
|
|
1610
|
+
return new _ValidationSnapshot(
|
|
1611
|
+
new Map(Object.entries(state.fields).map(([fieldKey, field]) => [fieldKey, field.value])),
|
|
1612
|
+
new Map(Object.entries(state.arrayKeys))
|
|
1613
|
+
);
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* @description Check value and array-key identities; metadata-only and error-only changes still match.
|
|
1617
|
+
* @param {ValidationState} state - Form snapshot used as the source of this calculation.
|
|
1618
|
+
* @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
|
|
1619
|
+
* @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
|
|
1620
|
+
* @returns {boolean} Whether all captured field values and array keys still have identical references.
|
|
1621
|
+
* @example
|
|
1622
|
+
* ```ts
|
|
1623
|
+
* snapshot.matches(state);
|
|
1624
|
+
* ```
|
|
1625
|
+
*/
|
|
1626
|
+
matches(state) {
|
|
1627
|
+
if (this.fieldValues.size !== Object.keys(state.fields).length) return false;
|
|
1628
|
+
if (this.arrayKeys.size !== Object.keys(state.arrayKeys).length) return false;
|
|
1629
|
+
for (const [fieldKey, value] of this.fieldValues) {
|
|
1630
|
+
if (!Object.is(state.fields[fieldKey]?.value, value)) return false;
|
|
1631
|
+
}
|
|
1632
|
+
for (const [fieldKey, keys] of this.arrayKeys) {
|
|
1633
|
+
if (!Object.is(state.arrayKeys[fieldKey], keys)) return false;
|
|
1634
|
+
}
|
|
1635
|
+
return true;
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
|
|
1639
|
+
// src/core/validation/ValidationEngine.ts
|
|
1640
|
+
var ValidationEngine = class _ValidationEngine {
|
|
1641
|
+
/** validateOn이 지정되지 않았을 때 submit에서만 자동 검증하도록 하는 기본값이다. */
|
|
1642
|
+
static DEFAULT_VALIDATE_ON = ["submit"];
|
|
1643
|
+
/** validation 대상 field value와 errors를 읽고 쓰는 저장소다. */
|
|
1644
|
+
store;
|
|
1645
|
+
/** Standard Schema compatible schema를 실행하고 issue를 field errors로 바꾸는 adapter다. */
|
|
1646
|
+
schema;
|
|
1647
|
+
/** field별로 form-level schema보다 우선 적용할 schema validator다. */
|
|
1648
|
+
fieldSchemas = /* @__PURE__ */ new Map();
|
|
1649
|
+
/** 어떤 trigger에서 자동 validation을 실행할지 나타내는 설정이다. */
|
|
1650
|
+
validateOn;
|
|
1651
|
+
/** field schema cleanup이 최신 등록만 제거하도록 구분하는 증가 id다. */
|
|
1652
|
+
nextFieldSchemaId = 0;
|
|
1653
|
+
sequencer = new ValidationSequencer();
|
|
1654
|
+
/**
|
|
1655
|
+
* @description Create a validation engine with optional form schema and configured automatic triggers.
|
|
1656
|
+
* @param {FormStateStore<TValues>} store - Shared form state store to read and update.
|
|
1657
|
+
* @param {CreateFormOptions<TValues>} options - Default values, optional form schema, and automatic validation triggers.
|
|
1658
|
+
* @param {TValues} options.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
1659
|
+
* @param {StandardSchemaV1<unknown, TValues> | undefined} [options.schema] - Standard Schema validator; a field-local schema takes precedence over the form schema.
|
|
1660
|
+
* @param {StandardSchemaV1.Props<unknown, TValues>} [options.schema.~standard] - Standard Schema version, vendor, type metadata, and validation entry point.
|
|
1661
|
+
* @param {1} [options.schema.~standard.version] - Standard Schema major version, which must be 1.
|
|
1662
|
+
* @param {string} [options.schema.~standard.vendor] - Name of the schema library implementation.
|
|
1663
|
+
* @param {StandardSchemaV1.Types<unknown, TValues> | undefined} [options.schema.~standard.types] - Optional compile-time input and output metadata.
|
|
1664
|
+
* @param {unknown} [options.schema.~standard.types.input] - Schema input type metadata.
|
|
1665
|
+
* @param {TValues} [options.schema.~standard.types.output] - Schema output type metadata.
|
|
1666
|
+
* @param {(value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<TValues> | Promise<StandardSchemaV1.Result<TValues>>} [options.schema.~standard.validate] - Validate unknown input and return accepted values or issues, synchronously or asynchronously.
|
|
1667
|
+
* @param {StandardSchemaV1.Options | undefined} [options.schemaOptions] - Options forwarded to the Standard Schema validator.
|
|
1668
|
+
* @param {Record<string, unknown> | undefined} [options.schemaOptions.libraryOptions] - Library-specific validation options; keys are defined by the schema library.
|
|
1669
|
+
* @param {readonly ValidationTrigger[] | undefined} [options.validateOn] - Triggers that run automatic validation; defaults to submit.
|
|
1670
|
+
* @example
|
|
1671
|
+
* ```ts
|
|
1672
|
+
* const validation = new ValidationEngine(store, { defaultValues: { email: "" } });
|
|
1673
|
+
* ```
|
|
1674
|
+
*/
|
|
1675
|
+
constructor(store, options) {
|
|
1676
|
+
this.store = store;
|
|
1677
|
+
this.schema = options.schema ? new StandardSchemaValidator(options.schema, options.schemaOptions) : void 0;
|
|
1678
|
+
this.validateOn = options.validateOn ?? _ValidationEngine.DEFAULT_VALIDATE_ON;
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* @description Check whether the configured automatic-validation triggers include this trigger.
|
|
1682
|
+
* @param {ValidationTrigger} trigger - Reason validation was requested; not passed to the schema.
|
|
1683
|
+
* @returns {boolean} Whether this trigger is enabled for automatic validation.
|
|
1684
|
+
* @example
|
|
1685
|
+
* ```ts
|
|
1686
|
+
* validation.shouldValidateOn("manual");
|
|
1687
|
+
* ```
|
|
1688
|
+
*/
|
|
1689
|
+
shouldValidateOn(trigger) {
|
|
1690
|
+
return this.validateOn.includes(trigger);
|
|
1691
|
+
}
|
|
1692
|
+
/**
|
|
1693
|
+
* @description Register a field-local schema; the returned cleanup removes only this registration if it is still current.
|
|
1694
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1695
|
+
* @param {FieldSchemaOptions} options - Field-local schema and validation settings.
|
|
1696
|
+
* @param {StandardSchemaV1<unknown, unknown>} options.schema - Standard Schema validator; a field-local schema takes precedence over the form schema.
|
|
1697
|
+
* @param {StandardSchemaV1.Props<unknown, unknown>} options.schema.~standard - Standard Schema version, vendor, type metadata, and validation entry point.
|
|
1698
|
+
* @param {1} options.schema.~standard.version - Standard Schema major version, which must be 1.
|
|
1699
|
+
* @param {string} options.schema.~standard.vendor - Name of the schema library implementation.
|
|
1700
|
+
* @param {StandardSchemaV1.Types<unknown, unknown> | undefined} [options.schema.~standard.types] - Optional compile-time input and output metadata.
|
|
1701
|
+
* @param {unknown} [options.schema.~standard.types.input] - Schema input type metadata.
|
|
1702
|
+
* @param {unknown} [options.schema.~standard.types.output] - Schema output type metadata.
|
|
1703
|
+
* @param {(value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>} options.schema.~standard.validate - Validate unknown input and return accepted values or issues, synchronously or asynchronously.
|
|
1704
|
+
* @param {StandardSchemaV1.Options | undefined} [options.schemaOptions] - Options forwarded to the Standard Schema validator.
|
|
1705
|
+
* @param {Record<string, unknown> | undefined} [options.schemaOptions.libraryOptions] - Library-specific validation options; keys are defined by the schema library.
|
|
1706
|
+
* @returns {() => void} Cleanup callback for this subscription or registration.
|
|
1707
|
+
* @example
|
|
1708
|
+
* ```ts
|
|
1709
|
+
* validation.registerFieldSchema(FormPath.pathToKey(["email"]), { schema });
|
|
1710
|
+
* ```
|
|
1711
|
+
*/
|
|
1712
|
+
registerFieldSchema(fieldKey, options) {
|
|
1713
|
+
const id = ++this.nextFieldSchemaId;
|
|
1714
|
+
this.fieldSchemas.set(fieldKey, {
|
|
1715
|
+
id,
|
|
1716
|
+
validator: new StandardSchemaValidator(options.schema, options.schemaOptions)
|
|
1717
|
+
});
|
|
1718
|
+
this.sequencer.invalidateFields([fieldKey]);
|
|
1719
|
+
return () => {
|
|
1720
|
+
if (this.fieldSchemas.get(fieldKey)?.id === id) {
|
|
1721
|
+
this.fieldSchemas.delete(fieldKey);
|
|
1722
|
+
this.sequencer.invalidateFields([fieldKey]);
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
/**
|
|
1727
|
+
* @description Validate one field with local-schema precedence and reject stale results.
|
|
1728
|
+
* @param {string} fieldKey - Normalized path key of the target field.
|
|
1729
|
+
* @param {ValidationTrigger} _trigger - Reason validation was requested; not passed to the schema.
|
|
1730
|
+
* @returns {Promise<boolean>} Promise resolving true only when the current validation result is valid.
|
|
1731
|
+
* @example
|
|
1732
|
+
* ```ts
|
|
1733
|
+
* await validation.validateField(FormPath.pathToKey(["email"]), "manual");
|
|
1734
|
+
* ```
|
|
1735
|
+
*/
|
|
1736
|
+
async validateField(fieldKey, _trigger) {
|
|
1737
|
+
return this.validateFields([fieldKey], _trigger);
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* @description Validate selected fields with local-schema precedence; an empty list validates the full form.
|
|
1741
|
+
* @param {readonly string[]} fieldKeys - Normalized path keys to target.
|
|
1742
|
+
* @param {ValidationTrigger} _trigger - Reason validation was requested; not passed to the schema.
|
|
1743
|
+
* @returns {Promise<boolean>} Promise resolving true only when the current validation result is valid.
|
|
1744
|
+
* @example
|
|
1745
|
+
* ```ts
|
|
1746
|
+
* await validation.validateFields([FormPath.pathToKey(["email"])], "manual");
|
|
1747
|
+
* ```
|
|
1748
|
+
*/
|
|
1749
|
+
async validateFields(fieldKeys, _trigger) {
|
|
1750
|
+
const targetFieldKeys = _ValidationEngine.unique(fieldKeys);
|
|
1751
|
+
if (targetFieldKeys.length === 0) {
|
|
1752
|
+
return this.validateRegisteredFields("manual");
|
|
1753
|
+
}
|
|
1754
|
+
const token = this.sequencer.startFields(targetFieldKeys);
|
|
1755
|
+
const snapshot = ValidationSnapshot.capture(this.store.getState());
|
|
1756
|
+
const localErrorsByKey = await this.validateFieldSchemas(targetFieldKeys);
|
|
1757
|
+
if (this.isStale(token, snapshot)) {
|
|
1758
|
+
return false;
|
|
1759
|
+
}
|
|
1760
|
+
const formSchemaFieldKeys = targetFieldKeys.filter((fieldKey) => !this.fieldSchemas.has(fieldKey));
|
|
1761
|
+
const schemaResult = formSchemaFieldKeys.length > 0 ? await this.validateFormSchema() : _ValidationEngine.createValidSchemaResult();
|
|
1762
|
+
if (this.isStale(token, snapshot)) {
|
|
1763
|
+
return false;
|
|
1764
|
+
}
|
|
1765
|
+
const errorsByKey = this.mergeErrorsByKey(schemaResult.errorsByKey, localErrorsByKey);
|
|
1766
|
+
this.applyErrors([...formSchemaFieldKeys, ...Object.keys(localErrorsByKey)], errorsByKey);
|
|
1767
|
+
return targetFieldKeys.every((fieldKey) => (errorsByKey[fieldKey] ?? []).length === 0);
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* @description Validate the form and local overrides, returning false for invalid or stale results.
|
|
1771
|
+
* @param {ValidationTrigger} _trigger - Reason validation was requested; not passed to the schema.
|
|
1772
|
+
* @returns {Promise<boolean>} Promise resolving true only when the current validation result is valid.
|
|
1773
|
+
* @example
|
|
1774
|
+
* ```ts
|
|
1775
|
+
* await validation.validateRegisteredFields("manual");
|
|
1776
|
+
* ```
|
|
1777
|
+
*/
|
|
1778
|
+
async validateRegisteredFields(_trigger) {
|
|
1779
|
+
const outcome = await this.validateRegisteredFieldsOutcome(_trigger);
|
|
1780
|
+
return outcome.kind === "valid";
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* @description Validate the form and local overrides, distinguishing accepted, invalid, and stale results.
|
|
1784
|
+
* @param {ValidationTrigger} _trigger - Reason validation was requested; not passed to the schema.
|
|
1785
|
+
* @returns {Promise<ValidationOutcome>} Promise of a valid, invalid, or stale validation outcome.
|
|
1786
|
+
* - kind `"invalid" | "stale" | "valid"` - Validation outcome: valid, invalid, or stale.
|
|
1787
|
+
* @example
|
|
1788
|
+
* ```ts
|
|
1789
|
+
* await validation.validateRegisteredFieldsOutcome("manual");
|
|
1790
|
+
* ```
|
|
1791
|
+
*/
|
|
1792
|
+
async validateRegisteredFieldsOutcome(_trigger) {
|
|
1793
|
+
const token = this.sequencer.startFull();
|
|
1794
|
+
const snapshot = ValidationSnapshot.capture(this.store.getState());
|
|
1795
|
+
const schemaResult = await this.validateFormSchema();
|
|
1796
|
+
if (this.isStale(token, snapshot)) {
|
|
1797
|
+
return { kind: "stale" };
|
|
1798
|
+
}
|
|
1799
|
+
const localErrorsByKey = await this.validateFieldSchemas([...this.fieldSchemas.keys()]);
|
|
1800
|
+
if (this.isStale(token, snapshot)) {
|
|
1801
|
+
return { kind: "stale" };
|
|
1802
|
+
}
|
|
1803
|
+
const errorsByKey = this.mergeErrorsByKey(schemaResult.errorsByKey, localErrorsByKey);
|
|
1804
|
+
const keysToWrite = this.getValidationWriteKeys(errorsByKey);
|
|
1805
|
+
this.applyErrors(keysToWrite, errorsByKey);
|
|
1806
|
+
return keysToWrite.every((fieldKey) => (errorsByKey[fieldKey] ?? []).length === 0) ? { kind: "valid" } : { kind: "invalid" };
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* Standard Schema가 있으면 전체 form values를 검증한다.
|
|
1810
|
+
*
|
|
1811
|
+
* @returns schema가 없으면 성공 결과, 있으면 schema validation 결과.
|
|
1812
|
+
*/
|
|
1813
|
+
validateFormSchema() {
|
|
1814
|
+
if (!this.schema) {
|
|
1815
|
+
return Promise.resolve(_ValidationEngine.createValidSchemaResult());
|
|
1816
|
+
}
|
|
1817
|
+
return this.schema.validate(this.store.getValues());
|
|
1818
|
+
}
|
|
1819
|
+
isStale(token, snapshot) {
|
|
1820
|
+
return this.sequencer.isStale(token) || !snapshot.matches(this.store.getState());
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* validation 결과를 store에 기록한다.
|
|
1824
|
+
*
|
|
1825
|
+
* @param fieldKeys - errors를 교체할 field key 목록.
|
|
1826
|
+
* @param errorsByKey - field key별 errors.
|
|
1827
|
+
*/
|
|
1828
|
+
applyErrors(fieldKeys, errorsByKey) {
|
|
1829
|
+
fieldKeys.forEach((fieldKey) => {
|
|
1830
|
+
this.store.setErrorsByKey(fieldKey, errorsByKey[fieldKey] ?? []);
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
/** field-local schema가 있으면 해당 field value를 검증한다. */
|
|
1834
|
+
async validateFieldSchema(fieldKey) {
|
|
1835
|
+
const fieldSchema = this.fieldSchemas.get(fieldKey);
|
|
1836
|
+
if (!fieldSchema) {
|
|
1837
|
+
return void 0;
|
|
1838
|
+
}
|
|
1839
|
+
return fieldSchema.validator.validateValue(this.store.getFieldStateByKey(fieldKey).value);
|
|
1840
|
+
}
|
|
1841
|
+
/** 지정된 field들 중 field-local schema가 등록된 field만 검증한다. */
|
|
1842
|
+
async validateFieldSchemas(fieldKeys) {
|
|
1843
|
+
const errorsByKey = {};
|
|
1844
|
+
await Promise.all(fieldKeys.map(async (fieldKey) => {
|
|
1845
|
+
const errors = await this.validateFieldSchema(fieldKey);
|
|
1846
|
+
if (errors) {
|
|
1847
|
+
errorsByKey[fieldKey] = errors;
|
|
1848
|
+
}
|
|
1849
|
+
}));
|
|
1850
|
+
return errorsByKey;
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* form-level schema 결과에 field-local schema 결과를 덮어쓴다.
|
|
1854
|
+
*
|
|
1855
|
+
* @remarks
|
|
1856
|
+
* field-local schema가 등록된 field는 valid 결과([])까지도 form-level error보다 우선한다.
|
|
1857
|
+
*/
|
|
1858
|
+
mergeErrorsByKey(formErrorsByKey, fieldErrorsByKey) {
|
|
1859
|
+
const merged = Object.entries(formErrorsByKey).reduce((errorsByKey, [fieldKey, errors]) => {
|
|
1860
|
+
if (!this.fieldSchemas.has(fieldKey)) {
|
|
1861
|
+
errorsByKey[fieldKey] = [...errors];
|
|
1862
|
+
}
|
|
1863
|
+
return errorsByKey;
|
|
1864
|
+
}, {});
|
|
1865
|
+
Object.entries(fieldErrorsByKey).forEach(([fieldKey, errors]) => {
|
|
1866
|
+
merged[fieldKey] = [...errors];
|
|
1867
|
+
});
|
|
1868
|
+
return merged;
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* 전체 validation 결과를 기록할 key 목록을 만든다.
|
|
1872
|
+
*
|
|
1873
|
+
* @remarks
|
|
1874
|
+
* 이전 schema error가 남아 있던 field도 clear해야 하므로 현재 store의 field key를 포함한다.
|
|
1875
|
+
*
|
|
1876
|
+
* @param schemaErrorsByKey - schema issue가 발생한 key 목록.
|
|
1877
|
+
* @returns errors를 교체할 key 목록.
|
|
1878
|
+
*/
|
|
1879
|
+
getValidationWriteKeys(schemaErrorsByKey) {
|
|
1880
|
+
return _ValidationEngine.unique([...Object.keys(this.store.getState().fields), ...Object.keys(schemaErrorsByKey)]);
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* 입력 순서를 유지하며 중복 field key를 제거한다.
|
|
1884
|
+
*
|
|
1885
|
+
* @param fieldKeys - 중복이 있을 수 있는 field key 목록.
|
|
1886
|
+
* @returns 중복 제거된 field key 목록.
|
|
1887
|
+
*/
|
|
1888
|
+
static unique(fieldKeys) {
|
|
1889
|
+
return [...new Set(fieldKeys)];
|
|
1890
|
+
}
|
|
1891
|
+
/** schema가 없거나 실행할 필요가 없을 때 쓰는 빈 성공 결과다. */
|
|
1892
|
+
static createValidSchemaResult() {
|
|
1893
|
+
return {
|
|
1894
|
+
valid: true,
|
|
1895
|
+
errorsByKey: {}
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
};
|
|
1899
|
+
|
|
1900
|
+
// src/core/form/CreateForm.ts
|
|
1901
|
+
var CreateForm = class {
|
|
1902
|
+
/** form의 단일 상태 저장소. 모든 값/필드 메타데이터/배열 키는 이 store를 통해 읽고 쓴다. */
|
|
1903
|
+
store;
|
|
1904
|
+
/** 필드 명령 뒤에 실행할 검증과 field-local schema 등록을 담당한다. */
|
|
1905
|
+
validation;
|
|
1906
|
+
/** 같은 form의 모든 배열 controller가 공유하는 item key 생성기. */
|
|
1907
|
+
arrayKeys = new ArrayKeyGenerator();
|
|
1908
|
+
/** submitCount 증가, submit validation, onValid/onInvalid 호출을 담당한다. */
|
|
1909
|
+
submitter;
|
|
1910
|
+
/**
|
|
1911
|
+
* @description Create a form and connect its state, array, validation, and submission collaborators.
|
|
1912
|
+
* @param {CreateFormOptions<TValues>} options - Default values, optional form schema, and automatic validation triggers.
|
|
1913
|
+
* @param {TValues} options.defaultValues - Initial values and the baseline used for dirty checks and reset.
|
|
1914
|
+
* @param {StandardSchemaV1<unknown, TValues> | undefined} [options.schema] - Standard Schema validator; a field-local schema takes precedence over the form schema.
|
|
1915
|
+
* @param {StandardSchemaV1.Props<unknown, TValues>} [options.schema.~standard] - Standard Schema version, vendor, type metadata, and validation entry point.
|
|
1916
|
+
* @param {1} [options.schema.~standard.version] - Standard Schema major version, which must be 1.
|
|
1917
|
+
* @param {string} [options.schema.~standard.vendor] - Name of the schema library implementation.
|
|
1918
|
+
* @param {StandardSchemaV1.Types<unknown, TValues> | undefined} [options.schema.~standard.types] - Optional compile-time input and output metadata.
|
|
1919
|
+
* @param {unknown} [options.schema.~standard.types.input] - Schema input type metadata.
|
|
1920
|
+
* @param {TValues} [options.schema.~standard.types.output] - Schema output type metadata.
|
|
1921
|
+
* @param {(value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<TValues> | Promise<StandardSchemaV1.Result<TValues>>} [options.schema.~standard.validate] - Validate unknown input and return accepted values or issues, synchronously or asynchronously.
|
|
1922
|
+
* @param {StandardSchemaV1.Options | undefined} [options.schemaOptions] - Options forwarded to the Standard Schema validator.
|
|
1923
|
+
* @param {Record<string, unknown> | undefined} [options.schemaOptions.libraryOptions] - Library-specific validation options; keys are defined by the schema library.
|
|
1924
|
+
* @param {readonly ValidationTrigger[] | undefined} [options.validateOn] - Triggers that run automatic validation; defaults to submit.
|
|
1925
|
+
* @example
|
|
1926
|
+
* ```ts
|
|
1927
|
+
* const form = new CreateForm({ defaultValues: { email: "" } });
|
|
1928
|
+
* ```
|
|
1929
|
+
*/
|
|
1930
|
+
constructor(options) {
|
|
1931
|
+
this.store = new FormStateStore(options.defaultValues);
|
|
1932
|
+
this.validation = new ValidationEngine(this.store, options);
|
|
1933
|
+
this.submitter = new FormSubmitter(this.store, this.validation);
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* @description Read the current immutable form snapshot without cloning it.
|
|
1937
|
+
* @returns {Readonly<FormState<TValues>>} Current read-only snapshot; callers must not mutate it.
|
|
1938
|
+
* - defaultValues `TValues` - Initial values and the baseline used for dirty checks and reset.
|
|
1939
|
+
* - fields `Record<string, FieldState<unknown>>` - Field snapshots indexed by normalized path keys.
|
|
1940
|
+
* - submitCount `number` - Number of submission attempts started by the form.
|
|
1941
|
+
* - isSubmitting `boolean` - Whether queued validation or a submit callback is still pending.
|
|
1942
|
+
* - isSubmitted `boolean` - Whether a submission has completed at least once.
|
|
1943
|
+
* - isSubmitSuccessful `boolean` - Whether the latest completed submission reached a successful valid callback.
|
|
1944
|
+
* - arrayKeys `ArrayKeys` - Stable rendering keys indexed by array path.
|
|
1945
|
+
* @example
|
|
1946
|
+
* ```ts
|
|
1947
|
+
* form.getState();
|
|
1948
|
+
* ```
|
|
1949
|
+
*/
|
|
1950
|
+
getState() {
|
|
1951
|
+
return this.store.getState();
|
|
1952
|
+
}
|
|
1953
|
+
/**
|
|
1954
|
+
* @description Subscribe to form state changes and return the callback that unsubscribes this listener.
|
|
1955
|
+
* @param {() => void} listener - Callback invoked synchronously after a state change.
|
|
1956
|
+
* @returns {() => void} Cleanup callback for this subscription or registration.
|
|
1957
|
+
* @example
|
|
1958
|
+
* ```ts
|
|
1959
|
+
* form.subscribe(() => render());
|
|
1960
|
+
* ```
|
|
1961
|
+
*/
|
|
1962
|
+
subscribe(listener) {
|
|
1963
|
+
return this.store.subscribe(listener);
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* @description Register a field-local schema; the returned cleanup removes only this registration if it is still current.
|
|
1967
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
1968
|
+
* @param {FieldSchemaOptions} options - Field-local schema and validation settings.
|
|
1969
|
+
* @param {StandardSchemaV1<unknown, unknown>} options.schema - Standard Schema validator; a field-local schema takes precedence over the form schema.
|
|
1970
|
+
* @param {StandardSchemaV1.Props<unknown, unknown>} options.schema.~standard - Standard Schema version, vendor, type metadata, and validation entry point.
|
|
1971
|
+
* @param {1} options.schema.~standard.version - Standard Schema major version, which must be 1.
|
|
1972
|
+
* @param {string} options.schema.~standard.vendor - Name of the schema library implementation.
|
|
1973
|
+
* @param {StandardSchemaV1.Types<unknown, unknown> | undefined} [options.schema.~standard.types] - Optional compile-time input and output metadata.
|
|
1974
|
+
* @param {unknown} [options.schema.~standard.types.input] - Schema input type metadata.
|
|
1975
|
+
* @param {unknown} [options.schema.~standard.types.output] - Schema output type metadata.
|
|
1976
|
+
* @param {(value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>} options.schema.~standard.validate - Validate unknown input and return accepted values or issues, synchronously or asynchronously.
|
|
1977
|
+
* @param {StandardSchemaV1.Options | undefined} [options.schemaOptions] - Options forwarded to the Standard Schema validator.
|
|
1978
|
+
* @param {Record<string, unknown> | undefined} [options.schemaOptions.libraryOptions] - Library-specific validation options; keys are defined by the schema library.
|
|
1979
|
+
* @returns {() => void} Cleanup callback for this subscription or registration.
|
|
1980
|
+
* @example
|
|
1981
|
+
* ```ts
|
|
1982
|
+
* form.registerFieldSchema(["email"], { schema });
|
|
1983
|
+
* ```
|
|
1984
|
+
*/
|
|
1985
|
+
registerFieldSchema(path, options) {
|
|
1986
|
+
return this.validation.registerFieldSchema(FormPath.pathInputToKey(path), options);
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* @description Read field metadata and use a default snapshot when the field is not present.
|
|
1990
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
1991
|
+
* @returns {Readonly<FieldState>} Field snapshot, with a default shape when the leaf field is absent.
|
|
1992
|
+
* - value `unknown` - Current field value.
|
|
1993
|
+
* - errors `FormError[]` - Current validation errors for the field.
|
|
1994
|
+
* - touched `boolean` - Whether the field has blurred at least once.
|
|
1995
|
+
* - dirty `boolean` - Whether the current value differs from its default by Object.is.
|
|
1996
|
+
* - modified `boolean` - Whether a user-originated write has changed this field.
|
|
1997
|
+
* - isFocused `boolean` - Whether focus has been recorded without a subsequent blur.
|
|
1998
|
+
* @example
|
|
1999
|
+
* ```ts
|
|
2000
|
+
* form.getFieldState(["email"]);
|
|
2001
|
+
* ```
|
|
2002
|
+
*/
|
|
2003
|
+
getFieldState(path) {
|
|
2004
|
+
return this.store.getFieldState(path);
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* @description Read only the current value of the selected field.
|
|
2008
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2009
|
+
* @returns {unknown} Stored field value, or undefined when the field has no value.
|
|
2010
|
+
* @example
|
|
2011
|
+
* ```ts
|
|
2012
|
+
* form.getValue(["email"]);
|
|
2013
|
+
* ```
|
|
2014
|
+
*/
|
|
2015
|
+
getValue(path) {
|
|
2016
|
+
return this.store.getValue(path);
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* @description Reconstruct the nested values object from leaf fields and array containers.
|
|
2020
|
+
* @returns {TValues} Nested values reconstructed in the shape of the supplied defaults.
|
|
2021
|
+
* @example
|
|
2022
|
+
* ```ts
|
|
2023
|
+
* form.getValues();
|
|
2024
|
+
* ```
|
|
2025
|
+
*/
|
|
2026
|
+
getValues() {
|
|
2027
|
+
return this.store.getValues();
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* @description Write a field value, compare dirty state with its default, and mark user-originated changes as modified. Start change validation when explicitly requested or configured.
|
|
2031
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2032
|
+
* @param {unknown} value - Value to store or inspect.
|
|
2033
|
+
* @param {SetValueOptions} [options] - Write origin and optional immediate validation request.
|
|
2034
|
+
* @param {"user" | "program" | undefined} [options.source] - Write origin; user writes mark the field as modified.
|
|
2035
|
+
* @param {boolean | undefined} [options.validate] - Whether to start validation immediately after this write.
|
|
2036
|
+
* @example
|
|
2037
|
+
* ```ts
|
|
2038
|
+
* form.setValue(["email"], "Ada", { source: "user" });
|
|
2039
|
+
* ```
|
|
2040
|
+
*/
|
|
2041
|
+
setValue(path, value, options = {}) {
|
|
2042
|
+
const fieldKey = this.store.setValue(FormPath.toFieldPath(path), value, options);
|
|
2043
|
+
if (options.validate || this.validation.shouldValidateOn("change")) {
|
|
2044
|
+
void this.validation.validateField(fieldKey, "change");
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
/**
|
|
2048
|
+
* @description Clear focus and mark touched before running configured blur validation; return true when validation is disabled.
|
|
2049
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2050
|
+
* @returns {Promise<boolean>} Promise resolving true when validation is disabled or the current field result is valid.
|
|
2051
|
+
* @example
|
|
2052
|
+
* ```ts
|
|
2053
|
+
* await form.blur(["email"]);
|
|
2054
|
+
* ```
|
|
2055
|
+
*/
|
|
2056
|
+
async blur(path) {
|
|
2057
|
+
const fieldKey = FormPath.pathInputToKey(path);
|
|
2058
|
+
this.store.unfocusField(fieldKey);
|
|
2059
|
+
this.store.touchField(fieldKey);
|
|
2060
|
+
if (!this.validation.shouldValidateOn("blur")) {
|
|
2061
|
+
return true;
|
|
2062
|
+
}
|
|
2063
|
+
return this.validation.validateField(fieldKey, "blur");
|
|
2064
|
+
}
|
|
2065
|
+
/**
|
|
2066
|
+
* @description Record focus for this field without modifying its value.
|
|
2067
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2068
|
+
* @example
|
|
2069
|
+
* ```ts
|
|
2070
|
+
* form.focus(["email"]);
|
|
2071
|
+
* ```
|
|
2072
|
+
*/
|
|
2073
|
+
focus(path) {
|
|
2074
|
+
this.store.focusField(FormPath.pathInputToKey(path));
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* @description Replace the selected field error list without running validation.
|
|
2078
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2079
|
+
* @param {readonly FormError[]} errors - Current validation errors for the field.
|
|
2080
|
+
* @example
|
|
2081
|
+
* ```ts
|
|
2082
|
+
* form.setErrors(["email"], errors);
|
|
2083
|
+
* ```
|
|
2084
|
+
*/
|
|
2085
|
+
setErrors(path, errors) {
|
|
2086
|
+
this.store.setErrorsByKey(FormPath.pathInputToKey(path), errors);
|
|
2087
|
+
}
|
|
2088
|
+
/**
|
|
2089
|
+
* @description Clear selected fields or all fields when no paths are provided.
|
|
2090
|
+
* @param {FieldPathInput[]} paths - Fields to target; no paths means all fields.
|
|
2091
|
+
* @example
|
|
2092
|
+
* ```ts
|
|
2093
|
+
* form.clearErrors("email");
|
|
2094
|
+
* ```
|
|
2095
|
+
*/
|
|
2096
|
+
clearErrors(...paths) {
|
|
2097
|
+
this.store.clearErrors(paths.length > 0 ? paths.map((path) => FormPath.pathInputToKey(path)) : void 0);
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* @description Run manual schema validation for selected paths or the whole form when no paths are supplied.
|
|
2101
|
+
* @param {FieldPathInput[]} paths - Fields to target; no paths means all fields.
|
|
2102
|
+
* @returns {Promise<boolean>} Promise resolving true only when the targeted current validation result is valid.
|
|
2103
|
+
* @example
|
|
2104
|
+
* ```ts
|
|
2105
|
+
* await form.trigger("email");
|
|
2106
|
+
* ```
|
|
2107
|
+
*/
|
|
2108
|
+
trigger(...paths) {
|
|
2109
|
+
if (paths.length === 0) {
|
|
2110
|
+
return this.validation.validateRegisteredFields("manual");
|
|
2111
|
+
}
|
|
2112
|
+
return this.validation.validateFields(paths.map((path) => FormPath.pathInputToKey(path)), "manual");
|
|
2113
|
+
}
|
|
2114
|
+
/**
|
|
2115
|
+
* @description Create commands for an array field that keep values, stable keys, and child state aligned.
|
|
2116
|
+
* @param {FieldPathInput} path - Literal field name or tuple path; strings are not split on dots.
|
|
2117
|
+
* @returns {FormArray} Array commands sharing the current form store and item-key generator.
|
|
2118
|
+
* - keys `() => readonly string[]` - Stable item keys in array order.
|
|
2119
|
+
* - insert `(index: number, value: unknown) => void` - Insert a value at a bounded array index.
|
|
2120
|
+
* - push `(value: unknown) => void` - Append a value and allocate a stable item key.
|
|
2121
|
+
* - remove `(index: number) => void` - Remove the indexed item and rebase surviving child fields.
|
|
2122
|
+
* - move `(fromIndex: number, toIndex: number) => void` - Move an item while preserving its key and child metadata.
|
|
2123
|
+
* - swap `(leftIndex: number, rightIndex: number) => void` - Swap item positions while preserving keys and child metadata.
|
|
2124
|
+
* - replace `(values: readonly unknown[]) => void` - Replace all array items and regenerate their keys and child state.
|
|
2125
|
+
* @example
|
|
2126
|
+
* ```ts
|
|
2127
|
+
* form.array("users").push({ email: "" });
|
|
2128
|
+
* ```
|
|
2129
|
+
*/
|
|
2130
|
+
array(path) {
|
|
2131
|
+
return new FormArrayController(this.store, this.arrayKeys, FormPath.toFieldPath(path));
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* @description Reinitialize values and metadata, optionally retaining dirty values, errors, touched flags, and submission state.
|
|
2135
|
+
* @param {TValues | undefined} [values] - Replacement or current form values.
|
|
2136
|
+
* @param {ResetOptions | undefined} [options] - State preservation flags for this reset.
|
|
2137
|
+
* @param {boolean | undefined} [options.keepDirtyValues] - Preserve current values and modified flags of dirty fields.
|
|
2138
|
+
* @param {boolean | undefined} [options.keepErrors] - Preserve errors on surviving field paths.
|
|
2139
|
+
* @param {boolean | undefined} [options.keepTouched] - Preserve touched flags on surviving field paths.
|
|
2140
|
+
* @param {boolean | undefined} [options.keepSubmitState] - Preserve submission counters and lifecycle flags.
|
|
2141
|
+
* @example
|
|
2142
|
+
* ```ts
|
|
2143
|
+
* form.reset({ email: "Ada" }, { keepTouched: true });
|
|
2144
|
+
* ```
|
|
2145
|
+
*/
|
|
2146
|
+
reset(values, options) {
|
|
2147
|
+
this.store.reset(values, options);
|
|
2148
|
+
}
|
|
2149
|
+
/**
|
|
2150
|
+
* @description Queue a submission, retry stale validation, and return the valid callback result or undefined after invalid validation.
|
|
2151
|
+
* @param {(values: TValues) => TResult | Promise<TResult>} onValid - Callback receiving current values after successful validation.
|
|
2152
|
+
* @param {((fields: Readonly<Record<PathKey, FieldState>>) => void) | undefined} [onInvalid] - Callback receiving field snapshots when validation fails.
|
|
2153
|
+
* @returns {Promise<TResult | undefined>} Promise of the valid callback result, or undefined when validation fails; callback errors reject.
|
|
2154
|
+
* @example
|
|
2155
|
+
* ```ts
|
|
2156
|
+
* await form.submit(values => save(values), fields => showErrors(fields));
|
|
2157
|
+
* ```
|
|
2158
|
+
*/
|
|
2159
|
+
submit(onValid, onInvalid) {
|
|
2160
|
+
return this.submitter.submit(onValid, onInvalid);
|
|
2161
|
+
}
|
|
2162
|
+
};
|
|
2163
|
+
|
|
2164
|
+
export { CreateForm };
|
|
2165
|
+
//# sourceMappingURL=chunk-M7Y4OJPP.js.map
|
|
2166
|
+
//# sourceMappingURL=chunk-M7Y4OJPP.js.map
|