@ilokesto/form 1.0.2 → 1.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.
Files changed (136) hide show
  1. package/dist/adapters/FormInput.d.ts +1 -1
  2. package/dist/adapters/FormInput.js +10 -0
  3. package/dist/adapters/FormStateSummary.d.ts +1 -1
  4. package/dist/adapters/FormStateSummary.js +27 -0
  5. package/dist/adapters/dom/FieldValue.d.ts +1 -1
  6. package/dist/adapters/dom/FieldValue.js +34 -0
  7. package/dist/adapters/dom/RegisterBinding.d.ts +2 -2
  8. package/dist/adapters/dom/RegisterBinding.js +110 -0
  9. package/dist/adapters/dom/SubmitHandler.d.ts +2 -2
  10. package/dist/adapters/dom/SubmitHandler.js +6 -0
  11. package/dist/adapters/dom/index.d.ts +5 -5
  12. package/dist/adapters/dom/index.js +3 -0
  13. package/dist/adapters/dom/types.d.ts +1 -1
  14. package/dist/adapters/dom/types.js +1 -0
  15. package/dist/core/array/ArrayItemReorder.js +24 -0
  16. package/dist/core/array/ArrayKeyGenerator.js +7 -0
  17. package/dist/core/array/FormArrayController.d.ts +3 -3
  18. package/dist/core/array/FormArrayController.js +54 -0
  19. package/dist/core/array/FormArrayFactory.d.ts +2 -2
  20. package/dist/core/array/FormArrayFactory.js +13 -0
  21. package/dist/core/array/FormArrayMutationPlanner.d.ts +1 -1
  22. package/dist/core/array/FormArrayMutationPlanner.js +68 -0
  23. package/dist/core/array/FormArrayPath.d.ts +1 -1
  24. package/dist/core/array/FormArrayPath.js +11 -0
  25. package/dist/core/array/FormArrayRebaser.d.ts +4 -4
  26. package/dist/core/array/FormArrayRebaser.js +54 -0
  27. package/dist/core/array/index.d.ts +1 -1
  28. package/dist/core/array/index.js +1 -0
  29. package/dist/core/form/CreateForm.d.ts +1 -1
  30. package/dist/core/form/CreateForm.js +64 -0
  31. package/dist/core/form/FormFieldCommands.d.ts +3 -3
  32. package/dist/core/form/FormFieldCommands.js +40 -0
  33. package/dist/core/form/FormSubmitter.d.ts +3 -3
  34. package/dist/core/form/FormSubmitter.js +26 -0
  35. package/dist/core/form/index.d.ts +1 -1
  36. package/dist/core/form/index.js +1 -0
  37. package/dist/core/index.d.ts +2 -2
  38. package/dist/core/index.js +1 -0
  39. package/dist/core/path/FormPath.d.ts +1 -1
  40. package/dist/core/path/FormPath.js +36 -0
  41. package/dist/core/path/index.d.ts +1 -1
  42. package/dist/core/path/index.js +1 -0
  43. package/dist/core/state/FieldStateFactory.d.ts +1 -1
  44. package/dist/core/state/FieldStateFactory.js +19 -0
  45. package/dist/core/state/FormStateInitializer.d.ts +1 -1
  46. package/dist/core/state/FormStateInitializer.js +45 -0
  47. package/dist/core/state/FormStateReader.d.ts +1 -1
  48. package/dist/core/state/FormStateReader.js +30 -0
  49. package/dist/core/state/FormStateStore.d.ts +1 -1
  50. package/dist/core/state/FormStateStore.js +66 -0
  51. package/dist/core/state/FormStateWriter.d.ts +1 -1
  52. package/dist/core/state/FormStateWriter.js +107 -0
  53. package/dist/core/state/index.d.ts +1 -1
  54. package/dist/core/state/index.js +1 -0
  55. package/dist/core/types.js +1 -0
  56. package/dist/core/validation/StandardSchemaValidator.d.ts +1 -1
  57. package/dist/core/validation/StandardSchemaValidator.js +63 -0
  58. package/dist/core/validation/ValidationEngine.d.ts +2 -2
  59. package/dist/core/validation/ValidationEngine.js +116 -0
  60. package/dist/core/validation/index.d.ts +1 -1
  61. package/dist/core/validation/index.js +1 -0
  62. package/dist/core/value/ValueHelper.d.ts +1 -1
  63. package/dist/core/value/ValueHelper.js +66 -0
  64. package/dist/core/value/index.d.ts +1 -1
  65. package/dist/core/value/index.js +1 -0
  66. package/dist/index.d.ts +2 -2
  67. package/dist/index.js +1 -4
  68. package/dist/react/RegisterBinding.d.ts +3 -3
  69. package/dist/react/RegisterBinding.js +21 -0
  70. package/dist/react/index.d.ts +2 -2
  71. package/dist/react/index.js +1 -91
  72. package/dist/react/types.d.ts +3 -3
  73. package/dist/react/types.js +1 -0
  74. package/dist/react/useField.d.ts +2 -2
  75. package/dist/react/useField.js +23 -0
  76. package/dist/react/useFieldSchemaRegistration.d.ts +2 -2
  77. package/dist/react/useFieldSchemaRegistration.js +25 -0
  78. package/dist/react/useFieldState.d.ts +2 -2
  79. package/dist/react/useFieldState.js +6 -0
  80. package/dist/react/useForm.d.ts +2 -2
  81. package/dist/react/useForm.js +30 -0
  82. package/dist/react/useFormSnapshot.d.ts +1 -1
  83. package/dist/react/useFormSnapshot.js +4 -0
  84. package/dist/react/useFormState.d.ts +2 -2
  85. package/dist/react/useFormState.js +7 -0
  86. package/dist/react/useRegister.d.ts +2 -2
  87. package/dist/react/useRegister.js +26 -0
  88. package/dist/solid/RegisterBinding.d.ts +3 -3
  89. package/dist/solid/RegisterBinding.js +28 -0
  90. package/dist/solid/index.d.ts +2 -2
  91. package/dist/solid/index.js +1 -117
  92. package/dist/solid/types.d.ts +3 -3
  93. package/dist/solid/types.js +1 -0
  94. package/dist/solid/useField.d.ts +2 -2
  95. package/dist/solid/useField.js +28 -0
  96. package/dist/solid/useFieldSchemaRegistration.d.ts +2 -2
  97. package/dist/solid/useFieldSchemaRegistration.js +15 -0
  98. package/dist/solid/useForm.d.ts +2 -2
  99. package/dist/solid/useForm.js +13 -0
  100. package/dist/solid/useFormSnapshot.d.ts +1 -1
  101. package/dist/solid/useFormSnapshot.js +9 -0
  102. package/dist/solid/useFormState.d.ts +2 -2
  103. package/dist/solid/useFormState.js +38 -0
  104. package/dist/solid/useRegister.d.ts +2 -2
  105. package/dist/solid/useRegister.js +21 -0
  106. package/dist/svelte/RegisterAction.d.ts +2 -2
  107. package/dist/svelte/RegisterAction.js +121 -0
  108. package/dist/svelte/index.d.ts +2 -2
  109. package/dist/svelte/index.js +1 -111
  110. package/dist/svelte/types.d.ts +4 -4
  111. package/dist/svelte/types.js +1 -0
  112. package/dist/svelte/useForm.d.ts +2 -2
  113. package/dist/svelte/useForm.js +17 -0
  114. package/dist/svelte/useFormState.d.ts +2 -2
  115. package/dist/svelte/useFormState.js +10 -0
  116. package/dist/vue/RegisterBinding.d.ts +3 -3
  117. package/dist/vue/RegisterBinding.js +28 -0
  118. package/dist/vue/index.d.ts +2 -2
  119. package/dist/vue/index.js +1 -117
  120. package/dist/vue/types.d.ts +3 -3
  121. package/dist/vue/types.js +1 -0
  122. package/dist/vue/useField.d.ts +2 -2
  123. package/dist/vue/useField.js +28 -0
  124. package/dist/vue/useFieldSchemaRegistration.d.ts +2 -2
  125. package/dist/vue/useFieldSchemaRegistration.js +17 -0
  126. package/dist/vue/useForm.d.ts +2 -2
  127. package/dist/vue/useForm.js +13 -0
  128. package/dist/vue/useFormSnapshot.d.ts +1 -1
  129. package/dist/vue/useFormSnapshot.js +11 -0
  130. package/dist/vue/useFormState.d.ts +2 -2
  131. package/dist/vue/useFormState.js +38 -0
  132. package/dist/vue/useRegister.d.ts +2 -2
  133. package/dist/vue/useRegister.js +21 -0
  134. package/package.json +2 -2
  135. package/dist/CreateForm-hQ4cxAK-.js +0 -1283
  136. package/dist/FormStateSummary-gmEQdNXj.js +0 -140
