react-f0rm 0.4.0 → 0.5.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/README.md +52 -3
- package/dist/devtools/index.cjs.js +20 -13
- package/dist/devtools/index.cjs.js.map +1 -1
- package/dist/devtools/index.d.ts +1 -1
- package/dist/devtools/index.mjs +20 -13
- package/dist/devtools/index.mjs.map +1 -1
- package/dist/{form-b9441d8c.cjs.js → form-B4r7INJ0.cjs.js} +10 -39
- package/dist/form-B4r7INJ0.cjs.js.map +1 -0
- package/dist/{form-94c70b4b.mjs → form-R1hDKjBm.mjs} +11 -40
- package/dist/form-R1hDKjBm.mjs.map +1 -0
- package/dist/{form-61297bc0.d.ts → form-rTlcIiWH.d.ts} +31 -2
- package/dist/index.cjs.js +73 -43
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +27 -11
- package/dist/index.mjs +73 -45
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +73 -43
- package/dist/index.umd.js.map +1 -1
- package/dist/index.umd.min.js +2 -2
- package/dist/index.umd.min.js.map +1 -1
- package/dist/resolvers/standard-schema.cjs.js +1 -1
- package/dist/resolvers/standard-schema.cjs.js.map +1 -1
- package/dist/resolvers/standard-schema.d.ts +2 -2
- package/dist/resolvers/standard-schema.mjs +1 -1
- package/dist/resolvers/standard-schema.mjs.map +1 -1
- package/dist/resolvers/yup.cjs.js +5 -7
- package/dist/resolvers/yup.cjs.js.map +1 -1
- package/dist/resolvers/yup.d.ts +2 -2
- package/dist/resolvers/yup.mjs +5 -7
- package/dist/resolvers/yup.mjs.map +1 -1
- package/dist/resolvers/zod.cjs.js +5 -7
- package/dist/resolvers/zod.cjs.js.map +1 -1
- package/dist/resolvers/zod.d.ts +2 -2
- package/dist/resolvers/zod.mjs +5 -7
- package/dist/resolvers/zod.mjs.map +1 -1
- package/dist/{validate-148fe167.d.ts → validate-CQX7BJOD.d.ts} +1 -1
- package/package.json +52 -51
- package/dist/form-94c70b4b.mjs.map +0 -1
- package/dist/form-b9441d8c.cjs.js.map +0 -1
|
@@ -5,7 +5,7 @@ function getSet(ee, key) {
|
|
|
5
5
|
ee.set(key, newSet);
|
|
6
6
|
return newSet;
|
|
7
7
|
}
|
|
8
|
-
function emit
|
|
8
|
+
function emit(ee, key) {
|
|
9
9
|
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
|
10
10
|
args[_key - 2] = arguments[_key];
|
|
11
11
|
}
|
|
@@ -157,7 +157,6 @@ function create(name) {
|
|
|
157
157
|
return { value, key: JSON.stringify(value) };
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
const emit = emit$1;
|
|
161
160
|
const VALIDATION_OUTCOME = /* @__PURE__ */ Symbol("validation-outcome");
|
|
162
161
|
function getValues(form) {
|
|
163
162
|
const { initialValues, parsedValues, values, deleted } = form;
|
|
@@ -171,21 +170,11 @@ function getValues(form) {
|
|
|
171
170
|
}
|
|
172
171
|
return merged;
|
|
173
172
|
}
|
|
174
|
-
function getValue(form, name) {
|
|
175
|
-
return getValueByPath(form, create(name));
|
|
176
|
-
}
|
|
177
|
-
function getValueByPath({ initialValues, parsedValues, values, deleted }, path) {
|
|
178
|
-
if (values.has(path.key)) return values.get(path.key);
|
|
179
|
-
if (deleted.has(path.key)) return void 0;
|
|
180
|
-
return get(parsedValues ?? initialValues, path.value);
|
|
181
|
-
}
|
|
182
173
|
function setValueByPath(form, path, value, options) {
|
|
183
174
|
const { emitter, values, deleted } = form;
|
|
184
175
|
values.set(path.key, value);
|
|
185
176
|
reviveBranch(deleted, path);
|
|
186
177
|
bumpDirtyVersion(form);
|
|
187
|
-
if (options?.shouldTouch) setTouchedByPath(form, path);
|
|
188
|
-
if (options?.shouldValidate) form.validators.get(path.key)?.();
|
|
189
178
|
emit(emitter, "change", path);
|
|
190
179
|
}
|
|
191
180
|
function getErrors({ errors }) {
|
|
@@ -223,19 +212,11 @@ function normalizeErrors(error) {
|
|
|
223
212
|
}
|
|
224
213
|
function clearErrors(form, name) {
|
|
225
214
|
const { emitter, errors } = form;
|
|
226
|
-
|
|
215
|
+
{
|
|
227
216
|
errors.clear();
|
|
228
217
|
emit(emitter, "errors");
|
|
229
218
|
return;
|
|
230
219
|
}
|
|
231
|
-
const paths = typeof name === "string" || isSegmentsPath(name) ? [create(name)] : name.map((one) => create(one));
|
|
232
|
-
for (const { key } of paths) errors.delete(key);
|
|
233
|
-
for (const path of paths) emit(emitter, "errors", path);
|
|
234
|
-
}
|
|
235
|
-
function setTouchedByPath({ emitter, touched }, path) {
|
|
236
|
-
if (touched.has(path.key)) return;
|
|
237
|
-
touched.add(path.key);
|
|
238
|
-
emit(emitter, "touched", path);
|
|
239
220
|
}
|
|
240
221
|
function forEachDirtyField({ initialValues, values }, fn) {
|
|
241
222
|
for (const [key, value] of values) {
|
|
@@ -287,21 +268,18 @@ function reviveBranch(deleted, { key }) {
|
|
|
287
268
|
}
|
|
288
269
|
}
|
|
289
270
|
function reset(form, initialValues, options) {
|
|
290
|
-
const dirtyValues =
|
|
291
|
-
key,
|
|
292
|
-
value: getValue(form, key)
|
|
293
|
-
})) : [];
|
|
271
|
+
const dirtyValues = [];
|
|
294
272
|
form.initialValues = initialValues;
|
|
295
273
|
form.parsedValues = void 0;
|
|
296
|
-
|
|
274
|
+
clearErrors(form);
|
|
297
275
|
const { emitter, touched, values, deleted, validating } = form;
|
|
298
276
|
values.clear();
|
|
299
277
|
deleted.clear();
|
|
300
|
-
|
|
278
|
+
touched.clear();
|
|
301
279
|
validating.clear();
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
280
|
+
form.isSubmitting = false;
|
|
281
|
+
form.submitCount = 0;
|
|
282
|
+
form.isSubmitSuccessful = void 0;
|
|
305
283
|
bumpDirtyVersion(form);
|
|
306
284
|
for (const { key, value } of dirtyValues) {
|
|
307
285
|
setValueByPath(form, create(key), value);
|
|
@@ -324,7 +302,7 @@ async function trigger(form, name) {
|
|
|
324
302
|
() => !form.validating.size,
|
|
325
303
|
() => false
|
|
326
304
|
);
|
|
327
|
-
|
|
305
|
+
{
|
|
328
306
|
form.validators.forEach((validator) => validator());
|
|
329
307
|
await settle();
|
|
330
308
|
if (form.validate) {
|
|
@@ -333,13 +311,6 @@ async function trigger(form, name) {
|
|
|
333
311
|
}
|
|
334
312
|
return !hasErrors(form);
|
|
335
313
|
}
|
|
336
|
-
const keys = typeof name === "string" || isSegmentsPath(name) ? [create(name).key] : name.map((one) => create(one).key);
|
|
337
|
-
keys.forEach((key) => form.validators.get(key)?.());
|
|
338
|
-
await settle();
|
|
339
|
-
return keys.every((key) => !form.errors.has(key));
|
|
340
|
-
}
|
|
341
|
-
function isSegmentsPath(name) {
|
|
342
|
-
return name.some((part) => typeof part === "number");
|
|
343
314
|
}
|
|
344
315
|
function isFieldError(value) {
|
|
345
316
|
return !!value && typeof value === "object" && typeof value.type === "string" && typeof value.message === "string";
|
|
@@ -374,5 +345,5 @@ function applyValidateResult(form, result) {
|
|
|
374
345
|
setFormErrors(form, result);
|
|
375
346
|
}
|
|
376
347
|
|
|
377
|
-
export { VALIDATION_OUTCOME as V,
|
|
378
|
-
//# sourceMappingURL=form-
|
|
348
|
+
export { VALIDATION_OUTCOME as V, getDirtyFields as a, getValues as b, getErrors as c, getTouchedFields as g, on as o, reset as r, trigger as t };
|
|
349
|
+
//# sourceMappingURL=form-R1hDKjBm.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-R1hDKjBm.mjs","sources":["../node_modules/.pnpm/@for-fun+event-emitter@1.0.1/node_modules/@for-fun/event-emitter/dist/event-emitter.esm.js","../src/util.ts","../src/path.ts","../src/form.ts"],"sourcesContent":["function getSet(ee, key) {\n var set = ee.get(key);\n if (set) return set;\n var newSet = new Set();\n ee.set(key, newSet);\n return newSet;\n}\nvar errorEvent = Symbol('error');\nfunction create() {\n return new Map();\n}\nfunction emit(ee, key) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n (ee.get(key) || []).forEach(function (h) {\n return h.apply(void 0, args);\n });\n}\nfunction emitError(ee, err) {\n var handlerSet = ee.get(errorEvent);\n if (!handlerSet || !handlerSet.size) throw err;\n handlerSet.forEach(function (h) {\n return h(err);\n });\n}\nfunction on(ee, key, handler) {\n var set = getSet(ee, key);\n set.add(handler);\n return function () {\n return set.delete(handler);\n };\n}\nfunction onError(ee, handler) {\n return on(ee, errorEvent, handler);\n}\nfunction once(ee, key, handler) {\n var off = on(ee, key, function () {\n off();\n handler.apply(void 0, arguments);\n });\n return off;\n}\nfunction onceError(ee, handler) {\n return once(ee, errorEvent, handler);\n}\nfunction bindContext(context) {\n return function (func) {\n return func.bind(null, context);\n };\n}\nfunction createAndBind() {\n var ee = create();\n var bind = bindContext(ee);\n return {\n emit: bind(emit),\n emitError: bind(emitError),\n on: bind(on),\n onError: bind(onError),\n once: bind(once),\n onceError: bind(onceError)\n };\n}\n\nexport { bindContext, create, createAndBind, emit, emitError, errorEvent, on, onError, once, onceError };\n//# sourceMappingURL=event-emitter.esm.js.map\n","import {on} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\n\nconst pathCache = new Map<string, (string | number)[]>();\n\nexport function normalizePath(\n path: string | (string | number)[]\n): (string | number)[] {\n if (Array.isArray(path)) return path;\n const cached = pathCache.get(path);\n if (cached) return cached;\n const value = parsePath(path);\n pathCache.set(path, value);\n return value;\n}\n\nfunction parsePath(path: string): (string | number)[] {\n const result: (string | number)[] = [];\n let identifier = '';\n const flushIdentifier = () => {\n result.push(identifier);\n identifier = '';\n };\n\n for (let i = 0; i < path.length; i++) {\n const char = path[i];\n if (char === '.') {\n if (identifier !== '') flushIdentifier();\n } else if (char === '[') {\n if (identifier !== '') flushIdentifier();\n const quote = path[i + 1];\n if (quote === '\"' || quote === \"'\") {\n const close = path.indexOf(quote, i + 2);\n if (close === -1) {\n throw new TypeError(`Unterminated quote in path: ${path}`);\n }\n if (path[close + 1] !== ']') {\n throw new TypeError(\n `Expected \"]\" after quoted segment in path: ${path}`\n );\n }\n result.push(path.slice(i + 2, close));\n i = close + 1;\n } else {\n const close = path.indexOf(']', i + 1);\n if (close === -1) {\n throw new TypeError(`Unterminated bracket in path: ${path}`);\n }\n const content = path.slice(i + 1, close);\n result.push(/^-?\\d+$/.test(content) ? Number(content) : content);\n i = close;\n }\n } else {\n identifier += char;\n }\n }\n if (identifier !== '' || result.length === 0) flushIdentifier();\n return result;\n}\n\nexport function get(values: any, path: (string | number)[]): any {\n return path.reduce((current: any, p: string | number) => {\n if (current == null) return undefined;\n return current[p];\n }, values);\n}\n\n/**\n * Immutable counterpart of {@link set}: removes the path from the value\n * tree, copying only along the touched branch (untouched branches stay\n * shared with the source, like set). Deletes the key entirely rather than\n * writing undefined, so the result carries no `a: undefined` entries.\n */\nexport function unset(values: any, path: (string | number)[]): any {\n if (!path.length || values == null) return values;\n const [prop, ...props] = path;\n if (props.length) {\n const next = unset(values[prop], props);\n return next === values[prop] ? values : set(values, path, next);\n }\n if (Array.isArray(values)) {\n if (!(prop in values)) return values;\n const arr = values.slice();\n delete arr[prop as number];\n return arr;\n }\n if (typeof values !== 'object' || !(prop in values)) return values;\n const copy = {...values};\n delete copy[prop as string];\n return copy;\n}\n\nexport function set(values: any, path: (string | number)[], value: any): any {\n if (!path.length) return value;\n\n const [prop, ...props] = path;\n if (typeof prop === 'number') {\n const arr = Array.isArray(values) ? values.slice() : [];\n arr[prop] = set(arr[prop], props, value);\n return arr;\n }\n return {...values, [prop]: set(values && values[prop], props, value)};\n}\n\n/**\n * Ownership-tracked {@link set}: merge many paths into one tree without\n * re-copying containers the merge itself already created.\n *\n * Containers present in `owned` (freshly created by an earlier call of the\n * same merge) are mutated in place; every other container -- nodes borrowed\n * from the seed tree and user leaf values -- is copied first with the exact\n * copy rules `set` applies (numeric prop: array slice, or a fresh array\n * when the node is not one; string prop: object spread). Chaining\n * `setOwned` over a list of paths therefore produces the tree chaining\n * `set` would, in the same insertion order, but allocates each distinct\n * container once (O(distinct path prefixes)) instead of re-copying the\n * whole branch for every path (O(paths x depth)).\n *\n * Use a fresh `owned` set per merge and thread the returned root (a copied\n * replacement when the seed root itself had to be copied) into the next\n * call. Borrowed containers are never mutated.\n */\nexport function setOwned(\n root: any,\n path: (string | number)[],\n value: any,\n owned: Set<object>\n): any {\n if (!path.length) return value;\n let container = root;\n let parent: any = null;\n let parentProp: string | number = '';\n for (let i = 0; i < path.length; i++) {\n const prop = path[i];\n if (!owned.has(container)) {\n let copy: any;\n if (typeof prop === 'number') {\n copy = Array.isArray(container) ? container.slice() : [];\n } else {\n copy = {...container};\n }\n owned.add(copy);\n if (i === 0) root = copy;\n else parent[parentProp] = copy;\n container = copy;\n }\n if (i === path.length - 1) {\n container[prop] = value;\n } else {\n parent = container;\n parentProp = prop;\n container = container[prop];\n }\n }\n return root;\n}\n\nexport function isNil(value: any): value is null | undefined {\n return value == null;\n}\n\nexport function isEmpty(value: any): boolean {\n if (isNil(value)) return true;\n if (typeof value !== 'object') return false;\n\n const values = Object.values(value);\n return values.length === 0 || values.every(isEmpty);\n}\n\nexport function isPromise(value: any): value is Promise<any> {\n return value && typeof value.then === 'function';\n}\n\n/** Structural equality for form default data (primitives, arrays, plain\n * objects, Dates). Class instances and other exotic objects compare as\n * unequal, which errs on the side of re-seeding when {@link\n * setInitialValues} uses it to tell a re-rendered inline literal from\n * genuinely changed content. */\nexport function isEqual(a: any, b: any): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n const isArray = Array.isArray(a);\n if (isArray !== Array.isArray(b)) return false;\n if (isArray) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n return true;\n }\n const proto = Object.getPrototypeOf(a);\n if (proto !== Object.prototype && proto !== null) return false;\n if (Object.getPrototypeOf(b) !== proto) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!isEqual(a[key], b[key])) return false;\n }\n return true;\n}\n\nexport function waitUntil(\n emitter: EventEmitter<any>,\n event: string,\n isResolve: () => boolean,\n isReject: () => boolean\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (isReject()) return void reject();\n if (isResolve()) return void resolve();\n\n const off = on(emitter, event as any, () => {\n if (isReject()) {\n off();\n reject();\n return;\n }\n // Condition not reached yet — stay subscribed and keep waiting. (The\n // previous `if (isResolve()) return` was inverted: it hung forever\n // once the condition held and resolved prematurely while it didn't.)\n if (!isResolve()) return;\n off();\n resolve();\n });\n });\n}\n","import {normalizePath} from './util';\n\nexport type PathSegments = (string | number)[];\nexport type Name = string | PathSegments;\nexport type Path = {value: PathSegments; key: string};\n\nexport default function create(name: Name): Path {\n const value = normalizePath(name);\n return {value, key: JSON.stringify(value)};\n}\n","import {create as createEmitter, emit} from '@for-fun/event-emitter';\nimport type {EventEmitter} from '@for-fun/event-emitter';\nimport createPath from './path';\nimport type {Name, Path, PathSegments} from './path';\nimport type {FieldPath, PathValueOf} from './types';\nimport {get, isEqual, normalizePath, setOwned, unset, waitUntil} from './util';\n\nexport type {Name};\nexport type {FieldPath, PathValue} from './types';\n\n/** A field error: `type` identifies the error kind ('custom' for plain\n * string errors), `message` is the display text. */\nexport interface FieldError {\n type: string;\n message: string;\n}\n\n/** A flattened entry from {@link getErrors}. */\nexport type FieldErrorEntry = {path: string; type: string; message: string};\n\n/** When a field is validated:\n * - `'onSubmit'` (default): only on submit\n * - `'onBlur'`: when the field loses focus\n * - `'onChange'`: on every change\n * - `'onTouched'`: on first blur, then on every change\n * - `'all'`: on both change and blur\n */\nexport type ValidationMode =\n 'onSubmit' | 'onBlur' | 'onChange' | 'onTouched' | 'all';\n\n/** When a field is re-validated after it already has an error:\n * - `'onChange'` (default): on every change\n * - `'onBlur'`: when the field loses focus\n * - `'onSubmit'`: only on submit (no live re-validation)\n */\nexport type ReValidateMode = 'onChange' | 'onBlur' | 'onSubmit';\n\n/** Brand marking a form-level validate result as a structured\n * {@link ValidationOutcome} (parsed values and/or errors) rather than a\n * plain nested error record. Symbols cannot collide with user error\n * records, so detection is an exact `VALIDATION_OUTCOME in result`. */\nexport const VALIDATION_OUTCOME: unique symbol = Symbol('validation-outcome');\n\n/** Structured form-level validate result: `errors` uses the same nested\n * shape a plain error record uses, `values` is the schema's parsed output\n * (coerce/transform results included). Either side may be omitted. */\nexport type ValidationOutcome<T> = {\n [VALIDATION_OUTCOME]: true;\n errors?: Record<string, any>;\n values?: T;\n};\n\n/** What a form-level validate function may return: a plain nested error\n * record (flattened into field errors — the long-standing shape), or a\n * branded {@link ValidationOutcome} whose `values` become the form's\n * parsedValues baseline. */\nexport type ValidateResult<T> =\n | Record<string, any>\n | ValidationOutcome<T>\n | Promise<Record<string, any> | ValidationOutcome<T>>;\n\nexport interface Form<T extends Record<string, any> = any> {\n emitter: EventEmitter;\n mode: ValidationMode;\n reValidateMode: ReValidateMode;\n initialValues: T;\n values: Map<string, any>;\n /** Tombstones of unregistered field paths (JSON path keys): reading or\n * merging values must not fall back to initialValues for these paths. */\n deleted: Set<string>;\n /** Every error registered for a field, as a non-empty array (the\n * write-side {@link setErrorByPath} normalizes to this invariant, so\n * readers never need to guard against an empty list). Readers wanting\n * the display error take the first entry ({@link getError}); readers\n * wanting all of them use {@link getFieldErrors}. */\n errors: Map<string, FieldError[]>;\n touched: Set<string>;\n validators: Map<string, () => void>;\n validating: Set<string>;\n /** Parsed values from the last successful schema validation: the\n * schema's complete output tree (coerced/transformed values included).\n * Sits between initialValues and the values Map in {@link getValues}\n * until `reset`/`setInitialValues` clears it. Never affects dirty\n * state — that compares live edits against initialValues only. */\n parsedValues: T | undefined;\n validate?: (values: T) => ValidateResult<T>;\n isSubmitting: boolean;\n submitCount: number;\n isSubmitSuccessful: boolean | undefined;\n /** Form-level disabled flag, OR-ed into every bound field's `disabled`\n * (form flag || the field's own option). Seeded from\n * {@link Options}.disabled at create time and toggled at runtime with\n * {@link setDisabled}, which emits a payload-less 'disabled' event so\n * subscribed fields re-render. */\n disabled: boolean;\n}\n\nexport type Options<T extends Record<string, any> = any> = {\n initialValues?: T;\n /** When fields are validated. Defaults to `'onSubmit'`. See\n * {@link ValidationMode}. */\n mode?: ValidationMode;\n /** When a field is re-validated after it already has an error — it only\n * takes effect once the field has an error. Defaults to `'onChange'`. See\n * {@link ReValidateMode}. */\n reValidateMode?: ReValidateMode;\n /**\n * Form-level validator. Returns a record of errors keyed by field path;\n * nested objects are flattened ('a.b' style) and array values contribute\n * every non-empty string they hold as separate errors (zod `flatten()`\n * formErrors style). Schema adapters instead return a branded\n * {@link ValidationOutcome}: `errors` flattens the same way, `values`\n * (the schema's parsed output) becomes the form's parsedValues baseline\n * that {@link getValues} layers over initialValues.\n */\n validate?: (values: T) => ValidateResult<T>;\n /** Start the form with every bound field disabled — the flag bound\n * fields OR with their own `disabled` option (a field cannot opt out\n * of a disabled form). Toggle later with {@link setDisabled}.\n * Defaults to `false`. */\n disabled?: boolean;\n};\n\n/**\n * Create form instance\n * @param options\n * @return form instance\n */\nexport default function create<T extends Record<string, any> = any>(\n options?: Options<T>\n): Form<T> {\n const emitter = createEmitter();\n return {\n emitter,\n ...options,\n mode: options?.mode ?? 'onSubmit',\n reValidateMode: options?.reValidateMode ?? 'onChange',\n disabled: options?.disabled ?? false,\n initialValues: (options?.initialValues ?? {}) as T,\n values: new Map(),\n deleted: new Set(),\n errors: new Map(),\n touched: new Set(),\n validators: new Map(),\n validating: new Set(),\n parsedValues: undefined,\n isSubmitting: false,\n submitCount: 0,\n isSubmitSuccessful: undefined\n };\n}\n\n/**\n * Get form values: the values Map layered over parsedValues (when a schema\n * validation produced them) layered over initialValues.\n *\n * Merged with copy-on-write ownership tracking ({@link setOwned}): every\n * distinct container on a written path is allocated once and shared by all\n * paths through it, instead of re-copying the whole branch for every key.\n * One owned set spans the whole merge, so containers borrowed from the\n * parsedValues tree are copied before mutation exactly like initialValues\n * ones. The result is still a freshly merged tree per call, with untouched\n * branches sharing references with the baseline exactly like chained\n * `set` did -- callers may treat it as their own copy.\n *\n * parsedValues is the schema's complete output tree: once validation\n * succeeds it replaces the initialValues baseline (fields the schema\n * dropped disappear), while live edits in the values Map still win over\n * both. It never affects dirty state — {@link isDirty} and\n * {@link getDirtyFields} compare live edits against initialValues only,\n * because parsing is not a user edit.\n *\n * @param form\n */\nexport function getValues<T extends Record<string, any> = any>(\n form: Form<T>\n): T {\n const {initialValues, parsedValues, values, deleted} = form;\n const owned = new Set<object>();\n let merged = parsedValues ?? initialValues;\n for (const [key, value] of values) {\n merged = setOwned(merged, JSON.parse(key), value, owned);\n }\n // Unregistered fields leave a tombstone in `deleted`; remove those paths\n // from the merged result so they don't fall back to initialValues. unset\n // is immutable (set() shares untouched branches with initialValues, so a\n // mutating delete would corrupt them) and deletes the key outright rather\n // than writing undefined, which would leave `a: undefined` entries behind\n // in anything that spreads getValues().\n for (const key of deleted) {\n merged = unset(merged, JSON.parse(key));\n }\n return merged;\n}\n\n/**\n * Get field value\n * @param form\n * @param name\n */\nexport function getValue<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): PathValueOf<T, P> {\n return getValueByPath(form, createPath(name));\n}\n\n/**\n * Get field value by path\n * @param form\n * @param path\n */\nexport function getValueByPath(\n {initialValues, parsedValues, values, deleted}: Form,\n path: Path\n): any {\n if (values.has(path.key)) return values.get(path.key);\n // Unregistered path: the tombstone blocks the initialValues fallback.\n if (deleted.has(path.key)) return undefined;\n // Same layering as getValues: parsed values (when present) are the\n // baseline above initialValues.\n return get(parsedValues ?? initialValues, path.value);\n}\n\n/** Options accepted by {@link setValue} / {@link setValueByPath}. Every flag\n * defaults to `false`; omitting the options object entirely keeps the plain\n * set-value behavior (no validation, no touched marking). */\nexport interface SetFieldOptions {\n /** Run the field's registered validator (if any) after the value lands,\n * same as triggering that single field. Defaults to `false`. */\n shouldValidate?: boolean;\n /** Mark the field as touched. Defaults to `false`. */\n shouldTouch?: boolean;\n /** Reserved for a future manual dirty marker. Dirty state is currently\n * derived from comparing values against initialValues, so this flag is\n * accepted but does nothing. Defaults to `false`. */\n shouldDirty?: boolean;\n}\n\n/**\n * Set field value\n * @param form\n * @param name\n * @param value\n * @param options\n */\nexport function setValue<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(\n form: Form<T>,\n name: P,\n value: PathValueOf<T, P>,\n options?: SetFieldOptions\n): void {\n setValueByPath(form, createPath(name), value, options);\n}\n\n/**\n * Set field value\n * @param form\n * @param path\n * @param value\n * @param options\n */\nexport function setValueByPath(\n form: Form,\n path: Path,\n value: any,\n options?: SetFieldOptions\n): void {\n const {emitter, values, deleted} = form;\n values.set(path.key, value);\n reviveBranch(deleted, path);\n bumpDirtyVersion(form);\n if (options?.shouldTouch) setTouchedByPath(form, path);\n if (options?.shouldValidate) form.validators.get(path.key)?.();\n emit(emitter, 'change', path);\n}\n\n/**\n * Get field error\n * @param form\n * @param name\n * @return FieldError object or undefined\n */\nexport function getError<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldError | undefined {\n return getErrorByPath(form, createPath(name));\n}\n\n/**\n * Get field error by path\n * @param form\n * @param path\n * @return first FieldError of the field, or undefined\n */\nexport function getErrorByPath(\n {errors}: Form,\n path: Path\n): FieldError | undefined {\n return errors.get(path.key)?.[0];\n}\n\n/** Shared empty result for {@link getFieldErrorsByPath}: a fresh `[]` per\n * call would allocate on the hot no-error path, and the stored arrays are\n * handed out by reference too, so callers must treat results as read-only. */\nconst NO_ERRORS: FieldError[] = [];\n\n/**\n * Get all errors of a field\n * @param form\n * @param name\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function getFieldErrors<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldError[] {\n return getFieldErrorsByPath(form, createPath(name));\n}\n\n/**\n * Get all errors of a field by path\n * @param form\n * @param path\n * @return every error registered for the field (insertion order); an empty\n * array when the field has none\n */\nexport function getFieldErrorsByPath({errors}: Form, path: Path): FieldError[] {\n return errors.get(path.key) ?? NO_ERRORS;\n}\n\n/**\n * Get all errors\n * @param form\n * @return array of {path, type, message} entries, in insertion order; path\n * is the user-facing dotted field path ('a.b', 'list.0'), and a\n * field holding several errors contributes one entry per error\n */\nexport function getErrors({errors}: Form): FieldErrorEntry[] {\n const entries: FieldErrorEntry[] = [];\n for (const [key, list] of errors) {\n const path = (JSON.parse(key) as PathSegments).join('.');\n for (const {type, message} of list) entries.push({path, type, message});\n }\n return entries;\n}\n\n/**\n * Get first error message\n * @param form\n * @return first error's message string, or undefined when there are no errors\n */\nexport function getFirstError({errors}: Form): string | undefined {\n return errors.values().next().value?.[0]?.message;\n}\n\n/** Snapshot of one field's aggregated state, as {@link getFieldState}\n * returns it. `errors` is the stored array shared with the form — treat it\n * as read-only, like every {@link getFieldErrors} result. */\nexport interface FieldState<T = any> {\n value: T;\n error: FieldError | undefined;\n errors: FieldError[];\n isDirty: boolean;\n isTouched: boolean;\n isValidating: boolean;\n}\n\n/**\n * Get one field's aggregated state: the layered value ({@link getValue}),\n * the first error ({@link getError}) and every error ({@link\n * getFieldErrors}), dirtiness, the touched flag, and whether a validator\n * is in flight. `isDirty` applies the same per-field rule as {@link\n * getDirtyFields}: a live value exists and differs from initialValues at\n * that path (parsedValues never counts — parsing is not an edit).\n *\n * @param form\n * @param name\n */\nexport function getFieldState<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): FieldState<PathValueOf<T, P>> {\n const path = createPath(name);\n const {initialValues, values, touched, validating} = form;\n const live = values.get(path.key);\n return {\n value: getValueByPath(form, path),\n error: getErrorByPath(form, path),\n errors: getFieldErrorsByPath(form, path),\n isDirty: values.has(path.key) && get(initialValues, path.value) !== live,\n isTouched: touched.has(path.key),\n isValidating: validating.has(path.key)\n };\n}\n\nexport function unsetValidatingByPath(\n {emitter, validating}: Form,\n path: Path\n): void {\n validating.delete(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'validating', path);\n}\n\nexport function setValidatingByPath(\n {emitter, validating}: Form,\n path: Path\n): void {\n validating.add(path.key);\n emit(emitter, 'validating', path);\n}\n\n/**\n * Set field error\n * @param form\n * @param name\n * @param error string is normalized to {type: 'custom', message}; a\n * FieldError object is stored as-is; an array holds several errors\n * (falsy items dropped, strings normalized); undefined clears\n */\nexport function setError<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(\n form: Form<T>,\n name: P,\n error: string | FieldError | (string | FieldError)[] | undefined\n): void {\n setErrorByPath(form, createPath(name), error);\n}\n\n/**\n * Set field error\n * @param form\n * @param path\n * @param error string is normalized to {type: 'custom', message}; a\n * FieldError object is stored as-is; an array holds several errors\n * (falsy items dropped, strings normalized); undefined clears\n */\nexport function setErrorByPath(\n {emitter, errors}: Form,\n path: Path,\n error: string | FieldError | (string | FieldError)[] | undefined\n): void {\n const list = normalizeErrors(error);\n // An empty result (undefined, '', or an array of only falsy items) clears\n // the key: the errors Map never stores an empty list, so hasErrors stays\n // a plain size check and readers can index [0] unguarded.\n if (list) errors.set(path.key, list);\n else errors.delete(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'errors', path);\n}\n\n/** Normalize any {@link setErrorByPath} input into the stored non-empty\n * FieldError[] shape, or undefined when there is nothing to store. */\nfunction normalizeErrors(\n error: string | FieldError | (string | FieldError)[] | undefined\n): FieldError[] | undefined {\n if (typeof error === 'string') {\n return error ? [{type: 'custom', message: error}] : undefined;\n }\n if (isFieldError(error)) return [error];\n if (!error) return undefined;\n // Falsy items drop out before normalization, so '' never becomes a\n // stored {type: 'custom', message: ''} placeholder.\n const list: FieldError[] = [];\n error.forEach(item => {\n if (typeof item === 'string' && item) {\n list.push({type: 'custom', message: item});\n } else if (isFieldError(item)) {\n list.push(item);\n }\n });\n return list.length ? list : undefined;\n}\n\n/**\n * Clear errors\n * @param form\n * @param name a single path or a list of paths; omit to clear every error\n */\nexport function clearErrors(form: Form, name?: Name | Name[]): void {\n const {emitter, errors} = form;\n if (name === undefined) {\n errors.clear();\n // Payload-less broadcast: every error subscriber re-syncs.\n emit(emitter, 'errors');\n return;\n }\n // Same single-path vs list discrimination as trigger: a segment array\n // holding a number is one path ('a.0' shape), not a list of names.\n const paths =\n typeof name === 'string' || isSegmentsPath(name)\n ? [createPath(name)]\n : name.map(one => createPath(one));\n for (const {key} of paths) errors.delete(key);\n // Path-payload emits — the setErrorByPath scoping — wake exactly the\n // affected fields' subscribers.\n for (const path of paths) emit(emitter, 'errors', path);\n}\n\n/** Options accepted by {@link setServerErrors}. */\nexport interface SetServerErrorsOptions {\n /** Keep existing field errors instead of clearing them first. Defaults\n * to `false`: a fresh server response replaces the prior error state. */\n keepExisting?: boolean;\n}\n\n/**\n * Land a server-side error response on the form: each entry becomes the\n * named field's error(s) with `type: 'server'`, ready for the same\n * renderError/`useError` channel client-side validation uses. Takes the\n * flat `Record<string, string | string[]>` shape REST APIs commonly\n * return (RealWorld: `422 {errors: {email: ['has already been taken']}}`)\n * without a hand-rolled `Object.entries` + `setError` loop.\n *\n * A string value lands as one error, a string array as several (first one\n * is what `getError`/`error` expose); an empty array clears that field's\n * errors. By default every existing error is cleared first — a fresh\n * response describes the current state, not a patch onto stale client\n * errors; pass `keepExisting: true` to layer instead.\n * @param form\n * @param errors field errors keyed by name\n * @param options\n */\nexport function setServerErrors(\n form: Form,\n errors: Record<string, string | string[]>,\n options?: SetServerErrorsOptions\n): void {\n if (!options?.keepExisting) clearErrors(form);\n for (const [name, error] of Object.entries(errors)) {\n setError(\n form,\n name,\n (Array.isArray(error) ? error : [error]).map(message => ({\n type: 'server',\n message\n }))\n );\n }\n}\n\n/**\n * Set field touched state\n * @param form\n * @param name\n */\nexport function setTouched(form: Form, name: Name): void {\n setTouchedByPath(form, createPath(name));\n}\n\n/**\n * Set field touched state\n * @param form\n * @param path\n */\nexport function setTouchedByPath({emitter, touched}: Form, path: Path): void {\n if (touched.has(path.key)) return;\n touched.add(path.key);\n // Path payload lets key-scoped subscribers (onKeyEvent) skip unrelated\n // fields; payload-less listeners ignore it.\n emit(emitter, 'touched', path);\n}\n\n/**\n * Check if field has been touched\n * @param form\n * @param name\n */\nexport function hasTouched<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P): boolean {\n return hasTouchedByPath(form, createPath(name));\n}\n\n/**\n * Check if field has been touched\n * @param form\n * @param path\n */\nexport function hasTouchedByPath({touched}: Form, path: Path): boolean {\n return touched.has(path.key);\n}\n\n/**\n * Is dirty -- any value differs from initialValues\n * @param form\n */\nexport function isDirty(form: Form): boolean {\n let dirty = false;\n forEachDirtyField(form, () => {\n dirty = true;\n });\n return dirty;\n}\n\nfunction forEachDirtyField(\n {initialValues, values}: Form,\n fn: (dottedKey: string) => void\n): void {\n for (const [key, value] of values) {\n const path = JSON.parse(key) as PathSegments;\n if (get(initialValues, path) !== value) fn(path.join('.'));\n }\n}\n\n/** Per-form memoization of {@link getDirtyFields}. `version` counts value\n * mutations since the cached `result` was computed: bump points increment\n * it, reads reset it, so a non-zero version means the cache is stale. */\ninterface DirtyFieldsCache {\n version: number;\n result: Record<string, boolean>;\n}\n\nconst dirtyFieldsCaches = new WeakMap<Form, DirtyFieldsCache>();\n\n/**\n * Invalidate `form`'s cached {@link getDirtyFields} result. Called at every\n * point that can change values or initialValues (setValueByPath,\n * removeFieldByPath, setInitialValues, reset) so repeated reads hand out a\n * stable reference and useWatch's Object.is snapshot check can skip\n * re-renders.\n */\nfunction bumpDirtyVersion(form: Form): void {\n const cache = dirtyFieldsCaches.get(form);\n if (cache) cache.version++;\n}\n\nfunction computeDirtyFields(form: Form): Record<string, boolean> {\n const dirtyFields: Record<string, boolean> = {};\n forEachDirtyField(form, key => {\n dirtyFields[key] = true;\n });\n return dirtyFields;\n}\n\n/** Dirty entries only ever map to `true`, so equal key sets mean shallow\n * equal results. */\nfunction sameDirtyKeys(\n a: Record<string, boolean>,\n b: Record<string, boolean>\n): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n return aKeys.every(key => b[key] === true);\n}\n\n/**\n * Get dirty fields -- fields whose current value differs from initialValues.\n * Keys are user-facing dotted paths ('a.b', 'a.0.c'), unlike the JSON array\n * keys stored in the values Map.\n * @param form\n * @return object mapping each dirty field's dotted path to true; the same\n * reference is returned until the dirty set actually changes\n */\nexport function getDirtyFields(form: Form): Record<string, boolean> {\n let cache = dirtyFieldsCaches.get(form);\n if (!cache) {\n cache = {version: 0, result: computeDirtyFields(form)};\n dirtyFieldsCaches.set(form, cache);\n } else if (cache.version > 0) {\n const result = computeDirtyFields(form);\n // Keep the old reference when the dirty set is unchanged (values always\n // map to true) so subscribers see identity-stable snapshots.\n if (!sameDirtyKeys(cache.result, result)) cache.result = result;\n cache.version = 0;\n }\n return cache.result;\n}\n\n/**\n * Get touched fields as user-facing dotted paths ('a.b', 'a.0.c'), unlike\n * the JSON array keys stored in the touched Set.\n * @param form\n * @return array of touched fields' dotted paths\n */\nexport function getTouchedFields({touched}: Form): string[] {\n return Array.from(touched, key =>\n (JSON.parse(key) as PathSegments).join('.')\n );\n}\n\n/**\n * Is touched -- any field has been touched\n * @param form\n */\nexport function isTouched({touched}: Form): boolean {\n return touched.size > 0;\n}\n\n/**\n * Remove field\n * @param form\n * @param name\n */\nexport function removeField(form: Form, name: Name): void {\n removeFieldByPath(form, createPath(name));\n}\n\n/**\n * Remove field\n * @param form\n * @param path\n */\nexport function removeFieldByPath(\n form: Form,\n {key, value: segments}: Path\n): void {\n const {emitter, values, touched, errors, validating, deleted} = form;\n values.delete(key);\n touched.delete(key);\n errors.delete(key);\n validating.delete(key);\n // Tombstone the unregistered path so later reads do not fall back to\n // initialValues and \"revive\" the field's old initial value. A tombstone\n // never shadows live values: skip it when the branch is already covered\n // by a live ancestor key (e.g. a FieldArray rewrite stored the whole\n // array at the parent path) or a still-mounted descendant key.\n if (!hasLiveBranch(values, segments)) deleted.add(key);\n bumpDirtyVersion(form);\n emit(emitter, 'change');\n emit(emitter, 'touched');\n emit(emitter, 'errors');\n emit(emitter, 'validating');\n}\n\n/**\n * Does a live value cover the branch at `segments` -- either at an ancestor\n * key or below it at a descendant key?\n */\nfunction hasLiveBranch(\n values: Map<string, any>,\n segments: PathSegments\n): boolean {\n for (let i = 1; i < segments.length; i++) {\n if (values.has(JSON.stringify(segments.slice(0, i)))) return true;\n }\n const stem = `${JSON.stringify(segments).slice(0, -1)},`;\n for (const key of values.keys()) {\n if (key.startsWith(stem)) return true;\n }\n return false;\n}\n\n/**\n * Writing a value revives its whole branch: drop any removal tombstone for\n * the path itself, its ancestors, or its descendants (a remounted field\n * overwrites its own tombstone; rewriting a parent array supersedes the\n * tombstones of shifted child paths).\n */\nfunction reviveBranch(deleted: Set<string>, {key}: Path): void {\n if (!deleted.size) return;\n for (const tombstone of deleted) {\n if (\n tombstone === key ||\n tombstone.startsWith(`${key.slice(0, -1)},`) ||\n key.startsWith(`${tombstone.slice(0, -1)},`)\n ) {\n deleted.delete(tombstone);\n }\n }\n}\n\n/**\n * Set form initialValues\n *\n * Content-based early return: a new reference with equal content (the\n * re-rendered inline literal) is a no-op, so committed edits survive, while\n * genuinely changed content swaps the baseline and re-seeds — live values\n * and tombstones are cleared, touched flags and errors survive.\n * @param form\n * @param initialValues\n */\nexport function setInitialValues(form: Form, initialValues: any): void {\n if (\n form.initialValues === initialValues ||\n isEqual(form.initialValues, initialValues)\n ) {\n return;\n }\n form.initialValues = initialValues;\n // A new baseline invalidates the previous schema parse.\n form.parsedValues = undefined;\n form.values.clear();\n form.deleted.clear();\n bumpDirtyVersion(form);\n emit(form.emitter, 'change');\n}\n\n/** Options accepted by {@link reset}. Every flag defaults to `false` —\n * omitting the object (or any flag) keeps the plain full-reset behavior.\n * Names mirror react-hook-form's reset options to ease migration. */\nexport interface ResetOptions {\n /** Keep the current values of fields that are dirty — differ from the\n * pre-reset initialValues (the same rule {@link getDirtyFields} applies).\n * Clean fields fall back to the new initialValues as usual. */\n keepDirtyValues?: boolean;\n /** Keep the touched set instead of clearing it. */\n keepTouched?: boolean;\n /** Keep field errors instead of clearing them. */\n keepErrors?: boolean;\n /** Keep the submitted flag (`isSubmitSuccessful`) instead of clearing\n * it. */\n keepIsSubmitted?: boolean;\n /** Keep `submitCount` instead of resetting it to 0. */\n keepSubmitCount?: boolean;\n /** Keep `isSubmitting` instead of resetting it to false. */\n keepIsSubmitting?: boolean;\n}\n\n/**\n * Reset form\n * @param form\n * @param initialValues\n * @param options keep-flags to preserve slices of state through the reset\n */\nexport function reset(\n form: Form,\n initialValues?: any,\n options?: ResetOptions\n): void {\n // Snapshot dirty fields' live values before the wipe: dirtiness is\n // measured against the pre-reset initialValues, so capture must happen\n // before form.values and form.initialValues are touched.\n const dirtyValues = options?.keepDirtyValues\n ? Object.keys(getDirtyFields(form)).map(key => ({\n key,\n value: getValue(form, key)\n }))\n : [];\n form.initialValues = initialValues;\n // The fresh baseline drops any schema parse from the previous cycle.\n form.parsedValues = undefined;\n if (!options?.keepErrors) clearErrors(form);\n const {emitter, touched, values, deleted, validating} = form;\n values.clear();\n deleted.clear();\n if (!options?.keepTouched) touched.clear();\n validating.clear();\n if (!options?.keepIsSubmitting) form.isSubmitting = false;\n if (!options?.keepSubmitCount) form.submitCount = 0;\n if (!options?.keepIsSubmitted) form.isSubmitSuccessful = undefined;\n bumpDirtyVersion(form);\n // Write the kept dirty values back over the fresh baseline: plain\n // setValueByPath, so no validation fires and nothing is marked touched.\n for (const {key, value} of dirtyValues) {\n setValueByPath(form, createPath(key), value);\n }\n emit(emitter, 'change');\n emit(emitter, 'touched');\n emit(emitter, 'validating');\n emit(emitter, 'submitting');\n emit(emitter, 'submitCount');\n emit(emitter, 'submitSuccessful');\n emit(emitter, 'reset');\n}\n\n/** Options accepted by {@link resetField}. The flags default to `false`;\n * `value` has no default — omitted, the field falls back to initialValues;\n * provided, the explicit value becomes the live value with no fallback at\n * all. Mirrors react-hook-form's resetField options (`value` plays their\n * `defaultValue`'s role) to ease migration. */\nexport interface ResetFieldOptions {\n /** Keep the field's touched flag instead of clearing it. */\n keepTouched?: boolean;\n /** Keep the field's errors instead of clearing them. */\n keepErrors?: boolean;\n /** Explicit post-reset value for the field — never falls back to\n * initialValues. */\n value?: any;\n}\n\n/**\n * Reset a single field: drop its live value (reads fall back to the\n * baseline — initialValues, or the schema's parsed output when one\n * exists, in which case the path is removed from parsedValues and the\n * initial value pinned back so the field reads initialValues again),\n * clear its touched flag and errors, and revive the path's removal\n * tombstones — the inverse of {@link removeFieldByPath}. Other fields\n * and the submission flags are untouched; see {@link reset} for the\n * form-wide counterpart.\n *\n * @param form\n * @param name\n * @param options\n */\nexport function resetField<\n T extends Record<string, any> = any,\n P extends FieldPath<T> | Name = Name\n>(form: Form<T>, name: P, options?: ResetFieldOptions): void {\n const path = createPath(name);\n const {emitter, values, touched, errors, deleted} = form;\n values.delete(path.key);\n // A parse baseline wholesale-shadows initialValues in reads (see\n // getValues), so unset alone would read the path as undefined. Remove\n // the path from the tree (immutable — parsedValues shares branches with\n // the schema's own output) and pin the initial value back as the live\n // value: equal to initialValues, so the field stays clean.\n if (form.parsedValues !== undefined) {\n form.parsedValues = unset(form.parsedValues, path.value);\n const initial = get(form.initialValues, path.value);\n if (initial !== undefined) values.set(path.key, initial);\n }\n if (options && 'value' in options) {\n values.set(path.key, options.value);\n }\n // A reset re-registers the branch, same as a write: tombstones on the\n // path or around it stop applying.\n reviveBranch(deleted, path);\n // Payload-less like removeFieldByPath: reviveBranch can un-tombstone\n // ancestor or descendant paths, whose readers must re-sync too.\n emit(emitter, 'change');\n if (!options?.keepTouched && touched.delete(path.key)) {\n emit(emitter, 'touched', path);\n }\n if (!options?.keepErrors && errors.delete(path.key)) {\n emit(emitter, 'errors', path);\n }\n bumpDirtyVersion(form);\n}\n\n/**\n * @param form\n */\nexport function hasErrors({errors}: Form): boolean {\n return errors.size > 0;\n}\n\n/**\n * Trigger field validation.\n *\n * Without `name` every registered field validator runs. A single `name` —\n * dotted string or segments array — runs only that field's validator, and\n * an array of names runs each one in order. An empty array is a no-op, as\n * is any name with no registered validator. An array argument counts as\n * one segments path only when it mixes in numbers (`['items', 0]`); pure\n * string arrays are name lists, so `['a', 'b']` triggers fields `a` and\n * `b`, not the nested path `a.b`.\n *\n * The returned promise waits for the triggered validation to settle —\n * async validators included — so their errors have already landed in\n * `form.errors` when it resolves. It never rejects: landing errors is the\n * expected outcome here, not a failure. Resolves `true` when the triggered\n * scope is error-free, `false` otherwise. Without `name` the scope is all\n * fields plus the form-level `validate` result (which runs after field\n * validators settle, same pipeline as {@link ensureValidate}); with `name`\n * only those fields' own errors count and form-level `validate` is\n * skipped (RHF semantics).\n *\n * Fire-and-forget callers may ignore the promise: the validator kicks\n * still happen synchronously, matching the pre-promise behavior.\n *\n * @param form\n * @param name field name(s) to trigger, or all fields when omitted\n * @return whether the triggered scope is error-free once validation settles\n */\nexport async function trigger(\n form: Form,\n name?: Name | Name[]\n): Promise<boolean> {\n // Never reject (an error landing is a normal outcome, not a failure), so\n // waitUntil's isReject is permanently false. Waiting on the whole\n // `validating` set is deliberately conservative: it also rides out\n // unrelated in-flight validators rather than racing them.\n const settle = () =>\n waitUntil(\n form.emitter,\n 'validating',\n () => !form.validating.size,\n () => false\n );\n\n if (name === undefined) {\n form.validators.forEach(validator => validator());\n await settle();\n if (form.validate) {\n const result = await form.validate(getValues(form));\n applyValidateResult(form, result);\n }\n return !hasErrors(form);\n }\n\n const keys: string[] =\n typeof name === 'string' || isSegmentsPath(name)\n ? [createPath(name).key]\n : name.map(one => createPath(one).key);\n keys.forEach(key => form.validators.get(key)?.());\n await settle();\n return keys.every(key => !form.errors.has(key));\n}\n\n/** Numbers only occur inside a segments path (`['a', 0]`), never as\n * standalone names, so a top-level number marks `name` as one single path\n * rather than a list of names. */\nfunction isSegmentsPath(name: PathSegments | Name[]): name is PathSegments {\n return (name as (number | unknown)[]).some(part => typeof part === 'number');\n}\n\nfunction isFieldError(value: any): value is FieldError {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof value.type === 'string' &&\n typeof value.message === 'string'\n );\n}\n\n/**\n * Flatten a form-level validate result and write each leaf error through\n * setError. Nested objects descend into deeper paths ({a: {b: 'msg'}} sets\n * the 'a.b' error), array values contribute every non-empty string they\n * hold as separate errors (zod flatten() formErrors style), and\n * FieldError-shaped objects are stored as-is. Falsy values are skipped.\n */\nfunction setFormErrors(\n form: Form,\n result: Record<string, any>,\n segments: PathSegments = []\n): void {\n Object.entries(result).forEach(([key, value]) => {\n const path: PathSegments = [...segments, ...normalizePath(key)];\n if (typeof value === 'string') {\n if (value) setError(form, path, value);\n } else if (Array.isArray(value)) {\n setError(form, path, value);\n } else if (isFieldError(value)) {\n setError(form, path, value);\n } else if (value && typeof value === 'object') {\n setFormErrors(form, value, path);\n }\n });\n}\n\n/** Store a schema validator's parsed output as the getValues baseline\n * layer above initialValues. Payload-less 'change' notifies value\n * watchers (useValue, useDirtyFields, ...); dirty state is untouched —\n * it only compares live edits against initialValues, and parsing is not\n * an edit. */\nfunction setParsedValues(form: Form, values: any): void {\n if (values === undefined || values === form.parsedValues) return;\n form.parsedValues = values;\n emit(form.emitter, 'change');\n}\n\n/**\n * Land a form-level validate result. A plain record keeps the\n * long-standing behavior — flattened into field errors by\n * {@link setFormErrors}. A branded {@link ValidationOutcome} splits\n * instead: `errors` flattens exactly like a plain record, and `values`\n * (the schema's parsed output — coerced/transformed values included)\n * becomes the form's parsedValues baseline. Falsy results are skipped,\n * branded or not.\n */\nfunction applyValidateResult(\n form: Form,\n result: ValidateResult<any> | undefined\n): void {\n if (!result) return;\n if (typeof result === 'object' && VALIDATION_OUTCOME in result) {\n const outcome = result as ValidationOutcome<any>;\n if (outcome.errors) setFormErrors(form, outcome.errors);\n setParsedValues(form, outcome.values);\n return;\n }\n setFormErrors(form, result as Record<string, any>);\n}\n\n/**\n * Validate and throw if any field error.\n * @param form\n * @return resolve if no error; reject and stop validate if has an error\n */\nexport async function ensureValidate(form: Form): Promise<void> {\n form.validators.forEach(validator => validator());\n\n await waitUntil(\n form.emitter,\n 'validating',\n () => !form.validating.size,\n () => hasErrors(form)\n ).catch(() => {\n throw new Error(getFirstError(form));\n });\n\n if (form.validate) {\n const result = await form.validate(getValues(form));\n applyValidateResult(form, result);\n if (hasErrors(form)) throw new Error(getFirstError(form));\n }\n}\n\n/**\n * Validate and return if any field error.\n * @param form\n * @return error message string or void\n */\nexport async function validate(form: Form): Promise<void | string> {\n return ensureValidate(form).catch(e => e.message);\n}\n\nexport function setIsSubmitting(form: Form, value: boolean): void {\n form.isSubmitting = value;\n emit(form.emitter, 'submitting');\n}\n\nexport function incrementSubmitCount(form: Form): void {\n form.submitCount++;\n emit(form.emitter, 'submitCount');\n}\n\nexport function setSubmitSuccessful(form: Form, value: boolean): void {\n form.isSubmitSuccessful = value;\n emit(form.emitter, 'submitSuccessful');\n}\n\n/**\n * Set the form-level disabled flag and emit a payload-less 'disabled'\n * event — subscribed fields (useField and the components built on it)\n * re-render with the merged disabled state: form flag || their own\n * `disabled` option.\n * @param form\n * @param value\n */\nexport function setDisabled(form: Form, value: boolean): void {\n form.disabled = value;\n emit(form.emitter, 'disabled');\n}\n\n/** Structural slice of a <form>-like element: an elements collection whose\n * controls expose the constraint-validation members we read. Matches the\n * DOM HTMLFormElement shape without coupling the core to DOM types. */\ninterface NativeFormElement {\n elements: ArrayLike<{\n name: string;\n checkValidity: () => boolean;\n validationMessage: string;\n }>;\n}\n\n/**\n * Converts a control's DOM name to the user-visible dotted path. Field\n * components render the path key (JSON.stringify'd segments, '[\"a\",\"0\"]')\n * as the name attribute, so JSON keys are parsed back and joined with\n * dots; any other name value is returned as-is.\n */\nfunction nameToPath(name: string): string {\n if (name.startsWith('[')) {\n try {\n const segments = JSON.parse(name);\n if (Array.isArray(segments)) return segments.join('.');\n } catch {\n // Not a JSON path key — fall through and use the raw name.\n }\n }\n return name;\n}\n\n/**\n * Collects the constraints failing native validation on a <form> as\n * {@link FieldErrorEntry} entries, in DOM order.\n *\n * Design note: native errors are deliberately NOT written into the form's\n * errors Map. That Map tracks custom validator state, while native\n * validity is transient DOM state owned by the browser (surfaced through\n * reportValidity); onInvalidSubmit receives this snapshot directly.\n */\nfunction getNativeErrors(formEl: NativeFormElement): FieldErrorEntry[] {\n const errors: FieldErrorEntry[] = [];\n const {elements} = formEl;\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n if (\n el.name &&\n typeof el.checkValidity === 'function' &&\n !el.checkValidity()\n ) {\n errors.push({\n path: nameToPath(el.name),\n type: 'native',\n message: el.validationMessage\n });\n }\n }\n return errors;\n}\n\n/** Submit callbacks for {@link handleSubmit}. All optional — a missing\n * callback is simply skipped, matching the <Form> component semantics. */\nexport interface HandleSubmitOptions<T extends Record<string, any> = any> {\n /** Called after validation passes, before onValidSubmit. */\n onSubmit?: (values: T, e?: any) => void | Promise<void>;\n /** Called after validation passes, following a successful onSubmit. */\n onValidSubmit?: (values: T, e?: any) => void | Promise<void>;\n /**\n * Called when validation fails.\n * @param errors array of {path, type, message} entries in insertion\n * order; path is the dotted field path ('a.b', 'list.0'), type is\n * the error kind ('custom' for plain string errors, 'native' for\n * failed DOM constraint validation), message is the display text\n * @param values current form values\n */\n onInvalidSubmit?: (errors: FieldErrorEntry[], values: T) => void;\n /**\n * Focus the first error field after a failed submit. Defaults to true —\n * only an explicit `false` disables it. When custom validation fails,\n * a 'focusError' event carrying the first error's path key is emitted\n * on the form (bound fields such as <Field> subscribe and focus their\n * input); when native constraint validation fails, the submitted\n * form's first ':invalid' control is focused directly.\n */\n shouldFocusError?: boolean;\n}\n\n/**\n * Create an async submit handler for `form` — the headless counterpart of\n * the <Form> component's onSubmit wiring.\n *\n * Behavior mirrors <Form> exactly: preventDefault when present, then the\n * submit state machine (isSubmitting/submitCount/isSubmitSuccessful) runs\n * around native constraint validation (via `e.currentTarget.checkValidity`,\n * skipped when the target has no checkValidity — e.g. React Native or\n * toolbar-button submits) and custom validators. Failed validation fires\n * onInvalidSubmit with the flattened error entries; a passing submit runs\n * onSubmit then onValidSubmit. Errors thrown by either are swallowed into\n * isSubmitSuccessful=false rather than rejecting the returned promise.\n * Failed validation also focuses the offending field (see\n * {@link HandleSubmitOptions.shouldFocusError}).\n *\n * @param form form instance\n * @param options submit callbacks\n * @return async event handler, callable without an event object\n */\nexport function handleSubmit<T extends Record<string, any> = any>(\n form: Form<T>,\n options?: HandleSubmitOptions<T>\n): (e?: {preventDefault?: () => void; currentTarget?: any}) => Promise<void> {\n const {\n onSubmit,\n onValidSubmit,\n onInvalidSubmit,\n shouldFocusError = true\n } = options ?? {};\n return async e => {\n if (e && typeof e.preventDefault === 'function') {\n e.preventDefault();\n }\n const formEl = e?.currentTarget;\n setIsSubmitting(form, true);\n incrementSubmitCount(form);\n const values = getValues(form);\n\n if (\n formEl &&\n typeof formEl.checkValidity === 'function' &&\n formEl.checkValidity() === false\n ) {\n formEl.reportValidity();\n // Focus the first natively-invalid control directly off the DOM;\n // native failures never enter the errors Map (see below).\n if (shouldFocusError && typeof formEl.querySelector === 'function') {\n const invalid = formEl.querySelector(':invalid') as HTMLElement | null;\n if (invalid && typeof invalid.focus === 'function') invalid.focus();\n }\n setIsSubmitting(form, false);\n setSubmitSuccessful(form, false);\n // Native constraint failures are read from the DOM (not the errors\n // Map, which only holds custom validation state — see getNativeErrors).\n if (onInvalidSubmit) onInvalidSubmit(getNativeErrors(formEl), values);\n return;\n }\n\n const error = await validate(form);\n\n if (error) {\n setIsSubmitting(form, false);\n setSubmitSuccessful(form, false);\n // Notify bound fields (e.g. <Field>) so the first errored one can\n // focus its input; the payload is the errors Map's first key.\n if (shouldFocusError) {\n const firstKey = form.errors.keys().next().value;\n if (firstKey !== undefined) emit(form.emitter, 'focusError', firstKey);\n }\n if (onInvalidSubmit) onInvalidSubmit(getErrors(form), values);\n return;\n }\n\n try {\n // Re-read after validation: a schema validator's parsed output\n // (ValidationOutcome.values) landed in parsedValues during\n // validate(), and the submit callbacks must see the coerced /\n // transformed values, not the raw pre-validation snapshot.\n const submitted = getValues(form);\n if (onSubmit) await onSubmit(submitted, e);\n if (onValidSubmit) await onValidSubmit(submitted, e);\n setSubmitSuccessful(form, true);\n } catch {\n setSubmitSuccessful(form, false);\n } finally {\n setIsSubmitting(form, false);\n }\n };\n}\n\n/** Options accepted by {@link setFocus}. All flags default to `false`. */\nexport interface SetFocusOptions {\n /** Select the field's text after focusing it. Bound fields call\n * `select()` on their element; elements without one (custom `as`\n * components) just focus. */\n shouldSelect?: boolean;\n}\n\n/**\n * Programmatically focus a bound field's element (e.g. the <Field>'s\n * input).\n *\n * Rides the same 'focusError' event channel a failed handleSubmit uses to\n * focus the first errored field: the payload is the target's path key,\n * with the focus options as a second, backward-compatible argument (older\n * subscribers declared with a single `key` parameter simply ignore it).\n * Being event-driven, it is a silent no-op when the field is unmounted or\n * nothing subscribes — unknown names never throw.\n *\n * @param form form instance\n * @param name field name (dot path or segments path)\n * @param options focus options\n */\nexport function setFocus(\n form: Form,\n name: Name,\n options?: SetFocusOptions\n): void {\n const {key} = createPath(name);\n // Omit the options argument when absent so the payload is exactly the\n // shape handleSubmit emits after a failed submit.\n if (options) emit(form.emitter, 'focusError', key, options);\n else emit(form.emitter, 'focusError', key);\n}\n"],"names":["createPath"],"mappings":"AAAA,SAAS,MAAM,CAAC,EAAE,EAAE,GAAG,EAAE;AACzB,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC;AACvB,EAAE,IAAI,GAAG,EAAE,OAAO,GAAG;AACrB,EAAE,IAAI,MAAM,GAAG,IAAI,GAAG,EAAE;AACxB,EAAE,EAAE,C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pB,EAAA,IAAA,CAAK,IAAA,CAAK,SAAS,QAAQ,CAAA;AAC7B;AAWA,SAAS,mBAAA,CACP,MACA,MAAA,EACM;AACN,EAAA,IAAI,CAAC,MAAA,EAAQ;AACb,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,kBAAA,IAAsB,MAAA,EAAQ;AAC9D,IAAA,MAAM,OAAA,GAAU,MAAA;AAChB,IAAA,IAAI,OAAA,CAAQ,MAAA,EAAQ,aAAA,CAAc,IAAA,EAAM,QAAQ,MAAM,CAAA;AACtD,IAAA,eAAA,CAAgB,IAAA,EAAM,QAAQ,MAAM,CAAA;AACpC,IAAA;AAAA,EACF;AACA,EAAA,aAAA,CAAc,MAAM,MAA6B,CAAA;AACnD;;;;","x_google_ignoreList":[0]}
|
|
@@ -320,6 +320,30 @@ declare function setErrorByPath({ emitter, errors }: Form, path: Path, error: st
|
|
|
320
320
|
* @param name a single path or a list of paths; omit to clear every error
|
|
321
321
|
*/
|
|
322
322
|
declare function clearErrors(form: Form, name?: Name | Name[]): void;
|
|
323
|
+
/** Options accepted by {@link setServerErrors}. */
|
|
324
|
+
interface SetServerErrorsOptions {
|
|
325
|
+
/** Keep existing field errors instead of clearing them first. Defaults
|
|
326
|
+
* to `false`: a fresh server response replaces the prior error state. */
|
|
327
|
+
keepExisting?: boolean;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Land a server-side error response on the form: each entry becomes the
|
|
331
|
+
* named field's error(s) with `type: 'server'`, ready for the same
|
|
332
|
+
* renderError/`useError` channel client-side validation uses. Takes the
|
|
333
|
+
* flat `Record<string, string | string[]>` shape REST APIs commonly
|
|
334
|
+
* return (RealWorld: `422 {errors: {email: ['has already been taken']}}`)
|
|
335
|
+
* without a hand-rolled `Object.entries` + `setError` loop.
|
|
336
|
+
*
|
|
337
|
+
* A string value lands as one error, a string array as several (first one
|
|
338
|
+
* is what `getError`/`error` expose); an empty array clears that field's
|
|
339
|
+
* errors. By default every existing error is cleared first — a fresh
|
|
340
|
+
* response describes the current state, not a patch onto stale client
|
|
341
|
+
* errors; pass `keepExisting: true` to layer instead.
|
|
342
|
+
* @param form
|
|
343
|
+
* @param errors field errors keyed by name
|
|
344
|
+
* @param options
|
|
345
|
+
*/
|
|
346
|
+
declare function setServerErrors(form: Form, errors: Record<string, string | string[]>, options?: SetServerErrorsOptions): void;
|
|
323
347
|
/**
|
|
324
348
|
* Set field touched state
|
|
325
349
|
* @param form
|
|
@@ -384,6 +408,11 @@ declare function removeField(form: Form, name: Name): void;
|
|
|
384
408
|
declare function removeFieldByPath(form: Form, { key, value: segments }: Path): void;
|
|
385
409
|
/**
|
|
386
410
|
* Set form initialValues
|
|
411
|
+
*
|
|
412
|
+
* Content-based early return: a new reference with equal content (the
|
|
413
|
+
* re-rendered inline literal) is a no-op, so committed edits survive, while
|
|
414
|
+
* genuinely changed content swaps the baseline and re-seeds — live values
|
|
415
|
+
* and tombstones are cleared, touched flags and errors survive.
|
|
387
416
|
* @param form
|
|
388
417
|
* @param initialValues
|
|
389
418
|
*/
|
|
@@ -574,5 +603,5 @@ interface SetFocusOptions {
|
|
|
574
603
|
*/
|
|
575
604
|
declare function setFocus(form: Form, name: Name, options?: SetFocusOptions): void;
|
|
576
605
|
|
|
577
|
-
export {
|
|
578
|
-
export type {
|
|
606
|
+
export { setServerErrors as $, getValueByPath as A, getValues as B, handleSubmit as C, hasErrors as D, hasTouched as E, hasTouchedByPath as G, incrementSubmitCount as I, isDirty as J, isTouched as K, removeField as L, removeFieldByPath as M, reset as Q, resetField as T, setDisabled as U, VALIDATION_OUTCOME as V, setError as W, setErrorByPath as X, setFocus as Y, setInitialValues as Z, setIsSubmitting as _, setSubmitSuccessful as a0, setTouched as a1, setTouchedByPath as a2, setValidatingByPath as a3, setValue as a4, setValueByPath as a5, trigger as a6, unsetValidatingByPath as a7, validate as a8, clearErrors as n, create as o, ensureValidate as p, getDirtyFields as q, getError as r, getErrorByPath as s, getErrors as t, getFieldErrors as u, getFieldErrorsByPath as v, getFieldState as w, getFirstError as x, getTouchedFields as y, getValue as z };
|
|
607
|
+
export type { Form as F, HandleSubmitOptions as H, Name as N, Options as O, PathValueOf as P, ReValidateMode as R, SetFieldOptions as S, FieldPath as a, FieldError as b, Path as c, FieldErrorEntry as d, FieldState as e, PathValue as f, ResetFieldOptions as g, ResetOptions as h, SetFocusOptions as i, SetServerErrorsOptions as j, ValidateResult as k, ValidationMode as l, ValidationOutcome as m };
|
package/dist/index.cjs.js
CHANGED
|
@@ -31,7 +31,7 @@ function getSet(ee, key) {
|
|
|
31
31
|
function create$2() {
|
|
32
32
|
return new Map();
|
|
33
33
|
}
|
|
34
|
-
function emit
|
|
34
|
+
function emit(ee, key) {
|
|
35
35
|
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
|
36
36
|
args[_key - 2] = arguments[_key];
|
|
37
37
|
}
|
|
@@ -164,6 +164,31 @@ function setOwned(root, path, value, owned) {
|
|
|
164
164
|
function isPromise(value) {
|
|
165
165
|
return value && typeof value.then === "function";
|
|
166
166
|
}
|
|
167
|
+
function isEqual(a, b) {
|
|
168
|
+
if (Object.is(a, b)) return true;
|
|
169
|
+
if (a instanceof Date && b instanceof Date)
|
|
170
|
+
return a.getTime() === b.getTime();
|
|
171
|
+
if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
|
|
172
|
+
const isArray = Array.isArray(a);
|
|
173
|
+
if (isArray !== Array.isArray(b)) return false;
|
|
174
|
+
if (isArray) {
|
|
175
|
+
if (a.length !== b.length) return false;
|
|
176
|
+
for (let i = 0; i < a.length; i++) {
|
|
177
|
+
if (!isEqual(a[i], b[i])) return false;
|
|
178
|
+
}
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
const proto = Object.getPrototypeOf(a);
|
|
182
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
183
|
+
if (Object.getPrototypeOf(b) !== proto) return false;
|
|
184
|
+
const keysA = Object.keys(a);
|
|
185
|
+
const keysB = Object.keys(b);
|
|
186
|
+
if (keysA.length !== keysB.length) return false;
|
|
187
|
+
for (const key of keysA) {
|
|
188
|
+
if (!isEqual(a[key], b[key])) return false;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
167
192
|
function waitUntil(emitter, event, isResolve, isReject) {
|
|
168
193
|
return new Promise((resolve, reject) => {
|
|
169
194
|
if (isReject()) return void reject();
|
|
@@ -186,7 +211,6 @@ function create$1(name) {
|
|
|
186
211
|
return { value, key: JSON.stringify(value) };
|
|
187
212
|
}
|
|
188
213
|
|
|
189
|
-
const emit = emit$1;
|
|
190
214
|
const VALIDATION_OUTCOME = /* @__PURE__ */ Symbol("validation-outcome");
|
|
191
215
|
function create(options) {
|
|
192
216
|
const emitter = create$2();
|
|
@@ -322,6 +346,19 @@ function clearErrors(form, name) {
|
|
|
322
346
|
for (const { key } of paths) errors.delete(key);
|
|
323
347
|
for (const path of paths) emit(emitter, "errors", path);
|
|
324
348
|
}
|
|
349
|
+
function setServerErrors(form, errors, options) {
|
|
350
|
+
if (!options?.keepExisting) clearErrors(form);
|
|
351
|
+
for (const [name, error] of Object.entries(errors)) {
|
|
352
|
+
setError(
|
|
353
|
+
form,
|
|
354
|
+
name,
|
|
355
|
+
(Array.isArray(error) ? error : [error]).map((message) => ({
|
|
356
|
+
type: "server",
|
|
357
|
+
message
|
|
358
|
+
}))
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
325
362
|
function setTouched(form, name) {
|
|
326
363
|
setTouchedByPath(form, create$1(name));
|
|
327
364
|
}
|
|
@@ -422,7 +459,9 @@ function reviveBranch(deleted, { key }) {
|
|
|
422
459
|
}
|
|
423
460
|
}
|
|
424
461
|
function setInitialValues(form, initialValues) {
|
|
425
|
-
if (form.initialValues === initialValues)
|
|
462
|
+
if (form.initialValues === initialValues || isEqual(form.initialValues, initialValues)) {
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
426
465
|
form.initialValues = initialValues;
|
|
427
466
|
form.parsedValues = void 0;
|
|
428
467
|
form.values.clear();
|
|
@@ -781,7 +820,7 @@ function requireUseSyncExternalStoreShim_production () {
|
|
|
781
820
|
var nextValue = latestGetSnapshot();
|
|
782
821
|
return !objectIs(inst, nextValue);
|
|
783
822
|
} catch (error) {
|
|
784
|
-
return
|
|
823
|
+
return true;
|
|
785
824
|
}
|
|
786
825
|
}
|
|
787
826
|
function useSyncExternalStore$1(subscribe, getSnapshot) {
|
|
@@ -823,7 +862,7 @@ function requireUseSyncExternalStoreShim_development () {
|
|
|
823
862
|
function useSyncExternalStore$2(subscribe, getSnapshot) {
|
|
824
863
|
didWarnOld18Alpha ||
|
|
825
864
|
void 0 === React$1.startTransition ||
|
|
826
|
-
((didWarnOld18Alpha =
|
|
865
|
+
((didWarnOld18Alpha = true),
|
|
827
866
|
console.error(
|
|
828
867
|
"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
|
|
829
868
|
));
|
|
@@ -834,7 +873,7 @@ function requireUseSyncExternalStoreShim_development () {
|
|
|
834
873
|
(console.error(
|
|
835
874
|
"The result of getSnapshot should be cached to avoid an infinite loop"
|
|
836
875
|
),
|
|
837
|
-
(didWarnUncachedGetSnapshot =
|
|
876
|
+
(didWarnUncachedGetSnapshot = true));
|
|
838
877
|
}
|
|
839
878
|
cachedValue = useState({
|
|
840
879
|
inst: { value: value, getSnapshot: getSnapshot }
|
|
@@ -868,7 +907,7 @@ function requireUseSyncExternalStoreShim_development () {
|
|
|
868
907
|
var nextValue = latestGetSnapshot();
|
|
869
908
|
return !objectIs(inst, nextValue);
|
|
870
909
|
} catch (error) {
|
|
871
|
-
return
|
|
910
|
+
return true;
|
|
872
911
|
}
|
|
873
912
|
}
|
|
874
913
|
function useSyncExternalStore$1(subscribe, getSnapshot) {
|
|
@@ -884,8 +923,8 @@ function requireUseSyncExternalStoreShim_development () {
|
|
|
884
923
|
useEffect = React$1.useEffect,
|
|
885
924
|
useLayoutEffect = React$1.useLayoutEffect,
|
|
886
925
|
useDebugValue = React$1.useDebugValue,
|
|
887
|
-
didWarnOld18Alpha =
|
|
888
|
-
didWarnUncachedGetSnapshot =
|
|
926
|
+
didWarnOld18Alpha = false,
|
|
927
|
+
didWarnUncachedGetSnapshot = false,
|
|
889
928
|
shim =
|
|
890
929
|
"undefined" === typeof window ||
|
|
891
930
|
"undefined" === typeof window.document ||
|
|
@@ -902,13 +941,21 @@ function requireUseSyncExternalStoreShim_development () {
|
|
|
902
941
|
return useSyncExternalStoreShim_development;
|
|
903
942
|
}
|
|
904
943
|
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
944
|
+
var hasRequiredShim;
|
|
945
|
+
|
|
946
|
+
function requireShim () {
|
|
947
|
+
if (hasRequiredShim) return shim.exports;
|
|
948
|
+
hasRequiredShim = 1;
|
|
949
|
+
|
|
950
|
+
if (process.env.NODE_ENV === 'production') {
|
|
951
|
+
shim.exports = requireUseSyncExternalStoreShim_production();
|
|
952
|
+
} else {
|
|
953
|
+
shim.exports = requireUseSyncExternalStoreShim_development();
|
|
954
|
+
}
|
|
955
|
+
return shim.exports;
|
|
909
956
|
}
|
|
910
957
|
|
|
911
|
-
var shimExports =
|
|
958
|
+
var shimExports = requireShim();
|
|
912
959
|
|
|
913
960
|
function isDescendant(key, ancestorKey) {
|
|
914
961
|
return key.startsWith(`${ancestorKey.slice(0, -1)},`);
|
|
@@ -1084,31 +1131,6 @@ function useIsSubmitting(form) {
|
|
|
1084
1131
|
function useSubmitCount(form) {
|
|
1085
1132
|
return useWatch(form.emitter, "submitCount", () => form.submitCount);
|
|
1086
1133
|
}
|
|
1087
|
-
function isEqual(a, b) {
|
|
1088
|
-
if (Object.is(a, b)) return true;
|
|
1089
|
-
if (a instanceof Date && b instanceof Date)
|
|
1090
|
-
return a.getTime() === b.getTime();
|
|
1091
|
-
if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
|
|
1092
|
-
const isArray = Array.isArray(a);
|
|
1093
|
-
if (isArray !== Array.isArray(b)) return false;
|
|
1094
|
-
if (isArray) {
|
|
1095
|
-
if (a.length !== b.length) return false;
|
|
1096
|
-
for (let i = 0; i < a.length; i++) {
|
|
1097
|
-
if (!isEqual(a[i], b[i])) return false;
|
|
1098
|
-
}
|
|
1099
|
-
return true;
|
|
1100
|
-
}
|
|
1101
|
-
const proto = Object.getPrototypeOf(a);
|
|
1102
|
-
if (proto !== Object.prototype && proto !== null) return false;
|
|
1103
|
-
if (Object.getPrototypeOf(b) !== proto) return false;
|
|
1104
|
-
const keysA = Object.keys(a);
|
|
1105
|
-
const keysB = Object.keys(b);
|
|
1106
|
-
if (keysA.length !== keysB.length) return false;
|
|
1107
|
-
for (const key of keysA) {
|
|
1108
|
-
if (!isEqual(a[key], b[key])) return false;
|
|
1109
|
-
}
|
|
1110
|
-
return true;
|
|
1111
|
-
}
|
|
1112
1134
|
|
|
1113
1135
|
function usePath(name) {
|
|
1114
1136
|
const path = React.useMemo(() => create$1(normalizePath(name)), [name]);
|
|
@@ -1491,6 +1513,9 @@ function errorIdFromKey(key) {
|
|
|
1491
1513
|
const id = key.replace(/["'[\],\s]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1492
1514
|
return id || "field";
|
|
1493
1515
|
}
|
|
1516
|
+
function fieldErrorId(name) {
|
|
1517
|
+
return errorIdFromKey(create$1(name).key);
|
|
1518
|
+
}
|
|
1494
1519
|
const Field = React__namespace.forwardRef(
|
|
1495
1520
|
({
|
|
1496
1521
|
validate,
|
|
@@ -1579,16 +1604,17 @@ const Field = React__namespace.forwardRef(
|
|
|
1579
1604
|
);
|
|
1580
1605
|
const toValue = eventToValue ?? ((e) => e.target.value);
|
|
1581
1606
|
const errorId = errorIdFromKey(fieldKey);
|
|
1607
|
+
const describedBy = error ? [props["aria-describedby"], errorId].filter(Boolean).join(" ") : props["aria-describedby"];
|
|
1582
1608
|
return /* @__PURE__ */ React__namespace.createElement(React__namespace.Fragment, null, /* @__PURE__ */ React__namespace.createElement(
|
|
1583
1609
|
Component,
|
|
1584
1610
|
{
|
|
1585
|
-
"aria-invalid": error ? true : void 0,
|
|
1586
|
-
"aria-describedby": error && renderError ? errorId : void 0,
|
|
1587
1611
|
...props,
|
|
1588
1612
|
name: fieldKey,
|
|
1589
1613
|
onBlur,
|
|
1590
1614
|
...asProps,
|
|
1591
1615
|
...valueToProps ? valueToProps(value) : { value },
|
|
1616
|
+
"aria-invalid": error ? true : props["aria-invalid"],
|
|
1617
|
+
"aria-describedby": describedBy,
|
|
1592
1618
|
disabled: isDisabled,
|
|
1593
1619
|
onChange: (e) => onChange(toValue(e)),
|
|
1594
1620
|
ref: mergedRef
|
|
@@ -1630,12 +1656,13 @@ const Checkbox = React__namespace.forwardRef(
|
|
|
1630
1656
|
return /* @__PURE__ */ React__namespace.createElement(
|
|
1631
1657
|
"input",
|
|
1632
1658
|
{
|
|
1633
|
-
"aria-invalid": error ? true : void 0,
|
|
1634
1659
|
...props,
|
|
1635
1660
|
name: fieldKey,
|
|
1636
1661
|
onBlur,
|
|
1637
1662
|
type: "checkbox",
|
|
1638
1663
|
checked: !!value,
|
|
1664
|
+
"aria-invalid": error ? true : props["aria-invalid"],
|
|
1665
|
+
"aria-describedby": error ? [props["aria-describedby"], errorIdFromKey(fieldKey)].filter(Boolean).join(" ") : props["aria-describedby"],
|
|
1639
1666
|
disabled: isDisabled,
|
|
1640
1667
|
onChange: (e) => onChange(e.target.checked),
|
|
1641
1668
|
ref
|
|
@@ -1683,12 +1710,13 @@ const Select = React__namespace.forwardRef(
|
|
|
1683
1710
|
return /* @__PURE__ */ React__namespace.createElement(
|
|
1684
1711
|
"select",
|
|
1685
1712
|
{
|
|
1686
|
-
"aria-invalid": error ? true : void 0,
|
|
1687
1713
|
...props,
|
|
1688
1714
|
name: fieldKey,
|
|
1689
1715
|
onBlur,
|
|
1690
1716
|
multiple,
|
|
1691
1717
|
value: toSelectValue(multiple, value),
|
|
1718
|
+
"aria-invalid": error ? true : props["aria-invalid"],
|
|
1719
|
+
"aria-describedby": error ? [props["aria-describedby"], errorIdFromKey(fieldKey)].filter(Boolean).join(" ") : props["aria-describedby"],
|
|
1692
1720
|
disabled: isDisabled,
|
|
1693
1721
|
onChange: (e) => onChange(
|
|
1694
1722
|
multiple ? Array.from(e.target.selectedOptions, (option) => option.value) : e.target.value
|
|
@@ -1713,6 +1741,7 @@ exports.clearErrors = clearErrors;
|
|
|
1713
1741
|
exports.createForm = create;
|
|
1714
1742
|
exports.createFormContext = createFormContext;
|
|
1715
1743
|
exports.ensureValidate = ensureValidate;
|
|
1744
|
+
exports.fieldErrorId = fieldErrorId;
|
|
1716
1745
|
exports.getDirtyFields = getDirtyFields;
|
|
1717
1746
|
exports.getError = getError;
|
|
1718
1747
|
exports.getErrorByPath = getErrorByPath;
|
|
@@ -1742,6 +1771,7 @@ exports.setErrorByPath = setErrorByPath;
|
|
|
1742
1771
|
exports.setFocus = setFocus;
|
|
1743
1772
|
exports.setInitialValues = setInitialValues;
|
|
1744
1773
|
exports.setIsSubmitting = setIsSubmitting;
|
|
1774
|
+
exports.setServerErrors = setServerErrors;
|
|
1745
1775
|
exports.setSubmitSuccessful = setSubmitSuccessful;
|
|
1746
1776
|
exports.setTouched = setTouched;
|
|
1747
1777
|
exports.setTouchedByPath = setTouchedByPath;
|