@pyreon/form 0.3.0 → 0.7.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/lib/analysis/index.js.html +1 -1
- package/lib/index.js +151 -152
- package/lib/index.js.map +1 -1
- package/lib/types/devtools.d.ts +22 -58
- package/lib/types/devtools.d.ts.map +1 -1
- package/lib/types/index.d.ts +275 -441
- package/lib/types/index.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/context.ts +3 -12
- package/src/index.ts +9 -13
- package/src/tests/devtools.test.ts +4 -4
- package/src/tests/{form.test.ts → form.test.tsx} +45 -36
- package/src/types.ts +1 -1
- package/src/use-field-array.ts +2 -2
- package/src/use-field.ts +2 -2
- package/src/use-form-state.ts +1 -1
- package/src/use-form.ts +1 -1
- package/src/use-watch.ts +1 -1
- package/lib/types/devtools2.d.ts +0 -31
- package/lib/types/devtools2.d.ts.map +0 -1
- package/lib/types/index2.d.ts +0 -291
- package/lib/types/index2.d.ts.map +0 -1
package/lib/types/index.d.ts
CHANGED
|
@@ -1,457 +1,291 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Props, VNode, VNodeChild } from "@pyreon/core";
|
|
2
|
+
import { Computed, Signal } from "@pyreon/reactivity";
|
|
3
3
|
|
|
4
|
-
//#region src/
|
|
4
|
+
//#region src/types.d.ts
|
|
5
|
+
type ValidationError = string | undefined;
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
} = options;
|
|
32
|
-
const fieldEntries = Object.entries(initialValues);
|
|
33
|
-
const fields = {};
|
|
34
|
-
const debounceTimers = {};
|
|
35
|
-
const validationVersions = {};
|
|
36
|
-
const getValues = () => {
|
|
37
|
-
const values = {};
|
|
38
|
-
for (const [name] of fieldEntries) values[name] = fields[name]?.value.peek() ?? initialValues[name];
|
|
39
|
-
return values;
|
|
40
|
-
};
|
|
41
|
-
const clearAllTimers = () => {
|
|
42
|
-
for (const key of Object.keys(debounceTimers)) {
|
|
43
|
-
clearTimeout(debounceTimers[key]);
|
|
44
|
-
delete debounceTimers[key];
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
const isValidating = signal(false);
|
|
48
|
-
const submitError = signal(void 0);
|
|
49
|
-
let disposed = false;
|
|
50
|
-
for (const [name, initial] of fieldEntries) {
|
|
51
|
-
const valueSig = signal(initial);
|
|
52
|
-
const errorSig = signal(void 0);
|
|
53
|
-
const touchedSig = signal(false);
|
|
54
|
-
const dirtySig = signal(false);
|
|
55
|
-
validationVersions[name] = 0;
|
|
56
|
-
const runValidation = async value => {
|
|
57
|
-
const fieldValidator = validators?.[name];
|
|
58
|
-
if (fieldValidator) {
|
|
59
|
-
validationVersions[name] = (validationVersions[name] ?? 0) + 1;
|
|
60
|
-
const currentVersion = validationVersions[name];
|
|
61
|
-
try {
|
|
62
|
-
const result = await fieldValidator(value, getValues());
|
|
63
|
-
if (!disposed && validationVersions[name] === currentVersion) errorSig.set(result);
|
|
64
|
-
return result;
|
|
65
|
-
} catch (err) {
|
|
66
|
-
if (!disposed && validationVersions[name] === currentVersion) {
|
|
67
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
68
|
-
errorSig.set(message);
|
|
69
|
-
}
|
|
70
|
-
return err instanceof Error ? err.message : String(err);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
errorSig.set(void 0);
|
|
74
|
-
};
|
|
75
|
-
const validateField = debounceMs ? value => {
|
|
76
|
-
clearTimeout(debounceTimers[name]);
|
|
77
|
-
return new Promise(resolve => {
|
|
78
|
-
debounceTimers[name] = setTimeout(async () => {
|
|
79
|
-
resolve(await runValidation(value));
|
|
80
|
-
}, debounceMs);
|
|
81
|
-
});
|
|
82
|
-
} : runValidation;
|
|
83
|
-
if (validateOn === "change") effect(() => {
|
|
84
|
-
validateField(valueSig());
|
|
85
|
-
});
|
|
86
|
-
fields[name] = {
|
|
87
|
-
value: valueSig,
|
|
88
|
-
error: errorSig,
|
|
89
|
-
touched: touchedSig,
|
|
90
|
-
dirty: dirtySig,
|
|
91
|
-
setValue: value => {
|
|
92
|
-
valueSig.set(value);
|
|
93
|
-
dirtySig.set(!structuredEqual(value, initial));
|
|
94
|
-
},
|
|
95
|
-
setTouched: () => {
|
|
96
|
-
touchedSig.set(true);
|
|
97
|
-
if (validateOn === "blur") validateField(valueSig.peek());
|
|
98
|
-
},
|
|
99
|
-
reset: () => {
|
|
100
|
-
valueSig.set(initial);
|
|
101
|
-
errorSig.set(void 0);
|
|
102
|
-
touchedSig.set(false);
|
|
103
|
-
dirtySig.set(false);
|
|
104
|
-
clearTimeout(debounceTimers[name]);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
onUnmount(() => {
|
|
109
|
-
disposed = true;
|
|
110
|
-
clearAllTimers();
|
|
111
|
-
});
|
|
112
|
-
const isSubmitting = signal(false);
|
|
113
|
-
const submitCount = signal(0);
|
|
114
|
-
const isValid = computed(() => {
|
|
115
|
-
for (const name of fieldEntries.map(([n]) => n)) if (fields[name].error() !== void 0) return false;
|
|
116
|
-
return true;
|
|
117
|
-
});
|
|
118
|
-
const isDirty = computed(() => {
|
|
119
|
-
for (const name of fieldEntries.map(([n]) => n)) if (fields[name].dirty()) return true;
|
|
120
|
-
return false;
|
|
121
|
-
});
|
|
122
|
-
const getErrors = () => {
|
|
123
|
-
const errors = {};
|
|
124
|
-
for (const [name] of fieldEntries) {
|
|
125
|
-
const err = fields[name].error.peek();
|
|
126
|
-
if (err !== void 0) errors[name] = err;
|
|
127
|
-
}
|
|
128
|
-
return errors;
|
|
129
|
-
};
|
|
130
|
-
const validate = async () => {
|
|
131
|
-
clearAllTimers();
|
|
132
|
-
isValidating.set(true);
|
|
133
|
-
try {
|
|
134
|
-
const allValues = getValues();
|
|
135
|
-
for (const [name] of fieldEntries) fields[name].error.set(void 0);
|
|
136
|
-
await Promise.all(fieldEntries.map(async ([name]) => {
|
|
137
|
-
const fieldValidator = validators?.[name];
|
|
138
|
-
if (fieldValidator) {
|
|
139
|
-
validationVersions[name] = (validationVersions[name] ?? 0) + 1;
|
|
140
|
-
const currentVersion = validationVersions[name];
|
|
141
|
-
try {
|
|
142
|
-
const error = await fieldValidator(fields[name].value.peek(), allValues);
|
|
143
|
-
if (validationVersions[name] === currentVersion) fields[name].error.set(error);
|
|
144
|
-
} catch (err) {
|
|
145
|
-
if (validationVersions[name] === currentVersion) fields[name].error.set(err instanceof Error ? err.message : String(err));
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}));
|
|
149
|
-
if (schema) try {
|
|
150
|
-
const schemaErrors = await schema(allValues);
|
|
151
|
-
for (const [name] of fieldEntries) {
|
|
152
|
-
const schemaError = schemaErrors[name];
|
|
153
|
-
if (schemaError !== void 0 && fields[name].error.peek() === void 0) fields[name].error.set(schemaError);
|
|
154
|
-
}
|
|
155
|
-
} catch (err) {
|
|
156
|
-
submitError.set(err);
|
|
157
|
-
return false;
|
|
158
|
-
}
|
|
159
|
-
for (const [name] of fieldEntries) if (fields[name].error.peek() !== void 0) return false;
|
|
160
|
-
return true;
|
|
161
|
-
} finally {
|
|
162
|
-
isValidating.set(false);
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
const handleSubmit = async e => {
|
|
166
|
-
if (e && typeof e.preventDefault === "function") e.preventDefault();
|
|
167
|
-
submitError.set(void 0);
|
|
168
|
-
submitCount.update(n => n + 1);
|
|
169
|
-
for (const [name] of fieldEntries) fields[name].touched.set(true);
|
|
170
|
-
if (!(await validate())) return;
|
|
171
|
-
isSubmitting.set(true);
|
|
172
|
-
try {
|
|
173
|
-
await onSubmit(getValues());
|
|
174
|
-
} catch (err) {
|
|
175
|
-
submitError.set(err);
|
|
176
|
-
throw err;
|
|
177
|
-
} finally {
|
|
178
|
-
isSubmitting.set(false);
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
const reset = () => {
|
|
182
|
-
clearAllTimers();
|
|
183
|
-
for (const [name] of fieldEntries) fields[name].reset();
|
|
184
|
-
submitCount.set(0);
|
|
185
|
-
submitError.set(void 0);
|
|
186
|
-
};
|
|
187
|
-
const setFieldValue = (field, value) => {
|
|
188
|
-
if (!fields[field]) throw new Error(`[@pyreon/form] Field "${String(field)}" does not exist. Available fields: ${fieldEntries.map(([n]) => n).join(", ")}`);
|
|
189
|
-
fields[field].setValue(value);
|
|
190
|
-
};
|
|
191
|
-
const setFieldError = (field, error) => {
|
|
192
|
-
if (!fields[field]) throw new Error(`[@pyreon/form] Field "${String(field)}" does not exist. Available fields: ${fieldEntries.map(([n]) => n).join(", ")}`);
|
|
193
|
-
fields[field].error.set(error);
|
|
194
|
-
};
|
|
195
|
-
const setErrors = errors => {
|
|
196
|
-
for (const [name, error] of Object.entries(errors)) setFieldError(name, error);
|
|
197
|
-
};
|
|
198
|
-
const clearErrors = () => {
|
|
199
|
-
for (const [name] of fieldEntries) fields[name].error.set(void 0);
|
|
200
|
-
};
|
|
201
|
-
const resetField = field => {
|
|
202
|
-
if (fields[field]) fields[field].reset();
|
|
203
|
-
};
|
|
204
|
-
const registerCache = /* @__PURE__ */new Map();
|
|
205
|
-
const register = (field, opts) => {
|
|
206
|
-
const cacheKey = `${field}:${opts?.type ?? "text"}`;
|
|
207
|
-
const cached = registerCache.get(cacheKey);
|
|
208
|
-
if (cached) return cached;
|
|
209
|
-
const fieldState = fields[field];
|
|
210
|
-
const props = {
|
|
211
|
-
value: fieldState.value,
|
|
212
|
-
onInput: e => {
|
|
213
|
-
const target = e.target;
|
|
214
|
-
if (opts?.type === "checkbox") fieldState.setValue(target.checked);else if (opts?.type === "number") {
|
|
215
|
-
const num = target.valueAsNumber;
|
|
216
|
-
fieldState.setValue(Number.isNaN(num) ? target.value : num);
|
|
217
|
-
} else fieldState.setValue(target.value);
|
|
218
|
-
},
|
|
219
|
-
onBlur: () => {
|
|
220
|
-
fieldState.setTouched();
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
if (opts?.type === "checkbox") props.checked = computed(() => Boolean(fieldState.value()));
|
|
224
|
-
registerCache.set(cacheKey, props);
|
|
225
|
-
return props;
|
|
226
|
-
};
|
|
227
|
-
return {
|
|
228
|
-
fields,
|
|
229
|
-
isSubmitting,
|
|
230
|
-
isValidating,
|
|
231
|
-
isValid,
|
|
232
|
-
isDirty,
|
|
233
|
-
submitCount,
|
|
234
|
-
submitError,
|
|
235
|
-
values: getValues,
|
|
236
|
-
errors: getErrors,
|
|
237
|
-
setFieldValue,
|
|
238
|
-
setFieldError,
|
|
239
|
-
setErrors,
|
|
240
|
-
clearErrors,
|
|
241
|
-
resetField,
|
|
242
|
-
register,
|
|
243
|
-
handleSubmit,
|
|
244
|
-
reset,
|
|
245
|
-
validate
|
|
246
|
-
};
|
|
7
|
+
* A reactive value that can be read by calling it.
|
|
8
|
+
* Both `Signal<T>` and `Computed<T>` satisfy this interface.
|
|
9
|
+
*/
|
|
10
|
+
type Accessor<T> = Signal<T> | Computed<T>;
|
|
11
|
+
/**
|
|
12
|
+
* Field validator function. Receives the field value and all current form values
|
|
13
|
+
* for cross-field validation.
|
|
14
|
+
*/
|
|
15
|
+
type ValidateFn<T, TValues = Record<string, unknown>> = (value: T, allValues: TValues) => ValidationError | Promise<ValidationError>;
|
|
16
|
+
type SchemaValidateFn<TValues> = (values: TValues) => Partial<Record<keyof TValues, ValidationError>> | Promise<Partial<Record<keyof TValues, ValidationError>>>;
|
|
17
|
+
interface FieldState<T = unknown> {
|
|
18
|
+
/** Current field value. */
|
|
19
|
+
value: Signal<T>;
|
|
20
|
+
/** Field error message (undefined if no error). */
|
|
21
|
+
error: Signal<ValidationError>;
|
|
22
|
+
/** Whether the field has been blurred at least once. */
|
|
23
|
+
touched: Signal<boolean>;
|
|
24
|
+
/** Whether the field value differs from its initial value. */
|
|
25
|
+
dirty: Signal<boolean>;
|
|
26
|
+
/** Set the field value. */
|
|
27
|
+
setValue: (value: T) => void;
|
|
28
|
+
/** Mark the field as touched (typically on blur). */
|
|
29
|
+
setTouched: () => void;
|
|
30
|
+
/** Reset the field to its initial value and clear error/touched/dirty. */
|
|
31
|
+
reset: () => void;
|
|
247
32
|
}
|
|
248
|
-
/**
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
255
|
-
if (a.length !== b.length) return false;
|
|
256
|
-
for (let i = 0; i < a.length; i++) if (!structuredEqual(a[i], b[i], depth + 1)) return false;
|
|
257
|
-
return true;
|
|
258
|
-
}
|
|
259
|
-
if (typeof a === "object" && typeof b === "object") {
|
|
260
|
-
const aObj = a;
|
|
261
|
-
const bObj = b;
|
|
262
|
-
const aKeys = Object.keys(aObj);
|
|
263
|
-
const bKeys = Object.keys(bObj);
|
|
264
|
-
if (aKeys.length !== bKeys.length) return false;
|
|
265
|
-
for (const key of aKeys) if (!structuredEqual(aObj[key], bObj[key], depth + 1)) return false;
|
|
266
|
-
return true;
|
|
267
|
-
}
|
|
268
|
-
return false;
|
|
33
|
+
/** Props returned by `register()` for binding an input element. */
|
|
34
|
+
interface FieldRegisterProps<T> {
|
|
35
|
+
value: Signal<T>;
|
|
36
|
+
onInput: (e: Event) => void;
|
|
37
|
+
onBlur: () => void;
|
|
38
|
+
checked?: Accessor<boolean>;
|
|
269
39
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
*/
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
},
|
|
332
|
-
replace(values) {
|
|
333
|
-
items.set(values.map(makeItem));
|
|
334
|
-
},
|
|
335
|
-
values() {
|
|
336
|
-
return items.peek().map(item => item.value.peek());
|
|
337
|
-
}
|
|
338
|
-
};
|
|
40
|
+
interface FormState<TValues extends Record<string, unknown>> {
|
|
41
|
+
/** Individual field states keyed by field name. */
|
|
42
|
+
fields: { [K in keyof TValues]: FieldState<TValues[K]> };
|
|
43
|
+
/** Whether the form is currently being submitted. */
|
|
44
|
+
isSubmitting: Signal<boolean>;
|
|
45
|
+
/** Whether async validation is currently running. */
|
|
46
|
+
isValidating: Signal<boolean>;
|
|
47
|
+
/** Whether any field has an error (computed — read-only). */
|
|
48
|
+
isValid: Accessor<boolean>;
|
|
49
|
+
/** Whether any field value differs from its initial value (computed — read-only). */
|
|
50
|
+
isDirty: Accessor<boolean>;
|
|
51
|
+
/** Number of times the form has been submitted. */
|
|
52
|
+
submitCount: Signal<number>;
|
|
53
|
+
/** Error thrown by onSubmit (undefined if no error). */
|
|
54
|
+
submitError: Signal<unknown>;
|
|
55
|
+
/** All current form values as a plain object. */
|
|
56
|
+
values: () => TValues;
|
|
57
|
+
/** All current errors as a record. */
|
|
58
|
+
errors: () => Partial<Record<keyof TValues, ValidationError>>;
|
|
59
|
+
/** Set a single field's value. */
|
|
60
|
+
setFieldValue: <K extends keyof TValues>(field: K, value: TValues[K]) => void;
|
|
61
|
+
/** Set a single field's error (e.g. from server-side validation). */
|
|
62
|
+
setFieldError: (field: keyof TValues, error: ValidationError) => void;
|
|
63
|
+
/** Set multiple field errors at once (e.g. from server-side validation). */
|
|
64
|
+
setErrors: (errors: Partial<Record<keyof TValues, ValidationError>>) => void;
|
|
65
|
+
/** Clear all field errors. */
|
|
66
|
+
clearErrors: () => void;
|
|
67
|
+
/** Reset a single field to its initial value. */
|
|
68
|
+
resetField: (field: keyof TValues) => void;
|
|
69
|
+
/**
|
|
70
|
+
* Returns props for binding an input element to a field.
|
|
71
|
+
* For text/select: includes `value` signal, `onInput`, and `onBlur`.
|
|
72
|
+
* For checkboxes: pass `{ type: 'checkbox' }` to also get a `checked` signal.
|
|
73
|
+
* For numbers: pass `{ type: 'number' }` to use `valueAsNumber` on input.
|
|
74
|
+
*/
|
|
75
|
+
register: <K extends keyof TValues & string>(field: K, options?: {
|
|
76
|
+
type?: 'checkbox' | 'number';
|
|
77
|
+
}) => FieldRegisterProps<TValues[K]>;
|
|
78
|
+
/**
|
|
79
|
+
* Submit handler — runs validation, then calls onSubmit if valid.
|
|
80
|
+
* Can be called directly or as a form event handler (calls preventDefault).
|
|
81
|
+
*/
|
|
82
|
+
handleSubmit: (e?: Event) => Promise<void>;
|
|
83
|
+
/** Reset all fields to initial values. */
|
|
84
|
+
reset: () => void;
|
|
85
|
+
/** Validate all fields and return whether the form is valid. */
|
|
86
|
+
validate: () => Promise<boolean>;
|
|
87
|
+
}
|
|
88
|
+
interface UseFormOptions<TValues extends Record<string, unknown>> {
|
|
89
|
+
/** Initial values for each field. */
|
|
90
|
+
initialValues: TValues;
|
|
91
|
+
/** Called with validated values on successful submit. */
|
|
92
|
+
onSubmit: (values: TValues) => void | Promise<void>;
|
|
93
|
+
/** Per-field validators. Receives field value and all form values. */
|
|
94
|
+
validators?: Partial<{ [K in keyof TValues]: ValidateFn<TValues[K], TValues> }>;
|
|
95
|
+
/** Schema-level validator (runs after field validators). */
|
|
96
|
+
schema?: SchemaValidateFn<TValues>;
|
|
97
|
+
/** When to validate: 'blur' (default), 'change', or 'submit'. */
|
|
98
|
+
validateOn?: 'blur' | 'change' | 'submit';
|
|
99
|
+
/** Debounce delay in ms for validators (useful for async validators). */
|
|
100
|
+
debounceMs?: number;
|
|
339
101
|
}
|
|
340
|
-
|
|
341
102
|
//#endregion
|
|
342
|
-
//#region src/
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
*
|
|
347
|
-
* @example
|
|
348
|
-
* function EmailField({ form }: { form: FormState<{ email: string }> }) {
|
|
349
|
-
* const field = useField(form, 'email')
|
|
350
|
-
* return (
|
|
351
|
-
* <>
|
|
352
|
-
* <input {...field.register()} />
|
|
353
|
-
* {field.showError() && <span>{field.error()}</span>}
|
|
354
|
-
* </>
|
|
355
|
-
* )
|
|
356
|
-
* }
|
|
357
|
-
*/
|
|
358
|
-
function useField(form, name) {
|
|
359
|
-
const fieldState = form.fields[name];
|
|
360
|
-
const hasError = computed(() => fieldState.error() !== void 0);
|
|
361
|
-
const showError = computed(() => fieldState.touched() && hasError());
|
|
362
|
-
return {
|
|
363
|
-
value: fieldState.value,
|
|
364
|
-
error: fieldState.error,
|
|
365
|
-
touched: fieldState.touched,
|
|
366
|
-
dirty: fieldState.dirty,
|
|
367
|
-
setValue: fieldState.setValue,
|
|
368
|
-
setTouched: fieldState.setTouched,
|
|
369
|
-
reset: fieldState.reset,
|
|
370
|
-
register: opts => form.register(name, opts),
|
|
371
|
-
hasError,
|
|
372
|
-
showError
|
|
373
|
-
};
|
|
103
|
+
//#region src/context.d.ts
|
|
104
|
+
interface FormProviderProps<TValues extends Record<string, unknown>> extends Props {
|
|
105
|
+
form: FormState<TValues>;
|
|
106
|
+
children?: VNodeChild;
|
|
374
107
|
}
|
|
375
|
-
|
|
108
|
+
/**
|
|
109
|
+
* Provide a form instance to the component tree so nested components
|
|
110
|
+
* can access it via `useFormContext()`.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* const form = useForm({ initialValues: { email: '' }, onSubmit: ... })
|
|
114
|
+
*
|
|
115
|
+
* <FormProvider form={form}>
|
|
116
|
+
* <EmailField />
|
|
117
|
+
* <SubmitButton />
|
|
118
|
+
* </FormProvider>
|
|
119
|
+
*/
|
|
120
|
+
declare function FormProvider<TValues extends Record<string, unknown>>(props: FormProviderProps<TValues>): VNode;
|
|
121
|
+
/**
|
|
122
|
+
* Access the form instance from the nearest `FormProvider`.
|
|
123
|
+
* Must be called within a component tree wrapped by `FormProvider`.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* function EmailField() {
|
|
127
|
+
* const form = useFormContext<{ email: string }>()
|
|
128
|
+
* return <input {...form.register('email')} />
|
|
129
|
+
* }
|
|
130
|
+
*/
|
|
131
|
+
declare function useFormContext<TValues extends Record<string, unknown> = Record<string, unknown>>(): FormState<TValues>;
|
|
376
132
|
//#endregion
|
|
377
|
-
//#region src/use-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
133
|
+
//#region src/use-field.d.ts
|
|
134
|
+
interface UseFieldResult<T> {
|
|
135
|
+
/** Current field value (reactive signal). */
|
|
136
|
+
value: Signal<T>;
|
|
137
|
+
/** Field error message (reactive signal). */
|
|
138
|
+
error: Signal<ValidationError>;
|
|
139
|
+
/** Whether the field has been touched (reactive signal). */
|
|
140
|
+
touched: Signal<boolean>;
|
|
141
|
+
/** Whether the field value differs from initial (reactive signal). */
|
|
142
|
+
dirty: Signal<boolean>;
|
|
143
|
+
/** Set the field value. */
|
|
144
|
+
setValue: (value: T) => void;
|
|
145
|
+
/** Mark the field as touched. */
|
|
146
|
+
setTouched: () => void;
|
|
147
|
+
/** Reset the field to its initial value. */
|
|
148
|
+
reset: () => void;
|
|
149
|
+
/** Register props for input binding. */
|
|
150
|
+
register: (opts?: {
|
|
151
|
+
type?: 'checkbox';
|
|
152
|
+
}) => FieldRegisterProps<T>;
|
|
153
|
+
/** Whether the field has an error (computed). */
|
|
154
|
+
hasError: Computed<boolean>;
|
|
155
|
+
/** Whether the field should show its error (touched + has error). */
|
|
156
|
+
showError: Computed<boolean>;
|
|
386
157
|
}
|
|
387
|
-
|
|
158
|
+
/**
|
|
159
|
+
* Extract a single field's state and helpers from a form instance.
|
|
160
|
+
* Useful for building isolated field components.
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* function EmailField({ form }: { form: FormState<{ email: string }> }) {
|
|
164
|
+
* const field = useField(form, 'email')
|
|
165
|
+
* return (
|
|
166
|
+
* <>
|
|
167
|
+
* <input {...field.register()} />
|
|
168
|
+
* {field.showError() && <span>{field.error()}</span>}
|
|
169
|
+
* </>
|
|
170
|
+
* )
|
|
171
|
+
* }
|
|
172
|
+
*/
|
|
173
|
+
declare function useField<TValues extends Record<string, unknown>, K extends keyof TValues & string>(form: FormState<TValues>, name: K): UseFieldResult<TValues[K]>;
|
|
388
174
|
//#endregion
|
|
389
|
-
//#region src/use-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
for (const key of Object.keys(form.fields)) {
|
|
396
|
-
const field = form.fields[key];
|
|
397
|
-
if (field.touched()) touchedFields[key] = true;
|
|
398
|
-
if (field.dirty()) dirtyFields[key] = true;
|
|
399
|
-
const err = field.error();
|
|
400
|
-
if (err !== void 0) errors[key] = err;
|
|
401
|
-
}
|
|
402
|
-
return {
|
|
403
|
-
isSubmitting: form.isSubmitting(),
|
|
404
|
-
isValidating: form.isValidating(),
|
|
405
|
-
isValid: form.isValid(),
|
|
406
|
-
isDirty: form.isDirty(),
|
|
407
|
-
submitCount: form.submitCount(),
|
|
408
|
-
submitError: form.submitError(),
|
|
409
|
-
touchedFields,
|
|
410
|
-
dirtyFields,
|
|
411
|
-
errors
|
|
412
|
-
};
|
|
413
|
-
};
|
|
414
|
-
if (selector) return computed(() => selector(buildSummary()));
|
|
415
|
-
return computed(buildSummary);
|
|
175
|
+
//#region src/use-field-array.d.ts
|
|
176
|
+
interface FieldArrayItem<T> {
|
|
177
|
+
/** Stable key for keyed rendering. */
|
|
178
|
+
key: number;
|
|
179
|
+
/** Reactive value for this item. */
|
|
180
|
+
value: Signal<T>;
|
|
416
181
|
}
|
|
417
|
-
|
|
182
|
+
interface UseFieldArrayResult<T> {
|
|
183
|
+
/** Reactive list of items with stable keys. */
|
|
184
|
+
items: Signal<FieldArrayItem<T>[]>;
|
|
185
|
+
/** Number of items. */
|
|
186
|
+
length: Computed<number>;
|
|
187
|
+
/** Append a new item to the end. */
|
|
188
|
+
append: (value: T) => void;
|
|
189
|
+
/** Prepend a new item to the start. */
|
|
190
|
+
prepend: (value: T) => void;
|
|
191
|
+
/** Insert an item at the given index. */
|
|
192
|
+
insert: (index: number, value: T) => void;
|
|
193
|
+
/** Remove the item at the given index. */
|
|
194
|
+
remove: (index: number) => void;
|
|
195
|
+
/** Update the value of an item at the given index. */
|
|
196
|
+
update: (index: number, value: T) => void;
|
|
197
|
+
/** Move an item from one index to another. */
|
|
198
|
+
move: (from: number, to: number) => void;
|
|
199
|
+
/** Swap two items by index. */
|
|
200
|
+
swap: (indexA: number, indexB: number) => void;
|
|
201
|
+
/** Replace all items. */
|
|
202
|
+
replace: (values: T[]) => void;
|
|
203
|
+
/** Get all current values as a plain array. */
|
|
204
|
+
values: () => T[];
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Manage a dynamic array of form fields with stable keys.
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* const tags = useFieldArray<string>([])
|
|
211
|
+
* tags.append('typescript')
|
|
212
|
+
* tags.append('pyreon')
|
|
213
|
+
* // tags.items() — array of { key, value } for keyed rendering
|
|
214
|
+
*/
|
|
215
|
+
declare function useFieldArray<T>(initial?: T[]): UseFieldArrayResult<T>;
|
|
418
216
|
//#endregion
|
|
419
|
-
//#region src/
|
|
420
|
-
|
|
217
|
+
//#region src/use-form.d.ts
|
|
421
218
|
/**
|
|
422
|
-
*
|
|
423
|
-
*
|
|
424
|
-
*
|
|
425
|
-
* @example
|
|
426
|
-
* const form = useForm({
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
219
|
+
* Create a signal-based form. Returns reactive field states, form-level
|
|
220
|
+
* signals, and handlers for submit/reset/validate.
|
|
221
|
+
*
|
|
222
|
+
* @example
|
|
223
|
+
* const form = useForm({
|
|
224
|
+
* initialValues: { email: '', password: '', remember: false },
|
|
225
|
+
* validators: {
|
|
226
|
+
* email: (v) => (!v ? 'Required' : undefined),
|
|
227
|
+
* password: (v, all) => (v.length < 8 ? 'Too short' : undefined),
|
|
228
|
+
* },
|
|
229
|
+
* onSubmit: async (values) => { await login(values) },
|
|
230
|
+
* })
|
|
231
|
+
*
|
|
232
|
+
* // Bind with register():
|
|
233
|
+
* // h('input', form.register('email'))
|
|
234
|
+
* // h('input', { type: 'checkbox', ...form.register('remember', { type: 'checkbox' }) })
|
|
235
|
+
*/
|
|
236
|
+
declare function useForm<TValues extends Record<string, unknown>>(options: UseFormOptions<TValues>): FormState<TValues>;
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/use-form-state.d.ts
|
|
239
|
+
interface FormStateSummary<TValues extends Record<string, unknown>> {
|
|
240
|
+
isSubmitting: boolean;
|
|
241
|
+
isValidating: boolean;
|
|
242
|
+
isValid: boolean;
|
|
243
|
+
isDirty: boolean;
|
|
244
|
+
submitCount: number;
|
|
245
|
+
submitError: unknown;
|
|
246
|
+
touchedFields: Partial<Record<keyof TValues, boolean>>;
|
|
247
|
+
dirtyFields: Partial<Record<keyof TValues, boolean>>;
|
|
248
|
+
errors: Partial<Record<keyof TValues, ValidationError>>;
|
|
438
249
|
}
|
|
439
250
|
/**
|
|
440
|
-
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
251
|
+
* Subscribe to the full form state as a single computed signal.
|
|
252
|
+
* Useful for rendering form-level UI (submit button disabled state,
|
|
253
|
+
* error summaries, progress indicators).
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* const state = useFormState(form)
|
|
257
|
+
* // state() => { isSubmitting, isValid, isDirty, errors, ... }
|
|
258
|
+
*
|
|
259
|
+
* @example
|
|
260
|
+
* // Use a selector for fine-grained reactivity
|
|
261
|
+
* const canSubmit = useFormState(form, (s) => s.isValid && !s.isSubmitting)
|
|
262
|
+
*/
|
|
263
|
+
declare function useFormState<TValues extends Record<string, unknown>>(form: FormState<TValues>): Computed<FormStateSummary<TValues>>;
|
|
264
|
+
declare function useFormState<TValues extends Record<string, unknown>, R>(form: FormState<TValues>, selector: (state: FormStateSummary<TValues>) => R): Computed<R>;
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region src/use-watch.d.ts
|
|
267
|
+
/**
|
|
268
|
+
* Watch specific field values reactively. Returns a computed signal
|
|
269
|
+
* that re-evaluates when any of the watched fields change.
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* // Watch a single field
|
|
273
|
+
* const email = useWatch(form, 'email')
|
|
274
|
+
* // email() => current email value
|
|
275
|
+
*
|
|
276
|
+
* @example
|
|
277
|
+
* // Watch multiple fields
|
|
278
|
+
* const [first, last] = useWatch(form, ['firstName', 'lastName'])
|
|
279
|
+
* // first() => firstName value, last() => lastName value
|
|
280
|
+
*
|
|
281
|
+
* @example
|
|
282
|
+
* // Watch all fields
|
|
283
|
+
* const all = useWatch(form)
|
|
284
|
+
* // all() => { email: '...', password: '...' }
|
|
285
|
+
*/
|
|
286
|
+
declare function useWatch<TValues extends Record<string, unknown>, K extends keyof TValues & string>(form: FormState<TValues>, name: K): Signal<TValues[K]>;
|
|
287
|
+
declare function useWatch<TValues extends Record<string, unknown>, K extends (keyof TValues & string)[]>(form: FormState<TValues>, names: K): { [I in keyof K]: Signal<TValues[K[I] & keyof TValues]> };
|
|
288
|
+
declare function useWatch<TValues extends Record<string, unknown>>(form: FormState<TValues>): Computed<TValues>;
|
|
455
289
|
//#endregion
|
|
456
|
-
export { FormProvider, useField, useFieldArray, useForm, useFormContext, useFormState, useWatch };
|
|
457
|
-
//# sourceMappingURL=
|
|
290
|
+
export { type Accessor, type FieldArrayItem, type FieldRegisterProps, type FieldState, FormProvider, type FormState, type FormStateSummary, type SchemaValidateFn, type UseFieldArrayResult, type UseFieldResult, type UseFormOptions, type ValidateFn, type ValidationError, useField, useFieldArray, useForm, useFormContext, useFormState, useWatch };
|
|
291
|
+
//# sourceMappingURL=index2.d.ts.map
|