@ilokesto/form 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ko.md CHANGED
@@ -70,7 +70,7 @@ DOM을 import하지 않습니다. 어댑터 소유자가 해제될 때 구독도
70
70
  <details>
71
71
  <summary>개발</summary>
72
72
 
73
- Node 24.22.1과 pnpm 10.17.1을 사용하고 저장소 루트에서 실행하세요.
73
+ Node 24.22.1과 `package.json`에 고정된 pnpm 버전을 사용하고 저장소 루트에서 실행하세요.
74
74
 
75
75
  ```sh
76
76
  pnpm install --frozen-lockfile
package/README.md CHANGED
@@ -70,7 +70,7 @@ of framework and DOM imports. Dispose adapter subscriptions when their owner unm
70
70
  <details>
71
71
  <summary>Development</summary>
72
72
 
73
- Use Node 24.22.1 and pnpm 10.17.1. Run these commands from this repository root:
73
+ Use Node 24.22.1 and the pnpm version pinned in `package.json`. Run these commands from this repository root:
74
74
 
75
75
  ```sh
76
76
  pnpm install --frozen-lockfile
@@ -366,6 +366,7 @@ var FormArrayPath = class {
366
366
 
367
367
  // src/core/state/FieldStateFactory.ts
368
368
  var FieldStateFactory = class {
369
+ static METADATA_ONLY = /* @__PURE__ */ Symbol("metadata-only field");
369
370
  /** 모든 field가 공통으로 갖는 기본 메타데이터 값이다. errors는 매번 새 배열로 복사해서 공유 참조를 피한다. */
370
371
  static DEFAULT_FIELD_STATE = {
371
372
  value: void 0,
@@ -398,7 +399,7 @@ var FieldStateFactory = class {
398
399
  };
399
400
  }
400
401
  /**
401
- * @description Create an empty field snapshot with undefined value and fresh errors.
402
+ * @description Create a metadata-only snapshot with undefined value and fresh errors, without introducing a value into the form.
402
403
  * @returns {FieldState} Independent empty snapshot with undefined value and false metadata flags.
403
404
  * - value `unknown` - Current field value.
404
405
  * - errors `FormError[]` - Current validation errors for the field.
@@ -412,7 +413,30 @@ var FieldStateFactory = class {
412
413
  * ```
413
414
  */
414
415
  static createDefault() {
415
- return this.create(void 0);
416
+ const field = {
417
+ ...this.create(void 0),
418
+ [this.METADATA_ONLY]: true
419
+ };
420
+ return field;
421
+ }
422
+ /**
423
+ * @description Identify value-owning snapshots, including explicit undefined values, separately from metadata-only snapshots.
424
+ * @param {Readonly<FieldState>} field - Field snapshot whose value ownership is inspected.
425
+ * @param {unknown} field.value - Current field value.
426
+ * @param {FormError[]} field.errors - Current validation errors for the field.
427
+ * @param {boolean} field.touched - Whether the field has blurred at least once.
428
+ * @param {boolean} field.dirty - Whether the current value differs from its default.
429
+ * @param {boolean} field.modified - Whether a user-originated write has changed this field.
430
+ * @param {boolean} field.isFocused - Whether focus has been recorded without a subsequent blur.
431
+ * @returns {boolean} Whether the snapshot contributes a value when reconstructing the form.
432
+ * @example
433
+ * ```ts
434
+ * FieldStateFactory.ownsValue(FieldStateFactory.create(undefined)); // true
435
+ * FieldStateFactory.ownsValue(FieldStateFactory.createDefault()); // false
436
+ * ```
437
+ */
438
+ static ownsValue(field) {
439
+ return !(this.METADATA_ONLY in field);
416
440
  }
417
441
  };
418
442
 
@@ -458,7 +482,9 @@ var FormStateInitializer = class {
458
482
  * @returns plain object이면 true.
459
483
  */
460
484
  static isTraversableObject(value) {
461
- return Object.prototype.toString.call(value) === "[object Object]";
485
+ if (value === null || typeof value !== "object") return false;
486
+ const prototype = Object.getPrototypeOf(value);
487
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
462
488
  }
463
489
  /**
464
490
  * defaultValues 안에 이미 존재하는 배열 item의 deterministic key를 만든다.
@@ -593,7 +619,7 @@ var ValueHelper = class {
593
619
  }, this.createEmptyRoot(state.defaultValues));
594
620
  return Object.entries(state.fields).reduce((values, [key, field]) => {
595
621
  const fieldPath = fieldPaths[key];
596
- if (!fieldPath) {
622
+ if (!fieldPath || !FieldStateFactory.ownsValue(field)) {
597
623
  return values;
598
624
  }
599
625
  return this.setValueAtPath(values, fieldPath, field.value);
@@ -741,7 +767,7 @@ var FormStateReader = class _FormStateReader {
741
767
  // src/core/array/FormArrayRebaser.ts
742
768
  var FormArrayRebaser = class {
743
769
  /**
744
- * @description Apply next array values and move surviving child metadata and nested array keys to their new indexes.
770
+ * @description Apply next array values and move surviving child metadata and nested array keys to their new indexes without changing the configured defaults.
745
771
  * @param {Readonly<FormState<TValues>>} previousState - Snapshot before the array mutation.
746
772
  * @param {TValues} previousState.defaultValues - Initial values and the baseline used for dirty checks and reset.
747
773
  * @param {Record<string, FieldState<unknown>>} previousState.fields - Field snapshots indexed by normalized path keys.
@@ -831,6 +857,7 @@ var FormArrayRebaser = class {
831
857
  rebasedArrayKeys[arrayKey] = [...mutation.keys];
832
858
  return {
833
859
  ...initializedState,
860
+ defaultValues: previousState.defaultValues,
834
861
  fields: rebasedFields,
835
862
  arrayKeys: rebasedArrayKeys,
836
863
  submitCount: previousState.submitCount,
@@ -1177,8 +1204,10 @@ var FormStateStore = class {
1177
1204
  (prevState) => produce(prevState, (draft) => {
1178
1205
  const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
1179
1206
  draft.fields[fieldKey] = {
1180
- ...previousField,
1181
- value,
1207
+ ...FieldStateFactory.create(value),
1208
+ errors: previousField.errors,
1209
+ touched: previousField.touched,
1210
+ isFocused: previousField.isFocused,
1182
1211
  dirty: !Object.is(value, defaultValue),
1183
1212
  modified: options.source === "user" ? true : previousField.modified
1184
1213
  };
@@ -1589,51 +1618,103 @@ var ValidationSequencer = class {
1589
1618
 
1590
1619
  // src/core/validation/ValidationSnapshot.ts
1591
1620
  var ValidationSnapshot = class _ValidationSnapshot {
1592
- constructor(fieldValues, arrayKeys) {
1621
+ constructor(fieldValues, arrayKeys, fieldKeys) {
1593
1622
  this.fieldValues = fieldValues;
1594
1623
  this.arrayKeys = arrayKeys;
1624
+ this.fieldKeys = fieldKeys;
1595
1625
  }
1596
1626
  fieldValues;
1597
1627
  arrayKeys;
1628
+ fieldKeys;
1598
1629
  /**
1599
- * @description Capture current field-value and array-key references without retaining a store.
1630
+ * @description Capture whole-form dependencies by default, or only values and array-item identities affecting selected fields.
1600
1631
  * @param {ValidationState} state - Form snapshot used as the source of this calculation.
1601
1632
  * @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
1602
1633
  * @param {ArrayKeys} state.arrayKeys - Stable rendering keys indexed by array path.
1634
+ * @param {readonly string[] | undefined} [fieldKeys] - Normalized field keys for local-only validation; omitted to capture the whole form.
1603
1635
  * @returns {ValidationSnapshot} Identity snapshot independent of validation revisions and the live store.
1604
1636
  * @example
1605
1637
  * ```ts
1606
1638
  * ValidationSnapshot.capture(state);
1607
1639
  * ```
1608
1640
  */
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
- );
1641
+ static capture(state, fieldKeys) {
1642
+ const paths = fieldKeys?.map((fieldKey) => FormPath.keyToPath(fieldKey));
1643
+ const fieldValues = new Map(Object.entries(state.fields).filter(([fieldKey, field]) => {
1644
+ if (!paths) {
1645
+ return true;
1646
+ }
1647
+ if (!FieldStateFactory.ownsValue(field)) {
1648
+ return false;
1649
+ }
1650
+ const fieldPath = FormPath.keyToPath(fieldKey);
1651
+ return paths.some((path) => this.hasPrefix(fieldPath, path) || this.hasPrefix(path, fieldPath));
1652
+ }).map(([fieldKey, field]) => [fieldKey, field.value]));
1653
+ const arrayKeys = /* @__PURE__ */ new Map();
1654
+ Object.entries(state.arrayKeys).forEach(([arrayKey, keys]) => {
1655
+ if (!paths) {
1656
+ arrayKeys.set(arrayKey, keys);
1657
+ return;
1658
+ }
1659
+ const arrayPath = FormPath.keyToPath(arrayKey);
1660
+ paths.forEach((path) => {
1661
+ if (this.hasPrefix(arrayPath, path)) {
1662
+ arrayKeys.set(`array:${arrayKey}`, keys);
1663
+ } else if (this.hasPrefix(path, arrayPath)) {
1664
+ const segment = path[arrayPath.length];
1665
+ const index = Number(segment);
1666
+ if (Number.isInteger(index) && index >= 0 && String(index) === String(segment)) {
1667
+ arrayKeys.set(`item:${arrayKey}:${index}`, keys[index]);
1668
+ } else {
1669
+ arrayKeys.set(`array:${arrayKey}`, keys);
1670
+ }
1671
+ }
1672
+ });
1673
+ });
1674
+ return new _ValidationSnapshot(fieldValues, arrayKeys, fieldKeys ? [...fieldKeys] : void 0);
1614
1675
  }
1615
1676
  /**
1616
- * @description Check value and array-key identities; metadata-only and error-only changes still match.
1677
+ * @description Compare captured dependencies, allowing copied local array-key lists when their item identities are unchanged.
1617
1678
  * @param {ValidationState} state - Form snapshot used as the source of this calculation.
1618
1679
  * @param {Record<string, FieldState<unknown>>} state.fields - Field snapshots indexed by normalized path keys.
1619
1680
  * @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.
1681
+ * @returns {boolean} Whether captured values and relevant array item identities remain unchanged.
1621
1682
  * @example
1622
1683
  * ```ts
1623
1684
  * snapshot.matches(state);
1624
1685
  * ```
1625
1686
  */
1626
1687
  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;
1688
+ const current = _ValidationSnapshot.capture(state, this.fieldKeys);
1689
+ if (this.fieldValues.size !== current.fieldValues.size) {
1690
+ return false;
1691
+ }
1692
+ if (this.arrayKeys.size !== current.arrayKeys.size) {
1693
+ return false;
1694
+ }
1629
1695
  for (const [fieldKey, value] of this.fieldValues) {
1630
- if (!Object.is(state.fields[fieldKey]?.value, value)) return false;
1696
+ if (!current.fieldValues.has(fieldKey) || !Object.is(current.fieldValues.get(fieldKey), value)) {
1697
+ return false;
1698
+ }
1631
1699
  }
1632
1700
  for (const [fieldKey, keys] of this.arrayKeys) {
1633
- if (!Object.is(state.arrayKeys[fieldKey], keys)) return false;
1701
+ if (!current.arrayKeys.has(fieldKey)) {
1702
+ return false;
1703
+ }
1704
+ const currentKeys = current.arrayKeys.get(fieldKey);
1705
+ if (this.fieldKeys && Array.isArray(keys) && Array.isArray(currentKeys)) {
1706
+ if (keys.length !== currentKeys.length || keys.some((key, index) => key !== currentKeys[index])) {
1707
+ return false;
1708
+ }
1709
+ } else if (!Object.is(currentKeys, keys)) {
1710
+ return false;
1711
+ }
1634
1712
  }
1635
1713
  return true;
1636
1714
  }