@@ -0,0 +1,40 @@
1
+ import { FormPath } from '../path/index';
2
+ export class FormFieldCommands {
3
+ store;
4
+ validation;
5
+ constructor(store, validation) {
6
+ this.store = store;
7
+ this.validation = validation;
8
+ }
9
+ setValue(path, value, options = {}) {
10
+ const fieldKey = this.store.setValue(FormPath.toFieldPath(path), value, options);
11
+ if (options.validate || this.validation.shouldValidateOn('change')) {
12
+ void this.validation.validateField(fieldKey, 'change');
13
+ }
14
+ }
15
+ registerFieldSchema(path, options) {
16
+ return this.validation.registerFieldSchema(FormPath.pathInputToKey(path), options);
17
+ }
18
+ async blur(path) {
19
+ const fieldKey = FormPath.pathInputToKey(path);
20
+ this.store.touchField(fieldKey);
21
+ if (!this.validation.shouldValidateOn('blur')) {
22
+ return true;
23
+ }
24
+ return this.validation.validateField(fieldKey, 'blur');
25
+ }
26
+ focus(_path) {
27
+ }
28
+ setErrors(path, errors) {
29
+ this.store.setErrorsByKey(FormPath.pathInputToKey(path), errors);
30
+ }
31
+ clearErrors(paths) {
32
+ this.store.clearErrors(paths.length > 0 ? paths.map(path => FormPath.pathInputToKey(path)) : undefined);
33
+ }
34
+ trigger(paths) {
35
+ if (paths.length === 0) {
36
+ return this.validation.validateRegisteredFields('manual');
37
+ }
38
+ return this.validation.validateFields(paths.map(path => FormPath.pathInputToKey(path)), 'manual');
39
+ }
40
+ }
@@ -1,6 +1,6 @@
1
- import type { FormStateStore } from '../state/index.js';
2
- import type { ValidationEngine } from '../validation/index.js';
3
- import type { FieldState, PathKey } from '../types.js';
1
+ import type { FormStateStore } from '../state/index';
2
+ import type { ValidationEngine } from '../validation/index';
3
+ import type { FieldState, PathKey } from '../types';
4
4
  export declare class FormSubmitter<TValues> {
5
5
  private readonly store;
6
6
  private readonly validation;
@@ -0,0 +1,26 @@
1
+ export class FormSubmitter {
2
+ store;
3
+ validation;
4
+ constructor(store, validation) {
5
+ this.store = store;
6
+ this.validation = validation;
7
+ }
8
+ async submit(onValid, onInvalid) {
9
+ this.store.beginSubmit();
10
+ try {
11
+ const isValid = await this.validation.validateRegisteredFields('submit');
12
+ if (!isValid) {
13
+ onInvalid?.(this.store.getState().fields);
14
+ this.store.completeSubmit(false);
15
+ return undefined;
16
+ }
17
+ const result = await onValid(this.store.getValues());
18
+ this.store.completeSubmit(true);
19
+ return result;
20
+ }
21
+ catch (error) {
22
+ this.store.completeSubmit(false);
23
+ throw error;
24
+ }
25
+ }
26
+ }
@@ -1 +1 @@
1
- export { CreateForm } from './CreateForm.js';
1
+ export { CreateForm } from './CreateForm';
@@ -0,0 +1 @@
1
+ export { CreateForm } from './CreateForm';
@@ -1,2 +1,2 @@
1
- export { CreateForm } from './form/index.js';
2
- export type { CreateFormOptions, FieldSchemaOptions, FieldPathValue, FieldPathInput, FieldState, Form, FormArray, FormError, FormState, ResetOptions, SetValueOptions, StandardSchemaV1, ValidationTrigger } from './types.js';
1
+ export { CreateForm } from './form/index';
2
+ export type { CreateFormOptions, FieldSchemaOptions, FieldPathValue, FieldPathInput, FieldState, Form, FormArray, FormError, FormState, ResetOptions, SetValueOptions, StandardSchemaV1, ValidationTrigger } from './types';
@@ -0,0 +1 @@
1
+ export { CreateForm } from './form/index';
@@ -1,4 +1,4 @@
1
- import type { FieldPath, FieldPathInput, PathKey } from '../types.js';
1
+ import type { FieldPath, FieldPathInput, PathKey } from '../types';
2
2
  export declare class FormPath {
3
3
  static readonly ROOT_PATH_KEY = "$";
4
4
  static path(...segments: FieldPath): FieldPath;
@@ -0,0 +1,36 @@
1
+ export class FormPath {
2
+ static ROOT_PATH_KEY = '$';
3
+ static path(...segments) {
4
+ return segments;
5
+ }
6
+ static toFieldPath(fieldPath) {
7
+ if (typeof fieldPath === 'string') {
8
+ return [fieldPath];
9
+ }
10
+ return fieldPath;
11
+ }
12
+ static pathInputToKey(fieldPath) {
13
+ return this.pathToKey(this.toFieldPath(fieldPath));
14
+ }
15
+ static pathToKey(fieldPath) {
16
+ if (fieldPath.length === 0) {
17
+ return this.ROOT_PATH_KEY;
18
+ }
19
+ return JSON.stringify(fieldPath);
20
+ }
21
+ static keyToPath(key) {
22
+ if (key === this.ROOT_PATH_KEY) {
23
+ return [];
24
+ }
25
+ const parsed = JSON.parse(key);
26
+ if (!Array.isArray(parsed)) {
27
+ throw new Error(`Invalid form path key: ${key}`);
28
+ }
29
+ return parsed.map(segment => {
30
+ if (typeof segment === 'string' || typeof segment === 'number') {
31
+ return segment;
32
+ }
33
+ throw new Error(`Invalid form path segment in key: ${key}`);
34
+ });
35
+ }
36
+ }
@@ -1 +1 @@
1
- export { FormPath } from './FormPath.js';
1
+ export { FormPath } from './FormPath';
@@ -0,0 +1 @@
1
+ export { FormPath } from './FormPath';
@@ -1,4 +1,4 @@
1
- import type { FieldState } from '../types.js';
1
+ import type { FieldState } from '../types';
2
2
  export declare class FieldStateFactory {
3
3
  private static readonly DEFAULT_FIELD_STATE;
4
4
  static create(value: unknown): FieldState;
@@ -0,0 +1,19 @@
1
+ export class FieldStateFactory {
2
+ static DEFAULT_FIELD_STATE = {
3
+ value: undefined,
4
+ errors: [],
5
+ touched: false,
6
+ dirty: false,
7
+ modified: false,
8
+ };
9
+ static create(value) {
10
+ return {
11
+ ...this.DEFAULT_FIELD_STATE,
12
+ value,
13
+ errors: [],
14
+ };
15
+ }
16
+ static createDefault() {
17
+ return this.create(undefined);
18
+ }
19
+ }
@@ -1,4 +1,4 @@
1
- import type { FormState } from '../types.js';
1
+ import type { FormState } from '../types';
2
2
  export declare class FormStateInitializer {
3
3
  static initialize<TValues>(defaultValues: TValues): FormState<TValues>;
4
4
  private static isTraversableObject;
@@ -0,0 +1,45 @@
1
+ import { FieldStateFactory } from './FieldStateFactory';
2
+ import { FormPath } from '../path/index';
3
+ export class FormStateInitializer {
4
+ static initialize(defaultValues) {
5
+ const fields = {};
6
+ const arrayKeys = {};
7
+ this.visitInitialValue(defaultValues, [], fields, arrayKeys);
8
+ return {
9
+ defaultValues,
10
+ fields,
11
+ submitCount: 0,
12
+ isSubmitting: false,
13
+ isSubmitted: false,
14
+ isSubmitSuccessful: false,
15
+ arrayKeys,
16
+ };
17
+ }
18
+ static isTraversableObject(value) {
19
+ return Object.prototype.toString.call(value) === '[object Object]';
20
+ }
21
+ static createInitialArrayKeys(length) {
22
+ return Array.from({ length }, (_, index) => `initial-${index}`);
23
+ }
24
+ static visitInitialValue(value, fieldPath, fields, arrayKeys) {
25
+ if (Array.isArray(value)) {
26
+ arrayKeys[FormPath.pathToKey(fieldPath)] = this.createInitialArrayKeys(value.length);
27
+ value.forEach((item, index) => {
28
+ this.visitInitialValue(item, [...fieldPath, index], fields, arrayKeys);
29
+ });
30
+ return;
31
+ }
32
+ if (this.isTraversableObject(value)) {
33
+ const entries = Object.entries(value);
34
+ if (entries.length === 0) {
35
+ fields[FormPath.pathToKey(fieldPath)] = FieldStateFactory.create(value);
36
+ return;
37
+ }
38
+ entries.forEach(([key, childValue]) => {
39
+ this.visitInitialValue(childValue, [...fieldPath, key], fields, arrayKeys);
40
+ });
41
+ return;
42
+ }
43
+ fields[FormPath.pathToKey(fieldPath)] = FieldStateFactory.create(value);
44
+ }
45
+ }
@@ -1,4 +1,4 @@
1
- import type { FieldPath, FieldPathInput, FieldState, FormState, PathKey } from '../types.js';
1
+ import type { FieldPath, FieldPathInput, FieldState, FormState, PathKey } from '../types';
2
2
  export declare class FormStateReader<TValues> {
3
3
  private readonly getSnapshot;
4
4
  constructor(getSnapshot: () => Readonly<FormState<TValues>>);
@@ -0,0 +1,30 @@
1
+ import { FieldStateFactory } from './FieldStateFactory';
2
+ import { FormPath } from '../path/index';
3
+ import { ValueHelper } from '../value/index';
4
+ export class FormStateReader {
5
+ getSnapshot;
6
+ constructor(getSnapshot) {
7
+ this.getSnapshot = getSnapshot;
8
+ }
9
+ getKnownFieldPaths() {
10
+ return Object.keys(this.getSnapshot().fields).reduce((paths, key) => {
11
+ paths[key] = FormPath.keyToPath(key);
12
+ return paths;
13
+ }, {});
14
+ }
15
+ getFieldStateByKey(fieldKey) {
16
+ return this.getSnapshot().fields[fieldKey] ?? FieldStateFactory.createDefault();
17
+ }
18
+ getFieldState(fieldPath) {
19
+ return this.getFieldStateByKey(FormPath.pathInputToKey(fieldPath));
20
+ }
21
+ getValue(fieldPath) {
22
+ return this.getFieldState(fieldPath).value;
23
+ }
24
+ getValues() {
25
+ return ValueHelper.getValuesFromFields(this.getSnapshot(), this.getKnownFieldPaths());
26
+ }
27
+ getValueAtPath(fieldPath) {
28
+ return ValueHelper.getValueAtPath(this.getValues(), fieldPath);
29
+ }
30
+ }
@@ -1,4 +1,4 @@
1
- import type { FieldPath, FieldPathInput, FieldState, FormError, FormState, PathKey, ResetOptions, SetValueOptions } from '../types.js';
1
+ import type { FieldPath, FieldPathInput, FieldState, FormError, FormState, PathKey, ResetOptions, SetValueOptions } from '../types';
2
2
  export declare class FormStateStore<TValues> {
3
3
  private readonly store;
4
4
  private readonly reader;
@@ -0,0 +1,66 @@
1
+ import { Store } from '@ilokesto/store';
2
+ import { FieldStateFactory } from './FieldStateFactory';
3
+ import { FormStateReader } from './FormStateReader';
4
+ import { FormStateWriter } from './FormStateWriter';
5
+ import { FormStateInitializer } from './FormStateInitializer';
6
+ export class FormStateStore {
7
+ store;
8
+ reader;
9
+ writer;
10
+ static getDefaultFieldState() {
11
+ return FieldStateFactory.createDefault();
12
+ }
13
+ constructor(defaultValues) {
14
+ this.store = new Store(FormStateInitializer.initialize(defaultValues));
15
+ this.reader = new FormStateReader(() => this.store.getState());
16
+ this.writer = new FormStateWriter(this.store);
17
+ }
18
+ getState() {
19
+ return this.store.getState();
20
+ }
21
+ subscribe(listener) {
22
+ return this.store.subscribe(listener);
23
+ }
24
+ getKnownFieldPaths() {
25
+ return this.reader.getKnownFieldPaths();
26
+ }
27
+ getFieldStateByKey(fieldKey) {
28
+ return this.reader.getFieldStateByKey(fieldKey);
29
+ }
30
+ getFieldState(fieldPath) {
31
+ return this.reader.getFieldState(fieldPath);
32
+ }
33
+ getValue(fieldPath) {
34
+ return this.reader.getValue(fieldPath);
35
+ }
36
+ getValues() {
37
+ return this.reader.getValues();
38
+ }
39
+ getValueAtPath(fieldPath) {
40
+ return this.reader.getValueAtPath(fieldPath);
41
+ }
42
+ setValue(fieldPath, value, options = {}) {
43
+ return this.writer.setValue(fieldPath, value, options);
44
+ }
45
+ touchField(fieldKey) {
46
+ this.writer.touchField(fieldKey);
47
+ }
48
+ setErrorsByKey(fieldKey, errors) {
49
+ this.writer.setErrorsByKey(fieldKey, errors);
50
+ }
51
+ clearErrors(fieldKeys) {
52
+ this.writer.clearErrors(fieldKeys);
53
+ }
54
+ reset(values, options) {
55
+ this.writer.reset(values, options);
56
+ }
57
+ beginSubmit() {
58
+ this.writer.beginSubmit();
59
+ }
60
+ completeSubmit(successful) {
61
+ this.writer.completeSubmit(successful);
62
+ }
63
+ replaceState(updater) {
64
+ this.writer.replaceState(updater);
65
+ }
66
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Store } from '@ilokesto/store';
2
- import type { FieldPath, FormError, FormState, PathKey, ResetOptions, SetValueOptions } from '../types.js';
2
+ import type { FieldPath, FormError, FormState, PathKey, ResetOptions, SetValueOptions } from '../types';
3
3
  type WritableFormStore<TValues> = Pick<Store<FormState<TValues>>, 'getState' | 'setState'>;
4
4
  export declare class FormStateWriter<TValues> {
5
5
  private readonly store;
@@ -0,0 +1,107 @@
1
+ import { produce } from 'immer';
2
+ import { FieldStateFactory } from './FieldStateFactory';
3
+ import { FormStateInitializer } from './FormStateInitializer';
4
+ import { FormPath } from '../path/index';
5
+ import { ValueHelper } from '../value/index';
6
+ export class FormStateWriter {
7
+ store;
8
+ constructor(store) {
9
+ this.store = store;
10
+ }
11
+ setValue(fieldPath, value, options = {}) {
12
+ const fieldKey = FormPath.pathToKey(fieldPath);
13
+ const defaultValue = ValueHelper.getValueAtPath(this.store.getState().defaultValues, fieldPath);
14
+ this.store.setState(prevState => produce(prevState, draft => {
15
+ const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
16
+ draft.fields[fieldKey] = {
17
+ ...previousField,
18
+ value,
19
+ dirty: !FormStateWriter.isSameValue(value, defaultValue),
20
+ modified: options.source === 'user' ? true : previousField.modified,
21
+ };
22
+ }));
23
+ return fieldKey;
24
+ }
25
+ touchField(fieldKey) {
26
+ this.store.setState(prevState => produce(prevState, draft => {
27
+ const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
28
+ draft.fields[fieldKey] = {
29
+ ...previousField,
30
+ touched: true,
31
+ };
32
+ }));
33
+ }
34
+ setErrorsByKey(fieldKey, errors) {
35
+ this.store.setState(prevState => produce(prevState, draft => {
36
+ const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
37
+ draft.fields[fieldKey] = {
38
+ ...previousField,
39
+ errors: [...errors],
40
+ };
41
+ }));
42
+ }
43
+ clearErrors(fieldKeys) {
44
+ this.store.setState(prevState => produce(prevState, draft => {
45
+ const keys = fieldKeys && fieldKeys.length > 0 ? fieldKeys : Object.keys(draft.fields);
46
+ keys.forEach(fieldKey => {
47
+ const previousField = draft.fields[fieldKey] ?? FieldStateFactory.createDefault();
48
+ draft.fields[fieldKey] = {
49
+ ...previousField,
50
+ errors: [],
51
+ };
52
+ });
53
+ }));
54
+ }
55
+ reset(values, options = {}) {
56
+ const previousState = this.store.getState();
57
+ const nextDefaultValues = values ?? previousState.defaultValues;
58
+ const initializedState = FormStateInitializer.initialize(nextDefaultValues);
59
+ this.store.setState(produce(initializedState, draft => {
60
+ Object.entries(draft.fields).forEach(([fieldKey, nextField]) => {
61
+ const previousField = previousState.fields[fieldKey];
62
+ if (!previousField) {
63
+ return;
64
+ }
65
+ if (options.keepDirtyValues && previousField.dirty) {
66
+ const fieldPath = FormPath.keyToPath(fieldKey);
67
+ const defaultValue = ValueHelper.getValueAtPath(nextDefaultValues, fieldPath);
68
+ nextField.value = previousField.value;
69
+ nextField.dirty = !FormStateWriter.isSameValue(previousField.value, defaultValue);
70
+ nextField.modified = previousField.modified;
71
+ }
72
+ if (options.keepErrors) {
73
+ nextField.errors = [...previousField.errors];
74
+ }
75
+ if (options.keepTouched) {
76
+ nextField.touched = previousField.touched;
77
+ }
78
+ });
79
+ if (options.keepSubmitState) {
80
+ draft.submitCount = previousState.submitCount;
81
+ draft.isSubmitting = previousState.isSubmitting;
82
+ draft.isSubmitted = previousState.isSubmitted;
83
+ draft.isSubmitSuccessful = previousState.isSubmitSuccessful;
84
+ }
85
+ }));
86
+ }
87
+ beginSubmit() {
88
+ this.store.setState(prevState => produce(prevState, draft => {
89
+ draft.submitCount += 1;
90
+ draft.isSubmitting = true;
91
+ draft.isSubmitSuccessful = false;
92
+ }));
93
+ }
94
+ completeSubmit(successful) {
95
+ this.store.setState(prevState => produce(prevState, draft => {
96
+ draft.isSubmitting = false;
97
+ draft.isSubmitted = true;
98
+ draft.isSubmitSuccessful = successful;
99
+ }));
100
+ }
101
+ replaceState(updater) {
102
+ this.store.setState(updater);
103
+ }
104
+ static isSameValue(left, right) {
105
+ return Object.is(left, right);
106
+ }
107
+ }
@@ -1 +1 @@
1
- export { FormStateStore } from './FormStateStore.js';
1
+ export { FormStateStore } from './FormStateStore';
@@ -0,0 +1 @@
1
+ export { FormStateStore } from './FormStateStore';
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,4 @@
1
- import type { FormError, PathKey, StandardSchemaV1 } from '../types.js';
1
+ import type { FormError, PathKey, StandardSchemaV1 } from '../types';
2
2
  export declare class StandardSchemaValidator<TValues> {
3
3
  private readonly schema;
4
4
  private readonly options?;
@@ -0,0 +1,63 @@
1
+ import { FormPath } from '../path/index';
2
+ export class StandardSchemaValidator {
3
+ schema;
4
+ options;
5
+ constructor(schema, options) {
6
+ this.schema = schema;
7
+ this.options = options;
8
+ }
9
+ async validate(values) {
10
+ const result = await this.schema['~standard'].validate(values, this.options);
11
+ if (!result.issues) {
12
+ return {
13
+ valid: true,
14
+ errorsByKey: {},
15
+ };
16
+ }
17
+ return {
18
+ valid: false,
19
+ errorsByKey: result.issues.reduce((errorsByKey, issue) => {
20
+ const fieldKey = FormPath.pathToKey(StandardSchemaValidator.issuePathToFieldPath(issue.path));
21
+ errorsByKey[fieldKey] = [
22
+ ...(errorsByKey[fieldKey] ?? []),
23
+ {
24
+ type: 'standard_schema',
25
+ message: issue.message,
26
+ },
27
+ ];
28
+ return errorsByKey;
29
+ }, {}),
30
+ };
31
+ }
32
+ async validateValue(value) {
33
+ const result = await this.schema['~standard'].validate(value, this.options);
34
+ if (!result.issues) {
35
+ return [];
36
+ }
37
+ return result.issues.map(issue => ({
38
+ type: 'standard_schema',
39
+ message: issue.message,
40
+ }));
41
+ }
42
+ static issuePathToFieldPath(issuePath) {
43
+ if (!issuePath || issuePath.length === 0) {
44
+ return [];
45
+ }
46
+ const fieldPath = [];
47
+ for (const segment of issuePath) {
48
+ const key = StandardSchemaValidator.issuePathSegmentToKey(segment);
49
+ if (key === undefined) {
50
+ return [];
51
+ }
52
+ fieldPath.push(key);
53
+ }
54
+ return fieldPath;
55
+ }
56
+ static issuePathSegmentToKey(segment) {
57
+ const key = typeof segment === 'object' ? segment.key : segment;
58
+ if (typeof key === 'string' || typeof key === 'number') {
59
+ return key;
60
+ }
61
+ return undefined;
62
+ }
63
+ }
@@ -1,5 +1,5 @@
1
- import type { FormStateStore } from '../state/index.js';
2
- import type { CreateFormOptions, FieldSchemaOptions, PathKey, ValidationTrigger } from '../types.js';
1
+ import type { FormStateStore } from '../state/index';
2
+ import type { CreateFormOptions, FieldSchemaOptions, PathKey, ValidationTrigger } from '../types';
3
3
  export declare class ValidationEngine<TValues> {
4
4
  private static readonly DEFAULT_VALIDATE_ON;
5
5
  private readonly store;
@@ -0,0 +1,116 @@
1
+ import { StandardSchemaValidator } from './StandardSchemaValidator';
2
+ export class ValidationEngine {
3
+ static DEFAULT_VALIDATE_ON = ['submit'];
4
+ store;
5
+ schema;
6
+ fieldSchemas = new Map();
7
+ validateOn;
8
+ nextFieldSchemaId = 0;
9
+ constructor(store, options) {
10
+ this.store = store;
11
+ this.schema = options.schema ? new StandardSchemaValidator(options.schema, options.schemaOptions) : undefined;
12
+ this.validateOn = options.validateOn ?? ValidationEngine.DEFAULT_VALIDATE_ON;
13
+ }
14
+ shouldValidateOn(trigger) {
15
+ return this.validateOn.includes(trigger);
16
+ }
17
+ registerFieldSchema(fieldKey, options) {
18
+ const id = ++this.nextFieldSchemaId;
19
+ this.fieldSchemas.set(fieldKey, {
20
+ id,
21
+ validator: new StandardSchemaValidator(options.schema, options.schemaOptions),
22
+ });
23
+ return () => {
24
+ if (this.fieldSchemas.get(fieldKey)?.id === id) {
25
+ this.fieldSchemas.delete(fieldKey);
26
+ }
27
+ };
28
+ }
29
+ async validateField(fieldKey, _trigger) {
30
+ const fieldSchemaErrors = await this.validateFieldSchema(fieldKey);
31
+ if (fieldSchemaErrors) {
32
+ this.applyErrors([fieldKey], { [fieldKey]: fieldSchemaErrors });
33
+ return fieldSchemaErrors.length === 0;
34
+ }
35
+ const schemaResult = await this.validateSchema();
36
+ this.applyErrors([fieldKey], schemaResult.errorsByKey);
37
+ return (schemaResult.errorsByKey[fieldKey] ?? []).length === 0;
38
+ }
39
+ async validateFields(fieldKeys, _trigger) {
40
+ const targetFieldKeys = ValidationEngine.unique(fieldKeys);
41
+ if (targetFieldKeys.length === 0) {
42
+ return this.validateRegisteredFields('manual');
43
+ }
44
+ const localErrorsByKey = await this.validateFieldSchemas(targetFieldKeys);
45
+ const formSchemaFieldKeys = targetFieldKeys.filter(fieldKey => !this.fieldSchemas.has(fieldKey));
46
+ const schemaResult = formSchemaFieldKeys.length > 0
47
+ ? await this.validateSchema()
48
+ : ValidationEngine.createValidSchemaResult();
49
+ const errorsByKey = this.mergeErrorsByKey(schemaResult.errorsByKey, localErrorsByKey);
50
+ this.applyErrors([...formSchemaFieldKeys, ...Object.keys(localErrorsByKey)], errorsByKey);
51
+ return targetFieldKeys.every(fieldKey => (errorsByKey[fieldKey] ?? []).length === 0);
52
+ }
53
+ async validateRegisteredFields(_trigger) {
54
+ const schemaResult = await this.validateSchema();
55
+ const localErrorsByKey = await this.validateRegisteredFieldSchemas();
56
+ const errorsByKey = this.mergeErrorsByKey(schemaResult.errorsByKey, localErrorsByKey);
57
+ const keysToWrite = this.getValidationWriteKeys(errorsByKey);
58
+ this.applyErrors(keysToWrite, errorsByKey);
59
+ return keysToWrite.every(fieldKey => (errorsByKey[fieldKey] ?? []).length === 0);
60
+ }
61
+ validateSchema() {
62
+ if (!this.schema) {
63
+ return Promise.resolve(ValidationEngine.createValidSchemaResult());
64
+ }
65
+ return this.schema.validate(this.store.getValues());
66
+ }
67
+ applyErrors(fieldKeys, errorsByKey) {
68
+ fieldKeys.forEach(fieldKey => {
69
+ this.store.setErrorsByKey(fieldKey, errorsByKey[fieldKey] ?? []);
70
+ });
71
+ }
72
+ async validateFieldSchema(fieldKey) {
73
+ const fieldSchema = this.fieldSchemas.get(fieldKey);
74
+ if (!fieldSchema) {
75
+ return undefined;
76
+ }
77
+ return fieldSchema.validator.validateValue(this.store.getFieldStateByKey(fieldKey).value);
78
+ }
79
+ async validateFieldSchemas(fieldKeys) {
80
+ const errorsByKey = {};
81
+ await Promise.all(fieldKeys.map(async (fieldKey) => {
82
+ const errors = await this.validateFieldSchema(fieldKey);
83
+ if (errors) {
84
+ errorsByKey[fieldKey] = errors;
85
+ }
86
+ }));
87
+ return errorsByKey;
88
+ }
89
+ validateRegisteredFieldSchemas() {
90
+ return this.validateFieldSchemas([...this.fieldSchemas.keys()]);
91
+ }
92
+ mergeErrorsByKey(formErrorsByKey, fieldErrorsByKey) {
93
+ const merged = Object.entries(formErrorsByKey).reduce((errorsByKey, [fieldKey, errors]) => {
94
+ if (!this.fieldSchemas.has(fieldKey)) {
95
+ errorsByKey[fieldKey] = [...errors];
96
+ }
97
+ return errorsByKey;
98
+ }, {});
99
+ Object.entries(fieldErrorsByKey).forEach(([fieldKey, errors]) => {
100
+ merged[fieldKey] = [...errors];
101
+ });
102
+ return merged;
103
+ }
104
+ getValidationWriteKeys(schemaErrorsByKey) {
105
+ return ValidationEngine.unique([...Object.keys(this.store.getState().fields), ...Object.keys(schemaErrorsByKey)]);
106
+ }
107
+ static unique(fieldKeys) {
108
+ return [...new Set(fieldKeys)];
109
+ }
110
+ static createValidSchemaResult() {
111
+ return {
112
+ valid: true,
113
+ errorsByKey: {},
114
+ };
115
+ }
116
+ }
@@ -1 +1 @@
1
- export { ValidationEngine } from './ValidationEngine.js';
1
+ export { ValidationEngine } from './ValidationEngine';