@gunubin/vorm-react 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +82 -0
- package/dist/index.cjs +519 -0
- package/dist/index.d.cts +87 -0
- package/dist/index.d.ts +87 -0
- package/dist/index.js +490 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 gunubin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @gunubin/vorm-react
|
|
2
|
+
|
|
3
|
+
React hooks for vorm — `useForm` and `useField` with per-field subscriptions via `useSyncExternalStore`.
|
|
4
|
+
|
|
5
|
+
Part of the [vorm](https://github.com/gunubin/vorm) monorepo.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @gunubin/vorm-core @gunubin/vorm-react
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { useForm, useField } from '@gunubin/vorm-react';
|
|
17
|
+
|
|
18
|
+
function LoginForm() {
|
|
19
|
+
const form = useForm(loginSchema, {
|
|
20
|
+
defaultValues: { email: '', password: '' },
|
|
21
|
+
mode: 'onBlur',
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const email = useField(form, 'email');
|
|
25
|
+
const password = useField(form, 'password');
|
|
26
|
+
|
|
27
|
+
return (
|
|
28
|
+
<form onSubmit={form.handleSubmit((values) => {
|
|
29
|
+
// values.email is Brand<string, 'Email'>
|
|
30
|
+
login(values.email, values.password);
|
|
31
|
+
})}>
|
|
32
|
+
<input value={email.value} onChange={(e) => email.onChange(e.target.value)} onBlur={email.onBlur} />
|
|
33
|
+
{email.error && <span>{email.error.message}</span>}
|
|
34
|
+
|
|
35
|
+
<input type="password" value={password.value} onChange={(e) => password.onChange(e.target.value)} onBlur={password.onBlur} />
|
|
36
|
+
{password.error && <span>{password.error.message}</span>}
|
|
37
|
+
|
|
38
|
+
<button type="submit" disabled={form.isSubmitting}>Log in</button>
|
|
39
|
+
</form>
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Why `useField`?
|
|
45
|
+
|
|
46
|
+
`useField(form, 'email')` subscribes **only** to the email field's state. When the password changes, the email input does not re-render.
|
|
47
|
+
|
|
48
|
+
`form.field('email')` also works but reads from the form-level snapshot, so it re-renders with every field change. Use `useField` for performance-critical forms.
|
|
49
|
+
|
|
50
|
+
## Validation Modes
|
|
51
|
+
|
|
52
|
+
| Mode | Behavior |
|
|
53
|
+
|------|----------|
|
|
54
|
+
| `onSubmit` | Validate only on submit (default) |
|
|
55
|
+
| `onBlur` | Validate when a field loses focus |
|
|
56
|
+
| `onChange` | Validate on every value change |
|
|
57
|
+
| `onTouched` | Validate on first blur, then re-validate on change |
|
|
58
|
+
|
|
59
|
+
## Async Validation
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
const form = useForm(schema, {
|
|
63
|
+
defaultValues: { email: '' },
|
|
64
|
+
asyncValidators: {
|
|
65
|
+
email: {
|
|
66
|
+
validate: async (value) => {
|
|
67
|
+
const taken = await checkEmailExists(value);
|
|
68
|
+
if (taken) return { code: 'TAKEN', message: 'Already registered' };
|
|
69
|
+
return null;
|
|
70
|
+
},
|
|
71
|
+
on: 'blur',
|
|
72
|
+
debounceMs: 300,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
For full documentation, see the [vorm README](https://github.com/gunubin/vorm#readme).
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createFormStore: () => createFormStore,
|
|
24
|
+
useField: () => useField,
|
|
25
|
+
useForm: () => useForm
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/use-form.ts
|
|
30
|
+
var import_react = require("react");
|
|
31
|
+
var import_vorm_core = require("@gunubin/vorm-core");
|
|
32
|
+
|
|
33
|
+
// src/form-store.ts
|
|
34
|
+
function createFormStore(initialState) {
|
|
35
|
+
let state = initialState;
|
|
36
|
+
let snapshot = state;
|
|
37
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
38
|
+
const fieldListeners = /* @__PURE__ */ new Map();
|
|
39
|
+
const fieldSnapshotCache = /* @__PURE__ */ new Map();
|
|
40
|
+
function emit(changedFields) {
|
|
41
|
+
snapshot = { ...state };
|
|
42
|
+
for (const listener of listeners) {
|
|
43
|
+
listener();
|
|
44
|
+
}
|
|
45
|
+
if (changedFields) {
|
|
46
|
+
for (const name of changedFields) {
|
|
47
|
+
fieldSnapshotCache.delete(name);
|
|
48
|
+
const set = fieldListeners.get(name);
|
|
49
|
+
if (set) {
|
|
50
|
+
for (const listener of set) {
|
|
51
|
+
listener();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
fieldSnapshotCache.clear();
|
|
57
|
+
for (const [, set] of fieldListeners) {
|
|
58
|
+
for (const listener of set) {
|
|
59
|
+
listener();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
subscribe(listener) {
|
|
66
|
+
listeners.add(listener);
|
|
67
|
+
return () => {
|
|
68
|
+
listeners.delete(listener);
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
getSnapshot() {
|
|
72
|
+
return snapshot;
|
|
73
|
+
},
|
|
74
|
+
subscribeField(name, listener) {
|
|
75
|
+
if (!fieldListeners.has(name)) {
|
|
76
|
+
fieldListeners.set(name, /* @__PURE__ */ new Set());
|
|
77
|
+
}
|
|
78
|
+
fieldListeners.get(name).add(listener);
|
|
79
|
+
return () => {
|
|
80
|
+
fieldListeners.get(name).delete(listener);
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
getFieldSnapshot(name) {
|
|
84
|
+
const cached = fieldSnapshotCache.get(name);
|
|
85
|
+
if (cached) return cached;
|
|
86
|
+
const snap = {
|
|
87
|
+
value: state.values[name],
|
|
88
|
+
error: state.errors[name] ?? null,
|
|
89
|
+
isTouched: state.touchedFields[name] ?? false
|
|
90
|
+
};
|
|
91
|
+
fieldSnapshotCache.set(name, snap);
|
|
92
|
+
return snap;
|
|
93
|
+
},
|
|
94
|
+
getState() {
|
|
95
|
+
return state;
|
|
96
|
+
},
|
|
97
|
+
setFieldValue(name, value) {
|
|
98
|
+
state = {
|
|
99
|
+
...state,
|
|
100
|
+
values: { ...state.values, [name]: value },
|
|
101
|
+
isDirty: true
|
|
102
|
+
};
|
|
103
|
+
emit([name]);
|
|
104
|
+
},
|
|
105
|
+
setFieldTouched(name) {
|
|
106
|
+
state = {
|
|
107
|
+
...state,
|
|
108
|
+
touchedFields: { ...state.touchedFields, [name]: true }
|
|
109
|
+
};
|
|
110
|
+
emit([name]);
|
|
111
|
+
},
|
|
112
|
+
setFieldError(name, error) {
|
|
113
|
+
state = {
|
|
114
|
+
...state,
|
|
115
|
+
errors: { ...state.errors, [name]: error }
|
|
116
|
+
};
|
|
117
|
+
emit([name]);
|
|
118
|
+
},
|
|
119
|
+
clearFieldError(name) {
|
|
120
|
+
if (name) {
|
|
121
|
+
const next = { ...state.errors };
|
|
122
|
+
delete next[name];
|
|
123
|
+
state = { ...state, errors: next };
|
|
124
|
+
emit([name]);
|
|
125
|
+
} else {
|
|
126
|
+
state = { ...state, errors: {} };
|
|
127
|
+
emit();
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
setErrors(errors) {
|
|
131
|
+
state = { ...state, errors };
|
|
132
|
+
emit();
|
|
133
|
+
},
|
|
134
|
+
setIsSubmitting(value) {
|
|
135
|
+
state = { ...state, isSubmitting: value };
|
|
136
|
+
emit();
|
|
137
|
+
},
|
|
138
|
+
setIsValidating(value) {
|
|
139
|
+
state = { ...state, isValidating: value };
|
|
140
|
+
emit();
|
|
141
|
+
},
|
|
142
|
+
reset(values) {
|
|
143
|
+
state = {
|
|
144
|
+
values,
|
|
145
|
+
errors: {},
|
|
146
|
+
isDirty: false,
|
|
147
|
+
isSubmitting: false,
|
|
148
|
+
isValidating: false,
|
|
149
|
+
touchedFields: {}
|
|
150
|
+
};
|
|
151
|
+
emit();
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/use-form.ts
|
|
157
|
+
function useForm(schema, options) {
|
|
158
|
+
const { defaultValues, mode = "onSubmit", asyncValidators } = options;
|
|
159
|
+
const storeRef = (0, import_react.useRef)(null);
|
|
160
|
+
if (storeRef.current === null) {
|
|
161
|
+
storeRef.current = createFormStore({
|
|
162
|
+
values: { ...defaultValues },
|
|
163
|
+
errors: {},
|
|
164
|
+
isDirty: false,
|
|
165
|
+
isSubmitting: false,
|
|
166
|
+
isValidating: false,
|
|
167
|
+
touchedFields: {}
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
const store = storeRef.current;
|
|
171
|
+
const state = (0, import_react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
|
|
172
|
+
const defaultValuesRef = (0, import_react.useRef)(defaultValues);
|
|
173
|
+
const asyncValidatorsRef = (0, import_react.useRef)(asyncValidators);
|
|
174
|
+
asyncValidatorsRef.current = asyncValidators;
|
|
175
|
+
const validatingFieldsRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
|
|
176
|
+
const abortControllersRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
|
|
177
|
+
const debounceTimersRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
|
|
178
|
+
const isValid = Object.keys(state.errors).length === 0;
|
|
179
|
+
const runAsyncValidation = (0, import_react.useCallback)(
|
|
180
|
+
async (name, value) => {
|
|
181
|
+
const asyncValidator = asyncValidatorsRef.current?.[name];
|
|
182
|
+
if (!asyncValidator) return null;
|
|
183
|
+
const prevController = abortControllersRef.current.get(name);
|
|
184
|
+
if (prevController) prevController.abort();
|
|
185
|
+
const controller = new AbortController();
|
|
186
|
+
abortControllersRef.current.set(name, controller);
|
|
187
|
+
validatingFieldsRef.current.add(name);
|
|
188
|
+
store.setIsValidating(true);
|
|
189
|
+
try {
|
|
190
|
+
const error = await asyncValidator.validate(value);
|
|
191
|
+
if (controller.signal.aborted) return null;
|
|
192
|
+
if (error) {
|
|
193
|
+
store.setFieldError(name, error);
|
|
194
|
+
} else {
|
|
195
|
+
store.clearFieldError(name);
|
|
196
|
+
}
|
|
197
|
+
return error;
|
|
198
|
+
} finally {
|
|
199
|
+
if (!controller.signal.aborted) {
|
|
200
|
+
validatingFieldsRef.current.delete(name);
|
|
201
|
+
abortControllersRef.current.delete(name);
|
|
202
|
+
if (validatingFieldsRef.current.size === 0) {
|
|
203
|
+
store.setIsValidating(false);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
[store]
|
|
209
|
+
);
|
|
210
|
+
const scheduleAsyncValidation = (0, import_react.useCallback)(
|
|
211
|
+
(name, value, trigger) => {
|
|
212
|
+
const asyncValidator = asyncValidatorsRef.current?.[name];
|
|
213
|
+
if (!asyncValidator) return;
|
|
214
|
+
const on = asyncValidator.on ?? "blur";
|
|
215
|
+
if (on !== trigger) return;
|
|
216
|
+
const fieldSchema = schema.fields[name];
|
|
217
|
+
if (fieldSchema) {
|
|
218
|
+
const formMessages = schema.messages?.[name];
|
|
219
|
+
const syncError = (0, import_vorm_core.validateField)(value, fieldSchema, formMessages);
|
|
220
|
+
if (syncError) return;
|
|
221
|
+
}
|
|
222
|
+
const existingTimer = debounceTimersRef.current.get(name);
|
|
223
|
+
if (existingTimer) clearTimeout(existingTimer);
|
|
224
|
+
const debounceMs = asyncValidator.debounceMs;
|
|
225
|
+
if (trigger === "change" && debounceMs && debounceMs > 0) {
|
|
226
|
+
const timer = setTimeout(() => {
|
|
227
|
+
debounceTimersRef.current.delete(name);
|
|
228
|
+
runAsyncValidation(name, value);
|
|
229
|
+
}, debounceMs);
|
|
230
|
+
debounceTimersRef.current.set(name, timer);
|
|
231
|
+
} else {
|
|
232
|
+
runAsyncValidation(name, value);
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
[schema, runAsyncValidation]
|
|
236
|
+
);
|
|
237
|
+
const validateSingleField = (0, import_react.useCallback)(
|
|
238
|
+
(name, value, trigger) => {
|
|
239
|
+
const fieldSchema = schema.fields[name];
|
|
240
|
+
if (!fieldSchema) return;
|
|
241
|
+
const formMessages = schema.messages?.[name];
|
|
242
|
+
const error = (0, import_vorm_core.validateField)(value, fieldSchema, formMessages);
|
|
243
|
+
if (error) {
|
|
244
|
+
store.setFieldError(name, error);
|
|
245
|
+
} else {
|
|
246
|
+
store.clearFieldError(name);
|
|
247
|
+
}
|
|
248
|
+
if (!error && trigger) {
|
|
249
|
+
scheduleAsyncValidation(name, value, trigger);
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
[schema, store, scheduleAsyncValidation]
|
|
253
|
+
);
|
|
254
|
+
const setFieldValue = (0, import_react.useCallback)(
|
|
255
|
+
(name, value) => {
|
|
256
|
+
store.setFieldValue(name, value);
|
|
257
|
+
if (mode === "onChange") {
|
|
258
|
+
validateSingleField(name, value, "change");
|
|
259
|
+
} else if (mode === "onTouched" && store.getState().touchedFields[name]) {
|
|
260
|
+
validateSingleField(name, value, "change");
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
[mode, store, validateSingleField]
|
|
264
|
+
);
|
|
265
|
+
const setFieldTouched = (0, import_react.useCallback)(
|
|
266
|
+
(name) => {
|
|
267
|
+
store.setFieldTouched(name);
|
|
268
|
+
if (mode === "onBlur" || mode === "onTouched") {
|
|
269
|
+
const currentValue = store.getState().values[name];
|
|
270
|
+
validateSingleField(name, currentValue, "blur");
|
|
271
|
+
} else {
|
|
272
|
+
const currentValue = store.getState().values[name];
|
|
273
|
+
const fieldSchema = schema.fields[name];
|
|
274
|
+
if (fieldSchema) {
|
|
275
|
+
const formMessages = schema.messages?.[name];
|
|
276
|
+
const syncError = (0, import_vorm_core.validateField)(currentValue, fieldSchema, formMessages);
|
|
277
|
+
if (!syncError) {
|
|
278
|
+
scheduleAsyncValidation(name, currentValue, "blur");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
[mode, schema, store, validateSingleField, scheduleAsyncValidation]
|
|
284
|
+
);
|
|
285
|
+
const setFieldError = (0, import_react.useCallback)(
|
|
286
|
+
(name, error) => {
|
|
287
|
+
store.setFieldError(name, error);
|
|
288
|
+
},
|
|
289
|
+
[store]
|
|
290
|
+
);
|
|
291
|
+
const clearFieldError = (0, import_react.useCallback)(
|
|
292
|
+
(name) => {
|
|
293
|
+
store.clearFieldError(name);
|
|
294
|
+
},
|
|
295
|
+
[store]
|
|
296
|
+
);
|
|
297
|
+
const validate = (0, import_react.useCallback)(
|
|
298
|
+
(name) => {
|
|
299
|
+
const currentValues = store.getState().values;
|
|
300
|
+
if (name) {
|
|
301
|
+
const fieldSchema = schema.fields[name];
|
|
302
|
+
if (!fieldSchema) return true;
|
|
303
|
+
const formMessages = schema.messages?.[name];
|
|
304
|
+
const error = (0, import_vorm_core.validateField)(
|
|
305
|
+
currentValues[name],
|
|
306
|
+
fieldSchema,
|
|
307
|
+
formMessages
|
|
308
|
+
);
|
|
309
|
+
if (error) {
|
|
310
|
+
store.setFieldError(name, error);
|
|
311
|
+
} else {
|
|
312
|
+
store.clearFieldError(name);
|
|
313
|
+
}
|
|
314
|
+
return !error;
|
|
315
|
+
}
|
|
316
|
+
const formErrors = (0, import_vorm_core.validateForm)(currentValues, schema);
|
|
317
|
+
store.setErrors(formErrors);
|
|
318
|
+
return Object.keys(formErrors).length === 0;
|
|
319
|
+
},
|
|
320
|
+
[schema, store]
|
|
321
|
+
);
|
|
322
|
+
const validateAsync = (0, import_react.useCallback)(
|
|
323
|
+
async (name) => {
|
|
324
|
+
const currentValues = store.getState().values;
|
|
325
|
+
if (name) {
|
|
326
|
+
const fieldSchema = schema.fields[name];
|
|
327
|
+
if (!fieldSchema) return true;
|
|
328
|
+
const formMessages = schema.messages?.[name];
|
|
329
|
+
const syncError = (0, import_vorm_core.validateField)(
|
|
330
|
+
currentValues[name],
|
|
331
|
+
fieldSchema,
|
|
332
|
+
formMessages
|
|
333
|
+
);
|
|
334
|
+
if (syncError) {
|
|
335
|
+
store.setFieldError(name, syncError);
|
|
336
|
+
} else {
|
|
337
|
+
store.clearFieldError(name);
|
|
338
|
+
}
|
|
339
|
+
if (syncError) return false;
|
|
340
|
+
const asyncError = await runAsyncValidation(name, currentValues[name]);
|
|
341
|
+
return !asyncError;
|
|
342
|
+
}
|
|
343
|
+
const formErrors = (0, import_vorm_core.validateForm)(currentValues, schema);
|
|
344
|
+
store.setErrors(formErrors);
|
|
345
|
+
if (Object.keys(formErrors).length > 0) return false;
|
|
346
|
+
const asyncEntries = Object.entries(asyncValidatorsRef.current ?? {});
|
|
347
|
+
if (asyncEntries.length === 0) return true;
|
|
348
|
+
const asyncResults = await Promise.all(
|
|
349
|
+
asyncEntries.map(async ([fieldName]) => {
|
|
350
|
+
const value = currentValues[fieldName];
|
|
351
|
+
return runAsyncValidation(fieldName, value);
|
|
352
|
+
})
|
|
353
|
+
);
|
|
354
|
+
return asyncResults.every((error) => error === null);
|
|
355
|
+
},
|
|
356
|
+
[schema, store, runAsyncValidation]
|
|
357
|
+
);
|
|
358
|
+
const handleSubmit = (0, import_react.useCallback)(
|
|
359
|
+
(handler) => {
|
|
360
|
+
return async (e) => {
|
|
361
|
+
e?.preventDefault?.();
|
|
362
|
+
const currentValues = store.getState().values;
|
|
363
|
+
const formErrors = (0, import_vorm_core.validateForm)(currentValues, schema);
|
|
364
|
+
store.setErrors(formErrors);
|
|
365
|
+
if (Object.keys(formErrors).length > 0) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const asyncEntries = Object.entries(asyncValidatorsRef.current ?? {});
|
|
369
|
+
if (asyncEntries.length > 0) {
|
|
370
|
+
const asyncResults = await Promise.all(
|
|
371
|
+
asyncEntries.map(async ([fieldName]) => {
|
|
372
|
+
const value = currentValues[fieldName];
|
|
373
|
+
const fieldSchema = schema.fields[fieldName];
|
|
374
|
+
if (fieldSchema) {
|
|
375
|
+
const formMessages = schema.messages?.[fieldName];
|
|
376
|
+
const syncError = (0, import_vorm_core.validateField)(value, fieldSchema, formMessages);
|
|
377
|
+
if (syncError) return null;
|
|
378
|
+
}
|
|
379
|
+
return runAsyncValidation(fieldName, value);
|
|
380
|
+
})
|
|
381
|
+
);
|
|
382
|
+
const hasAsyncErrors = asyncResults.some((error) => error !== null);
|
|
383
|
+
if (hasAsyncErrors) return;
|
|
384
|
+
}
|
|
385
|
+
store.setIsSubmitting(true);
|
|
386
|
+
try {
|
|
387
|
+
const outputValues = (0, import_vorm_core.buildOutputValues)(
|
|
388
|
+
currentValues,
|
|
389
|
+
schema.fields
|
|
390
|
+
);
|
|
391
|
+
await handler(outputValues);
|
|
392
|
+
} finally {
|
|
393
|
+
store.setIsSubmitting(false);
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
},
|
|
397
|
+
[schema, store, runAsyncValidation]
|
|
398
|
+
);
|
|
399
|
+
const reset = (0, import_react.useCallback)(
|
|
400
|
+
(newValues) => {
|
|
401
|
+
const resetValues = newValues ? { ...defaultValuesRef.current, ...newValues } : { ...defaultValuesRef.current };
|
|
402
|
+
store.reset(resetValues);
|
|
403
|
+
for (const controller of abortControllersRef.current.values()) {
|
|
404
|
+
controller.abort();
|
|
405
|
+
}
|
|
406
|
+
abortControllersRef.current.clear();
|
|
407
|
+
for (const timer of debounceTimersRef.current.values()) {
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
}
|
|
410
|
+
debounceTimersRef.current.clear();
|
|
411
|
+
validatingFieldsRef.current.clear();
|
|
412
|
+
},
|
|
413
|
+
[store]
|
|
414
|
+
);
|
|
415
|
+
(0, import_react.useEffect)(() => {
|
|
416
|
+
return () => {
|
|
417
|
+
for (const controller of abortControllersRef.current.values()) {
|
|
418
|
+
controller.abort();
|
|
419
|
+
}
|
|
420
|
+
for (const timer of debounceTimersRef.current.values()) {
|
|
421
|
+
clearTimeout(timer);
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}, []);
|
|
425
|
+
const field = (name) => {
|
|
426
|
+
const value = state.values[name];
|
|
427
|
+
const error = state.errors[name] ?? null;
|
|
428
|
+
const fieldIsDirty = value !== defaultValuesRef.current[name];
|
|
429
|
+
const isTouched = state.touchedFields[name] ?? false;
|
|
430
|
+
const fieldSchema = schema.fields[name];
|
|
431
|
+
const formatFn = fieldSchema?.format;
|
|
432
|
+
const parseFn = fieldSchema?.parse;
|
|
433
|
+
const formattedValue = formatFn ? formatFn(value) : String(value ?? "");
|
|
434
|
+
return {
|
|
435
|
+
value,
|
|
436
|
+
formattedValue,
|
|
437
|
+
error,
|
|
438
|
+
isDirty: fieldIsDirty,
|
|
439
|
+
isTouched,
|
|
440
|
+
onChange: (raw) => {
|
|
441
|
+
const parsed = parseFn ? parseFn(raw) : raw;
|
|
442
|
+
setFieldValue(name, parsed);
|
|
443
|
+
},
|
|
444
|
+
onBlur: () => {
|
|
445
|
+
setFieldTouched(name);
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
return {
|
|
450
|
+
values: state.values,
|
|
451
|
+
errors: state.errors,
|
|
452
|
+
isValid,
|
|
453
|
+
isDirty: state.isDirty,
|
|
454
|
+
isSubmitting: state.isSubmitting,
|
|
455
|
+
isValidating: state.isValidating,
|
|
456
|
+
touchedFields: state.touchedFields,
|
|
457
|
+
handleSubmit,
|
|
458
|
+
reset,
|
|
459
|
+
setFieldValue,
|
|
460
|
+
setFieldTouched,
|
|
461
|
+
setFieldError,
|
|
462
|
+
clearFieldError,
|
|
463
|
+
validate,
|
|
464
|
+
validateAsync,
|
|
465
|
+
field,
|
|
466
|
+
schema,
|
|
467
|
+
mode,
|
|
468
|
+
defaultValues: defaultValuesRef.current,
|
|
469
|
+
__store: store
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// src/use-field.ts
|
|
474
|
+
var import_react2 = require("react");
|
|
475
|
+
function useField(form, name) {
|
|
476
|
+
const store = form.__store;
|
|
477
|
+
const subscribe = (0, import_react2.useCallback)(
|
|
478
|
+
(listener) => store.subscribeField(name, listener),
|
|
479
|
+
[store, name]
|
|
480
|
+
);
|
|
481
|
+
const getSnapshot = (0, import_react2.useCallback)(
|
|
482
|
+
() => store.getFieldSnapshot(name),
|
|
483
|
+
[store, name]
|
|
484
|
+
);
|
|
485
|
+
const snap = (0, import_react2.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
486
|
+
const value = snap.value;
|
|
487
|
+
const error = snap.error;
|
|
488
|
+
const isTouched = snap.isTouched;
|
|
489
|
+
const isDirty = value !== form.defaultValues[name];
|
|
490
|
+
const fieldSchema = form.schema.fields[name];
|
|
491
|
+
const formatFn = fieldSchema?.format;
|
|
492
|
+
const parseFn = fieldSchema?.parse;
|
|
493
|
+
const formattedValue = formatFn ? formatFn(value) : String(value ?? "");
|
|
494
|
+
const onChange = (0, import_react2.useCallback)(
|
|
495
|
+
(raw) => {
|
|
496
|
+
const parsed = parseFn ? parseFn(raw) : raw;
|
|
497
|
+
form.setFieldValue(name, parsed);
|
|
498
|
+
},
|
|
499
|
+
[form.setFieldValue, name, parseFn]
|
|
500
|
+
);
|
|
501
|
+
const onBlur = (0, import_react2.useCallback)(() => {
|
|
502
|
+
form.setFieldTouched(name);
|
|
503
|
+
}, [form.setFieldTouched, name]);
|
|
504
|
+
return {
|
|
505
|
+
value,
|
|
506
|
+
formattedValue,
|
|
507
|
+
onChange,
|
|
508
|
+
onBlur,
|
|
509
|
+
error,
|
|
510
|
+
isDirty,
|
|
511
|
+
isTouched
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
515
|
+
0 && (module.exports = {
|
|
516
|
+
createFormStore,
|
|
517
|
+
useField,
|
|
518
|
+
useForm
|
|
519
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { FieldError, FieldSchema, FormInputValues, FormErrors, FormOutputValues, FormSchema } from '@gunubin/vorm-core';
|
|
2
|
+
|
|
3
|
+
type FieldState<TValue> = {
|
|
4
|
+
value: TValue;
|
|
5
|
+
formattedValue: string;
|
|
6
|
+
onChange: (raw: string) => void;
|
|
7
|
+
onBlur: () => void;
|
|
8
|
+
error: FieldError | null;
|
|
9
|
+
isDirty: boolean;
|
|
10
|
+
isTouched: boolean;
|
|
11
|
+
};
|
|
12
|
+
declare function useField<TFields extends Record<string, FieldSchema<any, any, boolean, any>>, TName extends string & keyof TFields>(form: FormState<TFields>, name: TName): FieldState<TFields[TName] extends FieldSchema<infer T, any, any, any> ? T : never>;
|
|
13
|
+
|
|
14
|
+
type FormStoreState<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
15
|
+
values: FormInputValues<TFields>;
|
|
16
|
+
errors: FormErrors;
|
|
17
|
+
isDirty: boolean;
|
|
18
|
+
isSubmitting: boolean;
|
|
19
|
+
isValidating: boolean;
|
|
20
|
+
touchedFields: Record<string, boolean>;
|
|
21
|
+
};
|
|
22
|
+
type FieldSnapshot = {
|
|
23
|
+
value: unknown;
|
|
24
|
+
error: FieldError | null;
|
|
25
|
+
isTouched: boolean;
|
|
26
|
+
};
|
|
27
|
+
type Listener = () => void;
|
|
28
|
+
type FormStore<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
29
|
+
subscribe: (listener: Listener) => () => void;
|
|
30
|
+
getSnapshot: () => FormStoreState<TFields>;
|
|
31
|
+
subscribeField: (name: string, listener: Listener) => () => void;
|
|
32
|
+
getFieldSnapshot: (name: string) => FieldSnapshot;
|
|
33
|
+
getState: () => FormStoreState<TFields>;
|
|
34
|
+
setFieldValue: (name: string, value: any) => void;
|
|
35
|
+
setFieldTouched: (name: string) => void;
|
|
36
|
+
setFieldError: (name: string, error: FieldError) => void;
|
|
37
|
+
clearFieldError: (name?: string) => void;
|
|
38
|
+
setErrors: (errors: FormErrors) => void;
|
|
39
|
+
setIsSubmitting: (value: boolean) => void;
|
|
40
|
+
setIsValidating: (value: boolean) => void;
|
|
41
|
+
reset: (values: FormInputValues<TFields>) => void;
|
|
42
|
+
};
|
|
43
|
+
declare function createFormStore<TFields extends Record<string, FieldSchema<any, any, boolean, any>>>(initialState: FormStoreState<TFields>): FormStore<TFields>;
|
|
44
|
+
|
|
45
|
+
type ValidationMode = 'onChange' | 'onBlur' | 'onTouched' | 'onSubmit';
|
|
46
|
+
type AsyncTrigger = 'blur' | 'change' | 'submit';
|
|
47
|
+
type AsyncFieldValidator<TInput> = {
|
|
48
|
+
validate: (value: TInput) => Promise<FieldError | null>;
|
|
49
|
+
on?: AsyncTrigger;
|
|
50
|
+
debounceMs?: number;
|
|
51
|
+
};
|
|
52
|
+
type AsyncValidators<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
53
|
+
[K in string & keyof TFields]?: AsyncFieldValidator<TFields[K] extends FieldSchema<infer TInput, any, any, any> ? TInput : never>;
|
|
54
|
+
};
|
|
55
|
+
type UseFormOptions<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
56
|
+
defaultValues: FormInputValues<TFields>;
|
|
57
|
+
mode?: ValidationMode;
|
|
58
|
+
asyncValidators?: AsyncValidators<TFields>;
|
|
59
|
+
};
|
|
60
|
+
type FormState<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
61
|
+
values: FormInputValues<TFields>;
|
|
62
|
+
errors: FormErrors;
|
|
63
|
+
isValid: boolean;
|
|
64
|
+
isDirty: boolean;
|
|
65
|
+
isSubmitting: boolean;
|
|
66
|
+
isValidating: boolean;
|
|
67
|
+
touchedFields: Record<string, boolean>;
|
|
68
|
+
handleSubmit: (handler: (values: FormOutputValues<TFields>) => void | Promise<void>) => (e?: {
|
|
69
|
+
preventDefault?: () => void;
|
|
70
|
+
}) => Promise<void>;
|
|
71
|
+
reset: (values?: Partial<FormInputValues<TFields>>) => void;
|
|
72
|
+
setFieldValue: (name: string, value: any) => void;
|
|
73
|
+
setFieldTouched: (name: string) => void;
|
|
74
|
+
setFieldError: (name: string & keyof TFields, error: FieldError) => void;
|
|
75
|
+
clearFieldError: (name?: string & keyof TFields) => void;
|
|
76
|
+
validate: (name?: string & keyof TFields) => boolean;
|
|
77
|
+
validateAsync: (name?: string & keyof TFields) => Promise<boolean>;
|
|
78
|
+
field: <TName extends string & keyof TFields>(name: TName) => FieldState<TFields[TName] extends FieldSchema<infer TInput, any, any, any> ? TInput : never>;
|
|
79
|
+
schema: FormSchema<TFields>;
|
|
80
|
+
mode: ValidationMode;
|
|
81
|
+
defaultValues: FormInputValues<TFields>;
|
|
82
|
+
/** @internal */
|
|
83
|
+
__store: FormStore<TFields>;
|
|
84
|
+
};
|
|
85
|
+
declare function useForm<TFields extends Record<string, FieldSchema<any, any, boolean, any>>>(schema: FormSchema<TFields>, options: UseFormOptions<TFields>): FormState<TFields>;
|
|
86
|
+
|
|
87
|
+
export { type AsyncFieldValidator, type AsyncValidators, type FieldSnapshot, type FieldState, type FormState, type FormStore, type FormStoreState, createFormStore, useField, useForm };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { FieldError, FieldSchema, FormInputValues, FormErrors, FormOutputValues, FormSchema } from '@gunubin/vorm-core';
|
|
2
|
+
|
|
3
|
+
type FieldState<TValue> = {
|
|
4
|
+
value: TValue;
|
|
5
|
+
formattedValue: string;
|
|
6
|
+
onChange: (raw: string) => void;
|
|
7
|
+
onBlur: () => void;
|
|
8
|
+
error: FieldError | null;
|
|
9
|
+
isDirty: boolean;
|
|
10
|
+
isTouched: boolean;
|
|
11
|
+
};
|
|
12
|
+
declare function useField<TFields extends Record<string, FieldSchema<any, any, boolean, any>>, TName extends string & keyof TFields>(form: FormState<TFields>, name: TName): FieldState<TFields[TName] extends FieldSchema<infer T, any, any, any> ? T : never>;
|
|
13
|
+
|
|
14
|
+
type FormStoreState<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
15
|
+
values: FormInputValues<TFields>;
|
|
16
|
+
errors: FormErrors;
|
|
17
|
+
isDirty: boolean;
|
|
18
|
+
isSubmitting: boolean;
|
|
19
|
+
isValidating: boolean;
|
|
20
|
+
touchedFields: Record<string, boolean>;
|
|
21
|
+
};
|
|
22
|
+
type FieldSnapshot = {
|
|
23
|
+
value: unknown;
|
|
24
|
+
error: FieldError | null;
|
|
25
|
+
isTouched: boolean;
|
|
26
|
+
};
|
|
27
|
+
type Listener = () => void;
|
|
28
|
+
type FormStore<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
29
|
+
subscribe: (listener: Listener) => () => void;
|
|
30
|
+
getSnapshot: () => FormStoreState<TFields>;
|
|
31
|
+
subscribeField: (name: string, listener: Listener) => () => void;
|
|
32
|
+
getFieldSnapshot: (name: string) => FieldSnapshot;
|
|
33
|
+
getState: () => FormStoreState<TFields>;
|
|
34
|
+
setFieldValue: (name: string, value: any) => void;
|
|
35
|
+
setFieldTouched: (name: string) => void;
|
|
36
|
+
setFieldError: (name: string, error: FieldError) => void;
|
|
37
|
+
clearFieldError: (name?: string) => void;
|
|
38
|
+
setErrors: (errors: FormErrors) => void;
|
|
39
|
+
setIsSubmitting: (value: boolean) => void;
|
|
40
|
+
setIsValidating: (value: boolean) => void;
|
|
41
|
+
reset: (values: FormInputValues<TFields>) => void;
|
|
42
|
+
};
|
|
43
|
+
declare function createFormStore<TFields extends Record<string, FieldSchema<any, any, boolean, any>>>(initialState: FormStoreState<TFields>): FormStore<TFields>;
|
|
44
|
+
|
|
45
|
+
type ValidationMode = 'onChange' | 'onBlur' | 'onTouched' | 'onSubmit';
|
|
46
|
+
type AsyncTrigger = 'blur' | 'change' | 'submit';
|
|
47
|
+
type AsyncFieldValidator<TInput> = {
|
|
48
|
+
validate: (value: TInput) => Promise<FieldError | null>;
|
|
49
|
+
on?: AsyncTrigger;
|
|
50
|
+
debounceMs?: number;
|
|
51
|
+
};
|
|
52
|
+
type AsyncValidators<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
53
|
+
[K in string & keyof TFields]?: AsyncFieldValidator<TFields[K] extends FieldSchema<infer TInput, any, any, any> ? TInput : never>;
|
|
54
|
+
};
|
|
55
|
+
type UseFormOptions<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
56
|
+
defaultValues: FormInputValues<TFields>;
|
|
57
|
+
mode?: ValidationMode;
|
|
58
|
+
asyncValidators?: AsyncValidators<TFields>;
|
|
59
|
+
};
|
|
60
|
+
type FormState<TFields extends Record<string, FieldSchema<any, any, boolean, any>>> = {
|
|
61
|
+
values: FormInputValues<TFields>;
|
|
62
|
+
errors: FormErrors;
|
|
63
|
+
isValid: boolean;
|
|
64
|
+
isDirty: boolean;
|
|
65
|
+
isSubmitting: boolean;
|
|
66
|
+
isValidating: boolean;
|
|
67
|
+
touchedFields: Record<string, boolean>;
|
|
68
|
+
handleSubmit: (handler: (values: FormOutputValues<TFields>) => void | Promise<void>) => (e?: {
|
|
69
|
+
preventDefault?: () => void;
|
|
70
|
+
}) => Promise<void>;
|
|
71
|
+
reset: (values?: Partial<FormInputValues<TFields>>) => void;
|
|
72
|
+
setFieldValue: (name: string, value: any) => void;
|
|
73
|
+
setFieldTouched: (name: string) => void;
|
|
74
|
+
setFieldError: (name: string & keyof TFields, error: FieldError) => void;
|
|
75
|
+
clearFieldError: (name?: string & keyof TFields) => void;
|
|
76
|
+
validate: (name?: string & keyof TFields) => boolean;
|
|
77
|
+
validateAsync: (name?: string & keyof TFields) => Promise<boolean>;
|
|
78
|
+
field: <TName extends string & keyof TFields>(name: TName) => FieldState<TFields[TName] extends FieldSchema<infer TInput, any, any, any> ? TInput : never>;
|
|
79
|
+
schema: FormSchema<TFields>;
|
|
80
|
+
mode: ValidationMode;
|
|
81
|
+
defaultValues: FormInputValues<TFields>;
|
|
82
|
+
/** @internal */
|
|
83
|
+
__store: FormStore<TFields>;
|
|
84
|
+
};
|
|
85
|
+
declare function useForm<TFields extends Record<string, FieldSchema<any, any, boolean, any>>>(schema: FormSchema<TFields>, options: UseFormOptions<TFields>): FormState<TFields>;
|
|
86
|
+
|
|
87
|
+
export { type AsyncFieldValidator, type AsyncValidators, type FieldSnapshot, type FieldState, type FormState, type FormStore, type FormStoreState, createFormStore, useField, useForm };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
// src/use-form.ts
|
|
2
|
+
import { useRef, useCallback, useEffect, useSyncExternalStore } from "react";
|
|
3
|
+
import { validateField, validateForm, buildOutputValues } from "@gunubin/vorm-core";
|
|
4
|
+
|
|
5
|
+
// src/form-store.ts
|
|
6
|
+
function createFormStore(initialState) {
|
|
7
|
+
let state = initialState;
|
|
8
|
+
let snapshot = state;
|
|
9
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
10
|
+
const fieldListeners = /* @__PURE__ */ new Map();
|
|
11
|
+
const fieldSnapshotCache = /* @__PURE__ */ new Map();
|
|
12
|
+
function emit(changedFields) {
|
|
13
|
+
snapshot = { ...state };
|
|
14
|
+
for (const listener of listeners) {
|
|
15
|
+
listener();
|
|
16
|
+
}
|
|
17
|
+
if (changedFields) {
|
|
18
|
+
for (const name of changedFields) {
|
|
19
|
+
fieldSnapshotCache.delete(name);
|
|
20
|
+
const set = fieldListeners.get(name);
|
|
21
|
+
if (set) {
|
|
22
|
+
for (const listener of set) {
|
|
23
|
+
listener();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
} else {
|
|
28
|
+
fieldSnapshotCache.clear();
|
|
29
|
+
for (const [, set] of fieldListeners) {
|
|
30
|
+
for (const listener of set) {
|
|
31
|
+
listener();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
subscribe(listener) {
|
|
38
|
+
listeners.add(listener);
|
|
39
|
+
return () => {
|
|
40
|
+
listeners.delete(listener);
|
|
41
|
+
};
|
|
42
|
+
},
|
|
43
|
+
getSnapshot() {
|
|
44
|
+
return snapshot;
|
|
45
|
+
},
|
|
46
|
+
subscribeField(name, listener) {
|
|
47
|
+
if (!fieldListeners.has(name)) {
|
|
48
|
+
fieldListeners.set(name, /* @__PURE__ */ new Set());
|
|
49
|
+
}
|
|
50
|
+
fieldListeners.get(name).add(listener);
|
|
51
|
+
return () => {
|
|
52
|
+
fieldListeners.get(name).delete(listener);
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
getFieldSnapshot(name) {
|
|
56
|
+
const cached = fieldSnapshotCache.get(name);
|
|
57
|
+
if (cached) return cached;
|
|
58
|
+
const snap = {
|
|
59
|
+
value: state.values[name],
|
|
60
|
+
error: state.errors[name] ?? null,
|
|
61
|
+
isTouched: state.touchedFields[name] ?? false
|
|
62
|
+
};
|
|
63
|
+
fieldSnapshotCache.set(name, snap);
|
|
64
|
+
return snap;
|
|
65
|
+
},
|
|
66
|
+
getState() {
|
|
67
|
+
return state;
|
|
68
|
+
},
|
|
69
|
+
setFieldValue(name, value) {
|
|
70
|
+
state = {
|
|
71
|
+
...state,
|
|
72
|
+
values: { ...state.values, [name]: value },
|
|
73
|
+
isDirty: true
|
|
74
|
+
};
|
|
75
|
+
emit([name]);
|
|
76
|
+
},
|
|
77
|
+
setFieldTouched(name) {
|
|
78
|
+
state = {
|
|
79
|
+
...state,
|
|
80
|
+
touchedFields: { ...state.touchedFields, [name]: true }
|
|
81
|
+
};
|
|
82
|
+
emit([name]);
|
|
83
|
+
},
|
|
84
|
+
setFieldError(name, error) {
|
|
85
|
+
state = {
|
|
86
|
+
...state,
|
|
87
|
+
errors: { ...state.errors, [name]: error }
|
|
88
|
+
};
|
|
89
|
+
emit([name]);
|
|
90
|
+
},
|
|
91
|
+
clearFieldError(name) {
|
|
92
|
+
if (name) {
|
|
93
|
+
const next = { ...state.errors };
|
|
94
|
+
delete next[name];
|
|
95
|
+
state = { ...state, errors: next };
|
|
96
|
+
emit([name]);
|
|
97
|
+
} else {
|
|
98
|
+
state = { ...state, errors: {} };
|
|
99
|
+
emit();
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
setErrors(errors) {
|
|
103
|
+
state = { ...state, errors };
|
|
104
|
+
emit();
|
|
105
|
+
},
|
|
106
|
+
setIsSubmitting(value) {
|
|
107
|
+
state = { ...state, isSubmitting: value };
|
|
108
|
+
emit();
|
|
109
|
+
},
|
|
110
|
+
setIsValidating(value) {
|
|
111
|
+
state = { ...state, isValidating: value };
|
|
112
|
+
emit();
|
|
113
|
+
},
|
|
114
|
+
reset(values) {
|
|
115
|
+
state = {
|
|
116
|
+
values,
|
|
117
|
+
errors: {},
|
|
118
|
+
isDirty: false,
|
|
119
|
+
isSubmitting: false,
|
|
120
|
+
isValidating: false,
|
|
121
|
+
touchedFields: {}
|
|
122
|
+
};
|
|
123
|
+
emit();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/use-form.ts
|
|
129
|
+
function useForm(schema, options) {
|
|
130
|
+
const { defaultValues, mode = "onSubmit", asyncValidators } = options;
|
|
131
|
+
const storeRef = useRef(null);
|
|
132
|
+
if (storeRef.current === null) {
|
|
133
|
+
storeRef.current = createFormStore({
|
|
134
|
+
values: { ...defaultValues },
|
|
135
|
+
errors: {},
|
|
136
|
+
isDirty: false,
|
|
137
|
+
isSubmitting: false,
|
|
138
|
+
isValidating: false,
|
|
139
|
+
touchedFields: {}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const store = storeRef.current;
|
|
143
|
+
const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
|
144
|
+
const defaultValuesRef = useRef(defaultValues);
|
|
145
|
+
const asyncValidatorsRef = useRef(asyncValidators);
|
|
146
|
+
asyncValidatorsRef.current = asyncValidators;
|
|
147
|
+
const validatingFieldsRef = useRef(/* @__PURE__ */ new Set());
|
|
148
|
+
const abortControllersRef = useRef(/* @__PURE__ */ new Map());
|
|
149
|
+
const debounceTimersRef = useRef(/* @__PURE__ */ new Map());
|
|
150
|
+
const isValid = Object.keys(state.errors).length === 0;
|
|
151
|
+
const runAsyncValidation = useCallback(
|
|
152
|
+
async (name, value) => {
|
|
153
|
+
const asyncValidator = asyncValidatorsRef.current?.[name];
|
|
154
|
+
if (!asyncValidator) return null;
|
|
155
|
+
const prevController = abortControllersRef.current.get(name);
|
|
156
|
+
if (prevController) prevController.abort();
|
|
157
|
+
const controller = new AbortController();
|
|
158
|
+
abortControllersRef.current.set(name, controller);
|
|
159
|
+
validatingFieldsRef.current.add(name);
|
|
160
|
+
store.setIsValidating(true);
|
|
161
|
+
try {
|
|
162
|
+
const error = await asyncValidator.validate(value);
|
|
163
|
+
if (controller.signal.aborted) return null;
|
|
164
|
+
if (error) {
|
|
165
|
+
store.setFieldError(name, error);
|
|
166
|
+
} else {
|
|
167
|
+
store.clearFieldError(name);
|
|
168
|
+
}
|
|
169
|
+
return error;
|
|
170
|
+
} finally {
|
|
171
|
+
if (!controller.signal.aborted) {
|
|
172
|
+
validatingFieldsRef.current.delete(name);
|
|
173
|
+
abortControllersRef.current.delete(name);
|
|
174
|
+
if (validatingFieldsRef.current.size === 0) {
|
|
175
|
+
store.setIsValidating(false);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
[store]
|
|
181
|
+
);
|
|
182
|
+
const scheduleAsyncValidation = useCallback(
|
|
183
|
+
(name, value, trigger) => {
|
|
184
|
+
const asyncValidator = asyncValidatorsRef.current?.[name];
|
|
185
|
+
if (!asyncValidator) return;
|
|
186
|
+
const on = asyncValidator.on ?? "blur";
|
|
187
|
+
if (on !== trigger) return;
|
|
188
|
+
const fieldSchema = schema.fields[name];
|
|
189
|
+
if (fieldSchema) {
|
|
190
|
+
const formMessages = schema.messages?.[name];
|
|
191
|
+
const syncError = validateField(value, fieldSchema, formMessages);
|
|
192
|
+
if (syncError) return;
|
|
193
|
+
}
|
|
194
|
+
const existingTimer = debounceTimersRef.current.get(name);
|
|
195
|
+
if (existingTimer) clearTimeout(existingTimer);
|
|
196
|
+
const debounceMs = asyncValidator.debounceMs;
|
|
197
|
+
if (trigger === "change" && debounceMs && debounceMs > 0) {
|
|
198
|
+
const timer = setTimeout(() => {
|
|
199
|
+
debounceTimersRef.current.delete(name);
|
|
200
|
+
runAsyncValidation(name, value);
|
|
201
|
+
}, debounceMs);
|
|
202
|
+
debounceTimersRef.current.set(name, timer);
|
|
203
|
+
} else {
|
|
204
|
+
runAsyncValidation(name, value);
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
[schema, runAsyncValidation]
|
|
208
|
+
);
|
|
209
|
+
const validateSingleField = useCallback(
|
|
210
|
+
(name, value, trigger) => {
|
|
211
|
+
const fieldSchema = schema.fields[name];
|
|
212
|
+
if (!fieldSchema) return;
|
|
213
|
+
const formMessages = schema.messages?.[name];
|
|
214
|
+
const error = validateField(value, fieldSchema, formMessages);
|
|
215
|
+
if (error) {
|
|
216
|
+
store.setFieldError(name, error);
|
|
217
|
+
} else {
|
|
218
|
+
store.clearFieldError(name);
|
|
219
|
+
}
|
|
220
|
+
if (!error && trigger) {
|
|
221
|
+
scheduleAsyncValidation(name, value, trigger);
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
[schema, store, scheduleAsyncValidation]
|
|
225
|
+
);
|
|
226
|
+
const setFieldValue = useCallback(
|
|
227
|
+
(name, value) => {
|
|
228
|
+
store.setFieldValue(name, value);
|
|
229
|
+
if (mode === "onChange") {
|
|
230
|
+
validateSingleField(name, value, "change");
|
|
231
|
+
} else if (mode === "onTouched" && store.getState().touchedFields[name]) {
|
|
232
|
+
validateSingleField(name, value, "change");
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
[mode, store, validateSingleField]
|
|
236
|
+
);
|
|
237
|
+
const setFieldTouched = useCallback(
|
|
238
|
+
(name) => {
|
|
239
|
+
store.setFieldTouched(name);
|
|
240
|
+
if (mode === "onBlur" || mode === "onTouched") {
|
|
241
|
+
const currentValue = store.getState().values[name];
|
|
242
|
+
validateSingleField(name, currentValue, "blur");
|
|
243
|
+
} else {
|
|
244
|
+
const currentValue = store.getState().values[name];
|
|
245
|
+
const fieldSchema = schema.fields[name];
|
|
246
|
+
if (fieldSchema) {
|
|
247
|
+
const formMessages = schema.messages?.[name];
|
|
248
|
+
const syncError = validateField(currentValue, fieldSchema, formMessages);
|
|
249
|
+
if (!syncError) {
|
|
250
|
+
scheduleAsyncValidation(name, currentValue, "blur");
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
[mode, schema, store, validateSingleField, scheduleAsyncValidation]
|
|
256
|
+
);
|
|
257
|
+
const setFieldError = useCallback(
|
|
258
|
+
(name, error) => {
|
|
259
|
+
store.setFieldError(name, error);
|
|
260
|
+
},
|
|
261
|
+
[store]
|
|
262
|
+
);
|
|
263
|
+
const clearFieldError = useCallback(
|
|
264
|
+
(name) => {
|
|
265
|
+
store.clearFieldError(name);
|
|
266
|
+
},
|
|
267
|
+
[store]
|
|
268
|
+
);
|
|
269
|
+
const validate = useCallback(
|
|
270
|
+
(name) => {
|
|
271
|
+
const currentValues = store.getState().values;
|
|
272
|
+
if (name) {
|
|
273
|
+
const fieldSchema = schema.fields[name];
|
|
274
|
+
if (!fieldSchema) return true;
|
|
275
|
+
const formMessages = schema.messages?.[name];
|
|
276
|
+
const error = validateField(
|
|
277
|
+
currentValues[name],
|
|
278
|
+
fieldSchema,
|
|
279
|
+
formMessages
|
|
280
|
+
);
|
|
281
|
+
if (error) {
|
|
282
|
+
store.setFieldError(name, error);
|
|
283
|
+
} else {
|
|
284
|
+
store.clearFieldError(name);
|
|
285
|
+
}
|
|
286
|
+
return !error;
|
|
287
|
+
}
|
|
288
|
+
const formErrors = validateForm(currentValues, schema);
|
|
289
|
+
store.setErrors(formErrors);
|
|
290
|
+
return Object.keys(formErrors).length === 0;
|
|
291
|
+
},
|
|
292
|
+
[schema, store]
|
|
293
|
+
);
|
|
294
|
+
const validateAsync = useCallback(
|
|
295
|
+
async (name) => {
|
|
296
|
+
const currentValues = store.getState().values;
|
|
297
|
+
if (name) {
|
|
298
|
+
const fieldSchema = schema.fields[name];
|
|
299
|
+
if (!fieldSchema) return true;
|
|
300
|
+
const formMessages = schema.messages?.[name];
|
|
301
|
+
const syncError = validateField(
|
|
302
|
+
currentValues[name],
|
|
303
|
+
fieldSchema,
|
|
304
|
+
formMessages
|
|
305
|
+
);
|
|
306
|
+
if (syncError) {
|
|
307
|
+
store.setFieldError(name, syncError);
|
|
308
|
+
} else {
|
|
309
|
+
store.clearFieldError(name);
|
|
310
|
+
}
|
|
311
|
+
if (syncError) return false;
|
|
312
|
+
const asyncError = await runAsyncValidation(name, currentValues[name]);
|
|
313
|
+
return !asyncError;
|
|
314
|
+
}
|
|
315
|
+
const formErrors = validateForm(currentValues, schema);
|
|
316
|
+
store.setErrors(formErrors);
|
|
317
|
+
if (Object.keys(formErrors).length > 0) return false;
|
|
318
|
+
const asyncEntries = Object.entries(asyncValidatorsRef.current ?? {});
|
|
319
|
+
if (asyncEntries.length === 0) return true;
|
|
320
|
+
const asyncResults = await Promise.all(
|
|
321
|
+
asyncEntries.map(async ([fieldName]) => {
|
|
322
|
+
const value = currentValues[fieldName];
|
|
323
|
+
return runAsyncValidation(fieldName, value);
|
|
324
|
+
})
|
|
325
|
+
);
|
|
326
|
+
return asyncResults.every((error) => error === null);
|
|
327
|
+
},
|
|
328
|
+
[schema, store, runAsyncValidation]
|
|
329
|
+
);
|
|
330
|
+
const handleSubmit = useCallback(
|
|
331
|
+
(handler) => {
|
|
332
|
+
return async (e) => {
|
|
333
|
+
e?.preventDefault?.();
|
|
334
|
+
const currentValues = store.getState().values;
|
|
335
|
+
const formErrors = validateForm(currentValues, schema);
|
|
336
|
+
store.setErrors(formErrors);
|
|
337
|
+
if (Object.keys(formErrors).length > 0) {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const asyncEntries = Object.entries(asyncValidatorsRef.current ?? {});
|
|
341
|
+
if (asyncEntries.length > 0) {
|
|
342
|
+
const asyncResults = await Promise.all(
|
|
343
|
+
asyncEntries.map(async ([fieldName]) => {
|
|
344
|
+
const value = currentValues[fieldName];
|
|
345
|
+
const fieldSchema = schema.fields[fieldName];
|
|
346
|
+
if (fieldSchema) {
|
|
347
|
+
const formMessages = schema.messages?.[fieldName];
|
|
348
|
+
const syncError = validateField(value, fieldSchema, formMessages);
|
|
349
|
+
if (syncError) return null;
|
|
350
|
+
}
|
|
351
|
+
return runAsyncValidation(fieldName, value);
|
|
352
|
+
})
|
|
353
|
+
);
|
|
354
|
+
const hasAsyncErrors = asyncResults.some((error) => error !== null);
|
|
355
|
+
if (hasAsyncErrors) return;
|
|
356
|
+
}
|
|
357
|
+
store.setIsSubmitting(true);
|
|
358
|
+
try {
|
|
359
|
+
const outputValues = buildOutputValues(
|
|
360
|
+
currentValues,
|
|
361
|
+
schema.fields
|
|
362
|
+
);
|
|
363
|
+
await handler(outputValues);
|
|
364
|
+
} finally {
|
|
365
|
+
store.setIsSubmitting(false);
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
},
|
|
369
|
+
[schema, store, runAsyncValidation]
|
|
370
|
+
);
|
|
371
|
+
const reset = useCallback(
|
|
372
|
+
(newValues) => {
|
|
373
|
+
const resetValues = newValues ? { ...defaultValuesRef.current, ...newValues } : { ...defaultValuesRef.current };
|
|
374
|
+
store.reset(resetValues);
|
|
375
|
+
for (const controller of abortControllersRef.current.values()) {
|
|
376
|
+
controller.abort();
|
|
377
|
+
}
|
|
378
|
+
abortControllersRef.current.clear();
|
|
379
|
+
for (const timer of debounceTimersRef.current.values()) {
|
|
380
|
+
clearTimeout(timer);
|
|
381
|
+
}
|
|
382
|
+
debounceTimersRef.current.clear();
|
|
383
|
+
validatingFieldsRef.current.clear();
|
|
384
|
+
},
|
|
385
|
+
[store]
|
|
386
|
+
);
|
|
387
|
+
useEffect(() => {
|
|
388
|
+
return () => {
|
|
389
|
+
for (const controller of abortControllersRef.current.values()) {
|
|
390
|
+
controller.abort();
|
|
391
|
+
}
|
|
392
|
+
for (const timer of debounceTimersRef.current.values()) {
|
|
393
|
+
clearTimeout(timer);
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}, []);
|
|
397
|
+
const field = (name) => {
|
|
398
|
+
const value = state.values[name];
|
|
399
|
+
const error = state.errors[name] ?? null;
|
|
400
|
+
const fieldIsDirty = value !== defaultValuesRef.current[name];
|
|
401
|
+
const isTouched = state.touchedFields[name] ?? false;
|
|
402
|
+
const fieldSchema = schema.fields[name];
|
|
403
|
+
const formatFn = fieldSchema?.format;
|
|
404
|
+
const parseFn = fieldSchema?.parse;
|
|
405
|
+
const formattedValue = formatFn ? formatFn(value) : String(value ?? "");
|
|
406
|
+
return {
|
|
407
|
+
value,
|
|
408
|
+
formattedValue,
|
|
409
|
+
error,
|
|
410
|
+
isDirty: fieldIsDirty,
|
|
411
|
+
isTouched,
|
|
412
|
+
onChange: (raw) => {
|
|
413
|
+
const parsed = parseFn ? parseFn(raw) : raw;
|
|
414
|
+
setFieldValue(name, parsed);
|
|
415
|
+
},
|
|
416
|
+
onBlur: () => {
|
|
417
|
+
setFieldTouched(name);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
return {
|
|
422
|
+
values: state.values,
|
|
423
|
+
errors: state.errors,
|
|
424
|
+
isValid,
|
|
425
|
+
isDirty: state.isDirty,
|
|
426
|
+
isSubmitting: state.isSubmitting,
|
|
427
|
+
isValidating: state.isValidating,
|
|
428
|
+
touchedFields: state.touchedFields,
|
|
429
|
+
handleSubmit,
|
|
430
|
+
reset,
|
|
431
|
+
setFieldValue,
|
|
432
|
+
setFieldTouched,
|
|
433
|
+
setFieldError,
|
|
434
|
+
clearFieldError,
|
|
435
|
+
validate,
|
|
436
|
+
validateAsync,
|
|
437
|
+
field,
|
|
438
|
+
schema,
|
|
439
|
+
mode,
|
|
440
|
+
defaultValues: defaultValuesRef.current,
|
|
441
|
+
__store: store
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// src/use-field.ts
|
|
446
|
+
import { useCallback as useCallback2, useSyncExternalStore as useSyncExternalStore2 } from "react";
|
|
447
|
+
function useField(form, name) {
|
|
448
|
+
const store = form.__store;
|
|
449
|
+
const subscribe = useCallback2(
|
|
450
|
+
(listener) => store.subscribeField(name, listener),
|
|
451
|
+
[store, name]
|
|
452
|
+
);
|
|
453
|
+
const getSnapshot = useCallback2(
|
|
454
|
+
() => store.getFieldSnapshot(name),
|
|
455
|
+
[store, name]
|
|
456
|
+
);
|
|
457
|
+
const snap = useSyncExternalStore2(subscribe, getSnapshot, getSnapshot);
|
|
458
|
+
const value = snap.value;
|
|
459
|
+
const error = snap.error;
|
|
460
|
+
const isTouched = snap.isTouched;
|
|
461
|
+
const isDirty = value !== form.defaultValues[name];
|
|
462
|
+
const fieldSchema = form.schema.fields[name];
|
|
463
|
+
const formatFn = fieldSchema?.format;
|
|
464
|
+
const parseFn = fieldSchema?.parse;
|
|
465
|
+
const formattedValue = formatFn ? formatFn(value) : String(value ?? "");
|
|
466
|
+
const onChange = useCallback2(
|
|
467
|
+
(raw) => {
|
|
468
|
+
const parsed = parseFn ? parseFn(raw) : raw;
|
|
469
|
+
form.setFieldValue(name, parsed);
|
|
470
|
+
},
|
|
471
|
+
[form.setFieldValue, name, parseFn]
|
|
472
|
+
);
|
|
473
|
+
const onBlur = useCallback2(() => {
|
|
474
|
+
form.setFieldTouched(name);
|
|
475
|
+
}, [form.setFieldTouched, name]);
|
|
476
|
+
return {
|
|
477
|
+
value,
|
|
478
|
+
formattedValue,
|
|
479
|
+
onChange,
|
|
480
|
+
onBlur,
|
|
481
|
+
error,
|
|
482
|
+
isDirty,
|
|
483
|
+
isTouched
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
export {
|
|
487
|
+
createFormStore,
|
|
488
|
+
useField,
|
|
489
|
+
useForm
|
|
490
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gunubin/vorm-react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "VO-first React form hooks with per-field subscriptions via useSyncExternalStore",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"form",
|
|
7
|
+
"react",
|
|
8
|
+
"hooks",
|
|
9
|
+
"validation",
|
|
10
|
+
"branded-types",
|
|
11
|
+
"typescript"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "gunubin",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/gunubin/vorm.git",
|
|
18
|
+
"directory": "packages/react"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/gunubin/vorm#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/gunubin/vorm/issues"
|
|
23
|
+
},
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./dist/index.cjs",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"require": "./dist/index.cjs"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@gunubin/vorm-core": "0.1.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@testing-library/react": "^16.3.0",
|
|
50
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
51
|
+
"@types/react": "^19.0.0",
|
|
52
|
+
"@types/react-dom": "^19.0.0",
|
|
53
|
+
"jsdom": "^26.0.0",
|
|
54
|
+
"react": "^19.0.0",
|
|
55
|
+
"react-dom": "^19.0.0",
|
|
56
|
+
"typescript": "^5.9.3",
|
|
57
|
+
"vitest": "^3.0.5"
|
|
58
|
+
},
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsup",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"test:watch": "vitest"
|
|
64
|
+
}
|
|
65
|
+
}
|