1715
+ static hasPrefix(path, prefix) {
1716
+ return prefix.length <= path.length && prefix.every((segment, index) => String(segment) === String(path[index]));
1717
+ }
1637
1718
  };
1638
1719
 
1639
1720
  // src/core/validation/ValidationEngine.ts
@@ -1723,6 +1804,16 @@ var ValidationEngine = class _ValidationEngine {
1723
1804
  }
1724
1805
  };
1725
1806
  }
1807
+ /**
1808
+ * @description Invalidate pending field and whole-form validation without executing any schemas.
1809
+ * @example
1810
+ * ```ts
1811
+ * validation.invalidatePending();
1812
+ * ```
1813
+ */
1814
+ invalidatePending() {
1815
+ this.sequencer.startFull();
1816
+ }
1726
1817
  /**
1727
1818
  * @description Validate one field with local-schema precedence and reject stale results.
1728
1819
  * @param {string} fieldKey - Normalized path key of the target field.
@@ -1752,12 +1843,15 @@ var ValidationEngine = class _ValidationEngine {
1752
1843
  return this.validateRegisteredFields("manual");
1753
1844
  }
1754
1845
  const token = this.sequencer.startFields(targetFieldKeys);
1755
- const snapshot = ValidationSnapshot.capture(this.store.getState());
1846
+ const formSchemaFieldKeys = targetFieldKeys.filter((fieldKey) => !this.fieldSchemas.has(fieldKey));
1847
+ const snapshot = ValidationSnapshot.capture(
1848
+ this.store.getState(),
1849
+ formSchemaFieldKeys.length === 0 ? targetFieldKeys : void 0
1850
+ );
1756
1851
  const localErrorsByKey = await this.validateFieldSchemas(targetFieldKeys);
1757
1852
  if (this.isStale(token, snapshot)) {
1758
1853
  return false;
1759
1854
  }
1760
- const formSchemaFieldKeys = targetFieldKeys.filter((fieldKey) => !this.fieldSchemas.has(fieldKey));
1761
1855
  const schemaResult = formSchemaFieldKeys.length > 0 ? await this.validateFormSchema() : _ValidationEngine.createValidSchemaResult();
1762
1856
  if (this.isStale(token, snapshot)) {
1763
1857
  return false;
@@ -1830,22 +1924,20 @@ var ValidationEngine = class _ValidationEngine {
1830
1924
  this.store.setErrorsByKey(fieldKey, errorsByKey[fieldKey] ?? []);
1831
1925
  });
1832
1926
  }
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만 검증한다. */
1927
+ /** 등록된 local schema는 한 번 복원한 현재 values에서 각 경로의 값을 검증한다. */
1842
1928
  async validateFieldSchemas(fieldKeys) {
1843
1929
  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
- }
1930
+ const registeredFields = fieldKeys.flatMap((fieldKey) => {
1931
+ const fieldSchema = this.fieldSchemas.get(fieldKey);
1932
+ return fieldSchema ? [{ fieldKey, validator: fieldSchema.validator }] : [];
1933
+ });
1934
+ if (registeredFields.length === 0) {
1935
+ return errorsByKey;
1936
+ }
1937
+ const values = this.store.getValues();
1938
+ await Promise.all(registeredFields.map(async ({ fieldKey, validator }) => {
1939
+ const value = ValueHelper.getValueAtPath(values, FormPath.keyToPath(fieldKey));
1940
+ errorsByKey[fieldKey] = await validator.validateValue(value);
1849
1941
  }));
1850
1942
  return errorsByKey;
1851
1943
  }
@@ -2131,7 +2223,7 @@ var CreateForm = class {
2131
2223
  return new FormArrayController(this.store, this.arrayKeys, FormPath.toFieldPath(path));
2132
2224
  }
2133
2225
  /**
2134
- * @description Reinitialize values and metadata, optionally retaining dirty values, errors, touched flags, and submission state.
2226
+ * @description Invalidate pending validation and reinitialize values and metadata, optionally retaining dirty values, errors, touched flags, and submission state.
2135
2227
  * @param {TValues | undefined} [values] - Replacement or current form values.
2136
2228
  * @param {ResetOptions | undefined} [options] - State preservation flags for this reset.
2137
2229
  * @param {boolean | undefined} [options.keepDirtyValues] - Preserve current values and modified flags of dirty fields.
@@ -2144,6 +2236,7 @@ var CreateForm = class {
2144
2236
  * ```
2145
2237
  */
2146
2238
  reset(values, options) {
2239
+ this.validation.invalidatePending();
2147
2240
  this.store.reset(values, options);
2148
2241
  }
2149
2242
  /**
@@ -2161,6 +2254,6 @@ var CreateForm = class {
2161
2254
  }
2162
2255
  };
2163
2256
 
2164
- export { CreateForm };
2165
- //# sourceMappingURL=chunk-M7Y4OJPP.js.map
2166
- //# sourceMappingURL=chunk-M7Y4OJPP.js.map
2257
+ export { CreateForm, FieldStateFactory, FormPath };
2258
+ //# sourceMappingURL=chunk-FJ6OHNA5.js.map
2259
+ //# sourceMappingURL=chunk-FJ6OHNA5.js.map